C++ Loops Interview Questions
All Types of Loops: for, while, do-while, nested loops
Basic Level (15 Questions)
What are the three main types of loops in C++?
C++ provides three main loop constructs:
| Loop Type | Syntax | When to Use |
|---|---|---|
| for loop | for(init; condition; increment) | Known number of iterations |
| while loop | while(condition) | Unknown iterations, condition check first |
| do-while loop | do {...} while(condition); | Execute at least once, condition check last |
What is the basic syntax and flow of a for loop?
// for loop syntax
for (initialization; condition; increment/decrement) {
// Loop body - executes while condition is true
}
// Example: Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
// Output: 1 2 3 4 5
for (initialization; condition; increment/decrement) {
// Loop body - executes while condition is true
}
// Example: Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
// Output: 1 2 3 4 5
What is the difference between while and do-while loops?
Key difference: When condition is checked.
// while - condition check FIRST
int count = 5;
while (count < 5) {
cout << count << " ";
count++;
}
// No output - condition false initially
// do-while - condition check LAST
count = 5;
do {
cout << count << " ";
count++;
} while (count < 5);
// Output: 5 - executes at least once
int count = 5;
while (count < 5) {
cout << count << " ";
count++;
}
// No output - condition false initially
// do-while - condition check LAST
count = 5;
do {
cout << count << " ";
count++;
} while (count < 5);
// Output: 5 - executes at least once
What are infinite loops and how to create/avoid them?
Infinite loops run forever (until program is terminated):
// Common infinite loop patterns
// 1. Missing increment
for (int i = 0; i < 10; ) { // i never increments
cout << "Infinite!";
}
// 2. Condition always true
while (true) {
cout << "Running forever";
}
// 3. No condition change
int x = 5;
while (x > 0) {
cout << x; // x never changes
}
// 1. Missing increment
for (int i = 0; i < 10; ) { // i never increments
cout << "Infinite!";
}
// 2. Condition always true
while (true) {
cout << "Running forever";
}
// 3. No condition change
int x = 5;
while (x > 0) {
cout << x; // x never changes
}
What are nested loops and provide an example?
Nested loops: loop inside another loop:
// Print multiplication table (nested for loops)
for (int i = 1; i <= 10; i++) { // Outer loop
for (int j = 1; j <= 10; j++) { // Inner loop
cout << i * j << " ";
}
cout << endl;
}
// Total iterations: outer * inner = 10 * 10 = 100
for (int i = 1; i <= 10; i++) { // Outer loop
for (int j = 1; j <= 10; j++) { // Inner loop
cout << i * j << " ";
}
cout << endl;
}
// Total iterations: outer * inner = 10 * 10 = 100
What are loop control statements: break, continue, goto?
// break - exit loop immediately
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop when i == 5
}
cout << i << " ";
}
// Output: 1 2 3 4
// continue - skip current iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip iteration when i == 3
}
cout << i << " ";
}
// Output: 1 2 4 5
// goto - jump to label (avoid when possible)
int i = 0;
start:
cout << i++ << " ";
if (i < 5) goto start;
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop when i == 5
}
cout << i << " ";
}
// Output: 1 2 3 4
// continue - skip current iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip iteration when i == 3
}
cout << i << " ";
}
// Output: 1 2 4 5
// goto - jump to label (avoid when possible)
int i = 0;
start:
cout << i++ << " ";
if (i < 5) goto start;
When to use for vs while vs do-while loops?
| Loop Type | Best Use Case | Example |
|---|---|---|
| for | Known number of iterations | Array traversal, fixed count |
| while | Condition-based, may be zero iterations | Reading until EOF, user input validation |
| do-while | Must execute at least once | Menu-driven programs, retry logic |
What is the range-based for loop in C++11?
Range-based for loop (C++11) simplifies iteration over containers:
// Traditional for loop
int arr[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
// Range-based for loop (C++11)
for (int num : arr) {
cout << num << " ";
}
// With auto keyword
for (auto num : arr) {
cout << num << " ";
}
// Reference to modify elements
for (int &num : arr) {
num *= 2; // Double each element
}
int arr[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
// Range-based for loop (C++11)
for (int num : arr) {
cout << num << " ";
}
// With auto keyword
for (auto num : arr) {
cout << num << " ";
}
// Reference to modify elements
for (int &num : arr) {
num *= 2; // Double each element
}
How to calculate factorial using different loops?
// Factorial using for loop
int n = 5, factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
// Factorial using while loop
factorial = 1;
int i = 1;
while (i <= n) {
factorial *= i;
i++;
}
// Factorial using do-while loop
factorial = 1;
i = 1;
do {
factorial *= i;
i++;
} while (i <= n);
int n = 5, factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
// Factorial using while loop
factorial = 1;
int i = 1;
while (i <= n) {
factorial *= i;
i++;
}
// Factorial using do-while loop
factorial = 1;
i = 1;
do {
factorial *= i;
i++;
} while (i <= n);
What are common loop errors and how to avoid them?
Common errors:
// 1. Off-by-one errors
// Wrong: Starts at 0, ends at 10 (11 iterations)
for (int i = 0; i <= 10; i++) {
cout << i << " ";
}
// Correct: 10 iterations (0-9 or 1-10)
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
// 2. Modifying loop variable in body
for (int i = 0; i < 10; i++) {
cout << i << " ";
i++; // Double increment!
}
// 3. Floating point counters
// Avoid: May cause infinite loops due to precision
for (double d = 0.0; d != 1.0; d += 0.1) {
cout << d << " ";
}
// Wrong: Starts at 0, ends at 10 (11 iterations)
for (int i = 0; i <= 10; i++) {
cout << i << " ";
}
// Correct: 10 iterations (0-9 or 1-10)
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
// 2. Modifying loop variable in body
for (int i = 0; i < 10; i++) {
cout << i << " ";
i++; // Double increment!
}
// 3. Floating point counters
// Avoid: May cause infinite loops due to precision
for (double d = 0.0; d != 1.0; d += 0.1) {
cout << d << " ";
}
How to implement Fibonacci series using loops?
// Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13...
int n = 10;
int t1 = 0, t2 = 1, nextTerm;
cout << "Fibonacci Series: " << t1 << ", " << t2;
// Using for loop
for (int i = 3; i <= n; i++) {
nextTerm = t1 + t2;
cout << ", " << nextTerm;
t1 = t2;
t2 = nextTerm;
}
// Using while loop
t1 = 0; t2 = 1;
int count = 2;
cout << " Fibonacci: " << t1 << ", " << t2;
while (count < n) {
nextTerm = t1 + t2;
cout << ", " << nextTerm;
t1 = t2;
t2 = nextTerm;
count++;
}
int n = 10;
int t1 = 0, t2 = 1, nextTerm;
cout << "Fibonacci Series: " << t1 << ", " << t2;
// Using for loop
for (int i = 3; i <= n; i++) {
nextTerm = t1 + t2;
cout << ", " << nextTerm;
t1 = t2;
t2 = nextTerm;
}
// Using while loop
t1 = 0; t2 = 1;
int count = 2;
cout << " Fibonacci: " << t1 << ", " << t2;
while (count < n) {
nextTerm = t1 + t2;
cout << ", " << nextTerm;
t1 = t2;
t2 = nextTerm;
count++;
}
What is loop optimization and best practices?
Optimization techniques:
// 1. Move invariant code out of loop
// Bad: Calculation repeated each iteration
for (int i = 0; i < n; i++) {
int result = expensiveCalculation() * i;
}
// Good: Calculate once outside loop
int base = expensiveCalculation();
for (int i = 0; i < n; i++) {
int result = base * i;
}
// 2. Use prefix increment (++i) vs postfix (i++)
// ++i is generally more efficient for objects
for (int i = 0; i < n; ++i) { // Use prefix
// loop body
}
// 3. Minimize loop overhead
// Bad: Function call in condition
for (int i = 0; i < getSize(); i++) {
// getSize() called each iteration
}
// Good: Cache value
int size = getSize();
for (int i = 0; i < size; i++) {
// loop body
}
// Bad: Calculation repeated each iteration
for (int i = 0; i < n; i++) {
int result = expensiveCalculation() * i;
}
// Good: Calculate once outside loop
int base = expensiveCalculation();
for (int i = 0; i < n; i++) {
int result = base * i;
}
// 2. Use prefix increment (++i) vs postfix (i++)
// ++i is generally more efficient for objects
for (int i = 0; i < n; ++i) { // Use prefix
// loop body
}
// 3. Minimize loop overhead
// Bad: Function call in condition
for (int i = 0; i < getSize(); i++) {
// getSize() called each iteration
}
// Good: Cache value
int size = getSize();
for (int i = 0; i < size; i++) {
// loop body
}
How to print patterns using nested loops?
// Right triangle pattern
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
/* Output:
*
* *
* * *
* * * *
* * * * *
// Pyramid pattern
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int space = 1; space <= rows - i; space++) {
cout << " ";
}
// Print stars
for (int j = 1; j <= 2*i-1; j++) {
cout << "* ";
}
cout << endl;
}
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
/* Output:
*
* *
* * *
* * * *
* * * * *
// Pyramid pattern
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int space = 1; space <= rows - i; space++) {
cout << " ";
}
// Print stars
for (int j = 1; j <= 2*i-1; j++) {
cout << "* ";
}
cout << endl;
}
What are loop variables and their scope?
// Loop variable declared inside for - limited scope
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
// i is NOT accessible here (out of scope)
// Loop variable declared outside - broader scope
int j;
for (j = 0; j < 5; j++) {
cout << j << " ";
}
// j IS accessible here (scope: whole function)
cout << " Final j = " << j;
// C++17: Initialization in condition
for (int i = 0, j = 10; i < j; i++, j--) {
cout << i << " " << j << endl;
}
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
// i is NOT accessible here (out of scope)
// Loop variable declared outside - broader scope
int j;
for (j = 0; j < 5; j++) {
cout << j << " ";
}
// j IS accessible here (scope: whole function)
cout << " Final j = " << j;
// C++17: Initialization in condition
for (int i = 0, j = 10; i < j; i++, j--) {
cout << i << " " << j << endl;
}
How to implement prime number check using loops?
// Check if number is prime
int num;
cout << "Enter a number: ";
cin >> num;
bool isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
// Check divisors from 2 to sqrt(num)
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = false;
break; // No need to check further
}
}
}
if (isPrime) {
cout << num << " is prime";
} else {
cout << num << " is not prime";
}
int num;
cout << "Enter a number: ";
cin >> num;
bool isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
// Check divisors from 2 to sqrt(num)
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = false;
break; // No need to check further
}
}
}
if (isPrime) {
cout << num << " is prime";
} else {
cout << num << " is not prime";
}
Tricky Level (10 Questions)
What is the difference between entry-controlled and exit-controlled loops?
| Type | Loops | Condition Check | Minimum Executions |
|---|---|---|---|
| Entry-controlled | for, while | Before loop body | 0 (may not execute at all) |
| Exit-controlled | do-while | After loop body | 1 (always executes at least once) |
How to implement bubble sort using nested loops?
// Bubble sort algorithm
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
// Outer loop: passes through array
for (int i = 0; i < n-1; i++) {
// Inner loop: compare adjacent elements
for (int j = 0; j < n-i-1; j++) {
// Swap if in wrong order
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Print sorted array
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
// Outer loop: passes through array
for (int i = 0; i < n-1; i++) {
// Inner loop: compare adjacent elements
for (int j = 0; j < n-i-1; j++) {
// Swap if in wrong order
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Print sorted array
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
What are loop variants and invariants?
// Loop invariant: true before and after each iteration
int sum = 0;
// Invariant: sum = sum of processed elements
for (int i = 1; i <= n; i++) {
// Before iteration: sum = sum of 1..(i-1)
sum += i;
// After iteration: sum = sum of 1..i
}
// Loop variant: changes each iteration, ensures termination
for (int i = n; i > 0; i--) {
// Variant: i decreases by 1 each iteration
// Ensures loop terminates when i == 0
cout << i << " ";
}
int sum = 0;
// Invariant: sum = sum of processed elements
for (int i = 1; i <= n; i++) {
// Before iteration: sum = sum of 1..(i-1)
sum += i;
// After iteration: sum = sum of 1..i
}
// Loop variant: changes each iteration, ensures termination
for (int i = n; i > 0; i--) {
// Variant: i decreases by 1 each iteration
// Ensures loop terminates when i == 0
cout << i << " ";
}
How to handle user input validation with loops?
// Input validation with do-while loop
int age;
bool validInput = false;
do {
cout << "Enter age (0-120): ";
cin >> age;
if (cin.fail()) {
cout << "Invalid input! Please enter a number." << endl;
cin.clear();
cin.ignore(1000, ' ');
} else if (age < 0 || age > 120) {
cout << "Age must be between 0 and 120!" << endl;
} else {
validInput = true;
}
} while (!validInput);
cout << "Valid age entered: " << age;
int age;
bool validInput = false;
do {
cout << "Enter age (0-120): ";
cin >> age;
if (cin.fail()) {
cout << "Invalid input! Please enter a number." << endl;
cin.clear();
cin.ignore(1000, ' ');
} else if (age < 0 || age > 120) {
cout << "Age must be between 0 and 120!" << endl;
} else {
validInput = true;
}
} while (!validInput);
cout << "Valid age entered: " << age;
What are the performance considerations for nested loops?
// Time complexity examples
// O(n) - Single loop
for (int i = 0; i < n; i++) {
// n iterations
}
// O(n²) - Nested loops (worst case)
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// n * n = n² iterations
}
}
// O(n³) - Triple nested loops
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
// n * n * n = n³ iterations
}
}
}
// Optimization: Reduce nesting when possible
// Break early when condition met
// Use more efficient algorithms
// O(n) - Single loop
for (int i = 0; i < n; i++) {
// n iterations
}
// O(n²) - Nested loops (worst case)
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// n * n = n² iterations
}
}
// O(n³) - Triple nested loops
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
// n * n * n = n³ iterations
}
}
}
// Optimization: Reduce nesting when possible
// Break early when condition met
// Use more efficient algorithms
What is a range-based for loop?
for (auto x : container) iterates over elements using begin/end. Works with arrays, STL containers, and initializer lists.
Why can `for(;;)` be preferred over `while(1)`?
Both create infinite loops; style choice. Some teams prefer for(;;) to signal intentional non-terminating server/event loops.
What is loop invariant code motion?
Compiler optimization hoisting computations that do not change per iteration out of the loop body for speed.
Difference between `break` and `return` inside a loop?
break exits only the innermost loop; return exits the entire function immediately.
Can you use `goto` to exit nested loops?
Yes, though rarely recommended; labeled goto can jump out of multiple nested loops when structured breaks are awkward.
Note: These questions cover core interview topics. Pair with the tutorial and MCQ quiz for this section. This page lists 15 basic and 10 tricky questions—use the tutorial and MCQ links above and below.