Lecture 04
Lecture 04
Programming
1. If statement
2. If/else statement
If
3. If/elseif/else statement Condition
4. Switch statement
5. Nested if/else statement
Switch Statement
• The switch statement evaluates an integral expression and chooses one of several
execution paths based on the expression's value.
• In other words, a Switch statement provides a convenient way of selecting among
a (possibly large) number of fixed alternatives.
Syntax Switch Statement
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
. . .
default:
// default statements
}
How switch statements work:
• The default code specifies some code to run if there is no case match.
• The default keyword must be used as the last statement in the switch, and it does
not need a break.
Write a program in C++ to input a number between 1 to
7 and print the corresponding day of a week (day name)
using if else statment.
• #include <iostream> • else if(n==4)
• using namespace std; • { cout<<"Wednesday";}
• int main() • else if(n==5)
• { int n; • { cout<<"Thursday"; }
• cout<<"Enter a number "; • else if(n==6)
• cin>>n; • { cout<<"Friday”;}
• if(n==1) • else if(n==7)
• { cout<<"Sunday"; } • { cout<<"Saturday"; }
• else if(n==2) • else
• { cout<<"Monday"; } • { cout<<"Invalid number"; }
• else if(n==3) • return 0;}
• { cout<<"Tuesday";}
Write a program in C++ to input a number between 1 to
7 and print the corresponding day of a week (day name)
using Switch statment.
• #include<iostream> • case 3:
• using namespace std; • cout<<"Wednesday";
• int main() • break;
• case 4:
• { int day;
• cout<<"Thursday";
• cout<<"\nEnter the Day's number :";
• break;
• cin>>day; • case 5:
• switch (day) • cout<<"Friday";
• { case 1: • break;
• cout<<"Monday"; • case 6:
• break; • cout<<"Saturday";
• break;
• case 2:
• case 7:
• cout<<"Tuesday";
• cout<<"Sunday";
• break; • break; } return 0; }
Nested if/else Statement
Sometimes, we need to use an if statement inside another if statement. This is
known as nested if statement.
1968 1971
2004 2006
2012 2010
1200 1700
1600 1800
2000 1900
Leap Year Example
#include <iostream> // all other years are not leap years
using namespace std; else {
int main() { cout << year << " is not a leap year.";
int year; }
cout << "Enter a year: ";
cin >> year; return 0;
// leap year if perfectly divisible by 400 }
if (year % 400 == 0) {
cout << year << " is a leap year.“ ; }
// not a century year and divided by 4
else if (year % 100! == 0 && year % 4 == 0) {
cout << year << " is not a leap year.";
}
Reference:
Tony Gaddis, “Starting out with C++”, 6th Edition, Pearson -> Chapter 01