Program Control: 3.1 Solve Problems Using Selection Control Structures
Program Control: 3.1 Solve Problems Using Selection Control Structures
0
PROGRAM CONTROL
true
condition
statement
false
Selection Control Structures
• Example 1:
if (x == 100)
cout << "x is 100";
• Example 2:
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;
}
Selection Control Structures
(b) If-else statement
• The form of an if-else statement is:
if (condition)
statement 1;
else
statement 2;
false true
condition
Statement2 Statement1
Selection Control Structures
• Example 1:
#include<iostream.h>
int main( )
{
int number;
cout<<“Please enter one number:”;
cin>>number;
if(number%2==0)
cout<<“This number is even number!”<<endl;
else
cout<< “This number is odd number!”<<endl;
return 0;
}
Selection Control Structures
(c) Nested if statement
• Nested if statements are used to choose between
several alternatives.
• If an IF statement contains an IF statement as
one of its possible branches, the IF statements are
said to be nested.
Selection Control Structures
• The simple form of a nested if statement:
if ( condition1 )
statement1 ;
else if ( condition2 )
statement2 ;
. . .
else if ( condition-n )
statement-n ;
else
statement-e ;
Selection Control Structures
• Another form of a nested if statement:
if (condition1)
if (condition2)
if (condition3)
statement1;
else
statement2;
else
statement3;
else
statement4;
Selection Control Structures
true
Condition 1 Statement 1
false
true
Condition 2 Statement 2
false
.
.
.
true
Condition -n Statement n
false
Statement -e
Selection Control Structures
• Example 1:
#include<iostream.h>
void main()
{
int mark;
switch (expression)
{
case val1:
statement
break;
case val2:
statement
break;
….
case valn:
statement
break;
default:
statement
break;
}
Selection Control Structures
case a true
case a action(s) break
false
case b true
case b action(s) break
false
.
.
.
case z true
case z action(s) break
false
default action(s)
Selection Control Structures
}
Selection Control Structures
Exercise:
Based on the algorithm given, write the complete C++ program.