C++ Cha3
C++ Cha3
Control Statements
A running program spends all of its time executing statements
The order in which statements are executed is called flow
control
Flow control in a program is typically sequential, from one
statement to the next
Flow control is an important consideration because it
determines what is executed during a run and what is not
Conditional Statements
The if Statement
The if statement provides a way of expressing this
the general form of which is(Syntax):
if (expression)
statement;
First expression is evaluated
If the outcome is nonzero (true) then statement is executed
Otherwise, nothing happens
Example:-
if (x == 100)
cout << "x is 100";
The if Statement else
We can additionally specify what we want to happen if the condition is not fulfilled
by using the keyword else
Its form used in conjunction with if is(Syntax):
if (condition) statement1 else statement2
Example 1:- Example 2:-
if (x == 100)
cout << "x is 100"; if (x > 0)
else cout << "x is positive";
cout << "x is not 100"; else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
Iteration structures (loops)
Syntax
do statement while (condition);
Its functionality is exactly the same as the while loop, except that
condition in the do-while loop is evaluated after the execution of
statement instead of before
#include <iostream.h>
int main ()
{
int i;
i = 0;
do
{
cout << i;
i ++;
}
while ( i < 10 ) Output:
return 0; 0123456789
}
The for loop
The for statement (also called for loop) is similar to the while statement,
but has two additional components
an expression which is evaluated only once before everything else
an expression which is evaluated once at the end of each iteration
Its format is:
for (initialization; condition; increase) statement;
It works in the following way:
1. Initialization is executed. Generally it is an initial value setting for a counter
variable. This is executed only once.
2. Condition is checked. If it is true the loop continues, otherwise the loop ends
and statement is skipped (not executed).
3. Statement is executed. As usual, it can be either a single statement or a block
enclosed in braces { }.
4. finally, whatever is specified in the increase field is executed and the loop gets
back to step 2.
Cont..
Example:-