Program Execution Control Statements
if - else Statement
The if statement evaluates the expression enclosed in parentheses. If the expression evaluates to a nonzero value (true), the statement dependent on the evaluation is executed; otherwise, it is skipped.
Syntax :
if( condition1 == true )
{
if( condition2 == true )
{
//do something
}
else
{
//do something
}
else
{
//do something
}
Example :
#include <iostream.h>
int main()
{
int iCondition=0;
cout<<"Ener a condition
";
cin>>iCondition;
if( iCondition==1)
cout<<"You entered 1
";
else if( iCondition==2)
cout<<"You entered 2
";
else
cout<<"Another value
";
}
Switch Case Statement :
This control statement allows us to make a decision from a number of choices.
Syntax :
switch (expression)
{
case constant 1:
[Block]
case constant 2:
[Block]
case constant n:
[Block]
default :
[Block]
}
Example :
#include <iostream.h>
int main(int argc, char* argv[])
{
char cLetter;
cout<<"Enter a letter
";
cin>>cLetter;
switch (cLetter)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
cout<<"The Letter is a Vowel
";
break;
default :
cout<<"The letter is not a Vowel
";
break;
}
return 0;
}
Loops
while Statement
The while statement lets you repeat a statement until a specified expression becomes false.
Syntax :
while ( expression ) statement
Example :
#include <iostream.h>
int main()
{
int iCount=0;
while (iCount< 10 )
{
cout<<iCount++;
}
}
do while Statement
The expression in a do-while statement is evaluated after the body of the loop is executed. Therefore, the body of the loop is always executed at least once.
Syntax :
do statement while ( expression ) ;
Example :
int main()
{
int iCount=0;
do
{
cout<<iCount++;
}while(iCount<10 );
}
for Statement :
The for statement lets you repeat a statement or compound statement, a specified number of times.
Syntax :
for ( init-expression; cond-expression ; loop-expression ) statement
Example :
int main()
{
for(int iCount=0;iCount<10;iCount++)
{
cout<<iCount;
}
}