|
| My Training Period: xx hours
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 and C/C++ program control selection 3.
6.3.3 Selection-The switch-case-break Statement
switch(expression) { case template_1 : statement(s); break; case template_2 : statement(s); break; ................... ................... case template_n : statement(s); break; default : statement(s); } next_statement;
#include <iostream> using namespace std;
int main() { char selection; cout<<"\n Menu"; cout<<"\n========"; cout<<"\n A - Append"; cout<<"\n M - Modify"; cout<<"\n D - Delete"; cout<<"\n X - Exit"; cout<<"\n Enter selection: "; cin>>selection; switch(selection) { case 'A' : {cout<<"\n To append a record\n";} break; case 'M' : {cout<<"\n To modify a record";} break; case 'D' : {cout<<"\n To delete a record";} break; case 'X' : {cout<<"\n To exit the menu";} break; // other than A, M, D and X... default : cout<<"\n Invalid selection"; // no break in the default case } cout<<"\n"; return 0; }
Output:
|
The statement sequence for case may also be NULL or empty. For example:
switch(selection)
{
case 'A' :
case 'M' :
case 'D' : cout<<"\n To Update a file";
break;
case 'X' : cout<<"\n To exit the menu";
break;
default : cout<<"\n Invalid selection";
}
next_statement;
The above program portion would display "To update a file" if the value entered at the prompt is A, M or D; "To exit menu" if the value is X; and "Invalid selection" if the value is some other character.
It is useful for multiple cases that need the same processing sequence.
The break statement may be omitted to allow the execution to continue to other cases.
Consider the following program segment:
cin>>choice;
switch(choice)
{
case 1 : cout<<"\n Value of choice = 1";
break;
case 2 : cout<<"\n Value of choice = 2";
case 3 : cout<<"\n Value of choice = 3";
break;
default : cout<<"\n Wrong choice";
}
printf("...");
It will display the message "Value of choice = 1" if choice has the value 1. It will display both the messages "Value of choice = 2" and "Value of choice = 3" if choice has the value 2.
It will display the message "Value of choice = 3" if choice has the value 3 and the message "Wrong choice" if it has any other value.
The switch structure can also be nested.
The different between nested if and switch.
The switch permits the execution of more than one alternative (by not placing break statements) whereas the if statement does not. In other words, alternatives in an if statement are mutually exclusive whereas they may or may not be in the case of a switch.
A switch can only perform equality tests involving integer (or character) constants, whereas the if statement allows more general comparison involving other data types as well.
When there are more than 3 or 4 conditions, use the switch-case-break statement rather than a long nested if statement and when there are several option to choose from and when testing for them involves only integer (or character) constants.
The following are the flow charts for selection structure program control.


Is a C/C++ programming construct that executes a code block, a certain number of times.
The block may contain no statement, one statement or more than one statement.
The for statement causes a for loop to be executed a fixed number of times.
The following is the for statement structure:
--------------------------------------------------------------------------------

initial_value1, condition and increment are all C/C++ expressions.
The subsequent statement(s) may be a single or compound C/C++ statement (a block of code).
When a for statement is encountered during program execution, the following events occurs:
The expression initial_value1 is evaluated, usually an assignment statement that sets a variable to a particular value.
The expression condition is evaluated. It is typically a relational expression.
If condition evaluates as false (zero), the for statement terminates and execution passes to the first statement following the for statement that is the next_statement.
If condition evaluates as true (non zero), the subsequent C/C++ statements are executed, in this case the statement(s).
The expression increment is executed, and execution returns to step no. 2.
Schematically, the for statement operation is shown in the following flow chart.

The following is a for statement program example followed by a flowchart:
// a simple for statement
#include <stdio.h>
void main()
{
int count;
// display the numbers 1 through 10
for(count = 1; count <= 10; count++)
printf("%d ", count);
printf("\n");
}

And the flowchart:

The for loop is a very flexible C/C++ construct.
We also can use the count down, decrementing the counter variable instead of incrementing.
For example:
for(count = 100; count > 0; count--)
We can use counter other than 1, for example 3:
for(count = 0; count < 1000; count += 3)
The initialization expression can be omitted if the test variable has been initialized previously in the program. However the semicolon must still be used in the statement.
For example:
count=1;
for( ; count < 1000; count++)
The initialization expression need not be an actual initialization, it can be any valid C/C++ expression, the expression is executed once when the for statement is first reached.
For example:
count=1;
for(printf("Now sorting the array…"); count < 1000; count++)
The incremented expression can be omitted as long as the counter variable is updated within the body of the for statement. The semicolon still must be included.
For example,
for(counter=0; counter < 100; )
printf("%d", counter++);
The test expression that terminates the loop can be any C/C++ expression. As long as it evaluates as true (non zero), the for statement continues to execute.
Logical operators can be used to construct complex test expressions.
For example:
for(count =0; count < 1000 && name[count] != 0; count++)
printf("%d", name[count]);
for(count = 0; count < 1000 && list[count];)
printf("%d", list[count++]);
The for statement and arrays are closely related, so it is difficult to define one without explaining the other. We will learn an array in another Module.
The for statement can be followed with a null statement, so that work is done in the for statement itself. Null statement consists of a semicolon alone on a line.
For example:
for(count = 0; count < 20000; count++)
;
This statement provides the pause (or time-delay) of 20000 milliseconds.
An expression can be created by separating two sub expressions with the comma operator, and are evaluated (in left-to-right order), and the entire expression evaluates to the value of the right sub expression.
Each part of the for statement can be made to perform multiple duties.
For example:
We have two 1000 element arrays, named a[ ] and b[ ]. Then we want to copy the contents of a[ ] to b[ ] in reverse order, so, after the copy operation, the array content should be,
b[0], b[1], b[2],… and a[999], a[998], a[997],… and so on, the coding is
for(i = 0, j = 999; i < 1000; i++, j--)
b[j] = a[i];
Another examples of the for statements:
sum = 0;
for(i = 1; i <=20; i++)
sum = sum + i;
cout<<"\n Sum of the first 20 natural numbers = ";
cout<<sum;
The above program segment will compute and display the sum of the first 20 natural numbers.
The above example can be rewritten as:
for(i = 1, sum = 0; i <= 20; i++)
sum = sum + i;
cout<<"\nSum of the first 20 natural numbers = "<<sum;
Note that the initialization part has two statements separated by a comma (,).
For example:
for(i = 2, sum=0, sum2 = 0; i <= 20; i = i + 2)
{
sum = sum + i;
sum2 = sum2 + i*i;
}
cout<<"\nSum of the first 20 even natural numbers=";
cout<<sum<<"\n";
cout<<"sum of the squares of first 20 even natural numbers=";
cout<<sum2;
In this example, the for statement is a compound or block statement. Note that, the initial value in the initialization part doesn’t have to be zero and the increment value in the incrementation part doesn’t have to be 1.
We can also create an infinite or never-ending loop by omitting the second expression or by using a non-zero constants in the following two code segments examples:
for( ; ; )
cout<<"\n This is an infinite loop";
And
for( ; 1 ; )
cout<<"\n This is an infinite loop";
In both cases, the message "This is an infinite loop" will be displayed repeatedly that is indefinitely.
All of the repetition constructs discussed so far can also be nested to any degree. The nesting of loops provides power and versatility required in some applications.
A program example:
// program to show the nested loops
#include <iostream>
using namespace std;
int main()
{
// variables for counter…
int i, j;
// outer loop, execute this first...
for(i=1; i<11; i++)
{
cout<<"\n"<<i;
// then...execute inner loop with loop index j
// the initial value of j is i + 1
for(j=i+1; j<11; j++)
// display the result…
cout<<j;
// increment counter by 1 for inner loop…
}
// increment counter by 1 for outer loop…
cout<<"\n";
return 0;
}

The program has two for loops. The loop index i for the outer (first) loop runs from 1 to 10 and for each value of i, the loop index j for the inner loop runs from i + 1 to 10.
Note that for the last value of i (i.e. 10), the inner loop is not executed at all because the starting value of j is 2 and the expression j < 11 yields the value false (j = 11).
Another nested example, study the program and the output.
/* nesting two for statements */
#include <stdio.h>
// function prototype
void DrawBox(int, int);
void main()
{
// row = 10, column = 25...
DrawBox(10, 25);
}
void DrawBox(int row, int column)
{
int col;
// row, execute outer for loop...
// start with the preset value and decrement until 1
for( ; row > 0; row--)
{
// column, execute inner loop...
// start with preset col, decrement until 1
for(col = column; col > 0; col--)
// print #....
printf("#");
// decrement by 1 for inner loop...
// go to new line for new row...
printf("\n");
}
// decrement by 1 for outer loop...repeats
}

In the first for loop, the initialization is skipped because the initial value of row, 10 was passed to the DrawBox() function; this for loop is executed until the row is 1 (row > 0). For every row value, the inner for loop will be executed until col = 1 (col > 0). In a simple word, the external for loop will print the row and the internal for loop will print the column so we got a rectangle of #.