My Training Period: xx hours
A continuation from previous Module. The source code for this Module is:C/C++ loops source codes. The lab worksheets for your practice are:C/C++ program control repetition 1,C/C++ program control repetition 2,C/C++ program control selection 1,C/C++ program control selection 2 andC/C++ program control selection 3.
The C and C++ programming abilities should be:
Able to understand and use:
6.4 The while Statement – Repetition Control Structure, Iteration
A program example:
// demonstrates a simple while statement
// print the numbers 1 through 12, set the initial value...
calculate = 1;
// set the while condition...
while(calculate <= 12)
printf("%d ", calculate);
// increment by 1...repeats
Actually, the same task that can be performed by for statement that we have discussed.
But, while statement does not contain an initialization section, the program must explicitly initialize any variables before executing the while expression.
As conclusion, while statement is essentially a for statement without the initialization and increment components.
The comparison between for and while:
for( ; condition; ) vs while(condition)
The tasks that can be accomplished with a for statement can also be done with a while statement.
If for statement is used, the initialization, test and increment expressions are located together and are easy to find and modify.
Just like for and if statements, while statements can also be nested. For example:
// a nested while statements
// this program have some array that you will learn in another module...
// array variable...
int count = 0,
number = 0;
printf("\nPrompting you for 5 numbers\n");
printf("Each number should be from 1 to 10\n");
// while condition is true
// set the initial condition...
number = 0;
// another while condition...
while((number < 1) || (number > 10))
printf("Enter number %d of 5: ", count + 1);
// inner while loop stop here...
arrange[count] = number;
// outer while loop stop here, start for loop for printing the result...
for (count = 0; count < 5; count++)
printf("\nValue %d is %d", count + 1, arrange[count]);
In the program example, the number less 1 or more than 10 will not be accepted and displayed.
Nested loop refers to a loop that is contained within another loop. C/C++ places no limitations on the nesting of loops, except that each inner loop must be enclosed completely in the outer loop.
Executes a block of statements as long as a specified condition is true.
Test the condition at the end of the loop rather than at the beginning, as is done by the for loop and the while loop.
Thedo-while loop construct is:
(condition) may be any C/C++ valid expression.
statement(s) may be either a single or compound (a block) C/C++ statement.
When the program execution reaches the do-while statement, the following events occur:
The statement(s) are executed.
The condition is evaluated. If it is true, execution returns to step number 1. If it is false, the loop terminates and thenext_statement is executed.
This means the statement in the do-while will be executed at least once.
The following is a flow chart for the do-while loop:
You can see that the execute statements are always executed at least once.
for and while loops evaluate the test condition at the start of the loop, so the associated statements are not executed if the test condition is initially false.
do-while is used less frequently than while and for loops, however a do-while loop probably would be more straight forward.
A program example:
// a program to illustrate a do-while loop
using namespace std;
// true for 1, 2 and 3 ONLY, then repeat
// false for other numbers including 0, then stop...
// the do loop is repeated if the while expression is true.
cout<<"\n 0. Exit";
cout<<"\n 1. Append";
cout<<"\n 2. Delete";
cout<<"\n 3. Modify";
cout<<"\n\n Enter selection: ";
}while((selection > 0) && (selection < 4));
Study the program source code and the output.
The program displays the menu and then requests a selection. If the selection is 1, 2, or 3, the menu is displayed again; otherwise, the loop is terminated. Note that the loop is repeatedly executed as long as the selection is 1, 2, or 3.
Another program example:
// another do…while statement example
choice = get_menu_choice();
printf("You have chosen Menu #%d\n", choice);
int selection = 0;
printf("1 - Add a record");
printf("\n2 - Change a record");
printf("\n3 - Delete a record");
printf("\n4 - Quit");
printf("\nEnter a selection: ");
scanf("%d", &selection );
} while ((selection < 1) || (selection > 4));
6.6 Other Program Controls
for(i=1, sum=0; i<100; i++)
if (i%2) // test value, 0 or non-zero
continue; // executed if the test value is non-zero and repeat the for statement
sum = sum + i; // executed if the test value is zero and then, also repeat the for statement
// continue example
// declare storage for input, an array and counter variable
// input and read a line of text using
// puts() and gets() are pre defined functions in stdio.h
puts("Enter a line of text and press Enter key,");
puts("all the vowels will be discarded!:\n");
// go through the string, displaying only those
// characters that are not lowercase vowels
for(ctr=0; buffer[ctr] != '\0'; ctr++)
// if the character is a lowercase vowel, loop back without displaying it
// if not a vowel, display it
Thegoto statement is one of C/C++ unconditional jump, or branching, statements and quite popular in Basic programming language.
When program execution reaches a goto statement, execution immediately jumps, or branches, to the location specified by thegoto statement.
The statement is unconditional because execution always branches when a goto statement is encountered, the branch does not depend on any program condition.
Agoto statement and its target label must be located in the same function, although they can be in different blocks. For example:
// demonstrates the goto statement
puts("Enter a number between 0 and 10: ");
if ((n < 0) || (n > 10))
else if (n == 0)
else if (n == 1)
puts("You entered 0.");
puts("You entered 1.");
puts("You entered something between 2 and 10.");
Programmer can use goto to transfer execution both into and out of loops, such as a for statement.
But, it is strongly recommended that a goto statement not be used anywhere in a program. It isn’t needed. Always use other C/C++ branching statements. Furthermore when program execution branches with a goto statement, no record is kept of where the execution came from.
The exit() function, normally used when the program want to terminates at any time by calling the library function exit(). Other similar functions that you will find in the program examples in this tutorial includes:
Abort current process and return error code defined in stdlib.h
Used when a handler for an exception cannot be found. The default action by terminate is to call abort() and causes immediate program termination. It is defined inexcept.h.
Table 6.2: Termination functions.
The exit() function terminates program execution and returns control to the Operating System.
The syntax of the exit() function is:
The program terminated normally.
Indicates that the program terminated with some sort of error. The return value is usually ignored. Other implementation may use other than 1 (non-zero) for termination with error.
Table 6.3: exit() status
We must include the header file stdlib.h or cstdlib if used in C++.
This header file also defines two symbolic constants for use as arguments to the exit() function, such as:
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
Then we can call the function like this:
The atexit() function, used to specify, or register, one or more functions that are automatically executed when the program terminates.
May not be available on non-DOS based system and as many as 32 functions can be registered for execution of the program.
These functions are executed on a last-in, first-out basis, the last function registered is the first function executed.
When all functions registered by atexit() have been executed, the program terminates and returns control to the OS.
The prototype of the atexit() function is located in the stdlib.h and the construct is:
atexit() function takes a function pointer as its argument and functions withatexit() must have a return type of void. Pointer will be explained in other Module.
The following is a program example that shows how to execute the functions cleanup1() and cleanup2(), in that order, on termination. Study the following program example and the output.
// function prototypes...
// end of main
// dummy cleanup.....
printf("\nThis is the demonstration...\n");
printf("You computer is SHUTTING DOWN!!!");
// another dummy cleanup...
printf("\nWINDOWS 20000 is closing the entire program...");
printf("\nSHUTTING DOWN IN PROGRESS...\n");
Another example, using exit() and atexit() functions.
// demonstrates the exit() and atexit() functions
#define DELAY 1500000
// function prototypes
// register the function to be called at exit
puts("Enter 1 to exit, any other to continue.");
if(reply == 1)
// pretend to do some work
for(reply = 0; reply < 5; reply++)
} // end of main
// function definition...
puts("\nPreparing for exit");
// function definition
for(x = 0; x < DELAY; x++)