Loop-Examples
Loop-Examples
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << "Count: " << i << endl;
i++;
}
return 0;
}
Explanation:
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:
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;
}
Explanation:
#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:
#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;
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 << "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;
return 0;
}
Explanation:
#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;
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;
return 0;
}
Explanation: