C++ While Loop Examples

Welcome to The Coding College! In this post, we’ll focus on practical C++ while loop examples to demonstrate how this loop can solve various problems efficiently.

What is a While Loop?

A while loop executes a block of code repeatedly as long as the specified condition evaluates to true. It’s especially useful when you don’t know in advance how many iterations are required.

Example 1: Print Numbers from 1 to N

This example prints all numbers from 1 to N.

#include <iostream>
using namespace std;

int main() {
    int n, i = 1;

    cout << "Enter a positive integer: ";
    cin >> n;

    while (i <= n) {
        cout << i << " ";
        i++;
    }

    return 0;
}

Output:

Enter a positive integer: 5  
1 2 3 4 5

Example 2: Calculate the Sum of First N Natural Numbers

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0, i = 1;

    cout << "Enter a positive integer: ";
    cin >> n;

    while (i <= n) {
        sum += i;
        i++;
    }

    cout << "The sum of the first " << n << " numbers is: " << sum << endl;

    return 0;
}

Output:

Enter a positive integer: 5  
The sum of the first 5 numbers is: 15

Example 3: Reverse a Number

#include <iostream>
using namespace std;

int main() {
    int number, reverse = 0;

    cout << "Enter a number: ";
    cin >> number;

    while (number != 0) {
        int digit = number % 10;  // Extract the last digit
        reverse = reverse * 10 + digit;  // Build the reverse
        number /= 10;  // Remove the last digit
    }

    cout << "Reversed number: " << reverse << endl;

    return 0;
}

Output:

Enter a number: 1234  
Reversed number: 4321

Example 4: Check if a Number is Prime

#include <iostream>
using namespace std;

int main() {
    int n, i = 2;
    bool isPrime = true;

    cout << "Enter a positive integer: ";
    cin >> n;

    while (i <= n / 2) {
        if (n % i == 0) {
            isPrime = false;
            break;
        }
        i++;
    }

    if (isPrime && n > 1) {
        cout << n << " is a prime number." << endl;
    } else {
        cout << n << " is not a prime number." << endl;
    }

    return 0;
}

Output Examples:

Enter a positive integer: 11  
11 is a prime number.
Enter a positive integer: 12  
12 is not a prime number.

Example 5: Factorial of a Number

#include <iostream>
using namespace std;

int main() {
    int n, factorial = 1;

    cout << "Enter a positive integer: ";
    cin >> n;

    int i = 1;
    while (i <= n) {
        factorial *= i;
        i++;
    }

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

    return 0;
}

Output:

Enter a positive integer: 5  
The factorial of 5 is: 120

Example 6: Find the Largest Digit in a Number

#include <iostream>
using namespace std;

int main() {
    int number, largest = 0;

    cout << "Enter a number: ";
    cin >> number;

    while (number != 0) {
        int digit = number % 10;  // Extract the last digit
        if (digit > largest) {
            largest = digit;
        }
        number /= 10;  // Remove the last digit
    }

    cout << "The largest digit is: " << largest << endl;

    return 0;
}

Output:

Enter a number: 2785  
The largest digit is: 8

Example 7: Input Validation

Ensure the user enters a positive integer using a while loop.

#include <iostream>
using namespace std;

int main() {
    int number;

    cout << "Enter a positive number: ";
    cin >> number;

    while (number <= 0) {
        cout << "Invalid input. Enter a positive number: ";
        cin >> number;
    }

    cout << "You entered: " << number << endl;

    return 0;
}

Output:

Enter a positive number: -5  
Invalid input. Enter a positive number: 10  
You entered: 10

Example 8: Guess the Number Game

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));  // Initialize random seed
    int target = rand() % 100 + 1;  // Random number between 1 and 100
    int guess;

    cout << "Guess the number between 1 and 100!" << endl;

    while (true) {
        cout << "Enter your guess: ";
        cin >> guess;

        if (guess == target) {
            cout << "Congratulations! You guessed the correct number!" << endl;
            break;
        } else if (guess < target) {
            cout << "Too low! Try again." << endl;
        } else {
            cout << "Too high! Try again." << endl;
        }
    }

    return 0;
}

Output Example:

Guess the number between 1 and 100!  
Enter your guess: 50  
Too low! Try again.  
Enter your guess: 75  
Too high! Try again.  
Enter your guess: 63  
Congratulations! You guessed the correct number!

Conclusion

The while loop is versatile and effective for a wide range of programming tasks, from simple iterations to complex problems. By mastering these examples, you’ll be well-equipped to handle repetitive tasks in your C++ programs.

Explore More at The Coding College

Visit The Coding College for more coding tutorials and examples to strengthen your programming skills.

What’s Next?

  • Learn about the do/while loop, which guarantees at least one execution.
  • Explore the for loop, ideal for fixed iterations.
  • Combine loops with arrays and functions for more advanced programming.

Leave a Comment