Sei sulla pagina 1di 45

Control Structure

Depending upon requirements of a problem, it is


often required to alter the normal sequence of
execution to in the program. This means that we
may desire to selectively or repetitively execute a
program segment.
Control Structure
Before studying above structure we will study
simple and block statement.
Statement is an expression like: c=0 or x- - or
cout<<x. Becomes a statement when it is
followed by a semicolon as in
c=0;
x- -;
cout<<x;
In C++ semicolon is a statement terminator. The
above statements are also known as simple
statements.
Control Structure
Block- are also known as compound statement.
Braces { and } are used to group declaration and
statements together into a compound statement,
or block, so that they are syntactically equivalent
to a single statement. There is no semicolon after
the right brace that ends a block.
e.g. { x1=y + z;
x2=y * z;
x3=y – z;
x4= y/z;
}
Control Structure
Conditional statement – are mainly used for
making decision. Depending on the value of an
expression decision can be made.
if statement – is the simplest of the decision
statement. The syntax of the if statement is as
follow:
if (expression)
body of if;
Expression is evaluated first if this is true then
body of if is executed. If the expression is false
then the body of if is skipped and execution
continues with the next statement.
Control Structure
Body of if is simple statement or block depending on the
programmer requirement. i.e. if body of if is simple statement
then that look like:
if (expression)
Statement ;
Or
if (expression)
{ statement ; }
If the body of if is compound or block then that look like:
if (expression)
{ statement1;
Statement2;
.
.
Statement n; }
Control Structure
If expression is true then all the statements
within the block are executed. In case expression
is false all the statements within the block are
skipped. If structure execute like follow:
Control Structure
E.g. write a program which reads two numbers
and then print greater one.
If (a>b) cout<<”greater is: “<<a;
If (b>a) cout<<”greater is: “<<b;
For example, the following code fragment prints
x is 100 only if the value stored in the x variable is
indeed 100:
if (x == 100)
cout << "x is 100";
• If we want more than a single statement to be
executed in case that the condition is true we
can specify a block using braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
Control Structure
if else statement – the expression is evaluated
first if that is true then the if body is executed
otherwise else body is executed. the syntax of if
else statement is as follow:
if (expression)
body of if
else
body of else
Control Structure
Body of if and body of else may be simple or block. If body of if
and else is compound then the structure looks like:
if (expression)
{ statement1;
Statement2;
.
.
Statement n; }
else
{ statement 1;
Statement2;
.
.
Statement n;
}
Control Structure
If else structure executed like follow:
E.g. write a program which reads a number and then
prints the message for that number (that is even or
odd).
If (n%2= =0)
cout<< “the number is even”;
else
cout<<”the number is odd”;
The following example also shows its use telling if
the value currently stored in x is positive, negative or
none of them (i.e. zero):
if (x > 0) cout << "x is positive";
else
if (x < 0) cout << "x is negative";
else
cout << "x is 0";
Remember that in case that we want more than a
single statement to be executed, we must group
them in a block by enclosing them in braces { }.
Nested if – else statement- in if statement of if-
else statement in place of body we can use again
if or if-else this concept is known as nested
structure.
e.g. write a program which reads three numbers
and then find the largest one
#include<iostream.h>
#include<conio.h>
void main ( )
{ float a,b,c;
cout<<”Enter three number: “;
cin>>a>>b>>c;
if (a>b)
{
if (a>c)
Cout<< “largest value : “<<a<<endl;
else
Cout<<”largest value: “<<c<<endl;
}
else
{
if (b>c)
Cout<<”largest value : “<<b<<endl;
else
Cout<<”largest value :”<<c<<endl:
}
Switch Statement
switch(expression)
{
case value 1:
Statement 1;
Statement 2;
.
Statement n;
break;
case value 2:
statement 1;
statement 2;
.
Statement n;
break;

case value n:
statement 1;
statement 2;
.
Statement n;
Break;
default:
statement 1;
statement 2;
.
Statement n;
}
Control Structure
This expression must be integer or character type.
That means the value 1, value 2,…, value n all are
also integer or character type. In switch statement;
switch, case, break and default are reserve word.
Switch first calculate the expression then match that
expression with value 1 if both are equal then first
case body is executed and switch is terminated
because of break statement, which is written at last
of everybody. If we skip the break statement then
after executing first body switch is not terminated
this match with next value and so on. If expression is
not equal to value 1, then expression checked with
value 2 if equal execute second case body and switch
is terminated.
If expression is not equal to value 2 then
expression checked with value 3 if there is no
match process continue to last value.
If expression is not match with any value from
value 1 to value n then default body is executed.
The diagram for execution of switch statement is:
Control Structure
// Output result
cout <<”the result is”<<result << endl;
return 0;
}
Loop Statement or Repetitive
Statement
Loop cause a section of our program to be
repeated a certain number of times. The
repetition continues up to when a condition is
true. There are three kinds of loop in C++. They
are for loop, while loop and do while loop.
for loop
for loop is easiest loop, this consists three
expressions. The syntax of for loop is as follow:
. for (i=0; i<=0; i++)
Statement;
First the initialization expression executes. Then test expression is checked
if it is false loop terminate, if this is true body of loop is executed. After this
assignment assign a new value (that increment or decrement the variable)
to variable. Then again test expression is checked if false loop terminate
otherwise body of loop again execute.
The diagram is as follows:
Here is an example of countdown using a for
loop:
// countdown using a for loop
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
The initialization and increase fields are
optional. They can remain empty, but in all cases
the semicolon signs between them must be
written. For example we could write: for (;n<10;)
if we wanted to specify no initialization and no
increase; or for (;n<10;n++) if we wanted to
include an increase field but no initialization
(maybe because the variable was already
initialized before).
Nested For loop
This program will print a 5 x 5 square of stars. It requires no input.
The program uses a constant integer in the event you wish to
change the sizes.
// for loops for square
#include <iostream>
using namespace std;

int main(){
const int SIZE = 5;
for (int r = 1; r <= SIZE; r++) {
for (int c = 1; c <= SIZE; c++) {
cout << "*";
}
cout << endl;
}

return 0;
}
while loop
The while loop allows programs to repeat a
statement or series of statements, over and over, as
long as a certain test condition is true. The format
is:
while(test condition)
{
block of code;
}
The test condition must be enclosed in
parentheses. The block of code is called the body
of the loop and is enclosed in braces and indented
for readability. (The braces are not required if the
body is composed of only ONE statement.) Semi-
colons follow the statements within the block only.
When a program encounters a while loop, the test
condition is evaluated first. If the condition is
TRUE, the program executes the body of the
loop. The program then returns to the test
condition and reevaluates. If the condition is still
TRUE, the body executes again. This cycle of
testing and execution continues until the test
condition evaluates to 0 or FALSE. If you want the
loop to eventually terminate, something within
the body of the loop must affect the test
condition. Otherwise, a disastrous INFINITE LOOP
is the result! The while loop is an entry-condition
loop. If the test condition is FALSE to begin with,
the program never executes the body of the loop.
#include <iostream.h>
int main()
{
int x = 0;
while(x < 10)
x = x + 1;
cout << “x is “ << x << “\n”;
return 0;
}
When the program starts the user is prompted
to insert a starting number for the countdown.
Then the while loop begins, if the value entered
by the user fulfills the condition n>0 (that n is
greater than zero) the block that follows the
condition will be executed and repeated while
the condition (n>0) remains being true.
do-while loop
In a while loop, the condition is evaluated at the beginning
of the loop. If the condition is false when the loop is
entered, the loop body will not be executed at all. But in
do-while loop first the body of loop is executed then the
condition is evaluated. In do-while loop the body of loop
always executes at least one time if the condition is false
also.
The syntax of do-while loop is:
Breaking Control Statements
C++ provides three different type of breaking
control statements. With the help of breaking
control statement the control structure power is
improved.
Break statement
Break statement causes an exit from a loop just as it
does from a switch statement. Break terminates the
loop in which that is written. We can use break in
any loop. The break statement terminates the
execution of the nearest enclosing loop or
conditional statement in which it appears.
Control passes to the statement that follows the
terminated statement, if any. break is used with
the conditional switch statement and with the
do, for, and while loop statements. In a switch
statement, break causes the program to execute
the next statement after the switch. Without a
break statement, every statement from the
matched case label to the end of the switch,
including the default, is executed.
In loops, break terminates execution of the
nearest enclosing do, for, or while statement.
Control passes to the statement that follows the
terminated statement, if any.
Within nested statements, the break statement
terminates only the do, for, switch, or while
statement that immediately encloses it. You
can use a return or goto statement to transfer
control from within more deeply nested
structures.
e.g. for(i=0;i<=100;i++)
{ statement 1;
Statement 2;
break;
Statement 3;
}
Statement 4;
In the above example statement 3 is not executed
because before that there is a break statement.
Continue Statement
The continue statement is used for inverse operation of
the break statement. The continue statement transfers
control to start of loop. The syntax of continue statement
is similar to break. Syntax of break break;
Syntax of continue continue;
both are reserve words.
E.g. while(condition)
{ statement 1;
Statement 2;
}
In the above example if a>b is true the control is
transferred to start means again condition is checked and
statement is executed. The arrow shows the flow of
control.
go to statement
By go to statement we can transfer the control to some other part.
Means by go to we can change the execution sequence of
program. The general syntax of go to is:
goto label;
go to is reserve word. Label is a name given by the user or
programmer but it must be a valid identifier. E.g. goto start;
goto A23;
but goto 23A; is invalid because 23A is not valid identifier.
Example1. statement 1;
statement 2;
start: statement 3;
statement 4;
goto start;

example2. statement 1;
statement 2;
B: statement 3;
Statement 4;
if ( a > b ) goto B;

A goto statement provides an unconditional jump from the goto to a


labeled statement in the same function.
NOTE: Use of goto statement is highly discouraged because it makes
difficult to trace the control flow of a program, making the program
hard to understand and hard to modify. Any program that uses a
goto can be rewritten so that it doesn't need the goto.

Syntax:
The syntax of a goto statement in C++ is:
goto label;
..
.
label: statement;
Where label is an identifier that identifies a labeled statement. A
labeled statement is any statement that is preceded by an identifier
followed by a colon (:).
Example:
#include <iostream.h>
When the above code is
compiled and executed, it
int main () produces following result:
{
// Local variable
declaration: value of a: 10
int a = 10;
value of a: 11
// do loop execution value of a: 12
LOOP:do
{
value of a: 13
if( a == 15) value of a: 14
{ value of a: 16
// skip the iteration.
a = a + 1; value of a: 17
goto LOOP; value of a: 18
}
cout << "value of a: " << a value of a: 19
<< endl;
a = a + 1;
}while( a < 20 );

return 0;
}
One good use for the goto is to exit from a deeply nested routine. For
example, consider the following code fragment:
for(...) {
for(...) {
while(...) {
if(...) goto stop;
.
.
.
}
}
}
stop:
cout << "Error in program.\n";
Eliminating the goto would force a number of additional tests to be
performed. A simple break statement would not work here, because it
would only cause the program to exit from the innermost loop.

Potrebbero piacerti anche