C++ While loop example

Spread the love

As part of the flow control, we will write a c++ while loop example then examine its elements.


#include <iostream>

int main(){
    int cnt = 0;
    bool isReady = true;
    while( isReady ){
      std::cout << "Are we really in a loop\n"; 
      ++cnt;
      if ( cnt > 5 )
         isReady = false;
    }
}

Line 9. Does the c++ while loop example really loop only 5 times?


C++ Loop Code Example

c++ while loop code example image. There are 6 repeated statements not 5 as expected. Something has gone wrong

So, did everything run ok? I see the std::cout statements.

But there are 6 and the code author looks they were expecting 5. Perhaps we need a further code correction.

Introducing std::cin >>

Lets be a bit bolder in this C++ while loop lesson and introduce std::cin >> in order to get user input. It’s a bit tricky because the user can give you non numeric input but lets ignore that for the moment and make the lesson a bit more interesting.


Image shows compiled code using the std::cin construct to get user input and loop that number of times. c++ while loop constructs.
// Copy and try running the code yourself.
#include <iostream>

int main(){
   int userCounter = 0,cnt=0;
   std::cout << "how many times should we loop ?\n";
   std::cin >> userCounter;
  
   while ( cnt < userCounter  ){
       std::cout << "Counting to " << userCounter 
                 << " now in the loop for " 
                 << cnt + 1 << " times\n";
       cnt++;
   }

}


Line 7, we introduce the std::cin >> for getting the user input

Line 9, we compare that user input against the cnt ( counter )

Line 12 – Tell us in the comments why we added 1 to cnt and why this doesn’t increment the value of cnt yet again


-> Lesson 8, C++ Do While Syntax


Top