Control Statements

A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon (;), and are executed in the same order in which they appear in a program.
But programs are not limited to a linear sequence of statements. During its process, a program may repeat segments of code, or take decisions and bifurcate. For that purpose, C++ provides flow control statements that serve to specify what has to be done by our program, when, and under which circumstances.
Many of the flow control statements explained in this section require a generic (sub)statement as part of its syntax. This statement may either be a simple C++ statement, -such as a single instruction, terminated with a semicolon (;) - or a compound statement. A compound statement is a group of statements (each of them terminated by its own semicolon), but all grouped together in a block, enclosed in curly braces: {}:
{ statement1; statement2; statement3; }
The entire block is considered a single statement (composed itself of multiple substatements). Whenever a generic statement is part of the syntax of a flow control statement, this can either be a simple statement or a compound statement.

A function is set up to perform a task. When the task is complex, many different algorithms can be designed to achieve the same goal. Some are simple to comprehend, while others are not. Exprience has also shown that the number of bugs that trace the flow of execution of statements. This would help not only in debugging but also in the review and maintenance of the program later. One method of achieving the objective of an accurte, error-resistant and maintainable code is to use one or any combination of the following three control structures:-
1. Sequence Structure(Straight line)
2. Selection Structure(Branching)
3. Loop Structure (iteration or repetition)

Like C,C++ also supports all the three basic control structures, and implements them using various control statements. This shows that c++ combines the power of structured programming with the object-oriented paradigm.
While Loop
The while statement, like other such statements, is a looping statement that controls the execution of a series of other statements. Looping statements cause parts of a program to execute repeatedly, as long as a certain condition is being met.
while (test expression) { block of one or more C statements; }
Exp: -
// To print the series 1,2,3,4...............n terms using while loops
#include< iostream.h >
#include< conio.h >
void main( )
{
int r=1,c;
clrscr();
cout<<" enter the value\n";
cin>>c;
while(r<=c)
{
cout<< r<<"\n";
r=r+1;
}
getch();
}
The parentheses around test expression are required. As long as the test expression is True (nonzero), the block of one or more C statements executes, repeatedly, until the test expression becomes False (evaluates to zero). Braces are required before and after the body of the while loop, unless you want to execute only one statement. Each statement in the body of the while loop requires a semicolon at the end.
The test expression usually contains relational, and possibly logical, operators. These operators provide the True-False condition checked in the test expression. If the test expression is False when the program reaches the while loop for the first time, the body of the while loop does not execute at all. Regardless of whether the body of the while loop executes no times, one time, or many times, the statements following the while loop's closing brace execute if and when the test expression becomes False
Because the test expression determines when the loop finishes, the body of the while loop must change the variables used in the test expression. Otherwise, the test expression never changes and the while loop repeats forever. This is known as an infinite loop, and you should avoid it.
For Loop
The for loop gathers all three actions (initializing, testing, and updating) into one place. By using a for loop, you can replace the preceding program .Unlike the while and do-while loops, the for loop is a determinate loop.The while and do-while loops continue only until a condition is met. The for loop does this and more: It continues looping until a count (or countdown) is reached. After the final for loop count is reached, execution continues with the next statement, in sequence.
for ( [expression1]; [expression2]; [expression3] )
statement
#include< iostream.h >
#include< conio.h >
// To print table for using for loop
void main( )
{
int r,c,x;
cout<<" enter the value \n";
cin>>c;
clrscr();
x=c;
for(r=1;r<=10;r++)
{
x=c*r;
cout<< x <<"\n";
}
getch();
}
expression1 : Initialization
Evaluated only once, before the first evaluation of the controlling expression, to perform any necessary initialization.
expression2 : Controlling expression
Tested before each iteration. Loop execution ends when this expression evaluates to false.
expression3 : Adjustment
An adjustment, such as the incrementation of a counter, performed after each loop iteration, and before expression2 is tested again.
do...while Statements
The while loop and the for loop are both entry-condition loops. The test condition is checked before each iteration of the loop, so it is possible for the statements in the loop to never execute. C also has an exit-condition loop, in which the condition is checked after each iteration of the loop, guaranteeing that statements are executed at least once. This variety is called a do while loop.
#include< iostream.h >
#include< conio.h >
void main( )
{
int r=1,c,x;
cout<<"enter the value \n";
cin>>c ;
clrscr();
do
{
x=r*r;
cout<< x <<"\n";
r++;
}
while(r<=c);
getch();
}
The loop body statement is executed once before the controlling expression is evaluated for the first time. Unlike the while and for statements, do ... while ensures that at least one iteration of the loop body is performed. If the controlling expression yields true, then another iteration follows. If false, the loop is finished.
If Statements
The general form of the if statement is
if (expression) statement;
else statement;
If expression evaluates to true (anything other than 0), the statement or block that forms the target of if is executed; otherwise, the statement or block that is the target of else will be executed, if it exists.Remember, only the code associated with if or the code associated with else executes, never both.
Exp: -
// To Find the maximum value between two variable using if statement
#include< iostream.h>
#include
void main()
{
int r,c;
cout<< "enter first number \n";
cin>>r;
cout<< "enter first number \n";
cin>>c;
if(r>c)
cout<< "r is max ="<< r;
else
cout<< "c is max ="<< c;
getch();
}
The if conditions are evaluated one after another. As soon as one of these expression yields TRue, the corresponding statement is executed. Because the rest of the else if chain is cascaded under the corresponding else clause, it is alternative to the statement executed, and hence skipped over. If none of the if conditions is true, then the last if statement's else clause is executed, if present.
Break Statement
The break statement goes in the body of the for loop. Programmers rarely put break on a line by itself, and it almost always comes after an if test. If the break were on a line by itself, the loop would always quit early, defeating the purpose of the for loop.
Expression : - break;
Thus the break statement can be used to end the execution of a loop statement at any position in the loop body. For example, the while loop in may be ended either at the user's request (by entering a non-numeric string), or by a numeric value outside the range that the programmer wants to accept.
The following program shows what can happen when C encounters an unconditional break statement. A break causes an exit from only the innermost loop.
// To Find the Factorial Series upto .................n terms & use of break statements
#include< iostream.h >
#include< conio.h >
void main()
{
int r,c=1,k=1,s;
cout << " enter the number";
cin >> r;
clrscr();
for(s=1;s {
if(c>=2)
k=s-c;
for(c=1;c {
k=k+k*c;
}
cout << k <<"\n";
if(c>7)
{
cout<< "Factorial number is out of Integer range 32767 to -32767";
break;
}
}
getch();
}
The following shows you the result of running this program. Notice that the break immediately terminates the for loop. It asks users if they want to see another number. If so, the for loop continues its next iteration. If not, the break statement terminates the for loop.
Continue Statement
This statement can be used in the three loop forms. When encountered, it causes the rest of an iteration to be skipped and the next iteration to be started. If the continue statement is inside nested structures, it affects only the innermost structure containing it.The continue statement can be used only within the body of a loop, and causes the program flow to skip over the rest of the current iteration of the loop:
continue;
The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place.skipping any code in between. For the for loop, continue causes the increment and then the conditional test portions of the loop to execute. For the while and do-while loops, program control passes to the conditional tests.For example, the following program print the Fibonacci Sequence of a given n terms.
\\ To evaluate the Fibonacci Sequence of a given n terms using continue statement
#include
#include
void main()
{
int r=0,c=1,s=1,x,t;
cout<<" enter the number";
cin>>x;
clrscr();
cout<< r << "\n";
cout<< c << "\n";
for(t=1;t {
s=c+r;
r=c;
c=s;
if(t==((x-2)/2))
{
cout<<"This is Middle point of Fibonacci Sequence\n";
continue;
}
cout<< s <<"\n";
}
getch();
}

An advantage of using continue in this case is that you can eliminate one level of indentation in the main group of statements. Being concise can enhance readability when the statements are long or are deeply nested already.
Another use for continue is as a placeholder. For example, the following loop reads and discards input up to, and including, the end of a line.
Such a technique is handy when a program has already read some input from a line and needs to skip to the beginning of the next line. The problem is that the lone semicolon is hard to spot. The code is much more readable if you use
goto statements
The goto statement causes an unconditional jump to another statement in the same function. The destination of the jump is specified by the name of a label:
goto label_name;
A label is a name followed by a colon:
label_name: statement
A statement label is named just as variables are . A statement label cannot have the same name as a C command, a C function, or another variable in the program. If you use a goto statement, there must be a statement label elsewhere in the program that the goto branches to. Execution then continues at the statement with the statement label.
The statement label precedes a line of code. Follow all statement labels with a colon (:) .A statement label is optional, unless you have a goto that branches to one.
The goto statement has two parts—the goto and a label name. The label is named following the same convention used in naming a variable, as in this example:
//To calculate the total salary using goto statement
#include< iostream.h >
#include< conio.h >
void main( )
{
int sa,da=0,ta=1,hra=0,pf=0,tsa=0;
clrscr();
cout<< "enter the salary";
cin >> sa;
if(sa>=100)
goto a;
else if(sa<100 && sa>=50)
goto b;
if(sa<50 && sa>=10)
goto c;
else
goto d;
a:
da=(sa*30)/100;
ta=(sa*25)/100;
hra=(sa*35)/100;
pf=(sa*40)/100;
tsa=sa+da+ta+hra-pf;
goto next;
b:
da=(sa*25)/100;
ta=(sa*20)/100;
hra=(sa*30)/100;
pf=(sa*35)/100;
tsa=sa+da+ta+hra-pf;
goto next;
c:
cout << "enter the salary";
cin >> sa;
da=(sa*20)/100;
ta=(sa*15)/100;
hra=(sa*25)/100;
pf=(sa*30)/100;
tsa=sa+da+ta+hra-pf;
goto next;
d:
da=(sa*15)/100;
ta=(sa*10)/100;
hra=(sa*20)/100;
pf=(sa*25)/100;
tsa=sa+ta+hra-pf;
goto next;
next:
cout<< "Basic Salary ="<< sa << "\n";
cout<< "Dally allowance =" << da<< "\n";
cout<< "Taravelling allowance ="<< ta<< "\n";
cout<< "House Rent Allowance = "<< hra<< "\n";
cout<< "Providend Fund "<< "\n";
cout<< "Total Salary = \n"< getch();
}
The advantages of using them are that their names tell you what they are supposed to do and that, because they don't use labels, there is no danger of putting a label in the wrong place.
The goto statement permits only local jumps; that is, jumps within a function. C also provides a feature to program non-local jumps to any point in the program, using the standard macro setjmp( ) and the standard function longjmp( ). The macro setjmp( ) marks a location in the program by storing the necessary process information, so that execution can be resumed at that point at another time by a call to the function longjmp( ).
return Statement
The return statement ends execution of the current function, and jumps back to where the function was called:
return [expression];
expression is evaluated and the result is given to the caller as the value of the function call. This return value is converted to the function's return type, if necessary.
A function can contain any number of return statements:
// Return the smaller of two integer arguments.
#include< stdio.h >
#include< conio.h >
void main()
{
int x=0;
x=fun();
clrscr();
cout<<"max ="< getch();
}
fun()
{
int r,c;
cout<<"enter two numbers";
scanf("%d %d",&r,&c);
return(r>c?r:c);
}
The parentheses do not affect the behavior of the return statement . However, complex return expressions are often enclosed in parentheses for the sake of readability.
A return statement with no expression can only be used in a function of type void. In fact, such functions do not need to have a return statement at all. If no return statement is encountered in a function, the program flow returns to the caller when the end of the function block is reached.


Free Web Hosting