0% found this document useful (0 votes)
12 views36 pages

4th Chap (Control Structure)

Uploaded by

leeminhoking1312
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views36 pages

4th Chap (Control Structure)

Uploaded by

leeminhoking1312
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

GHS CHITTA BATTA

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++

GHSs(Chap-4 Control Structure) Page 1


code
#include <iostream>
using namespace std;

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() {

GHSs(Chap-4 Control Structure) Page 2


bool isRaining = true;
bool isSunny = false;

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

GHSs(Chap-4 Control Structure) Page 3


/ \
v v
+-----------------+ +---------------------------+
| Grade = B | | Is score >= 70? |
+-----------------+ +---------------------------+
/ \
Yes / \ No
/ \
v v
+-----------------+ +-------------------+
| Grade = C | | Grade = F |
+-----------------+ +-------------------+
|
v
+-------------+
| End |
+-------------+
Example in C++:
code
#include <iostream>
using namespace std;

int main() {
int score = 85;
char grade;

if (score >= 90) {


grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'F';
}

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:

GHSs(Chap-4 Control Structure) Page 4


1. If the age is 18 or above, eligible to vote.
2. Otherwise, not eligible to vote.
Start --> Decision --> Process --> End

+-------------+
| 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;

if (age >= 18) {


cout << "You are eligible to vote." << endl;
} else {
cout << "You are not eligible to vote." << endl;
}

return 0;
}
Explanation: The program checks if the person is 18 or older to determine voting eligibility.
Example 3: Even or Odd Number

GHSs(Chap-4 Control Structure) Page 5


Flowchart:
1. If the number is divisible by 2, it's even.
2. Otherwise, it's odd.
Start --> Decision --> Process --> End
+-------------+
| Start |
+-------------+
|
v
+-----------------------------+
| Is number % 2 == 0? |
+-----------------------------+
/ \
Yes / \ No
/ \
v v
+-----------------+ +-------------------+
| Number is Even | | Number is Odd |
+-----------------+ +-------------------+
|
v
+-------------+
| End |
+-------------+
Example in C++:
code
#include <iostream>
using namespace std;

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.

Understanding if, else, and else if Statements

GHSs(Chap-4 Control Structure) Page 6


1. if Statement: Checks a condition and executes a block of code if the condition is true.
2. else Statement: Executes a block of code if the if condition is false.
3. else if Statement: Checks additional conditions if the previous if or else if conditions are false.
Examples and Flowcharts
Example 1: Single if-else Statement
Scenario: Checking if a number is positive or negative.
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+--------------------+
| Is number > 0? | <-- Decision (Diamond)
+--------------------+
/ \
Yes No
/ \
v v
+--------------+ +-----------------+
| Number is | | Number is |
| Positive | | Negative |
+--------------+ +-----------------+
|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

int main() {
int number = -5;

if (number > 0) {
cout << "Number is Positive." << endl;
} else {
cout << "Number is Negative." << endl;
}

return 0;
}

GHSs(Chap-4 Control Structure) Page 7


Explanation: The program checks if the number is greater than 0. If true, it prints "Number is Positive."
Otherwise, it prints "Number is Negative."
Example 2: if-else if-else Statement
Scenario: Determining the grade based on a score.
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+-----------------------------+
| Is score >= 90? | <-- Decision (Diamond)
+-----------------------------+
/ \
Yes No
/ \
v v
+--------------+ +------------------------------+
| Grade = A | | Is score >= 80? |
+--------------+ +------------------------------+
/ \
Yes No
/ \
v v
+----------------+ +----------------------+
| Grade = B | | Is score >= 70? |
+----------------+ +----------------------+
/ \
Yes No
/ \
v v
+----------------+ +------------------+
| Grade = C | | Grade = F |
+----------------+ +------------------+
|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

int main() {

GHSs(Chap-4 Control Structure) Page 8


int score = 85;
char grade;

if (score >= 90) {


grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'F';
}

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 |
+-------------------+ +-------------------+

GHSs(Chap-4 Control Structure) Page 9


|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

int main() {
int age = 20;
bool hasTicket = true;

if (age >= 18) {


if (hasTicket) {
cout << "Allowed to Enter the Movie." << endl;
} else {
cout << "You need to buy a ticket." << endl;
}
} else {
cout << "Cannot Enter the Movie." << endl;
}

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.

Understanding switch Statement


 switch: Used to execute different code blocks based on the value of a variable.
 case: Specifies a block of code to be executed if a variable matches a particular value.
 default: Specifies a block of code to be executed if none of the case values match.
Example 1: Basic switch Statement
Scenario: Determine the day of the week based on a number (1 for Monday, 2 for Tuesday, etc.).
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+-------------------------+
| Switch(day) | <-- Switch Statement
+-------------------------+

GHSs(Chap-4 Control Structure) Page 10


|
v
+-------------------------+
| Case 1: Monday | <-- Case
+-------------------------+
|
v
+-------------------------+
| Case 2: Tuesday | <-- Case
+-------------------------+
|
v
+-------------------------+
| Case 3: Wednesday | <-- Case
+-------------------------+
|
v
+-------------------------+
| Default: Invalid day | <-- Default
+-------------------------+
|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

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;

GHSs(Chap-4 Control Structure) Page 11


break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day" << endl;
break;
}

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

GHSs(Chap-4 Control Structure) Page 12


+-------------------------+
|
v
+-------------------------+
| Default: Poor | <-- Default
+-------------------------+
|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

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

GHSs(Chap-4 Control Structure) Page 13


Scenario: Handle different menu options in a restaurant.
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+-------------------------+
| Switch(option) | <-- Switch Statement
+-------------------------+
|
v
+-------------------------+
| Case 1: Pizza | <-- Case
+-------------------------+
|
v
+-------------------------+
| Case 2: Burger | <-- Case
+-------------------------+
|
v
+-------------------------+
| Case 3: Salad | <-- Case
+-------------------------+
|
v
+-------------------------+
| Default: Invalid option | <-- Default
+-------------------------+
|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

int main() {
int option = 2;

switch (option) {
case 1:

GHSs(Chap-4 Control Structure) Page 14


cout << "Pizza" << endl;
break;
case 2:
cout << "Burger" << endl;
break;
case 3:
cout << "Salad" << endl;
break;
default:
cout << "Invalid option" << endl;
break;
}

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
+-------------------------+
|

GHSs(Chap-4 Control Structure) Page 15


v
+-------------------------+
| Default: Invalid month | <-- Default
+-------------------------+
|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

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;

GHSs(Chap-4 Control Structure) Page 16


case 10:
cout << "October" << endl;
break;
case 11:
cout << "November" << endl;
break;
case 12:
cout << "December" << endl;
break;
default:
cout << "Invalid month" << 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.

Understanding Nested if Statements


Nested if statements involve placing one if statement inside another if statement. This allows for more
complex decision-making by evaluating multiple conditions.
Example 1: Check Voting Eligibility Based on Age and Citizenship
Scenario: Determine if a person is eligible to vote based on their age and citizenship.
Flowchart:
+-------------+
| Start |
+-------------+
|
v
+------------------------------+
| Is age >= 18? | <-- Outer `if`
+------------------------------+
/ \
Yes No
/ \
v v
+-----------------+ +---------------------------+
| Is citizen? | | Not eligible to vote | <-- Inner `if`
+-----------------+ +---------------------------+
/ \
Yes No
/ \
v v

GHSs(Chap-4 Control Structure) Page 17


+-----------------+ +---------------------------+
| Eligible to vote| | Not a citizen |
+-----------------+ +---------------------------+
|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

int main() {
int age = 20;
bool isCitizen = true;

if (age >= 18) {


if (isCitizen) {
cout << "Eligible to vote." << endl;
} else {
cout << "Not a citizen." << endl;
}
} else {
cout << "Not eligible to vote." << endl;
}

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 | +---------------------------+

GHSs(Chap-4 Control Structure) Page 18


+-----------------+
|
v
+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

int main() {
float gpa = 3.6;
float income = 45000;

if (gpa >= 3.5) {


if (income <= 50000) {
cout << "Eligible for scholarship." << endl;
} else {
cout << "Income too high." << endl;
}
} else {
cout << "GPA too low." << endl;
}

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

GHSs(Chap-4 Control Structure) Page 19


+-------------+
| End |
+-------------+
C++ Code:
#include <iostream>
using namespace std;

int main() {
int temperature = 18;
bool isRaining = true;

if (temperature < 20) {


if (isRaining) {
cout << "Wear a raincoat." << endl;
} else {
cout << "Wear warm clothing." << endl;
}
} else {
cout << "Wear light clothing." << endl;
}

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 |
+-------------+

GHSs(Chap-4 Control Structure) Page 20


C++ Code:
#include <iostream>
using namespace std;

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};

for (int i = 0; i < 5; i++) {


if (numbers[i] > 5) {
cout << "First number greater than 5 is: " << numbers[i] << endl;
break; // Exit the loop
}

GHSs(Chap-4 Control Structure) Page 21


}

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
}

cout << "You entered: " << number << endl;


}

cout << "Loop ended." << endl;

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:

GHSs(Chap-4 Control Structure) Page 22


cout << "Invalid month" << endl;
break;
}

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}};

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 3; j++) {
if (matrix[i][j] < 0) {
cout << "First negative number found: " << matrix[i][j] << endl;
break; // Exit inner loop
}
}
if (matrix[i][0] < 0) {
break; // Exit outer loop
}
}

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;

if (age < 18) {


cout << "You must be 18 or older." << endl;
exit(1); // Terminate program with error code 1
}

cout << "Welcome!" << endl;

GHSs(Chap-4 Control Structure) Page 23


return 0;
}
Explanation: The exit(1) function terminates the program if the age is less than 18, returning an error code
of 1 to the operating system.
Example 2: Exit with Success Code
Scenario: End the program successfully after performing a task.
C++ Code:
#include <iostream>
#include <cstdlib> // For exit()
using namespace std;

int main() {
cout << "Performing a task..." << endl;

// Task completed successfully


exit(0); // Terminate program with success code 0
}
Explanation: The exit(0) function ends the program successfully. The code 0 typically indicates that the
program completed without errors.
Example 3: Using exit() in Functions
Scenario: Use exit() in a function to terminate the program based on certain conditions.
C++ Code:
#include <iostream>
#include <cstdlib> // For exit()
using namespace std;

void checkCondition(bool condition) {


if (condition) {
cout << "Condition met. Exiting program." << endl;
exit(0); // Terminate program
}
}

int main() {
checkCondition(true); // This will terminate the program

cout << "This line will not be executed." << endl;

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");

GHSs(Chap-4 Control Structure) Page 24


if (!file) {
cout << "Error opening file." << endl;
exit(1); // Terminate program with error code 1
}

// 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;

GHSs(Chap-4 Control Structure) Page 25


for (int i = 1; i <= 10; i++) {
sum += i; // Add the current value of i to sum
}

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;

for (int i = 1; i <= 10; i++) {


cout << number << " x " << i << " = " << number * i << endl;
}

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]);

for (int i = 0; i < size; i++) {


cout << "Element at index " << i << " is: " << array[i] << endl;
}

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) {

GHSs(Chap-4 Control Structure) Page 26


// code to be executed
}
 Condition: The loop runs as long as this condition is true. If the condition is false at the start, the loop will
not execute at all.
Example 1: Print Numbers from 1 to 5
Scenario: Print numbers from 1 to 5 using a while loop.
C++ Code:
#include <iostream>
using namespace std;

int main() {
int i = 1; // Initialization

while (i <= 5) { // Condition


cout << i << endl;
i++; // Increment
}

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;

while (number > 0) {


factorial *= number; // Multiply factorial by number
number--; // Decrement
}

cout << "Factorial is: " << factorial << endl;

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

GHSs(Chap-4 Control Structure) Page 27


Scenario: Keep asking the user for positive numbers and sum them until the user enters a negative number.
C++ Code:
#include <iostream>
using namespace std;

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;

bool isPrime(int num) {


if (num <= 1) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}

int main() {
int num = 101; // Start checking from 101

while (!isPrime(num)) {
num++; // Increment until a prime number is found

GHSs(Chap-4 Control Structure) Page 28


}

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.

GHSs(Chap-4 Control Structure) Page 29


C++ Code:
cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

int main() {
string password;
string correctPassword = "secret";

do {
cout << "Enter password: ";
cin >> password;
} while (password != correctPassword); // Condition

cout << "Password correct!" << endl;

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

GHSs(Chap-4 Control Structure) Page 30


if (count > 0) {
cout << "Average is: " << static_cast<double>(sum) / count << endl;
} else {
cout << "No numbers entered." << endl;
}

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.

Understanding continue Statement


When the continue statement is encountered, it immediately jumps to the next iteration of the loop, skipping
any code that comes after it in the current iteration.
Syntax:
continue;
Example 1: Skipping Even Numbers

GHSs(Chap-4 Control Structure) Page 31


Scenario: Print only odd numbers from 1 to 10.
C++ Code:
cpp
Copy code
#include <iostream>
using namespace std;

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;

for (int i = 0; i < 5; i++) {


if (numbers[i] < 0) {
continue; // Skip negative numbers
}
sum += numbers[i]; // Add positive numbers to sum
}

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>

GHSs(Chap-4 Control Structure) Page 32


using namespace std;

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";

for (char ch : text) {


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
continue; // Skip vowels

GHSs(Chap-4 Control Structure) Page 33


}
cout << ch; // Print non-vowel characters
}

cout << endl;


return 0;
}
Explanation: The continue statement skips over vowels, so only non-vowel characters from the string are
printed.
Summary
 continue Statement: Used to skip the rest of the code in the current loop iteration and move to the next
iteration.
 Initialization: Typically occurs before the loop starts.
 Code Block: Contains the main logic of the loop.
 Condition: If met, the continue statement skips the remaining code for that iteration and proceeds to the
next iteration.

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.

Understanding Nested Loops


In a nested loop, the inner loop runs completely every time the outer loop runs once. This allows you to handle
more complex data structures or operations.
Syntax:
for (initialization; condition; increment) {
// Outer loop code

for (initialization; condition; increment) {


// Inner loop code
}

// More outer loop code


}
Example 1: Multiplication Table
Scenario: Print a multiplication table from 1 to 5.
C++ Code:
#include <iostream>
using namespace std;

int main() {
int n = 5; // Size of the table

for (int i = 1; i <= n; i++) {


for (int j = 1; j <= n; j++) {
cout << i * j << "\t"; // Print the product
}
cout << endl; // Move to the next line after each row
}

GHSs(Chap-4 Control Structure) Page 34


return 0;
}
Explanation: The outer loop iterates over rows, and the inner loop iterates over columns, printing the product
of the current row and column indices. This creates a multiplication table.
Example 2: Printing a Square Pattern
Scenario: Print a square pattern of asterisks (*) with a size of 4.
C++ Code:
#include <iostream>
using namespace std;

int main() {
int size = 4;

for (int i = 0; i < size; i++) {


for (int j = 0; j < size; j++) {
cout << "* "; // Print asterisks
}
cout << endl; // Move to the next line after each row
}

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;

for (int i = 1; i <= height; i++) {


for (int j = 1; j <= i; j++) {
cout << "* "; // Print asterisks
}
cout << endl; // Move to the next line after each row
}

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;

GHSs(Chap-4 Control Structure) Page 35


int cols = 4;

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= cols; j++) {
cout << "(" << i << "," << j << ")\t"; // Print row and column indices
}
cout << endl; // Move to the next line after each row
}

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).

END OF CHAP-4 (Control Structure)

GHSs(Chap-4 Control Structure) Page 36

You might also like