×

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

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.

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.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

6 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

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.