C and C++ abilities should be:
Able to understand and use:
▪ The while statement.
▪ The do-while loop.
▪ The nested loop.
▪ Other program controls such as goto, continue, exit, atexit and return statement.
6.4 The while Statement – Repetition Control Structure, Iteration
-
Also called the while loop, executes a block of statements as long as a specified condition is true.
-
The general form:
| while(condition) statement(s); |
| next_statement; |
-
The (condition) may be any C/C++ valid expression.
-
The statement(s) may be either a single or a compound (a block) C/C++ statement.
-
When program execution reaches a while statement, the following events occur:
The (condition) is evaluated.
If (condition) evaluates as false (that is zero), the while statement terminates and execution passes to the first statement following statement(s) that is the next_statement.
If (condition) evaluates as true (that is non zero), the C/C++ statement(s) are executed.
Then, the execution returns to step number 1.
-
The while statement flow chart is shown below.
-
A program example:
// demonstrates a simple while statement
#include
int main()
{
int calculate;
// print the numbers 1 through 12, set the initial value...
calculate = 1;
// set the while condition...
while(calculate <= 12)
{
// display...
printf("%d ", calculate);
// increment by 1...repeats
calculate++;
}
printf("\n");
return 0;
}
Output:
-
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
#include
// this program have some array that you will learn in another module...
void main()
{
// array variable...
int arrange[5];
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
while(count<5)
{
// set the initial condition...
number = 0;
// another while condition...
while((number <> 10))
{
printf("Enter number %d of 5: ", count + 1);
scanf("%d", &number);
}
// inner while loop stop here...
arrange[count] = number;
count++;
}
// outer while loop stop here, start for loop for printing the result...
for (count = 0; count <>
printf("\nValue %d is %d", count + 1, arrange[count]);
printf("\n");
}
Output:
-
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.
6.5 Repetition: The do-while Loop, Iteration
-
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.
-
The do-while loop construct is:
| do statement(s); while(condition); |
| next_statement; |
-
(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 the next_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
#include
using namespace std;
int main()
{
int selection;
do
{
// 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 Menu"<<"\n";
cout<<"\n 0. Exit";
cout<<"\n 1. Append";
cout<<"\n 2. Delete";
cout<<"\n 3. Modify";
cout<<"\n\n Enter selection: ";
cin>>selection;
}while((selection > 0) && (selection <>
return 0;
}
Output:
-
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
#include
int get_menu_choice(void);
void main()
{
int choice;
choice = get_menu_choice();
printf("You have chosen Menu #%d\n", choice);
printf("\n");
}
int get_menu_choice(void)
{
int selection = 0;
do
{
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 <> 4));
return selection;
}
Output:
6.6 Other Program Controls
for(i=1, sum=0; i<100;> { 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
#include
void main()
{
// declare storage for input, an array and counter variable
char buffer[81];
int ctr;
// 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");
gets(buffer);
// 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((buffer[ctr]=='a')||(buffer[ctr]=='e')|| (buffer[ctr]=='i')||(buffer[ctr]=='o')||(buffer[ctr]=='u'))
continue;
// if not a vowel, display it
putchar(buffer[ctr]);
}
printf("\n");
}
Output:
-
The goto 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 the goto statement.
-
The statement is unconditional because execution always branches when a goto statement is encountered, the branch does not depend on any program condition.
-
A goto 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
#include
void main()
{
int n;
start: ;
puts("Enter a number between 0 and 10: ");
scanf("%d", &n);
if ((n <> 10))
goto start;
else if (n == 0)
goto location0;
else if (n == 1)
goto location1;
else
goto location2;
location0: ;
{
puts("You entered 0.");
}
goto end;
location1: ;
{
puts("You entered 1.");
}
goto end;
location2: ;
{
puts("You entered something between 2 and 10.");
}
end: ;
}
Output:
-
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:
| Function | Description |
| abort() | Abort current process and return error code defined in stdlib.h |
| terminate() | 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 in except.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:
exit(status);
| Status | Description |
| 0 | The program terminated normally. |
| 1 | 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:
exit(EXIT_SUCCESS);
Or
exit(EXIT_FAILURE);
-
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:
int atexit(void(*)(void));
-
atexit() function takes a function pointer as its argument and functions with atexit() 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.
#include
#include
// function prototypes...
void cleanup1(void);
void cleanup2(void);
void main()
{
atexit(cleanup2);
atexit(cleanup1);
// end of main
}
void cleanup1(void)
{
// dummy cleanup.....
printf("\nThis is the demonstration...\n");
printf("cleanup....\n");
printf("You computer is SHUTTING DOWN!!!");
getchar();
}
void cleanup2(void)
{
// another dummy cleanup...
printf("\nAnother cleanup...");
printf("\nWINDOWS 20000 is closing the entire program...");
printf("\nPlease WAIT...");
printf("\nSHUTTING DOWN IN PROGRESS...\n");
getchar();
}
Output:
-
Another example, using exit() and atexit() functions.
// demonstrates the exit() and atexit() functions
#include
#include
#include
#define DELAY 1500000
// function prototypes
void cleanup(void);
void delay(void);
void main()
{
// register the function to be called at exit
int reply;
atexit(cleanup);
puts("Enter 1 to exit, any other to continue.");
scanf("%d", &reply);
if(reply == 1)
exit(EXIT_SUCCESS);
// pretend to do some work
for(reply = 0; reply <>
{
puts("WORKING...");
delay();
}
} // end of main
// function definition...
void cleanup(void)
{
puts("\nPreparing for exit");
delay();
}
// function definition
void delay(void)
{
long x;
for(x = 0; x <>
;
}
Output if user presses other than 1:
No comments:
Post a Comment