4th Chap (Control Structure)
4th Chap (Control Structure)
COMPUTER SCIENCE_2
nd
Year (Notes)
Decision Statements
Decision statements, also known as conditional statements, are like making choices based on certain
conditions. In programming, these statements help the computer decide what action to take based on
different scenarios. Let me explain this in simple terms with some real-life examples.
What are Decision Statements?
Imagine you are standing at a crossroads, and you have to decide which path to take. If the weather is sunny,
you might decide to go for a walk. If it’s raining, you might choose to stay indoors. This is exactly how
decision statements work in programming.
In technical terms, a decision statement allows the computer to execute certain blocks of code only when a
specified condition is true. The most common decision statements are if, else if, and else.
Types of Decision Statements
Understanding if Statements in C++ with Examples and Flowcharts
1. What is an if Statement?
An if statement is like making a decision based on a condition. If the condition is true, a certain action is
performed; if it’s false, the action is skipped.
For example, imagine you're checking the temperature before deciding whether to wear a jacket.
Condition: If the temperature is below 20°C, wear a jacket.
Single if Statement
Flowchart for Single if Statement
Here’s a simple flowchart to explain how a single if statement works:
Start
Is
Yes
Temperatu
re <20°C
Wear a jacket
END
Example in C++
int main() {
int temperature = 18;
if (temperature < 20) {
cout << "It's cold, wear a jacket!" << endl;
}
return 0;
}
Explanation: In this program, if the temperature is less than 20°C, the message "It's cold, wear a jacket!" is
displayed.
Multiple if Statements
When you have more than one condition to check, you can use multiple if statements. Each one is checked
independently.
Flowchart for Multiple if Statements Start
Imagine you’re deciding what to wear based on the weather:
1. If it’s raining, take an umbrella.
2. If it’s sunny, wear sunglasses.
Is No
Yes Next
temperatu
Decision
re < 20°C?
Is it raining?
Is it
Take an
raining?
umbrella No
Next Decision
Example in C++
code
#include <iostream>
using namespace std;
int main() {
if (isRaining) {
cout << "Take an umbrella." << endl;
}
if (isSunny) {
cout << "Wear sunglasses." << endl;
}
return 0;
}
Explanation: Here, two independent conditions are checked. If it’s raining, the program suggests taking an
umbrella. If it’s sunny, it suggests wearing sunglasses.
Programs with Multiple if-else Statements
In some cases, you might want to check several conditions in sequence and take different actions based on
each condition. This is where if-else comes in handy.
Example 1: Checking Exam Grades
Flowchart:
1. If the score is 90 or more, grade is A.
2. If the score is 80 or more, grade is B.
3. If the score is 70 or more, grade is C.
4. Otherwise, grade is F.
Start --> Decision --> Process --> Decision --> Process --> Decision --> Process --> End
+-------------+
| Start |
+-------------+
|
v
+-----------------------------+
| Is score >= 90? |
+-----------------------------+
/ \
Yes / \ No
/ \
v v
+-----------------+ +---------------------------+
| Grade = A | | Is score >= 80? |
+-----------------+ +---------------------------+
/ \
Yes / \ No
int main() {
int score = 85;
char grade;
cout << "Your grade is: " << grade << endl;
return 0;
}
Explanation: This program checks the score and assigns a grade based on the score.
Example 2: Checking Age for Voting Eligibility
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+-----------------------------+
| Is age >= 18? |
+-----------------------------+
/ \
Yes / \ No
/ \
v v
+-----------------+ +-------------------+
| Eligible to vote| | Not eligible |
+-----------------+ | to vote |
+-------------------+
|
v
+-------------+
| End |
+-------------+
Example in C++:
code
#include <iostream>
using namespace std;
int main() {
int age = 17;
return 0;
}
Explanation: The program checks if the person is 18 or older to determine voting eligibility.
Example 3: Even or Odd Number
int main() {
int number = 5;
if (number % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
return 0;
}
Explanation: The program checks if the number is divisible by 2 to determine if it’s even or odd.
int main() {
int number = -5;
if (number > 0) {
cout << "Number is Positive." << endl;
} else {
cout << "Number is Negative." << endl;
}
return 0;
}
int main() {
cout << "Your grade is: " << grade << endl;
return 0;
}
Explanation: This program evaluates the score and assigns a grade based on the range in which the score
falls.
Example 3: Nested if-else Statements
Scenario: Checking if a person can enter a movie based on age and whether they have a ticket.
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+-----------------------------+
| Is age >= 18? | <-- Decision (Diamond)
+-----------------------------+
/ \
Yes No
/ \
v v
+-------------------+ +-------------------+
| Has Ticket? | | Cannot Enter |
+-------------------+ +-------------------+
/ \
Yes No
/ \
v v
+-------------------+ +-------------------+
| Allowed to Enter | | Buy a Ticket |
+-------------------+ +-------------------+
int main() {
int age = 20;
bool hasTicket = true;
return 0;
}
Explanation: This program first checks if the person is 18 or older. If true, it then checks if they have a ticket.
If they do, they are allowed to enter; if not, they need to buy a ticket. If they are younger than 18, they
cannot enter.
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
return 0;
}
Explanation: This program prints the name of the day based on the number. If the number doesn’t match any
case, it prints "Invalid day."
Example 2: Grading System
Scenario: Assign a grade based on the letter received (A, B, C, etc.).
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+-------------------------+
| Switch(grade) | <-- Switch Statement
+-------------------------+
|
v
+-------------------------+
| Case 'A': Excellent | <-- Case
+-------------------------+
|
v
+-------------------------+
| Case 'B': Good | <-- Case
+-------------------------+
|
v
+-------------------------+
| Case 'C': Average | <-- Case
int main() {
char grade = 'B';
switch (grade) {
case 'A':
cout << "Excellent" << endl;
break;
case 'B':
cout << "Good" << endl;
break;
case 'C':
cout << "Average" << endl;
break;
case 'D':
cout << "Below Average" << endl;
break;
case 'F':
cout << "Fail" << endl;
break;
default:
cout << "Invalid grade" << endl;
break;
}
return 0;
}
Explanation: This program assigns a description to each grade. If the grade doesn’t match any case, it prints
"Invalid grade."
Example 3: Menu Selection
int main() {
int option = 2;
switch (option) {
case 1:
return 0;
}
Explanation: This program prints the name of the menu item based on the option chosen. If the option
doesn’t match any case, it prints "Invalid option."
Example 4: Month of the Year
Scenario: Display the name of the month based on a number (1 for January, 2 for February, etc.).
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+-------------------------+
| Switch(month) | <-- Switch Statement
+-------------------------+
|
v
+-------------------------+
| Case 1: January | <-- Case
+-------------------------+
|
v
+-------------------------+
| Case 2: February | <-- Case
+-------------------------+
|
v
+-------------------------+
| Case 3: March | <-- Case
+-------------------------+
|
int main() {
int month = 5;
switch (month) {
case 1:
cout << "January" << endl;
break;
case 2:
cout << "February" << endl;
break;
case 3:
cout << "March" << endl;
break;
case 4:
cout << "April" << endl;
break;
case 5:
cout << "May" << endl;
break;
case 6:
cout << "June" << endl;
break;
case 7:
cout << "July" << endl;
break;
case 8:
cout << "August" << endl;
break;
case 9:
cout << "September" << endl;
break;
return 0;
}
Explanation: This program prints the name of the month based on the number. If the number doesn’t match
any case, it prints "Invalid month."
Summary
switch Statement: Allows you to select one of many code blocks to execute.
case: Specifies code to be executed if the value matches.
default: Specifies code to be executed if no cases match.
int main() {
int age = 20;
bool isCitizen = true;
return 0;
}
Explanation: This program first checks if the person is 18 or older. If they are, it then checks if they are a
citizen. If both conditions are met, they are eligible to vote; otherwise, appropriate messages are displayed.
Example 2: Determine Eligibility for a Scholarship Based on Grades and Income
Scenario: Check if a student is eligible for a scholarship based on their GPA and family income.
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+------------------------------+
| Is GPA >= 3.5? | <-- Outer `if`
+------------------------------+
/ \
Yes No
/ \
v v
+-----------------+ +---------------------------+
| Is income <= 50000? | | Not eligible for scholarship | <-- Inner `if`
+-----------------+ +---------------------------+
/ \
Yes No
/ \
v v
+-----------------+ +---------------------------+
| Eligible for | | Income too high |
| scholarship | +---------------------------+
int main() {
float gpa = 3.6;
float income = 45000;
return 0;
}
Explanation: This program first checks if the GPA is above or equal to 3.5. If true, it then checks if the family
income is 50,000 or less. If both conditions are met, the student is eligible for the scholarship.
Example 3: Determine Clothing Based on Temperature and Weather
Scenario: Decide what to wear based on the temperature and whether it is raining.
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+------------------------------+
| Is temperature < 20°C? | <-- Outer `if`
+------------------------------+
/ \
Yes No
/ \
v v
+-----------------+ +---------------------------+
| Is it raining? | | Wear light clothing | <-- Inner `if`
+-----------------+ +---------------------------+
/ \
Yes No
/ \
v v
+-----------------+ +---------------------------+
| Wear a raincoat | | Wear warm clothing |
+-----------------+ +---------------------------+
|
v
int main() {
int temperature = 18;
bool isRaining = true;
return 0;
}
Explanation: This program checks if the temperature is below 20°C. If true, it then checks if it is raining. If
both conditions are met, it suggests wearing a raincoat; otherwise, it suggests wearing warm clothing.
Example 4: Calculate Shipping Cost Based on Weight and Distance
Scenario: Calculate shipping cost based on the weight of the package and the distance to be shipped.
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+------------------------------+
| Is weight <= 5 kg? | <-- Outer `if`
+------------------------------+
/ \
Yes No
/ \
v v
+-----------------+ +---------------------------+
| Is distance <= 100 km? | | Cost for heavier weight | <-- Inner `if`
+-----------------+ +---------------------------+
/ \
Yes No
/ \
v v
+-----------------+ +---------------------------+
| Cost = $10 | | Cost for long distance |
+-----------------+ +---------------------------+
|
v
+-------------+
| End |
+-------------+
int main() {
float weight = 3.0;
float distance = 120;
if (weight <= 5) {
if (distance <= 100) {
cout << "Cost = $10" << endl;
} else {
cout << "Cost = $15" << endl;
}
} else {
if (distance <= 100) {
cout << "Cost = $20" << endl;
} else {
cout << "Cost = $30" << endl;
}
}
return 0;
}
Explanation: This program first checks if the weight of the package is 5 kg or less. If true, it then checks if the
distance is 100 km or less to determine the cost. If the weight exceeds 5 kg, it calculates the cost based on the
distance accordingly.
Summary
Nested if Statements: Allow for complex decision-making by evaluating multiple conditions in a
hierarchical manner.
Flowchart Symbols:
o Oval: Start and End.
o Diamond: Decision points.
o Rectangle: Process or action.
o Arrows: Indicate the flow of decisions and actions.
Break Statement
The break statement is used to exit from a loop or a switch statement prematurely. When encountered, it
immediately stops the execution of the loop or switch block and continues with the code following it.
Example 1: Exiting a for Loop
Scenario: Find the first number greater than 5 in a list and stop the loop.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 3, 5, 7, 9};
return 0;
}
Explanation: The for loop iterates through the array. When it finds a number greater than 5, it prints the
number and then exits the loop using break.
Example 2: Exiting a while Loop
Scenario: Keep asking a user for a positive number and stop if they enter a negative number.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int number;
while (true) {
cout << "Enter a positive number (negative to quit): ";
cin >> number;
if (number < 0) {
break; // Exit the loop
}
return 0;
}
Explanation: The while loop continues indefinitely. If the user enters a negative number, the break statement
exits the loop.
Example 3: Exiting a switch Statement
Scenario: Use a switch statement to determine the season based on the month.
#include <iostream>
using namespace std;
int main() {
int month = 8; // August
switch (month) {
case 12: case 1: case 2:
cout << "Winter" << endl;
break;
case 3: case 4: case 5:
cout << "Spring" << endl;
break;
case 6: case 7: case 8:
cout << "Summer" << endl;
break;
case 9: case 10: case 11:
cout << "Fall" << endl;
break;
default:
return 0;
}
Explanation: In the switch statement, the break statement ensures that only the block of code corresponding
to the matched case is executed.
Example 4: Nested Loops with break
Scenario: Find the first negative number in a 2D array and exit both loops.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, -5, 6}};
return 0;
}
Explanation: The break statement is used in the inner loop to exit when a negative number is found. The
outer loop also has a break to ensure it stops once a negative number is found.
exit() Function
The exit() function is used to terminate a program immediately. It can be used to return a status code to the
operating system.
Example 1: Terminate Program Early
Scenario: Exit the program if a certain condition is met.
C++ Code:
#include <iostream>
#include <cstdlib> // For exit()
using namespace std;
int main() {
int age = 17;
int main() {
cout << "Performing a task..." << endl;
int main() {
checkCondition(true); // This will terminate the program
return 0;
}
Explanation: The checkCondition() function uses exit(0) to terminate the program if the condition is met.
Any code after the call to exit() will not be executed.
Example 4: Handling Errors with exit()
Scenario: Exit the program if a file cannot be opened.
C++ Code:
#include <iostream>
#include <fstream>
#include <cstdlib> // For exit()
using namespace std;
int main() {
ifstream file("nonexistent_file.txt");
// File operations...
file.close();
return 0;
}
Explanation: If the file cannot be opened, exit(1) is used to terminate the program and return an error code.
Summary
break Statement: Used to exit loops or switch statements early.
exit() Function: Used to terminate a program immediately and optionally return a status code.
Understanding Loops
Loops are used to repeat a block of code multiple times based on a condition. They help automate repetitive
tasks and reduce code redundancy.
For Loop
The for loop is used when you know beforehand how many times you want to execute a statement or a block
of statements. It is often used for counting iterations.
Syntax:
code
for (initialization; condition; increment/decrement) {
// code to be executed
}
Initialization: Sets up the loop counter variable.
Condition: The loop runs as long as this condition is true.
Increment/Decrement: Updates the loop counter after each iteration.
Example 1: Print Numbers from 1 to 5
Scenario: Print numbers from 1 to 5.
C++ Code:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << endl;
}
return 0;
}
Explanation: The for loop starts with i initialized to 1. It prints the value of i, then increments i by 1. The
loop continues until i exceeds 5.
Example 2: Calculate the Sum of First 10 Natural Numbers
Scenario: Find the sum of numbers from 1 to 10.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int sum = 0;
cout << "Sum of numbers from 1 to 10 is: " << sum << endl;
return 0;
}
Explanation: The for loop iterates from 1 to 10, adding each number to the sum variable. After the loop
completes, the total sum is printed.
Example 3: Print Multiplication Table of 3
Scenario: Print the multiplication table for the number 3.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int number = 3;
return 0;
}
Explanation: The for loop iterates from 1 to 10, printing the result of multiplying number (3) by each value of
i. This produces the multiplication table for 3.
Example 4: Print Elements of an Array
Scenario: Print all elements in an array.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int array[] = {10, 20, 30, 40, 50};
int size = sizeof(array) / sizeof(array[0]);
return 0;
}
Explanation: The for loop iterates over the indices of the array. It prints each element along with its index.
The size of the array is calculated using size of(array) / size of(array[0]).
Understanding while Loop
A while loop is used when you want to repeat a block of code as long as a specified condition is true. It is
particularly useful when the number of iterations is not known before the loop starts.
Syntax:
code
while (condition) {
int main() {
int i = 1; // Initialization
return 0;
}
Explanation: The while loop starts with i set to 1. It prints the value of i and increments i by 1 each time. The
loop continues until i exceeds 5.
Example 2: Calculate the Factorial of a Number
Scenario: Calculate the factorial of a given number (e.g., 5).
C++ Code:
#include <iostream>
using namespace std;
int main() {
int number = 5;
int factorial = 1;
return 0;
}
Explanation: The while loop multiplies the factorial variable by number and then decrements number until it
becomes 0. This calculates the factorial of the original number.
Example 3: Sum of Positive Numbers
int main() {
int number;
int sum = 0;
cout << "Enter positive numbers to sum (negative number to quit):" << endl;
while (true) {
cin >> number;
if (number < 0) {
break; // Exit loop if a negative number is entered
}
sum += number; // Add number to sum
}
cout << "Sum of entered positive numbers is: " << sum << endl;
return 0;
}
Explanation: The while loop continuously asks the user for a number. If the number is negative, the break
statement exits the loop. Otherwise, the number is added to sum.
Example 4: Find the First Prime Number Greater Than 100
Scenario: Find the first prime number greater than 100.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int num = 101; // Start checking from 101
while (!isPrime(num)) {
num++; // Increment until a prime number is found
cout << "First prime number greater than 100 is: " << num << endl;
return 0;
}
Explanation: The while loop checks numbers starting from 101 to find the first prime number. The is Prime
function determines if a number is prime. The loop continues until a prime number is found.
Understanding do-while Loop
The do-while loop is similar to the while loop but with a key difference: it guarantees that the loop body will
execute at least once before checking the condition. This is because the condition is checked after the loop
body is executed.
Syntax:
cpp
Copy code
do {
// code to be executed
} while (condition);
Code Block: The block of code inside the do is executed first.
Condition: After executing the code block, the condition is checked. If it's true, the loop executes again. If
false, the loop ends.
Example 1: Print Numbers from 1 to 5
Scenario: Print numbers from 1 to 5 using a do-while loop.
C++ Code:
cpp
Copy code
#include <iostream>
using namespace std;
int main() {
int i = 1; // Initialization
do {
cout << i << endl;
i++; // Increment
} while (i <= 5); // Condition
return 0;
}
Explanation: The do-while loop starts with i set to 1, prints i, and then increments it. The loop continues until
i exceeds 5. The key difference here is that the loop body executes at least once even if i were initially
greater than 5.
Example 2: Prompt User for Password
Scenario: Prompt the user to enter a password until they enter the correct one.
int main() {
string password;
string correctPassword = "secret";
do {
cout << "Enter password: ";
cin >> password;
} while (password != correctPassword); // Condition
return 0;
}
Explanation: The do-while loop prompts the user to enter a password and keeps asking until the correct
password ("secret") is entered.
Example 3: Calculate the Average of Numbers
Scenario: Calculate the average of a series of numbers input by the user. Continue until the user enters 0.
C++ Code:
cpp
Copy code
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
int count = 0;
do {
cout << "Enter a number (0 to stop): ";
cin >> number;
if (number != 0) {
sum += number;
count++;
}
} while (number != 0); // Condition
return 0;
}
Explanation: The do-while loop continues to ask the user for numbers and adds them to sum until 0 is
entered. It then calculates and displays the average of the entered numbers.
Example 4: Generate a Random Number Until It Meets a Condition
Scenario: Generate random numbers between 1 and 100 until a number greater than 90 is generated.
C++ Code:
cpp
Copy code
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
using namespace std;
int main() {
srand(static_cast<unsigned int>(time(0))); // Seed for randomness
int number;
do {
number = rand() % 100 + 1; // Generate random number between 1 and 100
cout << "Generated number: " << number << endl;
} while (number <= 90); // Condition
cout << "Number greater than 90 found: " << number << endl;
return 0;
}
Explanation: The do-while loop generates random numbers between 1 and 100 until it finds a number
greater than 90. The rand() function is used to generate random numbers, and srand() seeds the random
number generator.
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip the rest of the loop for even numbers
}
cout << i << endl; // Print odd numbers
}
return 0;
}
Explanation: The continue statement skips printing the number if it is even, so only odd numbers from 1 to
10 are printed.
Example 2: Skip Negative Numbers in Summation
Scenario: Sum only positive numbers in an array, skipping any negative numbers.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int numbers[] = {3, -1, 4, -2, 5};
int sum = 0;
cout << "Sum of positive numbers is: " << sum << endl;
return 0;
}
Explanation: The continue statement skips negative numbers, so only positive numbers are added to the
sum.
Example 3: Skip Processing When User Enters 0
Scenario: Calculate the average of a series of positive numbers entered by the user, ignoring any zeros.
C++ Code:
#include <iostream>
int main() {
int number;
int sum = 0;
int count = 0;
cout << "Enter numbers to calculate the average (0 to skip, negative number to quit):" << endl;
while (true) {
cin >> number;
if (number < 0) {
break; // Exit loop if a negative number is entered
}
if (number == 0) {
continue; // Skip processing if the number is 0
}
sum += number;
count++;
}
if (count > 0) {
cout << "Average is: " << static_cast<double>(sum) / count << endl;
} else {
cout << "No positive numbers entered." << endl;
}
return 0;
}
Explanation: The continue statement skips zero values, so they are not included in the summation and
average calculation.
Example 4: Skip Specific Characters in a String
Scenario: Print all characters in a string except for vowels.
C++ Code:
#include <iostream>
using namespace std;
int main() {
string text = "Hello World";
Nested loops in C++ involve placing one loop inside another. They are useful for scenarios where you need to
perform repeated actions in a structured manner, such as handling multi-dimensional data or creating
complex patterns.
int main() {
int n = 5; // Size of the table
int main() {
int size = 4;
return 0;
}
Explanation: The outer loop controls the number of rows, and the inner loop controls the number of columns,
printing asterisks to form a square pattern.
Example 3: Triangle Pattern
Scenario: Print a right-angle triangle pattern with a height of 5.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int height = 5;
return 0;
}
Explanation: The outer loop controls the number of rows, and the inner loop prints the appropriate number of
asterisks in each row to form a right-angle triangle.
Example 4: Generating a Grid of Numbers
Scenario: Print a grid of numbers where each cell contains its row and column indices.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int rows = 3;
return 0;
}
Explanation: The outer loop iterates over rows, and the inner loop iterates over columns, printing each cell's
row and column indices to create a grid.
Summary
Nested Loops: Loops within loops, used to handle multi-dimensional structures or repetitive patterns.
Outer Loop: Controls the major iteration (e.g., rows in a table or pattern).
Inner Loop: Controls the minor iteration within each iteration of the outer loop (e.g., columns or elements in
each row).