0% found this document useful (0 votes)
2 views

Loop-Examples

The document provides an overview of C++ loops, including examples of while and for loops, along with their explanations and outputs. It covers various scenarios such as simple counting, user input handling, input validation, and nested loops for complex patterns and searches. Each example illustrates key concepts and syntax in C++ programming.

Uploaded by

jacorral
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Loop-Examples

The document provides an overview of C++ loops, including examples of while and for loops, along with their explanations and outputs. It covers various scenarios such as simple counting, user input handling, input validation, and nested loops for complex patterns and searches. Each example illustrates key concepts and syntax in C++ programming.

Uploaded by

jacorral
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

C++ Loops - are fundamental control flow structures used to repeat blocks of code.

Example 1: while loop

#include <iostream>
using namespace std;

int main() {
int i = 1;
while (i <= 5) {
cout << "Count: " << i << endl;
i++;
}
return 0;
}

Explanation:

• #include <iostream>: Includes the iostream library, which provides input/output


functionalities like cout (for printing to the console).
• using namespace std;: Brings the standard namespace into scope, allowing you to
use elements like cout directly without the std:: prefix.
• int i = 1;: Initializes an integer variable i to 1. This variable will act as our counter.
• while (i <= 5): This is the while loop condition. The code inside the curly braces will
continue to execute as long as the value of i is less than or equal to 5.
• cout << "Count: " << i << endl;: Prints the current value of i to the console.
• i++;: Increments the value of i by 1. This is crucial; otherwise, the loop would run
indefinitely (an infinite loop).
• return 0;: Indicates that the program executed successfully.

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Example 2: for loop

#include <iostream>
using namespace std;

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

Explanation:
• #include <iostream> and using namespace std;: Same as the previous example.
• for (int i = 1; i <= 5; i++): This is the for loop. It combines initialization, condition
checking, and increment/decrement into a single line:
o int i = 1;: Initializes the loop counter variable i to 1. This is executed only
once at the beginning of the loop.
o i <= 5;: This is the loop condition. The code inside the curly braces will
execute as long as this condition is true.
o i++;: This is the increment statement. It's executed after each iteration of
the loop.
• cout << "Number: " << i << endl;: Prints the current value of i.
• return 0;: Indicates successful execution.

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Example 3: for loop with a different step

#include <iostream>
using namespace std;

int main() {
for (int i = 0; i <= 10; i += 2) {
cout << "Even Number: " << i << endl;
}
return 0;
}

Explanation:

• #include <iostream> and using namespace std;: Same as before.


• for (int i = 0; i <= 10; i += 2): This for loop iterates through even numbers:
o int i = 0;: Initializes i to 0.
o i <= 10;: The loop continues as long as i is less than or equal to 10.
o i += 2;: Increments i by 2 in each iteration.
• cout << "Even Number: " << i << endl;: Prints the current even number.
• return 0;: Successful execution.

Output:
Even Number: 0
Even Number: 2
Even Number: 4
Even Number: 6
Even Number: 8
Even Number: 10
Example 4: while loop with user input

#include <iostream>
using namespace std;

int main() {
int number;
cout << "Enter a positive number (or 0 to exit): ";
cin >> number;

while (number != 0) {
cout << "You entered: " << number << endl;
cout << "Enter another positive number (or 0 to exit): ";
cin >> number;
}

cout << "Exiting program." << endl;


return 0;
}

Explanation:

• #include <iostream> and using namespace std;: Standard setup.


• int number;: Declares an integer variable to store user input.
• cout << "Enter a positive number (or 0 to exit): ";: Prompts the user for input.
• cin >> number;: Reads the integer entered by the user and stores it in the number
variable.
• while (number != 0): The loop continues as long as the entered number is not equal
to 0. This allows the user to control the loop's execution.
• cout << "You entered: " << number << endl;: Prints the number entered by the user.
• cout << "Enter another positive number (or 0 to exit): ";: Prompts for more input.
• cin >> number;: Reads the new input.
• cout << "Exiting program." << endl;: Printed when the user enters 0, terminating the
loop.
• return 0;: Successful execution.
Example 5: Nested for loop

#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; // Move to the next line after the inner loop finishes
}
return 0;
}

Explanation:
• #include <iostream> and using namespace std;: Standard setup.
• for (int i = 1; i <= 3; i++): This is the outer loop. It iterates from i = 1 to 3.
• for (int j = 1; j <= 3; j++): This is the inner loop. It is executed completely for each
iteration of the outer loop. It iterates from j = 1 to 3.
• cout << "(" << i << ", " << j << ") ";: Inside the inner loop, it prints a pair of values: the
current value of the outer loop counter i and the current value of the inner loop
counter j.
• cout << endl;: After the inner loop finishes its iterations (for a specific value of i),
this line prints a newline character, moving the cursor to the next line in the
console output. This ensures that the output is formatted in a grid-like structure.
• return 0;: Successful execution.

Output:

(1, 1) (1, 2) (1, 3)


(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
Example 6: while loop for input validation
This example demonstrates how a while loop can be used to repeatedly ask for input
until the user provides valid data, incorporating error handling for non-integer input.

#include <iostream>
#include <limits> // Required for numeric_limits
using namespace std;

int main() {
int age;
bool validInput = false;

while (!validInput) {
cout << "Enter your age (0-120): ";
cin >> age;

// Check if the input was a valid integer


if (cin.fail()) {
cout << "Invalid input. Please enter a number." << endl;
cin.clear(); // Clear the error flags
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard the invalid input
} else if (age >= 0 && age <= 120) {
cout << "Your age is: " << age << endl;
validInput = true; // Set the flag to exit the loop
} else {
cout << "Age must be between 0 and 120." << endl;
}
}

return 0;
}

Explanation:
• #include <iostream> and using namespace std;: Standard setup for input/output.
• #include <limits>: Includes the <limits> header, which provides access to
information about the limits of data types, specifically used here for error handling
with input streams.
• int age;: Declares an integer variable to store the user's age.
• bool validInput = false;: Initializes a boolean flag to false. This flag will be set to true
when valid input is received, controlling the loop.
• while (!validInput): The loop continues as long as validInput is false.
• cout << "Enter your age (0-120): ";: Prompts the user to enter their age.
• cin >> age;: Attempts to read an integer from the input and store it in the age
variable.
• if (cin.fail()): This checks if the input operation failed (e.g., the user entered text
instead of a number).
o cout << "Invalid input. Please enter a number." << endl;: Displays an error
message.
o cin.clear();: Clears the error flags of the cin stream, allowing further input
operations.
o cin.ignore(numeric_limits<streamsize>::max(), '\n');: Discards any remaining
characters in the input buffer up to the newline character. This is important
to prevent the same invalid input from being processed repeatedly in the
next loop iteration.
• else if (age >= 0 && age <= 120): If the input was a valid integer, this condition
checks if the age is within the acceptable range (0 to 120).
o cout << "Your age is: " << age << endl;: Prints the entered age.
o validInput = true;: Sets the validInput flag to true, which will cause the while
loop to terminate.
• else: If the input was a valid integer but outside the allowed range.
o cout << "Age must be between 0 and 120." << endl;: Displays an error message.
• return 0;: Successful execution.
Example 7: for loop to calculate the sum of numbers in a range
This example demonstrates using a for loop to perform a calculation over a user-defined
range of numbers, including basic input validation.

#include <iostream>
using namespace std;

int main() {
int start, end;
int sum = 0;

cout << "Enter the starting number: ";


cin >> start;
cout << "Enter the ending number: ";
cin >> end;

if (start > end) {


cout << "Error: Starting number cannot be greater than the ending number." << endl;
return 1; // Indicate an error
}

for (int i = start; i <= end; i++) {


sum += i; // Add the current number to the sum
}

cout << "The sum of numbers from " << start << " to " << end << " is: " << sum << endl;

return 0;
}

Explanation:
• #include <iostream> and using namespace std;: Standard setup.
• int start, end;: Declares integer variables to store the starting and ending numbers
of the range.
• int sum = 0;: Initializes an integer variable sum to 0. This variable will accumulate
the sum of the numbers.
• Prompts for and reads the starting and ending numbers from the user.
• if (start > end): Checks if the starting number is greater than the ending number. If
it is, it prints an error message and exits the program with a non-zero return code
(typically indicating an error).
• for (int i = start; i <= end; i++): This for loop iterates through the numbers from start to
end (inclusive).
o sum += i;: In each iteration, the current number i is added to the sum
variable. This is shorthand for sum = sum + i;.
• cout << "The sum of numbers from " << start << " to " << end << " is: " << sum << endl;:
Prints the calculated sum.
• return 0;: Successful execution.
Example 8: Nested for loop to create a pattern
This example uses nested for loops to generate a more complex text-based pattern (an
upward-facing pyramid). The logic involves carefully controlling the number of spaces
and asterisks printed in each row based on the current row number.

#include <iostream>
using namespace std;

int main() {
int rows;

cout << "Enter the number of rows for the pattern: ";
cin >> rows;

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


// Inner loop to print spaces
for (int j = 1; j <= rows - i; j++) {
cout << " ";
}
// Inner loop to print asterisks
for (int k = 1; k <= 2 * i - 1; k++) {
cout << "*";
}
cout << endl; // Move to the next line
}

return 0;
}

Explanation:

• #include <iostream> and using namespace std;: Standard setup.


• int rows;: Declares an integer variable to store the number of rows for the pattern.
• Prompts the user to enter the number of rows.
• for (int i = 1; i <= rows; i++): The outer loop iterates through each row of the pattern.
• for (int j = 1; j <= rows - i; j++): The first inner loop is responsible for printing spaces
at the beginning of each row. The number of spaces decreases as the row
number i increases, creating the pyramid shape.
• cout << " ";: Prints a single space.
• for (int k = 1; k <= 2 * i - 1; k++): The second inner loop is responsible for printing the
asterisks in each row. The number of asterisks increases as the row number i
increases, following the formula 2 * i - 1.
• cout << "*";: Prints a single asterisk.
• cout << endl;: Moves the cursor to the next line after all the spaces and asterisks
for the current row have been printed.
• return 0;: Successful execution.
Example 9: Using a while loop with nested for loops for a complex search
This example combines a while loop for overall control with nested for loops for
searching within a more complex data structure. The user interaction and the possibility
of multiple search attempts add to the difficulty.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
vector<vector<string>> data = {
{"apple", "banana", "cherry"},
{"melon", "santol", "avocado"},
{"grape", "mango", "kiwi", "lemon"}
};

string searchTerm;
bool found = false;
int rowIndex = -1, colIndex = -1;
int outerLoopCounter = 0;
int innerLoopCounter = 0;

cout << "Enter the fruit to search for: ";


cin >> searchTerm;

// Outer while loop to control the search and allow re-attempts


while (!found) {
outerLoopCounter++;
found = false; // Reset found for each attempt

// Nested for loops to iterate through the 2D vector


for (int i = 0; i < data.size(); ++i) {
innerLoopCounter = 0;
for (int j = 0; j < data[i].size(); ++j) {
innerLoopCounter++;
if (data[i][j] == searchTerm) {
found = true;
rowIndex = i;
colIndex = j;
break; // Exit the inner loop once found
}
}
if (found) {
break; // Exit the outer loop once found
}
}

if (found) {
cout << searchTerm << " found at row " << rowIndex << ", column " << colIndex << endl;
cout << "Outer loop iterations: " << outerLoopCounter << endl;
cout << "Total inner loop iterations: " << (outerLoopCounter * innerLoopCounter) << endl;
} else {
cout << searchTerm << " not found in this attempt." << endl;
cout << "Would you like to try again? (yes/no): ";
string response;
cin >> response;
if (response != "yes") {
break; // Exit the while loop if the user doesn't want to retry
}
}
}

return 0;
}

Explanation:
• #include <iostream>, #include <vector>, #include <string>: Includes necessary headers
for input/output, dynamic arrays (vectors), and string manipulation.
• vector<vector<string>> data: Creates a 2D vector (a vector of vectors) to store
strings representing fruit names. This simulates a more complex data structure.
• The code prompts the user for a searchTerm.
• The while (!found) loop acts as a control mechanism, allowing the user to
search multiple times if the fruit is not found initially.
• Nested for loops iterate through the data vector. The outer loop iterates
through the rows, and the inner loop iterates through the elements (fruit names)
in each row.
• if (data[i][j] == searchTerm): Checks if the current element matches the searchTerm.
• If found, the found flag is set to true, and the row and column indices are
recorded. break statements are used to exit both the inner and outer for
loops to optimize the search once the item is found.
• If the searchTerm is not found in an attempt, the user is asked if they want to
try again.
• The code also tracks the number of iterations for both the outer and inner
loops to demonstrate the execution flow.
Example 10: Using a for loop with complex conditional logic and nested loops for
pattern generation with variations
This example uses nested for loops to generate a pattern with a more intricate shape
and introduces conditional logic to vary the output based on row and column indices,
making it more challenging to understand and implement correctly.

#include <iostream>
using namespace std;

int main() {
int rows;
char patternChar = '*';
bool alternate = true;

cout << "Enter the number of rows for the pattern: ";
cin >> rows;
cout << "Do you want to alternate the pattern character? (1 for yes, 0 for no): ";
cin >> alternate;

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


for (int j = 1; j <= rows; ++j) {
// Complex condition to determine what to print
if (i == 1 || i == rows || j == 1 || j == rows || i == j || i + j == rows + 1) {
if (alternate && (i + j) % 2 == 0) {
cout << "#";
} else {
cout << patternChar;
}
} else {
cout << " ";
}
}
cout << endl;
}

return 0;
}

Explanation:

• #include <iostream> and using namespace std;: Standard setup.


• The code takes input for the number of rows and whether to alternate the
pattern character.
• The outer for loop iterates through the rows.
• The inner for loop iterates through the columns.
• The if condition within the inner loop is complex:
o i == 1 || i == rows || j == 1 || j == rows: Checks if the current position is on the
border of the pattern.
o i == j: Checks if the current position is on the main diagonal.
o i + j == rows + 1: Checks if the current position is on the anti-diagonal.
o If any of these conditions are true, a pattern character is printed.
• if (alternate && (i + j) % 2 == 0): If the alternate flag is true and the sum of the row and
column indices is even, a different character (#) is printed, creating an alternating
pattern.
• else { cout << " "; }: If the complex condition is false, a space is printed.

You might also like