C++ While loop


Go to main Page

While loop C++

With the aid of examples, we will learn about loops in this instructional exercise.

Loops

Loops are used in C++ to run the code block repeatedly.
For instance, if we want to show Pakistan 100 times, we must write code 100 times.
However, by using loops, we can represent Pakistan with just one line of code.


There are three types of loops in C++ Programming:

In this tutorial we will focus on While Loop.We will learn about other Loops in upcoming tutorials.

While Loop

The syntax of While Loop is:

while (condition) {
    // body of the loop
}

While loop evaluates the condition.

If conditions become true the code will evaluate.

The condition evaluates again.

Until the condition become false.

Diagram
Example 1: Print number 1 to 5

#include <iostream>

using namespace std;

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

Output

1 2 3 4 5

Explaination

Example 2:Sum of positive numbers only.

#include <iostream>
using namespace std;
int main() {
    int number;
    int sum = 0;
    cout << "Enter a number: ";
    cin >> number;

    while (number >= 0) {
        sum += number;
        cout << "Enter a number: ";
        cin >> number;
    }
    cout << "\nThe sum is " << sum << endl;
    
    return 0;
}

Output

Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25