You are on page 1of 13

Programming Fundamentals

Lab
Lecture 3

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Switch Statement

 It is also a conditional statement.


 The switch statement uses the value of an integer expression to determine which group of
statements to branch through.
 Each value is called a case, and the variable is checked for each case.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Syntax

switch ( variable name )


{
case ‘a’ :
statements;
case ‘b’ :
statements;
case ‘c’ :
statements;

}

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Flowchart
Switch statement starts

Expression

Yes
Case1 Code block 1
No

Yes
Case2
Code block 2

No
Default code

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Switch terminates
Example

switch ( grade)
{
case ‘A’ :
cout << “ Excellent ” ;
case ‘B’ :
cout << “ Very Good ” ;
case ‘C’ :
cout << “Good ” ;
case ‘D’ :
cout << “ Poor ” ;
case ‘F’ :
cout << “ Fail ” ;
}

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Break statement

 Break statement is used inside each case block, Its used to terminate the switch statements.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Example
switch ( grade )
{
case ‘A’ :
cout << “ Excellent ” ;
break ;
case ‘B’ :
cout << “ Very Good ” ;
break ;
case ‘C’ :
cout << “Good ” ;
break ;
case ‘D’ :
cout << “ Poor ” ;
break ;
case ‘F’ :
cout << “ Fail ” ;
break ;
Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
}
Default statement

default :
cout << “ Please Enter Grade from ‘A’ to ‘D’ or ‘F’ “ ;

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Practice

 Create a Calculator using the switch Statement

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Goto statement

 Unconditional branch of execution


 Used for transferring the control of a program.
 It allows the program’s execution flow to jump to a specified location within the function.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


 There are two ways to call the goto statement
goto label;
//block of statements
label:  ;

label:  ;
//block of statements
goto  label;

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Example
#include<iostream>
using namespace std;
// Program to check greater number using goto statement
int main()
{
int i, j;
i =2;j=5;
if(i > j)
goto iGreater;
else
goto jGreater;
iGreater:
cout<<i<<" is greater";
return;
jGreater:
cout<<j<<" is greater";
return 0;
}Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
Practice

 Find min and max number from user entered numbers using switch statement
 Print day of the week selected by the user through switch statement

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar

You might also like