Unit2 1 (Statements)
Unit2 1 (Statements)
CHAPTER 2
Program Control Statements
Kukutla Alekhya
Objectives
Conditional Execution: Control statements like if, else if, and else allow you to
selectively execute blocks of code based on certain conditions.
Looping: Control statements like for, while, and do-while allow you to execute a
block of code repeatedly.
Control Flow Alteration: Control statements like break, continue, and goto alter the
normal flow of execution in a program.
if/else Selection Structure
2
if (condition) {
/ / block of code to be executed if the condition is true
}
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
Use the else statement to specify a block of code to be executed if the condition is false
Syntax
if (condition) {
/ / block of code to be executed if the condition is true
} else {
/ / block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18)
{
cout << "Good day.";
}
else
{
cout << "Good evening.";
}
// Outputs "Good evening."
©ISBATUNIVERSITY – 2023. 3/25/2020
if/else Selection Structure
6
false true
grade >= 60
switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement in C++.
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched;
break;
}
#include <iostream>
int main() {
char operation;
double num1, num2, result;
switch (operation) {
case '+':
result = num1 + num2;
cout << "Sum: " << result << endl;
break;
case '-':
result = num1 - num2;
cout << "Difference: " << result << endl;
break;
case '*':
result = num1 * num2;
cout << "Product: " << result << endl;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
cout << "Quotient: " << result << endl;
} else {
cout << "Error: Division by zero is not allowed." << endl;
}
break;
default:
cout << "Invalid operation." << endl;
break;
}
return 0;
}
To Do
Write a C++ program that prompts the user to enter the marks of a student in five subjects
(out of 100) and calculates the total marks and percentage. The program should then use an
else-if ladder to determine the grade of the student based on the following criteria:
Percentage >= 90: Grade A+
Percentage >= 80: Grade A
Percentage >= 70: Grade B
Percentage >= 60: Grade C
Percentage >= 50: Grade D
Percentage < 50: Grade F
Program Objectives
18