×

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples.

What is the While Loop?

The “while loop” is a control flow statement that enables code to run repeatedly in response to a specified condition. The while loop is an iterative control statement. A while loop repeatedly executes loop’s statement(s) several times, as a given condition is true. Execution of the loop is terminated when the condition of the while loop becomes false and executes code after the loop.

Syntax:

It has the following syntax:

while (condition) {

    // Code to be executed

}

Explanation:

  • Condition: A boolean statement that determines whether the loop continues or stops.
  • The loop keeps going as long as the condition is true.
  • If the condition is found to be false, the loop ends.

Working Process of While Loop:

  • While the loop first checks, the condition is applied.
  • If the condition of a while loop is satisfied (true), statement(s) within the loop is executed. If the condition of a while loop is not satisfied (false), program execution is terminated from the loop and a statement after the loop is executed.
  • Repeatedly check the loop condition and execute according to step 2.

Key features:

Several key features of the while loop in C++ are as follows:

1. Entry-Controlled Loop:

Before the body of the loop is executed, the condition is examined.
The loop never runs if the condition is originally false.

2. The process continues until the condition is no longer met.

The loop keeps running once the condition is met.

3. This technique is applied when the number of iterations is unknown.

The while loop is utilized when we are unsure of the number of times it should run, compared to the for loop, which is employed when the number of iterations is known.

4. Loop Control Variable Must Be Updated Manually

In order to prevent endless loops, we must update the condition variable inside the loop (for example, by increasing a counter).

5. If a condition is not updated correctly, it may result in endless loops.

An endless loop could result from the condition never becoming false if the loop control variable is left unaltered inside the loop.

6. It is Compatible with Any Condition.

The condition may entail logical operations (&&, ||), comparisons (<, >, ==), or even function return values.

7. Suitable for a Range of Uses

It is useful for continuing a program until an exit condition is satisfied, reading files line by line, verifying user input, and more.

Pseudo code:

START

    Initialize a variable (e.g., count = 1)

   

    WHILE (condition is true)  // Example: count <= 5

        PRINT "Count: " and the current value of count

        Increment count by 1

    END WHILE


STOP

Algorithm:

  • Start the program.
  • Initialize a variable (e.g., count = 1).
  • Check the condition (count <= 5).
  • If the condition is true, proceed to step 4.
  • If the condition is false, go to step 6.
  • Execute the loop body:      
  • Print the current value of count.
  • Increment count by 1.
  • Repeat step 3 until the condition becomes false.
  • Stop the program.

Example 1:

Let us take an example to illustrate the while loop in C++.

#include <iostream>

using namespace std;


int main() {

    int count = 1;


    while (count <= 5) {  // Loop runs while count is ≤ 5

        cout << "Count: " << count << endl;

        count++;  // Increment count

    }


    return 0;

}

Output:

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

Key points:

  • The condition is evaluated before to the loop’s body being run.
  • If the condition is false from the start, the loop doesn’t execute at all.
  • Make sure the loop has an exit condition at all times to prevent an unending loop.

Pseudo code for above example code:

For count = 1, while (count <= 5):

Iteration 1 → Print Count: 1, count = 2

Iteration 2 → Print Count: 2, count = 3

Iteration 3 → Print Count: 3, count = 4

Iteration 4 → Print Count: 4, count = 5

Iteration 5 → Print Count: 5, count = 6

Condition count <= 5 is now false, so loop stops.

Infinite loop Example:

while (true) {  // This loop will run forever

    cout << "This is an infinite loop!" << endl;

}

Example 2:

Let us take another example to illustrate the while loop in C++.

#include <iostream>

using namespace std;

int main()

{

    int n, sum = 0, i = 1;

    cout << "Enter a positive number: ";

    cin >> n;

    while (i <= n) {  // Loop runs until i is greater than n

        sum += i;  // Add i to sum

        i++;  // Increment i

    }

    cout << "Sum of first " << n << " natural numbers is: " << sum << endl;

    return 0;

}

Output:

Enter a positive number: 5

Sum of first 5 natural numbers is: 15

Explanation:

  • The user enters n.
  • Every number is added to the sum in a while loop that runs from 1 to n.
  • When i > n, the loop ends, and the total is shown.

Conclusion:

In conclusion, the simplest while loop structure in C++ is a way of executing a block of statements repeatedly based on a certain condition. Since it is an entry-controlled loop, the condition has to be checked before the execution of the loop body; hence, it is suitable for cases where the number of iterations beforehand is not known. The loop control variable should be properly used to prevent an infinite loop and allow the program to run smoothly without any interruptions. Input validation, calculations that need repetition, and auto processes are examples that use the while loop commonly. Developers can create efficient, faultless looping constructs by understanding C++ best practices and features.


Related Topics

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.