PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » C++ Exercises » C++ Loops Exercises: 30+ Coding Problems with Solutions

C++ Loops Exercises: 30+ Coding Problems with Solutions

Updated on: January 7, 2026 | Leave a Comment

Loops and control flow are foundational constructs essential for processing data, validating input, and performing complex operations. Proficiency in for, while, and nested loops is crucial.

This article provides 30+ C++ programming exercises focusing entirely on loops and control flow statements. Each exercise includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.

Also, See: C++ Exercises with 10 topic-wise sets and 300+ practice questions.

What You Will Practice

30 coding challenges cover a range of C++ loop applications, categorized as follows:

  • Loops Fundamentals: Sequences, sums, multiplication tables, factorials, and powers.
  • Number Theory: Checking for prime and Armstrong numbers, Fibonacci series, finding GCD/LCM.
  • Digit Operations: Counting digits, reversing numbers, palindromes, and sum of digits.
  • Data Structures: Calculating array sums, finding min/max elements, counting vowels/consonants.
  • Patterns: Generating geometric shapes (squares, triangles), Floyd’s, Pascal’s triangles, and multiplication charts.
+ Table Of Contents

Table of contents

  • Exercise 1: Print Numbers From 1 to N
  • Exercise 2: Print Even Numbers Between 1-20
  • Exercise 3: Sum of N Natural Numbers
  • Exercise 4: Separate Even/Odd Sums
  • Exercise 5: Calculate Factorial Of a Number
  • Exercise 6: Multiplication Table of Number
  • Exercise 7: Count Digits In a Number
  • Exercise 8: Reverse Number
  • Exercise 9: Palindrome Number
  • Exercise 10: Sum of Digits of a Number
  • Exercise 11: Power of a Number
  • Exercise 12: Check Armstrong Number
  • Exercise 13: Fibonacci Series up to N terms
  • Exercise 14: GCD (HCF) of Two Numbers
  • Exercise 15: LCM of Two Numbers
  • Exercise 16: Count Vowels/Consonants in a String
  • Exercise 17: Array Element Sum Using Loop
  • Exercise 18: Find Array Max and Min
  • Exercise 19: Check Prime Number
  • Exercise 20: Print All Primes in Range (1-100)
  • Exercise 21: Square Pattern of Stars ( * )
  • Exercise 22: Right triangle Pattern of Stars
  • Exercise 23: Print Inverted Right Triangle Pattern
  • Exercise 24: Print Pyramid Pattern of Stars
  • Exercise 25: Print Inverted Pyramid Pattern
  • Exercise 26: Full Multiplication Chart Using Nested Loops
  • Exercise 27: Pattern of Numbers (1 to N)
  • Exercise 28: Number Pattern (Repeating Row Number)
  • Exercise 29: Number Pattern (Inverted Right Triangle of Decreasing Numbers)
  • Exercise 30: Password Attempt Simulation
  • Exercise 31: Reverse Word Order in a Sentence

Exercise 1: Print Numbers From 1 to N

Practice Problem: Develop a C++ program that prints all numbers from 1 up to and including N using a for loop.

Given:

int N = 10;Code language: C++ (cpp)

Expected Output:

Numbers from 1 to 10 are: 1 2 3 4 5 6 7 8 9 10 
+ Hint
  • Initialize the loop control variable, say i, to 1.
  • The loop condition should be i≤N.
  • Increment i by 1 in each iteration.
+ Show Solution
#include <iostream>

int main() {
    std::cout << "Numbers between 1 and 10 are:"<<std::endl;
    
    // Method 2: Start at 2 and increment by 2
    for (int i = 1; i <= 10; i++) {
        std::cout << i << " ";
    }
    
    std::cout << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The program starts by reading the limit N from the user. The for loop is structured with three parts:

  1. Initialization: int i = 1 sets the counter to the starting value.
  2. Condition: i <= N ensures the loop continues as long as the counter is less than or equal to the target number.
  3. Update: ++i increments the counter by 1 after each iteration. Inside the loop, std::cout << i << " "; prints the current value of the counter, effectively printing every number from 1 to N.

Exercise 2: Print Even Numbers Between 1-20

Practice Problem: Write a C++ program that uses a for loop to display all even numbers in the range from 1 to 20 (inclusive).

Expected Output:

Even numbers between 1 and 20 are:
2 4 6 8 10 12 14 16 18 20
+ Hint

There are two common methods:

  1. Iterate from 1 to 100 and use the modulo operator (%) to check if i % 2 == 0.
  2. Or Start the loop at 2 and increment the counter by 2 in each iteration (i += 2).
+ Show Solution
#include <iostream>

int main() {
    std::cout << "Even numbers between 1 and 20 are:\n";
    
    // Method 2: Start at 2 and increment by 2
    for (int i = 2; i <= 20; i += 2) {
        std::cout << i << " ";
    }
    
    std::cout << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • This solution uses the more efficient approach (Method 2).
  • The for loop is initialized with int i = 2, as 2 is the first even number in the range. The condition i <= 20 ensures we don’t exceed the limit.
  • Crucially, the update statement is i += 2, which means the counter skips all odd numbers, jumping directly from one even number to the next (e.g., 2,4,6,8,…). This reduces the total number of loop iterations by half compared to checking every number.

Exercise 3: Sum of N Natural Numbers

Practice Problem: Write a C++ program that calculates the sum of all natural numbers from 1 to N using a while loop.

Given:

int N = 10;Code language: C++ (cpp)

Expected Output:

The sum of the first 10 natural numbers is: 55
+ Hint
  • Use a variable, say sum, initialized to 0. Use a counter variable, say i, initialized to 1.
  • The while loop should continue as long as i <= N.
  • Inside the loop, update sum = sum + i and increment i.
+ Show Solution
#include <iostream>

int main() {
    int N = 10;
    long long sum = 0; // Use long long for the sum to prevent overflow for large N
    int i = 1;
    
    // The 'while' loop runs as long as the counter 'i' is less than or equal to N
    while (i <= N) {
        sum += i; // Add the current number to the running sum
        i++;      // Increment the counter
    }
    
    std::cout << "The sum of the first " << N << " natural numbers is: " << sum << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

A while loop is used here. We initialize sum to 0 and the counter i to 1. The loop condition i <= N checks if there are still numbers to be added. Inside the loop:

  1. sum += i; adds the current value of i to the total sum.
  2. i++; increments the counter. This is crucial for two reasons: it moves to the next number, and it ensures the loop condition will eventually become false, preventing an infinite loop. Once i exceeds N, the loop terminates, and the final sum is printed.

Exercise 4: Separate Even/Odd Sums

Practice Problem: Write a C++ program that calculates and displays the separate sums of all even numbers and all odd numbers between 1 and N (inclusive).

Given:

int N = 10;Code language: C++ (cpp)

Expected Output:

Results up to 10:
Sum of even numbers: 30
Sum of odd numbers: 25
+ Hint
  • Use one loop to iterate from 1 to N.
  • Inside the loop, use an if-else statement with the modulo operator (%) to check if the current number is even (i % 2 == 0) or odd, and add it to the corresponding sum variable (evenSum or oddSum).
+ Show Solution
#include <iostream>

int main() {
    int N = 10;
    long long evenSum = 0;
    long long oddSum = 0;
    
    // Loop from 1 to N
    for (int i = 1; i <= N; ++i) {
        // Check if the current number 'i' is even or odd
        if (i % 2 == 0) {
            evenSum += i;
        } else {
            oddSum += i;
        }
    }
    
    std::cout << "Results up to " << N << ":" << std::endl;
    std::cout << "Sum of even numbers: " << evenSum << std::endl;
    std::cout << "Sum of odd numbers: " << oddSum << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The program initializes two accumulator variables, evenSum and oddSum, to 0. A for loop iterates through every number i from 1 to N. Inside the loop, the expression i % 2 == 0 is checked.

  • If the remainder of i divided by 2 is 0, the number is even, and it’s added to evenSum.
  • Otherwise (in the else block), the number is odd, and it’s added to oddSum. This single loop efficiently classifies and sums all the numbers in the given range.

Exercise 5: Calculate Factorial Of a Number

Practice Problem: Develop a C++ program that calculates the factorial of a number (n!) using a loop.

Factorial: The factorial of a number is the product of all positive integers less than or equal to that number. It is denoted by an exclamation mark (!) after the number. For example, (4!) is (4*3*2*1=24). 

Given:

int N = 5;Code language: C++ (cpp)

Expected Output:

5! (Factorial of 5) is: 120
+ Hint
  • Initialize a variable, say factorial, to 1.
  • Use a for loop that iterates from 1 up to n, multiplying factorial by the current loop counter in each iteration: factorial = factorial * i.
  • Use a data type like long long for the result to handle larger factorials.
+ Show Solution
#include <iostream>

int main() {
    int n = 5;
    long long factorial = 1; // Start with 1 as 0! = 1 and it's the multiplication identity
    
    // Handle the special case for 0!
    if (n == 0) {
        // Factorial is already 1, nothing more to do
    } else {
        // Loop from 1 up to n
        for (int i = 1; i <= n; ++i) {
            factorial *= i; // Equivalent to: factorial = factorial * i;
        }
    }
    
    std::cout << n << "! (Factorial of " << n << ") is: " << factorial << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The program handles input validation and the edge case where n=0 (where 0!=1). For any n>0, the for loop executes. The variable factorial is initialized to 1. The loop runs from i=1 to i=n.

  • In the first iteration, factorial becomes 1×1=1.
  • In the second, factorial becomes 1×2=2.
  • In the third, factorial becomes 2×3=6. …and so on, accumulating the product until the loop finishes. Using long long for the factorial variable helps accommodate the rapid growth of factorials (e.g., 13! exceeds the capacity of a standard 32-bit int).

Exercise 6: Multiplication Table of Number

Practice Problem: Write a C++ program that prints its multiplication table of a given number from 1 to 10.

Given:

int N = 2;Code language: C++ (cpp)

Expected Output:

Multiplication Table for 2 (1 to 10):
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
...
2 x 10 = 20
+ Hint
  • Use a for loop to iterate a counter variable i from 1 to 10.
  • Inside the loop, calculate the product as number * i and print the result in the format number x i = product.
+ Show Solution
#include <iostream>

int main() {
    int number = 2;    
    std::cout << "Multiplication Table for " << number << " (1 to 10):" <<std::endl;
    
    // Loop from 1 to 10
    for (int i = 1; i <= 10; ++i) {
        int product = number * i;
        
        // Print the result in the format: 5 x 1 = 5
        std::cout << number << " x " << i << " = " << product << std::endl;
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The program reads the number for which the table is needed. The for loop controls the multiplier i, which ranges from 1 to 10. In each iteration:

  1. The product is calculated by multiplying the user’s number by the current loop multiplier i.
  2. std::cout prints the full line in the standard multiplication table format. The loop ensures that the calculation and output are performed exactly 10 times, covering the full range requested.

Exercise 7: Count Digits In a Number

Practice Problem: Develop a C++ program that counts the total number of digits it contains using a while loop.

Given:

long long number = 7568;Code language: C++ (cpp)

Expected Output:

Enter an integer: 7568 
The number 7568 has 4 digits.
+ Hint
  • Use a counter initialized to 0.
  • The while loop should continue as long as the number is not 0.
  • Inside the loop, increment the counter and update the number by performing integer division by 10 (number /= 10).
  • Handle the case of 0 as input separately.
+ Show Solution
#include <iostream>

int main() {
    long long number = 7568;
    int count = 0;
    
    // Handle the special case where the input is 0
    if (number == 0) {
        count = 1;
    } else {
        // Use the absolute value to handle negative numbers (e.g., -123 has 3 digits)
        long long tempNumber = std::abs(number);
        
        // Loop continues until the number is reduced to 0
        while (tempNumber > 0) {
            tempNumber /= 10; // Remove the last digit
            count++;          // Increment the digit count
        }
    }
    
    std::cout << "The number " << number << " has " << count << " digits." << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The solution uses a while loop to repeatedly remove the last digit of the number until the number becomes 0.

  1. The initial check handles the input 0, which has 1 digit.
  2. For non-zero numbers, the absolute value is used to correctly count digits for negative inputs (e.g., −7568).
  3. The condition while (tempNumber > 0) keeps the loop running.
  4. The update tempNumber /= 10 is integer division; for 7568, it becomes 756, then 75, then 7, then 0.
  5. The counter count is incremented in each step, representing the digit that was just “removed.”

Exercise 8: Reverse Number

Practice Problem: Write a C++ program to reverse a integer number using a loop.

Given:

int N = 7568;Code language: C++ (cpp)

Expected Output:

The reverse of 7568 is: 8657
+ Hint

Use a while loop that continues as long as the original number is greater than 0. In each iteration:

  1. Extract the last digit using the modulo operator: digit = number % 10.
  2. Construct the reversed number: reversedNumber = reversedNumber * 10 + digit.
  3. Update the original number: number /= 10.
+ Show Solution
#include <iostream>

int main() {
    int originalNumber = 7568;
    long long reversedNumber = 0; // Use long long for safety
    
    int tempNumber = originalNumber; // Work with a copy
    
    // Loop until all digits are processed
    while (tempNumber != 0) {
        int digit = tempNumber % 10;         // Get the last digit
        reversedNumber = reversedNumber * 10 + digit; // Build the reversed number
        tempNumber /= 10;                    // Remove the last digit
    }
    
    std::cout << "The reverse of " << originalNumber << " is: " << reversedNumber << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This C++ program takes an integer input from the user and prints its reverse.

  1. It first asks the user to enter an integer and validates the input.
  2. It then copies that number into a temporary variable tempNumber.
  3. Inside a while loop, it repeatedly extracts the last digit using % 10, adds it to reversedNumber (after shifting existing digits left by multiplying by 10), and removes the last digit from tempNumber using /= 10.
  4. The loop continues until all digits are processed.
  5. Finally, it displays the reversed number.
  6. If input = 1234, then output = 4321.

Exercise 9: Palindrome Number

Practice Problem: Write a C++ program that determines whether a given integer is a palindrome (i.e., it reads the same forwards and backwards).

Given:

int N = 121;Code language: C++ (cpp)

Expected Output:

121 is a palindrome.
+ Hint
  • This problem builds directly on Exercise 8.
  • Store the original number in a separate variable. Use the loop logic from Exercise 8 to calculate the reversed number.
  • Finally, check if the reversedNumber is equal to the originalNumber.
+ Show Solution
#include <iostream>

int main() {
    int n = 121;
    long long reversedN = 0;
    
    int originalN = n; // Store the original number for comparison
    int tempN = n;     // Use a temporary variable for manipulation
    
    // Handle negative numbers (e.g., -121 is usually not considered a palindrome)
    if (n < 0) {
        tempN = -n;
        originalN = -n;
    }
    
    // Loop to reverse the number
    while (tempN != 0) {
        int digit = tempN % 10;
        reversedN = reversedN * 10 + digit;
        tempN /= 10;
    }
    
    // Compare the original and reversed numbers
    if (reversedN == originalN) {
        std::cout << originalN << " is a **palindrome**." << std::endl;
    } else {
        std::cout << originalN << " is **not** a palindrome." << std::endl;
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • This solution first copies the input n into originalN (which must not be changed) and tempN (which the loop modifies).
  • The while loop is identical to the one used in the reversal problem (Exercise 8). After the loop completes, reversedN holds the reversed version of the input.
  • The program then uses a simple if statement to compare reversedN with the invariant originalN. If they are equal, the number is a palindrome (e.g., 121 reversed is 121).

Exercise 10: Sum of Digits of a Number

Practice Problem: Write a C++ program that calculates the sum of all digits of a number using a loop.

Given:

int N = 1234;Code language: C++ (cpp)

Expected Output:

The sum of the digits of 1234 is: 10
+ Hint

Use a while loop that continues as long as the number is not 0. Inside the loop:

  1. Extract the last digit using the modulo operator: digit = number % 10.
  2. Add the digit to a running sum variable, initialized to 0.
  3. Update the number by removing the last digit: number /= 10.
+ Show Solution
#include <iostream>

int main() {
    int number = 1234;
    int sumOfDigits = 0;
    
    // Use the absolute value of the number for the calculation
    int tempNumber = std::abs(number);
    
    // Loop until the temporary number is reduced to 0
    while (tempNumber > 0) {
        int digit = tempNumber % 10; // Extract the last digit
        sumOfDigits += digit;        // Add the digit to the sum
        tempNumber /= 10;            // Remove the last digit
    }
    
    std::cout << "The sum of the digits of " << number << " is: " << sumOfDigits << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This problem uses the same digit-extraction pattern as the reversal and digit-counting problems. The while loop continuously breaks down the number.

  1. tempNumber % 10 isolates the rightmost digit.
  2. sumOfDigits += digit adds this digit to the total.
  3. tempNumber /= 10 shifts the remaining digits one position right, effectively dropping the digit that was just processed. The loop terminates when tempNumber becomes 0. For example, with 456: the digits 6, 5, and 4 are extracted sequentially, and 6+5+4=15. The use of std::abs() ensures the logic works correctly for negative numbers, as the sum of digits is usually considered the sum of the absolute values of the digits

Exercise 11: Power of a Number

Practice Problem: Develop a C++ program that calculates the value of ab (a raised to the power b), where a is the base and b is a non-negative integer exponent, without using the standard library function pow(). Use a loop to perform the calculation.

Given:

int base = 2, exponent = 4;Code language: C++ (cpp)

Expected Output:

2 raised to the power of 4 is: 16
+ Hint
  • Initialize a result variable, say result, to 1.
  • Use a for loop that iterates b times (from i=1 to i=b).
  • In each iteration, multiply the result by the base a: result = result * a. Handle the edge case where b=0, in which case the result is 1.
+ Show Solution
#include <iostream>

int main() {
    int base = 2, exponent = 4;
    long long result = 1; // Use long long for the result as power values grow fast
    
    // Any number raised to the power of 0 is 1 (except 0^0, which is undefined/1)
    if (exponent == 0) {
        // result remains 1, no loop needed
    } else {
        // Loop 'exponent' number of times
        for (int i = 0; i < exponent; ++i) {
            result *= base; // result = result * base;
        }
    }
    
    std::cout << base << " raised to the power of " << exponent << " is: " << result << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  1. It takes two inputs: base and exponent.
  2. It validates both inputs — the exponent must be non-negative.
  3. It initializes result to 1.
  4. If the exponent is 0, the result remains 1 (since any number to the power 0 is 1).
  5. Otherwise, it multiplies result by base repeatedly in a for loop that runs exponent times.
  6. Finally, it prints the calculated power.

Exercise 12: Check Armstrong Number

Practice Problem: Write a C++ program that checks whether a positive integer N is an Armstrong number.

An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. (Example: 153=13+53+33).

Given:

int N = 153;Code language: C++ (cpp)

Expected Output:

153 is an Armstrong number.
+ Hint
  • First, use a loop (similar to Exercise 7) to count the total number of digits (D).
  • Then, use a second loop (similar to Exercise 10) to extract each digit, raise it to the power D (using the manual power loop from Exercise 11), and add it to a running sum.
  • Finally, compare the sum to the original number.
+ Show Solution
#include <iostream>

// Helper function for manual power calculation (as per the spirit of Ex 11)
long long calculatePower(int base, int exponent) {
    long long res = 1;
    for (int i = 0; i < exponent; ++i) {
        res *= base;
    }
    return res;
}

int main() {
    int originalN = 153;
    long long sumOfPowers = 0;
    int digitCount = 0;
    
    int tempN = originalN; 
    
    // 1. Loop to count the number of digits (D)
    while (tempN > 0) {
        tempN /= 10;
        digitCount++;
    }
    
    tempN = originalN; // Reset tempN to original value
    
    // 2. Loop to calculate the sum of each digit raised to the power D
    while (tempN > 0) {
        int digit = tempN % 10;
        sumOfPowers += calculatePower(digit, digitCount);
        tempN /= 10;
    }
    
    // 3. Comparison
    if (sumOfPowers == originalN) {
        std::cout << originalN << " is an Armstrong number." << std::endl;
    } else {
        std::cout << originalN << " is not an Armstrong number." << std::endl;
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The program is solved using two consecutive loops.

1) The first while loop determines D, the total number of digits in the number.
2) The second while loop then iterates over the digits again:

  • It extracts the digit using the modulo operator.
  • It uses the helper function calculatePower(digit, digitCount) (which uses an internal for loop) to raise the digit to the power D.
  • It adds this result to sumOfPowers. Finally, the result is compared to the originalN. If they match, the number is Armstrong.

Exercise 13: Fibonacci Series up to N terms

Practice Problem: Write a C++ program that generates and prints the first N terms of the Fibonacci series.

The Fibonacci series starts with 0 and 1, and each subsequent term is the sum of the two preceding terms (Fn​=Fn−1​+Fn−2​).

Given:

int N = 8;Code language: C++ (cpp)

Expected Output:

Fibonacci Series up to 8 terms:
0 1 1 2 3 5 8 13
+ Hint

Initialize two variables, n1 = 0 and n2 = 1. These are the first two terms. Use a for loop starting from i=3 up to N. Inside the loop:

  1. Calculate the next term: nextTerm = n1 + n2.
  2. Print nextTerm.
  3. Update the preceding terms: n1 = n2 and n2 = nextTerm.
+ Show Solution
#include <iostream>

int main() {
    int N = 8;
    long long n1 = 0, n2 = 1, nextTerm;
    
    std::cout << "Fibonacci Series up to " << N << " terms:\n";
    
    if (N >= 1) {
        std::cout << n1; // Print 0
    }
    if (N >= 2) {
        std::cout << " " << n2; // Print 1
    }
    
    // Loop starting from the 3rd term (i=3) up to N
    for (int i = 3; i <= N; ++i) {
        nextTerm = n1 + n2; // Calculate the next term
        std::cout << " " << nextTerm;
        
        // Update terms for the next iteration
        n1 = n2;
        n2 = nextTerm;
    }
    
    std::cout << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The program handles the edge cases N=1 and N=2 separately since they are fixed starting values. For N≥3, the for loop takes over. The crucial part is the variable update:

  • nextTerm = n1 + n2: The new term is calculated from the two previous terms (n1 and n2).
  • n1 = n2: The second-to-last term (n1) is updated to become the previous term (n2).
  • n2 = nextTerm: The previous term (n2) is updated to become the newly calculated term (nextTerm). This shifting process effectively moves the calculation forward, always maintaining the last two terms needed to find the next number in the series.

Exercise 14: GCD (HCF) of Two Numbers

Practice Problem: Given a two positive integers, A and B. Write a C++ program to find their Greatest Common Divisor (GCD), also known as the Highest Common Factor (HCF), using a loop.

Given:

int A = 5, B = 10;Code language: C++ (cpp)

Expected Output:

The GCD (HCF) of 5 and 10 is: 5
+ Hint
  • Iterate a loop variable i from 1 up to the smaller of the two numbers (min(A,B)).
  • In each iteration, check if both A and B are perfectly divisible by i (i.e., A%i==0 AND B%i==0).
  • The last value of i that satisfies this condition is the GCD.
+ Show Solution
#include <iostream>
#include <algorithm> // Required for std::min

int main() {
    int A = 5, B = 10, gcd = 1;

    int minimum = std::min(A, B);
    
    // Loop from 1 up to the smallest of A or B
    for (int i = 1; i <= minimum; ++i) {
        // Check if i divides both A and B perfectly
        if (A % i == 0 && B % i == 0) {
            gcd = i; // Store this factor. The last one stored will be the GCD.
        }
    }
    
    std::cout << "The GCD (HCF) of " << A << " and " << B << " is: " << gcd << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • The program finds the smaller of the two numbers using std::min() to set the limit for the for loop, as the GCD cannot be larger than the smallest number.
  • The loop iterates through every number i from 1 up to this limit.
  • The condition if (A % i == 0 && B % i == 0) checks if i is a common factor of both A and B. When a common factor is found, the gcd variable is updated.
  • Because the loop progresses in increasing order, the last common factor stored in gcd upon loop termination will necessarily be the Greatest Common Divisor.

Exercise 15: LCM of Two Numbers

Practice Problem: Given a for two positive integers, A and B. Write a C++ program that finds their Least Common Multiple (LCM) using loops.

Given:

int A = 45, B = 10;Code language: C++ (cpp)

Expected Output:

The LCM of 45 and 10 is: 90
+ Hint
  • Start a loop variable i from max(A,B).
  • The loop should continue indefinitely (or use a while(true) condition with a break).
  • Inside the loop, check if i is divisible by both A and B (i.e., i%A==0 AND i%B==0).
  • The first value of i that satisfies this is the LCM.
+ Show Solution
#include <iostream>
#include <algorithm> // Required for std::max

int main() {
    int A = 45, B = 10, larger;
   
    // The LCM must be at least as large as the larger number
    larger = std::max(A, B);
    
    // Loop starting from the larger number
    int i = larger;
    while (true) { 
        // Check if 'i' is divisible by both A and B
        if (i % A == 0 && i % B == 0) {
            std::cout << "The LCM of " << A << " and " << B << " is: " << i << std::endl;
            break; // Exit the loop immediately once the first multiple is found
        }
        i++; // Check the next integer
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The program efficiently searches for the LCM by starting the search at max(A,B) (since the LCM cannot be smaller than the largest number). A while(true) loop is used to iterate through candidate numbers i. In each iteration:

  • The condition i % A == 0 && i % B == 0 checks if i is a common multiple of A and B.
  • The first time this condition is met, i is the smallest number that satisfies the condition, thus it is the Least Common Multiple (LCM).
  • The break statement immediately terminates the loop once the LCM is found. If the condition is false, i is incremented, and the next candidate number is checked.

Exercise 16: Count Vowels/Consonants in a String

Practice Problem: Write a C++ program that reads a string of characters and uses a loop to count the total number of vowels (a, e, i, o, u) and consonants present in the string. Ignore spaces and non-alphabetic characters.

Given:

std::string text = "PYnative";Code language: C++ (cpp)

Expected Output:

Analysis of the string: PYnative
Total Vowels: 3
Total Consonants: 5
+ Hint
  • Use a for loop to iterate through each character of the string.
  • Convert the character to lowercase using std::tolower() for easier comparison.
  • Use an if/else if chain to check if the character is a vowel, or if it’s an alphabetic character (and thus a consonant). Use std::isalpha() to filter out non-letters.
+ Show Solution
#include <iostream>
#include <string>
#include <cctype> // Required for tolower() and isalpha()

int main() {
    std::string text = "PYnative";
    int vowelCount = 0;
    int consonantCount = 0;

    // Loop through each character in the string
    for (char c : text) { // C++11 range-based for loop
        // 1. Convert to lowercase for case-insensitive checking
        char lowerC = std::tolower(c);
        
        // 2. Check if the character is an alphabet
        if (std::isalpha(lowerC)) {
            // 3. Check if it's a vowel
            if (lowerC == 'a' || lowerC == 'e' || lowerC == 'i' || lowerC == 'o' || lowerC == 'u') {
                vowelCount++;
            } else {
                // 4. If it's an alphabet but not a vowel, it's a consonant
                consonantCount++;
            }
        }
    }
    
    std::cout << "Analysis of the string: "<< text << std::endl;
    std::cout << "Total Vowels: " << vowelCount << std::endl;
    std::cout << "Total Consonants: " << consonantCount << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The solution uses a range-based for loop (a concise C++ feature) to iterate over every char in the input text.

  • std::tolower(c) ensures that comparisons are case-insensitive (e.g., ‘A’ is treated the same as ‘a’).
  • std::isalpha(lowerC) filters out non-alphabetic characters (numbers, spaces, punctuation). Only letters proceed to the next step.
  • The if condition explicitly checks for the five vowel characters.
  • The else block catches all characters that passed the isalpha check but failed the vowel check, classifying them as consonants.

Exercise 17: Array Element Sum Using Loop

Practice Problem: Write a C++ program that uses a loop to calculate and print the sum of all elements in the array.

Given:

int arr[5] = {10, 20, 30, 40, 50};Code language: C++ (cpp)

Expected Output:

The sum of all elements in the array is: 150
+ Hint
  • Declare a sum variable initialized to 0.
  • Use a for loop to iterate through the array elements, adding each element to the sum variable.
+ Show Solution
#include <iostream>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    long long sum = 0;
    
    // 2. Loop to calculate the sum (using range-based for loop)
    for (int element : arr) {
        sum += element;
    }
    std::cout << "\nThe sum of all elements in the array is: " << sum << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • The for loop uses a range-based loop (for (int element : arr)). This construct iterates over the elements of the array directly, assigning the value of the current element to the variable element in each step.
  • sum += element; accumulates the total. This approach is cleaner and less error-prone than managing an index variable manually for summation.

Exercise 18: Find Array Max and Min

Practice Problem: Write a C++ program that reads an integer array from user (or vector) and uses a loop to find and display the largest (maximum) and smallest (minimum) elements stored within it.

Expected Output:

Enter the number of elements: 5
Enter 5 integers:
Element 1: 10
Element 2: 30
Element 3: 90
Element 4: 20
Element 5: 40

Maximum element is: 90
Minimum element is: 10
+ Hint
  • Initialize max to the smallest possible integer value (or the first element of the array) and min to the largest possible integer value (or the first element).
  • Iterate through the array starting from the second element. Inside the loop, use if conditions to check: if (current_element > max) and if (current_element < min)
+ Show Solution
#include <iostream>
#include <vector>
#include <limits> // Required for std::numeric_limits

int main() {
    int size;
    
    std::cout << "Enter the number of elements: ";
    if (!(std::cin >> size) || size <= 0) return 1;
    
    std::vector<int> arr(size);
    
    // Input loop omitted for brevity, assuming arr is filled.
    // For demonstration, let's assume the array is filled:
    std::cout << "Enter " << size << " integers:\n";
    for (int i = 0; i < size; ++i) {
        std::cout << "Element " << i + 1 << ": ";
        if (!(std::cin >> arr[i])) return 1;
    }
    
    // Check for empty array case
    if (size == 0) {
        std::cout << "Array is empty." << std::endl;
        return 0;
    }
    
    // Initialize max and min to the first element's value
    int maxElement = arr[0];
    int minElement = arr[0];
    
    // Loop through the array starting from the second element (index 1)
    for (int i = 1; i < size; ++i) {
        if (arr[i] > maxElement) {
            maxElement = arr[i]; // New maximum found
        }
        
        if (arr[i] < minElement) {
            minElement = arr[i]; // New minimum found
        }
    }
    
    std::cout << "\nMaximum element is: " << maxElement << std::endl;
    std::cout << "Minimum element is: " << minElement << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The solution uses a std::vector for dynamic array handling.

After the array is populated, the maxElement and minElement variables are initialized to the value of the first element (arr[0]). This guarantees that the initial values are actual numbers present in the array, making the comparison accurate regardless of the potential range of the array values.

The for loop then starts from the second element (index 1). In each step:

  • if (arr[i] > maxElement) updates the maximum if the current element is larger.
  • if (arr[i] < minElement) updates the minimum if the current element is smaller. By the time the loop finishes iterating through all elements, maxElement and minElement will hold the correct extreme values.

Exercise 19: Check Prime Number

Practice Problem: Write a C++ program that uses a loop to determine whether N is a prime number.

Prime number is a whole number greater than 1 that cannot be exactly divided by any whole number other than itself and 1 (e.g. 2, 3, 5, 7, 11).

Given:

int N = 11;Code language: C++ (cpp)

Expected Output:

11 is a prime number.
+ Hint
  • Handle the cases N≤1 and N=2 separately.
  • For N>2, use a for loop starting from i=2. The loop should check for divisibility: N % i == 0.
  • Optimally, the loop should only run up to square root of N (or i∗i<=N). If a divisor is found, the number is not prime, and the loop can be broken using break or a boolean flag.
+ Show Solution
#include <iostream>
#include <cmath> // Required for sqrt()

int main() {
    int N = 11;
    bool isPrime = true;
      
    // Handle special cases: 0, 1, and 2
    if (N <= 1) {
        isPrime = false;
    } else if (N == 2) {
        isPrime = true;
    } else if (N % 2 == 0) {
        // Optimization: all other even numbers are not prime
        isPrime = false;
    } else {
        // Optimization: loop only up to the square root of N
        // We only check odd divisors (i=3, i+=2)
        for (int i = 3; i * i <= N; i += 2) {
            if (N % i == 0) {
                isPrime = false;
                break; // Found a divisor, no need to check further
            }
        }
    }
    
    if (isPrime) {
        std::cout << N << " is a prime number." << std::endl;
    } else {
        std::cout << N << " is not a prime number." << std::endl;
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The program uses a boolean flag isPrime, initialized to true.

  • Edge cases N≤1 and N=2 are handled first.
  • An initial check for divisibility by 2 quickly handles all even numbers greater than 2.
  • The main for loop iterates using the Image​square root of N optimization. The condition i * i <= N is mathematically equivalent to i≤ square root of NImage​ but avoids the sqrt() function call in every iteration.
  • The step i += 2 ensures we only check odd divisors (since even divisors were already covered).
  • If N % i == 0 is ever true, a divisor other than 1 and N is found, so isPrime is set to false, and the break statement stops the loop immediately, maximizing efficiency.

Exercise 20: Print All Primes in Range (1-100)

Practice Problem: Write a C++ program that uses nested loops to find and print all prime numbers in the range from 1 to 100 (inclusive).

Expected Output:

Prime numbers between 1 and 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
+ Hint
  • Use an outer for loop to iterate through every number N from 2 to 100.
  • Inside this loop, use an inner for loop (similar to Exercise 19) to check if the current number N is prime. Use a boolean flag to track primality within the outer loop.
+ Show Solution
#include <iostream>
#include <cmath>

int main() {
    std::cout << "Prime numbers between 1 and 100 are:\n";
    
    // Outer loop: iterate through every number N from 2 to 100
    for (int N = 2; N <= 100; ++N) {
        bool isPrime = true; // Assume current number is prime initially
        
        // Inner loop: check for divisibility (optimization: check up to sqrt(N))
        // Start check from 2 up to sqrt(N)
        for (int i = 2; i * i <= N; ++i) {
            if (N % i == 0) {
                isPrime = false; // Found a divisor, so N is not prime
                break;           // No need to check other divisors
            }
        }
        
        // If the flag is still true after the inner loop, the number is prime
        if (isPrime) {
            std::cout << N << " ";
        }
    }
    
    std::cout << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • The Outer Loop (for (int N = 2; N <= 100; ++N)) picks each number N to be tested.
  • The isPrime flag is reset to true for each new number N.
  • The Inner Loop (for (int i = 2; i * i <= N; ++i)) tests N for divisibility by i. If a factor is found, isPrime becomes false, and the inner loop breaks.
  • After the inner loop completes, the outer if condition checks the final status of isPrime. Only if it remains true (meaning no divisors were found) is the number N printed. This process is repeated for every number up to 100.

Exercise 21: Square Pattern of Stars (*)

Practice Problem: Given an integer N. Write a C++ program that uses nested loops to print an N×N square pattern composed of asterisks (*).

Given:

int N = 4;Code language: C++ (cpp)

Expected Output:

* * * * 
* * * *
* * * *
* * * *
+ Hint
  • The outer loop controls the rows (from 1 to N).
  • The inner loop controls the columns (also from 1 to N).
  • Inside the inner loop, print one asterisk. After the inner loop completes (a row is finished), print a newline character (\n or std::endl) using std::cout in the outer loop to move to the next row.
+ Show Solution
#include <iostream>

int main() {
    int N = 4;
    
    // Outer loop: controls rows (i)
    for (int i = 0; i < N; ++i) {
        
        // Inner loop: controls columns (j)
        for (int j = 0; j < N; ++j) {
            std::cout << "* "; // Print star and a space
        }
        
        std::cout << "\n"; // Move to the next line after completing a row
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

For an N=4 square, the outer loop runs 4 times (for rows). In each iteration of the outer loop, the inner loop runs 4 times, printing one ‘*‘ for each column. The core structure of nested loops for 2D patterns is:

for (rows) {
    for (columns) {
        // Print character
    }
    // Print newline
}Code language: C++ (cpp)

This ensures that the correct number of characters are printed across the row before moving down to print the next row.

Exercise 22: Right triangle Pattern of Stars

Practice Problem: Write a C++ program that prompts the user for an integer N and uses nested loops to print a right-angled triangle pattern of asterisks where the i-th row has i stars.

Expected Output:

Enter the height (N) for the triangle: 4
*
**
***
****
+ Hint
  • The outer loop runs N times (for rows).
  • The key difference from the square is the inner loop condition. For the i-th row (where i ranges from 1 to N), the inner loop for the columns should only run i times. Set the inner loop condition to j <= i.
+ Show Solution
#include <iostream>

int main() {
    int N;
    
    std::cout << "Enter the height (N) for the triangle: ";
    if (!(std::cin >> N) || N <= 0) return 1;
    
    // Outer loop: controls rows (i) from 1 to N
    for (int i = 1; i <= N; ++i) {
        
        // Inner loop: controls columns (j). It runs 'i' times.
        for (int j = 1; j <= i; ++j) {
            std::cout << "*"; // No space needed here for tighter look
        }
        
        std::cout << std::endl; // Newline for the next row
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

  • The outer loop counter i not only tracks the current row number but also dictates the number of columns to be printed in that row.
  • When i=1 (Row 1), the inner loop condition j <= 1 runs once, printing one ‘*‘.
  • When i=4 (Row 4), the inner loop condition j <= 4 runs four times, printing four *.
  • By making the inner loop’s termination condition dependent on the outer loop’s counter, the desired triangular shape is generated.

Exercise 23: Print Inverted Right Triangle Pattern

Practice Problem: Given an integer N (height for the triangle). Write a C++ program that uses nested loops to print an inverted right-angled triangle pattern of asterisks.

Given:

int N = 4;Code language: C++ (cpp)

Expected Output:

****
***
**
*
+ Hint
  • The total number of rows is N.
  • The first row needs N stars, and the last row needs 1 star.
  • Set the outer loop to iterate backwards, from i=N down to 1. The inner loop condition should again be controlled by i: run j from 1 up to i.
+ Show Solution
#include <iostream>

int main() {
    int N = 4;
    
    // Outer loop: controls rows (i) from N down to 1
    for (int i = N; i >= 1; --i) {
        
        // Inner loop: controls columns (j). It runs 'i' times.
        for (int j = 1; j <= i; ++j) {
            std::cout << "*"; 
        }
        
        std::cout << "\n"; // Newline for the next row
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The structure is similar to the standard right triangle, but the outer loop initialization and update are reversed:

  • Initialization: int i = N (starts with the longest row).
  • Condition: i >= 1 (continues until the shortest row is printed).
  • Update: --i (decreases the row length by one in each iteration)

Since the inner loop’s condition (j <= i) still depends on the outer loop counter i, the number of stars printed starts at N and decreases by 1 in each subsequent row.

Exercise 24: Print Pyramid Pattern of Stars

Practice Problem: Write a C++ program that uses nested loops to print an N-row full pyramid pattern of asterisks.

Given:

int N = 4;Code language: C++ (cpp)

Expected Output:

Height (N) for the pyramid: 4
*
***
*****
*******
+ Hint

This requires three parts in the inner logic for each row i:

  1. An inner loop to print the leading spaces (j from 1 to N−i).
  2. A second inner loop to print the stars (which is always 2×i−1 stars, where i is the row number starting from 1).
  3. A newline character.
+ Show Solution
#include <iostream>

int main() {
    int N = 4;
    
    // Outer loop: controls rows (i)
    for (int i = 1; i <= N; ++i) {
        
        // 1. Inner loop for leading spaces
        // The number of spaces is (N - i)
        for (int j = 1; j <= N - i; ++j) {
            std::cout << " ";
        }
        
        // 2. Inner loop for stars
        // The number of stars is (2 * i - 1)
        for (int k = 1; k <= 2 * i - 1; ++k) {
            std::cout << "*";
        }
        
        std::cout << std::endl; // Newline for the next row
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This pattern needs two inner loops within the outer row loop.

Space Loop: As the row number i increases, the number of spaces needed decreases. The formula N−i correctly calculates this:

  • Row 1 (i=1): N−1 spaces.
  • Row N (i=N): 0 spaces.

Star Loop: The number of stars in a standard pyramid increases by 2 in each row. The formula 2×i−1 correctly calculates this:

  • Row 1 (i=1): 2(1)−1=1 star.
  • Row 2 (i=2): 2(2)−1=3 stars.

These two inner loops work together to align the pattern centrally.

Exercise 25: Print Inverted Pyramid Pattern

Practice Problem: Write a C++ program that uses nested loops to print an N-row inverted full pyramid pattern of asterisks.

Given:

int N = 4;Code language: C++ (cpp)

Expected Output:

Height (N) for the inverted pyramid: 4
*******
*****
***
*
+ Hint

This is the reverse of Exercise 24. The outer loop should iterate backwards (from N down to 1). Inside the loop:

  1. Print the increasing number of spaces (from 0 up to N−i).
  2. Print the decreasing number of stars (which is still 2×i−1, but i starts at N).
+ Show Solution
#include <iostream>

int main() {
    int N = 4;
    
    // Outer loop: controls rows (i) from N down to 1
    for (int i = N; i >= 1; --i) {
        
        // 1. Inner loop for leading spaces
        // The number of spaces increases: N - i is constant, but N - i is the number of rows already processed from the bottom
        for (int j = 1; j <= N - i; ++j) {
            std::cout << " ";
        }
        
        // 2. Inner loop for stars
        // The number of stars decreases: (2 * i - 1)
        for (int k = 1; k <= 2 * i - 1; ++k) {
            std::cout << "*";
        }
        
        std::cout << std::endl; // Newline
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The solution adapts the logic from the standard pyramid by reversing the outer loop’s iteration direction: i goes from N down to 1.

Space Loop: The number of spaces is determined by how many rows have been printed so far from the top, which is equivalent to N−i.

  • Row 1 (i=N): N−N=0 spaces.
  • Row 2 (i=N−1): N−(N−1)=1 space.

Star Loop: The formula 2×i−1 still determines the number of stars, but because i is decreasing, the stars decrease in odd steps:

  • Row 1 (i=N=3): 2(3)−1=5 stars.
  • Row 2 (i=2): 2(2)−1=3 stars.

Exercise 26: Full Multiplication Chart Using Nested Loops

Practice Problem: Write a C++ program that uses nested loops to generate and display a full multiplication chart for numbers from 1 to 10.

Expected Output:

--- 1 to 10 Multiplication Chart ---

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
+ Hint
  • Use an outer for loop to iterate through the first multiplier i (from 1 to 10).
  • Use an inner for loop to iterate through the second multiplier j (also from 1 to 10).
  • Inside the inner loop, print the product i×j.
  • Ensure uniform spacing for the table format.
+ Show Solution
#include <iostream>
#include <iomanip> // Required for std::setw

int main() {
    std::cout << "--- 1 to 10 Multiplication Chart ---\n\n";
    
    // Outer loop: controls the row multiplier (i)
    for (int i = 1; i <= 10; ++i) {
        
        // Inner loop: controls the column multiplier (j)
        for (int j = 1; j <= 10; ++j) {
            int product = i * j;
            
            // Use std::setw(4) to ensure each number takes 4 characters, 
            // guaranteeing clean column alignment.
            std::cout << std::setw(4) << product; 
        }
        
        std::cout << std::endl; // Newline for the next multiplication row
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This is the standard application of nested loops for grid/table generation.

  • The Outer Loop determines which row we are printing (e.g., the “5 times” row when i=5).
  • The Inner Loop iterates through the multipliers j=1 through 10.
  • The line int product = i * j; calculates the result.
  • std::setw(4) is used to format the output. It forces the printed number to occupy a minimum field width of 4 characters, aligning the table neatly regardless of whether the product is single-digit (5) or three-digit (100).

Exercise 27: Pattern of Numbers (1 to N)

Practice Problem: Given an integer N. Write a C++ program that uses nested loops to print a number triangle pattern where the i-th row contains numbers from 1 up to i.

Given:

int N = 44Code language: C++ (cpp)

Expected Output:

Height (N) for the number pattern: 4
1
1 2
1 2 3
1 2 3 4
+ Hint
  • The outer loop controls the rows (i=1 to N).
  • The inner loop controls the columns (j). Crucially, the number being printed is the inner loop counter j itself, and the inner loop’s condition should be j≤i.
+ Show Solution
#include <iostream>

int main() {
    int N = 4;
    
    // Outer loop: controls rows (i)
    for (int i = 1; i <= N; ++i) {
        
        // Inner loop: controls columns (j). Runs 'i' times.
        // Print the column counter 'j' in each iteration
        for (int j = 1; j <= i; ++j) {
            std::cout << j << " "; // Print the column number 'j'
        }
        
        std::cout << std::endl; // Newline for the next row
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This pattern combines the structure of the right triangle pattern (Exercise 22) with the logic of printing a dynamic value.

  • The Outer Loop defines the row i.
  • The Inner Loop runs j from 1 to i.
  • By printing the inner loop counter j (std::cout << j << " ";), the value printed automatically resets to 1 at the beginning of every new row and increments up to the limit i defined by the outer loop. This results in the sequence 1, then 1,2, then 1,2,3, and so on.

Exercise 28: Number Pattern (Repeating Row Number)

Practice Problem: Given an integer N. Write a C++ program that uses nested loops to print a pattern where the i-th row contains the number i repeated i times.

Given:

int N = 4;Code language: C++ (cpp)

Expected Output:

Height (N) for the repeating number pattern: 4
1
2 2
3 3 3
4 4 4 4
+ Hint
  • Use an outer loop for rows (i=1 to N) and an inner loop for columns (j=1 to i).
  • Inside the inner loop, the value you print should be the outer loop counter i, not the inner loop counter j.
+ Show Solution
#include <iostream>

int main() {
    int N = 4;
    
    // Outer loop: controls rows (i) and the number to be printed
    for (int i = 1; i <= N; ++i) {
        
        // Inner loop: controls columns (j). Runs 'i' times.
        for (int j = 1; j <= i; ++j) {
            // Print the row number 'i'
            std::cout << i << " "; 
        }
        
        std::cout << std::endl; // Newline for the next row
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This pattern builds on the right triangle structure.

  • The Outer Loop counter i determines both the value to be printed and the length of the row.
  • The Inner Loop runs j from 1 up to i, correctly generating the triangular shape.
  • The key is that we print i inside the inner loop. When i=3, the inner loop runs three times, and in all three iterations, it prints 3, resulting in ‘3 3 3‘.

Exercise 29: Number Pattern (Inverted Right Triangle of Decreasing Numbers)

Practice Problem: Given an integer N. Write a C++ program that uses nested loops to print an inverted right-angled number triangle where the i-th row starts at N and decreases to i.

Given:

int N = 4;Code language: C++ (cpp)

Expected Output:

Height (N) for the inverted decreasing number pattern: 4
4
4 3
4 3 2
4 3 2 1
+ Hint
  • Use an outer loop for rows (i=N down to 1).
  • The inner loop should start at N and continue as long as the column counter j >=i. Print the inner loop counter j in each iteration.
+ Show Solution
#include <iostream>

int main() {
    int N = 4;
    
    // Outer loop: controls rows (i) from N down to 1
    for (int i = N; i >= 1; --i) {
        
        // Inner loop: controls columns (j). It starts at N and decreases to 'i'.
        for (int j = N; j >= i; --j) {
            std::cout << j << " "; // Print the current column number 'j'
        }
        
        std::cout << std::endl; // Newline for the next row
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This pattern uses both the outer and inner loops in a decreasing fashion.

1) The Outer Loop counter i runs backwards (from N to 1), defining the ending number for each row.
2) The Inner Loop counter j controls the numbers printed in the row. It is initialized to N and decrements (--j).
3) The Inner Loop Condition j >= i is key.

  • When i=1 (first row), the loop runs as long as j≥1, printing 5,4,3,2,1.
  • When i=4 (fourth row), the loop runs as long as j≥4, printing 5,4.
  • When i=5 (last row), the loop runs as long as j≥5, printing 5.
  • By printing the decreasing inner counter j, we achieve the desired pattern.

Exercise 30: Password Attempt Simulation

Practice Problem: Develop a C++ program that simulates a password prompt using a do-while loop. The program must allow the user exactly three attempts to enter a specific hardcoded password (e.g., “secret”). The loop should terminate if the password is correct or if all three attempts are exhausted.

Given:

const std::string CORRECT_PASSWORD = "Pass1212";Code language: C++ (cpp)

Expected Output:

--- Password Lock Simulation ---
Attempt 1/3. Enter password: pass1234
Wrong Password. Access denied. Try again.
Attempt 2/3. Enter password: pass1225
Wrong Password. Access denied. Try again.
Attempt 3/3. Enter password: Pass1212

Access GRANTED. Welcome!
+ Hint
  • Define the correct password as a const std::string.
  • Use a counter variable initialized to 0.
  • The do-while loop condition should check two things: whether the entered password is incorrect AND whether the attempt count is less than 3.
  • Increment the counter inside the loop. The do-while loop guarantees the code inside executes at least once.
+ Show Solution
#include <iostream>
#include <string>

int main() {
    const std::string CORRECT_PASSWORD = "Pass1212";
    std::string userAttempt;
    int attempts = 0;
    const int MAX_ATTEMPTS = 3;
    bool isAuthenticated = false;
    
    std::cout << "--- Password Lock Simulation ---\n";

    do {
        attempts++; // Increment attempt counter first
        std::cout << "Attempt " << attempts << "/" << MAX_ATTEMPTS << ". Enter password: ";
        
        // Read the user's input, allowing spaces
        std::getline(std::cin, userAttempt); 
        
        if (userAttempt == CORRECT_PASSWORD) {
            isAuthenticated = true;
            break; // Exit loop immediately on success
        } 
        
        if (attempts < MAX_ATTEMPTS) {
            std::cout << "Wrong Password. Access denied. Try again.\n";
        }
        
    } while (attempts < MAX_ATTEMPTS); // Loop condition checks if max attempts haven't been reached
    
    // Final result output
    if (isAuthenticated) {
        std::cout << "\nAccess GRANTED. Welcome!\n";
    } else {
        std::cout << "\nMaximum attempts reached. Account locked.\n";
    }
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

The do-while loop is ideal here because the password check must happen at least once.

  • The attempts counter tracks the usage. It is incremented at the start of the do block.
  • The std::getline function is used to read the full line of input, ensuring the password can contain spaces if required.
  • If the password matches, the isAuthenticated flag is set, and break immediately exits the loop.
  • The while condition (attempts < MAX_ATTEMPTS) only allows the loop to repeat if the maximum limit of 3 attempts hasn’t been hit.
  • After the third failed attempt, attempts becomes 3, the condition fails, and the loop terminates, leading to the “Account locked” message.

Exercise 31: Reverse Word Order in a Sentence

Practice Problem: Write a C++ program that uses loops and string manipulation to print the words in reverse order. (e.g., “This is a test” → “test a is This”).

Given:

std::string sentence = "This is a test";Code language: C++ (cpp)

Expected Output:

Sentence with words reversed:
test a is This
+ Hint
  • The simplest approach is to use a stringstream (from <sstream>) to easily extract words one by one.
  • Use a while loop to read all words into a std::vector<std::string>.
  • Then, use a for loop to iterate over the vector in reverse order (from size−1 down to 0) and print each word.
+ Show Solution
#include <iostream>
#include <string>
#include <vector>
#include <sstream> // Required for stringstream

int main() {
    std::string sentence = "This is a test";
    std::vector<std::string> words;
    
    // Check if the input is empty
    if (sentence.empty()) {
        std::cout << "No words entered." << std::endl;
        return 0;
    }
    
    // 1. Use stringstream to break the sentence into words
    std::stringstream ss(sentence);
    std::string word;
    
    // Loop (implicitly a while loop) to read each word into the vector
    while (ss >> word) {
        words.push_back(word);
    }
    
    std::cout << "\nSentence with words reversed:\n";
    
    // 2. Loop through the vector backwards
    // Start at the last index (size - 1) and stop at index 0
    for (int i = words.size() - 1; i >= 0; --i) {
        std::cout << words[i];
        
        // Print a space after every word except the last one
        if (i > 0) {
            std::cout << " ";
        }
    }
    
    std::cout << std::endl;
    
    return 0;
}Code language: C++ (cpp)
Run

Explanation:

This solution uses two distinct control flow mechanisms:

  • Word Extraction (Implicit Loop): The statement while (ss >> word) uses the overloaded stream extraction operator (>>). This automatically tokenizes the string ss by whitespace, extracting words one by one and storing them sequentially in the words vector. The while loop terminates when ss reaches the end of the string.
  • Reverse Output (Explicit Loop): A standard for loop is used to iterate over the words vector. By setting the initialization to words.size() - 1, the condition to i >= 0, and the update to –i, the loop iterates from the last word to the first, achieving the reverse order output.

Filed Under: C++ Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

C++ Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: C++ Exercises
TweetF  sharein  shareP  Pin

  CPP Exercises

  • All C++ Exercises
  • C++ Exercise for Beginners
  • C++ Loops Exercise
  • C++ Functions Exercise
  • C++ Arrays Exercise
  • C++ String Exercise
  • C++ Pointers Exercise
  • C++ OOP Exercise
  • C++ File Handling Exercise
  • C++ Structures and Enums Exercise
  • C++ Templates and Generic Programming Exercise

All Coding Exercises

C Exercises C++ Exercises Python Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement