0% found this document useful (0 votes)
5 views24 pages

Chapter 4 Control Structure

The document provides an overview of control structures in C++, including if, if-else, else-if, and switch statements, along with their syntax, importance, and examples. It also covers looping structures such as for, while, and do-while loops, as well as the use of break, continue, and exit functions. Additionally, it explains nested loops and their applications in handling multidimensional data.

Uploaded by

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

Chapter 4 Control Structure

The document provides an overview of control structures in C++, including if, if-else, else-if, and switch statements, along with their syntax, importance, and examples. It also covers looping structures such as for, while, and do-while loops, as well as the use of break, continue, and exit functions. Additionally, it explains nested loops and their applications in handling multidimensional data.

Uploaded by

bachasaab11
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

KHYBER MODEL COLLEGE & SCHOOL

NOWSHERA

COMPUTER NOTES
2nd Year
CHAPTER # 4 : CONTROL STRUCTURES

1
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
Control Structures in C++

Control structures are a fundamental part of programming, allowing the program to make
decisions and choose different actions based on conditions. The main control structures for
decision-making in C++ are:

1. if Statement
2. if-else Statement
3. else-if Statement
4. switch Statement

Each of these has its own purpose, syntax, and use cases. Let's break them down.

1. If Statement

Definition:

The if statement checks a condition. If the condition is true, a specific block of code is
executed. If it’s false, the block of code is skipped.

Syntax:

if (condition) {
// Code to execute if the condition is true
}

Importance:

 It allows conditional execution of code based on certain criteria.


 It’s essential for controlling the flow of the program.

Where to Use:

Use the if statement when you need to execute code only when a specific condition holds true.

Why to Use:

To avoid running code unnecessarily, based on user input or other conditions. It helps in
optimizing program efficiency.

Example:

#include <iostream>
using namespace std;

int main() {

2
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
int number = 10;

if (number > 5) {
cout << "The number is greater than 5." << endl;
}

return 0;
}

 Explanation: The program checks if the number is greater than 5. If true, it prints the message.

2. If-Else Statement

Definition:

The if-else statement allows the program to take two different paths: one if the condition is
true, and another if it is false.

Syntax:

if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

Importance:

 Provides an alternative action when the condition is false.


 Makes programs dynamic by providing two possible paths.

Where to Use:

When you need an alternative action if the condition is not met. For example, when providing
feedback based on user input.

Why to Use:

It is useful when you want to handle both true and false outcomes.

Example:

#include <iostream>
using namespace std;

int main() {
int number = 3;

if (number > 5) {
3
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
cout << "Number is greater than 5." << endl;
} else {
cout << "Number is less than or equal to 5." << endl;
}

return 0;
}

 Explanation: If the number is greater than 5, the first message is printed. If not, the second
message is printed.

3. Else-If Statement

Definition:

The else-if statement allows checking multiple conditions in a sequence. If the first condition
is false, it checks the next one, and so on.

Syntax:

if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if all conditions are false
}

Importance:

 Allows multiple conditions to be checked.


 Makes the program flexible when there are several possible outcomes.

Where to Use:

When there are more than two possibilities. For example, grading systems where scores fall into
multiple ranges (A, B, C, etc.).

Why to Use:

It’s useful for handling a series of conditions where only one block of code should run depending
on the input.

Example:

#include <iostream>

4
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
using namespace std;

int main() {
int marks = 85;

if (marks >= 90) {


cout << "Grade A" << endl;
} else if (marks >= 80) {
cout << "Grade B" << endl;
} else if (marks >= 70) {
cout << "Grade C" << endl;
} else {
cout << "Grade D" << endl;
}

return 0;
}

 Explanation: The program checks multiple ranges of marks and prints the appropriate grade.

4. Switch Statement

Definition:

The switch statement evaluates an expression and executes code based on the matching case.
It's primarily used for handling multiple possible values for a variable.

Syntax:

switch(expression) {
case constant1:
// Code for constant1
break;
case constant2:
// Code for constant2
break;
default:
// Code if no case matches
}

Importance:

 Allows handling of different cases for a single variable.


 Simplifies code when there are multiple options to choose from.

Where to Use:

Use the switch statement when a variable can have multiple values, and you want to execute
different blocks of code for each value.

5
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
Why to Use:

It is clearer and easier to manage than writing many if-else statements when the variable has
many possible values.

Example:

#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;
default:
cout << "Invalid day" << endl;
}

return 0;
}

 Explanation: The program evaluates the value of day. Since the value is 3, it prints
"Wednesday".

Comparison of Decision Statements

Statement Use Case Example Advantage

To execute code based on a


if if (x > 5) Simple and effective for a single condition
single condition

To handle two possible if (x > 5) Allows handling of both true and false
if-else
outcomes else conditions

To check multiple conditions else if (x >


else-if Good for multiple options
in sequence 10)

switch switch (day)


When a variable has multiple Cleaner for handling many cases based on

6
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
Statement Use Case Example Advantage

specific values the value of a variable

Nested If in C++

Definition:

A nested if is an if statement inside another if statement. It allows you to check multiple


conditions one inside the other. If the first if condition is true, the second if condition is
checked, and so on.

Syntax:
if (condition1) {
if (condition2) {
// Code to execute if both condition1 and condition2 are true
}
}

Importance:

 Nested if statements allow more complex decision-making in a program.


 It is useful when decisions depend on multiple conditions being true.

Where to Use:

Use nested if when you need to check more than one condition in a dependent manner. For
example, when validating multiple user inputs.

Why to Use:

 Helps in fine-tuning the decision-making process.


 More control over program logic.

Example:
#include <iostream>
using namespace std;

int main() {
int age = 20;
char gender = 'M';

if (age > 18) {


if (gender == 'M') {
cout << "You are an adult male." << endl;
}

7
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
}

return 0;
}

 Explanation: If the person’s age is above 18 and they are male, the message "You are an adult
male" will be displayed.

Break Statement and Exit Function in C++

Break Statement

Definition:

The break statement is used to exit from a loop or switch case immediately. When the program
encounters a break, it stops the execution of the loop or switch case and continues with the next
line of code after it.

Syntax:

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


if (i == 5) {
break;
}
// Other code
}

Importance:

 Helps in controlling loops.


 Useful for terminating loops early when a certain condition is met.

Where to Use:

 Use break in loops (like for, while, do-while) when you need to stop the loop based on a
condition.
 Can also be used in switch statements.

Example:

#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Loop ends when i is 5
}
cout << i << endl;
8
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
}

return 0;
}

 Explanation: The loop prints numbers from 0 to 4. When i becomes 5, the loop stops due to the
break statement.

Exit Function

Definition:

The exit() function is used to terminate the program immediately. When exit() is called, the
program stops running completely.

Syntax:

exit(0);

Importance:

 exit() helps in safely terminating the program.


 Can be used when a fatal error occurs and the program cannot continue.

Where to Use:

Use the exit() function when the program encounters an error or a condition where continuing
execution is not possible.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
cout << "Program starts." << endl;

exit(0); // Program stops here

cout << "This will not print." << endl;


return 0;
}

 Explanation: The program terminates after printing "Program starts." The next line does not
execute because of the exit() function.

9
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
Looping Structures in C++

Loops allow repeating blocks of code multiple times. There are three main types of loops in
C++:

1. For Loop

Definition:

The for loop is used when you know in advance how many times you want to repeat a block of
code.

Syntax:

for (initialization; condition; increment/decrement) {


// Code to repeat
}

Importance:

 For loops are used for iterating over a block of code a known number of times.
 It provides a compact way to loop, with initialization, condition, and update all in one line.

Where to Use:

Use for loops when you know the exact number of iterations in advance.

Example:

#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 5; i++) {
cout << "Number: " << i << endl;
}

return 0;
}

 Explanation: This loop prints the numbers from 0 to 4. The loop runs five times.

10
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
2. While Loop

Definition:

The while loop repeats a block of code as long as a condition is true. The condition is checked
before each iteration.

Syntax:

while (condition) {
// Code to repeat
}

Importance:

 Useful when you do not know in advance how many times the loop should run.
 The loop continues until the condition becomes false.

Where to Use:

Use while loops when the number of iterations is not known beforehand, such as when waiting
for user input.

Example:

#include <iostream>
using namespace std;

int main() {
int i = 0;

while (i < 5) {
cout << "Number: " << i << endl;
i++;
}

return 0;
}

 Explanation: The loop runs as long as i is less than 5, printing the numbers 0 to 4.

3. Do-While Loop

Definition:

11
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
The do-while loop is similar to the while loop, but it guarantees that the code inside the loop
runs at least once, regardless of the condition.

Syntax:

do {
// Code to repeat
} while (condition);

Importance:

 Ensures that the loop runs at least once.


 The condition is checked after the first iteration.

Where to Use:

Use do-while loops when you want the loop to execute at least once, even if the condition is
false from the beginning.

Example:

#include <iostream>
using namespace std;

int main() {
int i = 0;

do {
cout << "Number: " << i << endl;
i++;
} while (i < 5);

return 0;
}

 Explanation: The loop runs five times, printing numbers from 0 to 4. It checks the condition
after the code executes once.

Continue Statement in C++

Definition:

The continue statement is used to skip the current iteration of a loop and move to the next
iteration. When a continue statement is encountered, the loop stops executing the remaining
code in the current iteration and jumps to the next iteration.

Syntax:

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


if (i == 2) {
continue; // Skip the rest of the loop for i == 2
12
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
}
// Other code to execute
}

Importance:

 The continue statement allows skipping certain iterations in a loop based on a condition.
 It is useful when you want to skip specific values or conditions without exiting the loop.

Where to Use:

 In loops (for, while, do-while), use continue when you want to skip specific iterations
without breaking the loop entirely.

Why to Use:

 Helps optimize loop behavior by avoiding unnecessary computations for certain conditions.
 Simplifies the code by reducing the need for additional if-else structures.

Example:

#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skips the rest of the code for i == 2
}
cout << "Number: " << i << endl;
}

return 0;
}

 Explanation: The loop prints numbers from 0 to 4, but when i is 2, it skips printing it due to the
continue statement.

Nested Loop in C++

Definition:

A nested loop is a loop inside another loop. The inner loop runs completely every time the outer
loop runs one iteration. It is commonly used when dealing with multidimensional data like
matrices or tables.

Syntax:

13
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Code to repeat
}
}

Importance:

 Nested loops are essential for processing multiple levels of data, such as 2D arrays, grids, or
tables.
 They are commonly used in matrix operations, graphical programming, and scenarios where
multiple layers of data need to be processed.

Where to Use:

 Use nested loops when you need to work with multidimensional data, like rows and columns in
a table.
 Common in algorithms that need to repeat actions over two or more sets of data.

Why to Use:

 To handle complex data structures like 2D arrays and matrices.


 Simplifies the logic when working with multi-level data processing.

Example:
#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << i << "," << j << " ";
}
cout << endl;
}

return 0;
}

 Explanation: The outer loop controls the rows, while the inner loop controls the columns. This
prints pairs of numbers from (1,1) to (3,3).

14
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
COMPREHENSIONS:
ii. Program to Print Square if Number is Greater than 10, Otherwise Print Cube

#include <iostream>
using namespace std;

int main() {
int num;

// Input number
cout << "Enter a number: ";
cin >> num;

// Check and print square or cube


if (num > 10) {
cout << "Square of " << num << " is: " << num * num << endl;
} else {
cout << "Cube of " << num << " is: " << num * num * num << endl;
}

return 0;
}

iii. Program to Check if an Integer is Odd or Even

#include <iostream>
using namespace std;

int main() {
int num;

// Input number
cout << "Enter an integer: ";
cin >> num;

// Check if odd or even


if (num % 2 == 0) {
cout << num << " is even." << endl;
} else {
cout << num << " is odd." << endl;
}

15
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
return 0;
}

iv. Program to Find the Largest of Three Numbers

#include <iostream>
using namespace std;

int main() {
int a, b, c;

// Input three numbers


cout << "Enter three numbers: ";
cin >> a >> b >> c;

// Find the largest number


int largest = a;
if (b > largest) largest = b;
if (c > largest) largest = c;

// Output the largest number


cout << "The largest number is: " << largest << endl;

return 0;
}

v. Program to Check if a Letter is Lowercase or Uppercase

#include <iostream>
using namespace std;

int main() {
char letter;

// Input letter
cout << "Enter a letter: ";
cin >> letter;

// Check if letter is uppercase or lowercase


if (letter >= 'a' && letter <= 'z') {
cout << letter << " is a lowercase letter." << endl;
} else if (letter >= 'A' && letter <= 'Z') {
cout << letter << " is an uppercase letter." << endl;
} else {
cout << letter << " is not a letter." << endl;
}

return 0;
}

vi. Program to Print Multiplication Table Up to 20

16
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
#include <iostream>
using namespace std;

int main() {
int num;

// Input number
cout << "Enter an integer: ";
cin >> num;

// Print multiplication table up to 20


for (int i = 1; i <= 20; ++i) {
cout << num << " x " << i << " = " << num * i << endl;
}

return 0;
}

vii. Program to Calculate Net Pay with House Rent Based on Basic Pay

#include <iostream>
using namespace std;

int main() {
float basicPay, houseRent, netPay;

// Input basic pay


cout << "Enter basic pay: ";
cin >> basicPay;

// Calculate house rent based on basic pay


if (basicPay < 30000) {
houseRent = 0.30 * basicPay;
} else if (basicPay >= 30000 && basicPay <= 50000) {
houseRent = 0.35 * basicPay;
} else {
houseRent = 0.40 * basicPay;
}

// Calculate net pay


netPay = basicPay + houseRent;

// Output net pay


cout << "Net pay: " << netPay << endl;

return 0;
}

viii. Program to Produce a Table of Equivalent Temperatures in Fahrenheit and


Celsius

17
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
#include <iostream>
using namespace std;

int main() {
float fahrenheit, celsius;

// Print header
cout << "Fahrenheit\tCelsius" << endl;

// Generate temperature table


for (fahrenheit = 50; fahrenheit <= 100; fahrenheit += 5) {
celsius = 5.0 / 9.0 * (fahrenheit - 32);
cout << fahrenheit << "\t\t" << celsius << endl;
}

return 0;
}

ix. Program to Print Sum of the Sequence Using a for Loop

#include <iostream>
using namespace std;

int main() {
int sum = 0;

// Sum of the sequence using for loop


for (int i = 30; i <= 60; i += 3) {
sum += i;
}

// Output the result


cout << "The sum of the sequence is: " << sum << endl;

return 0;
}

x. Program to Print Sum of the Sequence Using a while Loop

#include <iostream>
using namespace std;

int main() {
int sum = 0;
int i = 30;

// Sum of the sequence using while loop


while (i <= 60) {
sum += i;
i += 3;
}

18
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
// Output the result
cout << "The sum of the sequence is: " << sum << endl;

return 0;
}

xi. Program to Print Positive Odd Numbers Up to 50 Skipping Those Divisible by


5

#include <iostream>
using namespace std;

int main() {
// Print positive odd numbers up to 50 skipping those divisible by 5
for (int num = 1; num <= 50; num += 2) {
if (num % 5 == 0) {
continue; // Skip numbers divisible by 5
}
cout << num << " ";
}

cout << endl;

return 0;
}

xii. Program to Read an Integer and Print Its Factorial

#include <iostream>
using namespace std;

int main() {
int num;
long long factorial = 1;

// Input integer
cout << "Enter an integer: ";
cin >> num;

// Compute factorial
for (int i = 1; i <= num; ++i) {
factorial *= i;
}

// Output the factorial


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

return 0;
}

19
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
xiii. Program to Read Coefficients of a Quadratic Equation and Print Real
Solutions

#include <iostream>
#include <cmath> // For sqrt function
using namespace std;

int main() {
float a, b, c;
float discriminant, root1, root2;

// Input coefficients
cout << "Enter coefficients a, b, and c: ";
cin >> a >> b >> c;

// Calculate discriminant
discriminant = b * b - 4 * a * c;

// Find real solutions based on discriminant


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "The roots are: " << root1 << " and " << root2 << endl;
} else if (discriminant == 0) {
root1 = -b / (2 * a);
cout << "The root is: " << root1 << endl;
} else {
cout << "No Real Solutions" << endl;
}

return 0;
}

Other C++ Programs:

1. Right-Angle Triangle Pattern

#include <iostream>
using namespace std;

int main() {
int rows = 5;

20
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= i; ++j) {
cout << "*";
}
cout << endl;
}

return 0;
}

2. Inverted Right-Angle Triangle Pattern

#include <iostream>
using namespace std;

int main() {
int rows = 5;

for (int i = rows; i >= 1; --i) {


for (int j = 1; j <= i; ++j) {
cout << "*";
}
cout << endl;
}

return 0;
}

3. Pyramid Pattern

#include <iostream>
using namespace std;

int main() {
int rows = 5;

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


// Print spaces
for (int j = i; j < rows; ++j) {
cout << " ";
}
// Print stars
for (int k = 1; k <= (2 * i - 1); ++k) {
cout << "*";
}
cout << endl;
}

return 0;
}

21
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
4. Inverted Pyramid Pattern

#include <iostream>
using namespace std;

int main() {
int rows = 5;

for (int i = rows; i >= 1; --i) {


// Print spaces
for (int j = rows; j > i; --j) {
cout << " ";
}
// Print stars
for (int k = 1; k <= (2 * i - 1); ++k) {
cout << "*";
}
cout << endl;
}

return 0;
}

5. Diamond Pattern

#include <iostream>
using namespace std;

int main() {
int rows = 5;

// Upper part
for (int i = 1; i <= rows; ++i) {
// Print spaces
for (int j = i; j < rows; ++j) {
cout << " ";
}
// Print stars
for (int k = 1; k <= (2 * i - 1); ++k) {
cout << "*";
}
cout << endl;
}

// Lower part
for (int i = rows - 1; i >= 1; --i) {
// Print spaces
for (int j = rows; j > i; --j) {
cout << " ";
}
// Print stars
for (int k = 1; k <= (2 * i - 1); ++k) {
cout << "*";
22
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
}
cout << endl;
}

return 0;
}

6. Hollow Square Pattern


#include <iostream>
using namespace std;

int main() {
int size = 5;

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


for (int j = 1; j <= size; ++j) {
if (i == 1 || i == size || j == 1 || j == size) {
cout << "*";
} else {
cout << " ";
}
}
cout << endl;
}

return 0;
}

7. Number Pyramid Pattern


#include <iostream>
using namespace std;

int main() {
int rows = 5;

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


// Print spaces
for (int j = i; j < rows; ++j) {
cout << " ";
}
// Print numbers
for (int k = 1; k <= i; ++k) {
cout << k;
}
cout << endl;
}

return 0;
}

8. Right-Angle Triangle with Numbers


#include <iostream>
using namespace std;
23
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748
int main() {
int rows = 5;

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


for (int j = 1; j <= i; ++j) {
cout << j << " ";
}
cout << endl;
}

return 0;
}

9. Triangle Pattern with Asterisks


#include <iostream>
using namespace std;

int main() {
int rows = 5;

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


for (int j = 1; j <= i; ++j) {
cout << "* ";
}
cout << endl;
}

return 0;
}

10. Checkerboard Pattern


#include <iostream>
using namespace std;

int main() {
int size = 8;

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


for (int j = 1; j <= size; ++j) {
if ((i + j) % 2 == 0) {
cout << "*";
} else {
cout << " ";
}
}
cout << endl;
}

return 0;
}

24
KMC COLLGE NSR WRITTEN BY : SIR JAWAD CONTACT : 0304-9486748

You might also like