Experiment#9: Use of Nested If Else and Switch Statement Objective
Experiment#9: Use of Nested If Else and Switch Statement Objective
Experiment#9: Use of Nested If Else and Switch Statement Objective
EE DEPARTMENT
Experiment#9
Use of nested if else and switch statement
Objective
An introduction with
1. The use of switch statement for decision making among multiple paths.
Software Tools
1. Dev C++
Theory
C++ Program
A computer program is a sequence of instructions that tell the computer what to do.
EE DEPARTMENT
clrscr();
cout << "enter 3 number";
cin >> a >> b >> c;
if(a > b)
{
if( a > c)
{
cout << "a is greatest";
}
else
{
cout << "c is greatest";
}
}
else
{
if( b> c)
{
cout << "b is greatest";
}
else
{
cout <<"c is greatest";
}
}
getch();
}
Switch statement
If there are a number of decision making conditions instead of making an if..else construct, the
programmer can use switch statement.
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
Computer Fundamentals 1st Semester-EE HITEC UNI Taxila
HITEC UNIVERSITY, TAXILA
FACULTY OF ELECTRICAL ENGINEERING
EE DEPARTMENT
.
.
default:
default group of statements
}
In the above example, the expression is first evaluated and the value id checked with the
constant1 in the case statement. If this is evaluated with the same value, then the group of
statements is executed. When a break statement is encountered, the control is switched to the end
of the switch statement. If the value of the expression is not equal to constant1, it is checked with
constant2. If it evaluates the same value, then the group of statements (in the case of constant2) is
executed. When a break statement is encountered, the control is then switched to the end of the
switch statement. This proceeds until the value of expressions equal one of the constant values
given. If the value of the expression is not equal to any of the constant values given, then, by
default, the statements present are executed.
Example
void main()
{
int x;
cout<<"Enter Input Value: ";
cin>>x;
switch(x)
{
case 10:
cout<< "Value is 10";
break;
case 20:
cout<<"Value is 20";
break;
default:
cout<<"Invalid Input";
}
}
Lab Tasks
EE DEPARTMENT
1. Write a program that will arrange user given 3 input numbers in ascending and descending
order using nested if else statement.
2. Write a program that will arrange user given 4 input numbers in ascending and descending
order using nested if else statement.
3. Perform the task 1 and 2 using switch statement.