5th Lecture
5th Lecture
1
If statement
• If the value of the expression inside the parentheses is true, the very next statement is executed. Otherwise, it is
skipped.
int main()
{
int x;
cin>>x;
if(x % 2 ==0)
cout<<“x is even”; else is optional, it can be added in certain
else cases.
cout<<“x is odd”;
}
2
Expanding if statement
• The if statement can conditionally execute a block of statements
enclosed in braces.
3
Expanding if statement
4
Don’t forget the braces
5
If statement
Exercise 1:
Write an if statement that performs the following logic: if the variable sales is
greater than 50,000, then assign 0.25 to the commission Rate variable, and assign
250 to the bonus variable.
Exercise 2:
Write an if/else statement that assigns 1 to x if y is equal to 100. Otherwise it
should assign 0 to x.
6
Nested If
The if/else if statement tests a series of conditions.
7
Nested If
Write a program to display the grade of a student according to his/her score.
8
Checking numeric ranges
Logical operators are effective for determining whether a number is in or
out of a range.
For example, the following if statement checks the value in x to determine whether
it is in the range of 20 through 40:
9
Comparing characters and strings
Example, a program to
differentiate an input
whether it’s upper
case, lower case, digit,
or something else
10
Comparing characters and strings
Write a program to convert the uppercase letter to lowercase and vise versa.
11
Conditional Operator
The conditional operator is powerful and unique. It provides a shorthand method of
expressing a simple if/else statement. The operator consists of the question-mark (?)
and the colon (:). Its format is:
12
Switch statement
The switch statement lets the value of a variable or expression determine where the
program will branch. The format of the switch statement:
13
Switch statement
14
Switch statement
Class work:
1- Write a program accepts a digit (0-9) and print the corresponding name of the
given value.
2- Write a program to read two numbers and an arithmetic operation. The program
implements the operation between the numbers.
HW:
Write a program to read a sequence of a month and print the corresponding name of
that month.
15
The End
16