Chapter 3
Chapter 3
Programming
with C++
Reema Thareja
SYNTAX OF IF STATEMENT
FALSE
if (test expression)
Test
{ Expression
statement 1;
..............
statement n; TRUE
}
Statement Block 1
statement x;
Statement x
Statement x
TRUE FALSE
if ( test expression 1)
{
statement block 1; Test Expression
1
}
else if ( test expression 2)
{ FALSE
statement block 2; Statement Block 1
Test
} Expression 2
........................... TRUE
else if (test expression N)
{ Statement Block 2 Statement Block X
statement block N;
}
else
{ Statement Y
Statement Block X;
}
Statement Y;
WHILE LOOP
• The while loop is used to repeat one or more statements while a particular condition is true.
• In the while loop, the condition is tested before any of the statements in the statement block is
executed.
• If the condition is true, only then the statements will be executed otherwise the control will
jump to the immediate statement outside the while loop block.
• We must constantly update the condition of the while loop. Statement x
while (condition)
{ Update the condition
expression
statement_block; TRUE Condition
}
statement x; Statement Block FALSE
Statement y
Statement x
Statement x;
do Statement Block
{
statement_block;
} while (condition); Update the condition expression
statement y;
TRUE
Condition
FALSE
Statement y
• When a for loop is used, the loop variable is initialized only once.
• With every iteration of the loop, the value of the loop variable is updated and the condition is
checked. If the condition is true, the statement block of the loop is executed else, the
statements comprising the statement block of the for loop are skipped and the control jumps
to the immediate statement following the for loop body.
• Updating the loop variable may include incrementing the loop variable, decrementing the
loop variable or setting it to some other value like, i +=2, where i is the loop variable.
CONTINUE STATEMENT
• The continue statement can only appear in the body of a loop.
• When the compiler encounters a continue statement then the rest of the statements in the loop are skipped and the
control is unconditionally transferred to the loop-continuation portion of the nearest enclosing loop. Its syntax is quite
simple, just type keyword continue followed with a semi-colon.
continue;
• If placed within a for loop, the continue statement causes a branch to the code that updates the loop variable. For
example,
int i;
for(i=0; i<= 10; i++)
{ if (i==5)
continue;
cout<<i;
}