0% found this document useful (0 votes)
3 views16 pages

Decision Making in C++

The document discusses decision-making and looping structures in C++, focusing on various types of loops such as while, for, do-while, and nested loops. It explains the syntax, components, and execution flow of while and do-while loops, highlighting their strengths and limitations, including potential infinite loops and performance overhead. Additionally, it provides examples and comparisons between while and do-while loops, emphasizing their use cases and error handling capabilities.

Uploaded by

noopursakpal1309
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)
3 views16 pages

Decision Making in C++

The document discusses decision-making and looping structures in C++, focusing on various types of loops such as while, for, do-while, and nested loops. It explains the syntax, components, and execution flow of while and do-while loops, highlighting their strengths and limitations, including potential infinite loops and performance overhead. Additionally, it provides examples and comparisons between while and do-while loops, emphasizing their use cases and error handling capabilities.

Uploaded by

noopursakpal1309
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
You are on page 1/ 16

Decision Making & Loops in C++

• Loops in C++
There may be a situation, when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages –

C++ programming language provides the following type of loops to handle looping
requirements.

Sr.No Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given condition is true. It tests


the condition before executing the loop body.

2 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop
body.

4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
While Loop in C++
In C++, a while loop is a control structure used to execute a block of code repeatedly as long
as a given condition evaluates to true. The condition is checked before every iteration,
making it a pre-test loop.

Syntax of a While Loop in C++


while (condition) {
// Code block to be executed repeatedly
statement(s);
}

Components of a While Loop


Condition
• A boolean expression that determines whether the loop executes.
• The loop continues until the condition evaluates to false.
• If the condition is false at the start, the loop body is skipped entirely.
Example:
int x = 5;
while (x > 0) {
// Runs as long as x is greater than 0
x--;
}
Body
• The body is the set of statements enclosed in { } that are executed as long as the
condition is true.
• Typically, the body modifies variables that affect the condition, ensuring the loop
eventually terminates.
Example:
int x = 0;
while (x < 5) {
cout << "Value of x: " << x << endl; // Output the value of x
x++; // Increment x
}

How a While Loop Works in C++


A while loop follows these steps during execution:
1. Initialization: Any variables required for the condition are initialized before entering
the loop.
2. Condition Check: Before every iteration, the condition is evaluated:
o If true, the loop body executes.
o If false, the loop terminates, and control moves to the statement after the loop.
3. Body Execution: The statements inside the loop are executed in sequence.
4. Condition Update: Variables affecting the condition are usually updated in the body
to ensure the loop eventually terminates.
5. Repeat: Steps 2–4 repeat until the condition evaluates to false.

Flow Diagram

Example of a While Loop in C++


Basic Example: Printing Numbers
#include <iostream>
using namespace std;
int main() {
int x = 1;
while (x <= 5) { // Condition: Loop runs while x is less than or equal to
5
cout << "x = " << x << endl; // Body: Print x
x++; // Increment x to avoid infinite loop
}
return 0;
}
Output:
x=1
x=2
x=3
x=4
x=5

Analyze the Behavior of an Infinite Loop and Explain Why It


Occurs
An infinite loop occurs when the condition in a while loop is always true and there's no
mechanism to make it false. This leads to the loop running indefinitely.
#include <iostream>
using namespace std;
int main() {
int x = 1;
while (x > 0) { // Condition always true because x is positive
cout << "x = " << x << endl;
x++; // x keeps increasing, so the condition remains true
}
return 0;
}
Analysis:
• Initial Condition: x = 1 and x > 0 is true.
• Body Execution: x increments endlessly because integers in C++ can grow
until they overflow.
• Issue: The condition x > 0 will never evaluate to false. Eventually, an integer
overflow occurs, but the loop remains infinite in behavior.

How to Prevent Infinite Loops:


1. Ensure the condition will eventually become false:
int x = 1;
while (x > 0 && x < 10) { // Add a terminating condition
cout << "x = " << x << endl;
x++;
}
2. Use a break statement for dynamic termination:
int x = 1;
while (true) {
cout << "x = " << x << endl;
if (x == 10) break; // Exit condition
x++;
}

Strengths of a While Loop in C++:


1. Dynamic Iteration:
o Condition-Controlled: The loop continues as long as the condition remains
true, allowing it to adapt to varying data inputs.
o Flexibility: Suitable for scenarios where the number of iterations is not
predetermined. It can handle user inputs, file inputs, or dynamic calculations.
o Input Validation: Perfect for programs that require repeated user input until
valid data is provided (e.g., age input validation).
2. Simple Syntax:
o Readability: The basic structure while (condition) { ... } is easy to understand,
making the code more readable and maintainable.
o Minimal Overhead: No need for loop counters or manual increments, as the
loop depends solely on the condition.
3. Efficient Memory Usage:
o Constant Space: The while loop requires minimal additional memory since it
uses a few variables (condition and potentially some additional variables
inside the loop).
o Avoids Extra Overhead: Unlike for loops, while loops do not need to
manage initialization and update steps within the loop structure itself.
4. Error Handling:
o Infinite Loop Control: Allows easy handling of cases where a process might
go into an infinite loop due to invalid conditions. The loop can be exited with
a break statement when necessary.
Limits of a While Loop in C++:
1. Potential for Infinite Loops:
o Risk of Infinite Loop: If the loop condition is never false, the program can
enter an infinite loop, causing it to run indefinitely.
o Debugging: Detecting and fixing an infinite loop can be challenging,
especially if the condition is set incorrectly.
2. Complexity in Nested Loops:
o Readability Issues: When a while loop is nested inside another while loop,
the code can become hard to follow and understand, leading to complex logic
and potential bugs.
o Debugging: Nested while loops can be difficult to debug, particularly if the
conditions are not carefully controlled.
3. Performance Overhead:
o Repetitive Condition Checks: Each iteration requires checking the condition,
which can be inefficient if the condition involves complex expressions.
o Loop-Body Execution: If the loop body executes multiple times
unnecessarily due to frequent rechecking of the condition, performance may
degrade.
4. No Control Over Number of Iterations:
o Unpredictable Iterations: Unlike for loops, where the number of iterations is
known upfront, a while loop may run indefinitely unless the loop condition
ensures its termination.
do-while loop in C++
Definition: A do-while loop in C++ is a control structure that executes a block of code
repeatedly until a specified condition evaluates to false. The condition is checked after the
loop body has been executed, guaranteeing at least one iteration.
Syntax:
do {
// loop body
} while (condition);

Components of a do-while loop in C++


1. Loop Header:
• do: The keyword that begins the do-while loop. The loop body follows this keyword.
2. Loop Body:
• { ... }: The block of code that contains one or more statements. These statements are
executed repeatedly until the loop condition evaluates to false.
• Example:
do {
// Statements to execute
} while (condition);
• The statements inside the loop are executed at least once before the condition is
checked.
3. Condition:
• while (condition): The condition that follows the do block.
• This is a boolean expression that is evaluated after each iteration of the loop.
• Purpose: Determines whether the loop should continue executing the statements
inside the loop.
• If the condition is true, the loop repeats; if false, the loop exits.
Here, condition is evaluated after the loop body has been executed. If the condition is false,
the loop exits; if true, the loop body executes again.
Key Points:
• The do-while loop guarantees at least one iteration because the condition is checked
only after the loop body has executed.
• The loop continues to execute until the condition becomes false.
• The loop body can include any valid C++ statements, including other loops,
conditional statements, and function calls.
• The condition must eventually evaluate to false to prevent the loop from becoming
infinite.
By understanding these components, you can effectively use a do-while loop to manage
iterations and control flow in your C++ programs.
Flow Diagram

How a Do-While Loop Works:


1. Initial Execution:
o The loop body inside the do block is executed first.
o This execution happens at least once, regardless of the condition.
do {
// Statements
} while (condition);
o Here, condition is the boolean expression that is evaluated after the loop body.
2. Condition Check:
o After the loop body executes, the condition is evaluated.
o The condition is a boolean expression (true or false).
o If the condition is true, the loop repeats: the body executes again, and the
condition is checked again.
o If the condition is false, the loop exits, and the program continues with the
next statement after the do-while loop.
3. Flow of Execution:
o Step 1: The loop body executes.
o Step 2: The condition is checked.
o Step 3: If the condition is true, the loop repeats from Step 1.
o Step 4: If the condition is false, the loop exits, and the program continues after
the do-while block.
Example:
#include <iostream>
int main() {
int age;

// Prompt the user for their age


do {
cout << "Enter your age (1-120): ";
cin >> age;

if (age < 1 || age > 120) {


cout << "Invalid input. Please try again." << endl;
}

} while (age < 1 || age > 120);

cout << "Your age is: " << age << endl;

return 0;
}
Explanation:
• Iteration 1:
o The user is prompted for an age.
o If the age entered is not between 1 and 120, the loop runs again.
o The condition age < 1 || age > 120 checks if the input is invalid.
• Iteration 2:
o After the invalid input in the first iteration, the loop prompts the user again.
o This process continues until a valid age is entered.
• Exit:
o When a valid age is entered (e.g., 25), the condition becomes false.
o The loop exits, and the program prints the user's age.

Comparison with While Loop


1. Condition Check:
• while loop: The condition is checked before the loop body executes. If the condition
is false, the loop body may never execute.
• do-while loop: The condition is checked after the loop body executes, ensuring the
loop body executes at least once.
2. Use Case:
• while loop: Suitable for situations where the condition may initially be false (e.g.,
reading from a file where there might not be any data).
• do-while loop: Ideal when the loop body needs to run at least once regardless of the
condition.
Example Comparisons:
Example 1: Input Validation
• Using while loop:
int age;
cout << "Enter your age (1-120): ";
cin >> age;
while (age < 1 || age > 120) {
cout << "Invalid input. Please try again." << endl;
cout << "Enter your age (1-120): ";
cin >> age;
}
cout << "Your age is: " << age << endl;
o Explanation:
▪ The condition age < 1 || age > 120 is checked before the loop body
executes.
▪ If the input is invalid on the first attempt, the loop doesn’t execute, and
no prompt is displayed.
▪ The loop executes only if the condition fails on the first attempt.
• Using do-while loop:
int age;
do {
cout << "Enter your age (1-120): ";
cin >> age;

if (age < 1 || age > 120) {


cout << "Invalid input. Please try again." << endl;
}
} while (age < 1 || age > 120);

cout << "Your age is: " << age << endl;
• Explanation:
o The loop body executes at least once before checking the condition.
o Even if the condition is initially false (e.g., entering a value of -5), the prompt
still appears once before validating.
o The loop guarantees that the user is prompted at least once.
Key Differences:
• while Loop:
o Condition first: The loop may not execute at all if the condition is false
initially.
o Best for: Cases where the loop might not need to run at all.
o Examples: Reading from a file where no data might be available.
• do-while Loop:
o At least one iteration: The loop body executes at least once.
o Best for: Situations where the loop must run at least once (e.g., user prompts,
menu-driven programs).
o Examples: Input validation, repeatedly prompting the user for a valid option.

Strengths of a Do-While Loop


1. Guaranteed Execution:
o Post-test Loop: The do-while loop guarantees at least one execution of the
loop body, regardless of the condition.
o User Interaction: Ideal for scenarios where user input must be validated at
least once, even if the first input fails validation.
o Example: A menu-driven program where users must input a valid choice at
least once before the condition checks.
2. Simple to Use:
o Readability: The loop structure do { ... } while (condition); is straightforward
and more intuitive for those not familiar with the intricacies of while loops.
o Easy to Implement: Particularly useful for beginners in C++ due to its
simplicity in ensuring the loop executes at least once.

3. Error Handling:
o Control Flow: The do-while loop is useful for error handling in iterative
processes. It ensures that the loop runs once regardless of the condition, which
can be beneficial for scenarios where input is expected at least once.
o Avoids Infinite Loop: By ensuring the loop executes at least once, the do-
while loop mitigates risks of an infinite loop that might occur in a simple
while loop due to an incorrect condition.
4. Flexibility:
o Dynamic Conditions: The condition is checked after the loop body, which
allows the body to execute first regardless of the condition. This can be useful
in applications that require user interaction or input validation.

Limits of a Do-While Loop


1. Redundant Execution:
o At Least One Iteration: The do-while loop executes the body at least once
regardless of the condition. If the condition is false initially, the body will
execute once unnecessarily.
o Inefficiency: This redundancy can lead to inefficient code if the loop body
doesn’t need to run at all in the first iteration.
2. Complexity in Nested Loops:
o Readability Issues: When combined with nested loops, the do-while loop can
complicate the code structure, making it harder to follow and maintain.
o Debugging: Debugging nested do-while loops can be challenging, especially
when conditions need careful handling across multiple loops.
3. Performance Overhead:
o Repeated Condition Check: Each iteration involves checking the condition,
which can be computationally expensive if the condition is complex.
o Loop-Body Execution: The body may execute multiple times due to the post-
check structure, which can impact performance.
4. No Predefined Iteration Count:
o Unpredictable Iterations: Similar to a while loop, the number of iterations
isn’t predetermined and depends entirely on the loop’s condition, which can
complicate performance considerations.
o Uncertainty: The exact number of iterations is unknown until the condition
fails, making it less predictable for operations requiring a known iteration
count.

for loop in C++


• Definition:
A for loop in C++ is a control structure used to execute a block of code repeatedly for
a specified number of iterations.
It is commonly used when the number of iterations is known ahead of time.
• Syntax:
for (initialization; condition; update) {
// loop body
}
• Example:
• "A for loop in C++ is used to execute a block of code a specific number of times."
• "The for loop initializes a loop variable, checks a condition, and updates the
variable after each iteration."
1. Initialization:
The for loop starts by initializing a loop control variable (int i = 0;).
This variable is typically used as a counter and is defined only once before the loop
starts.
2. Condition:
A condition is specified (i < 10;).
This condition is checked before each iteration of the loop.
If the condition is true, the loop executes; if false, the loop exits.
3. Update:
After each iteration, the loop control variable is updated (i++).
This update can be incrementing, decrementing, or modifying the loop variable based
on some logic.
The update is automatically handled by the for loop syntax, making the loop concise
and easy to read.

• Example:
for (int i = 0; i < 10; i++) {
cout << i << endl;
}

o Initialization: int i = 0;
o Condition: i < 10; — The loop runs until i is less than 10.
o Update: i++ — i is incremented after each iteration.
o Explanation:
▪ The loop starts with i = 0, runs as long as i < 10, and increments i
by 1 after each iteration, printing values from 0 to 9.
Flow Diagram

Example
#include <iostream>
using namespace std;

int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) {
cout << "value of a: " << a << endl;
}

return 0;
}
When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
Example
1. Write a program that calculates the sum of all integers from 1 up to a given integer n
#include <iostream>
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;

int sum = 0;

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


sum += i;
}

cout << "Sum of numbers from 1 to " << n << " is: " << sum << endl;

return 0;
}

2. How would you use a for loop to calculate the factorial of a given integer n?
#include <iostream>
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;

long long factorial = 1;

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


factorial *= i;
}

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

return 0;
}
3. Printing Multiplication Table
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;

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


cout << n << " * " << i << " = " << n * i << endl;
}

return 0;
}
4. Write a program that finds and prints all prime numbers up to a given integer n
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;

cout << "Prime numbers up to " << n << " are: ";

for (int num = 2; num <= n; num++) {


bool isPrime = true;

for (int i = 2; i <= num / 2; i++) {


if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime) {
cout << num << " ";
}
}

cout << endl;

return 0;
}

5. Write a program that generates the first n numbers in the Fibonacci sequence.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;

int a = 0, b = 1;

cout << "Fibonacci sequence: ";


for (int i = 1; i <= n; i++) {
cout << a << " ";
int next = a + b;
a = b;
b = next;
}
cout << endl;

return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy