While loop Cplusplus

What is while loop?

While loop have the following properties;

  • Conditional loop structure
  • Executes the statements until the given condition remains true. Stop the loop when given condition false.

When to use while loop?

  • When programmer does not know in advance the total number of repetitions of loop.

What is the syntax of while loop?

Syntax
While (condition)

{

statements;

Loop increment;

}

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

 

#include<iostream>

using namespace std;

int main()

{

int number=1;

while(number<=10)

{

cout<<“number is “<<number<<endl;

number++;

}

cout<<“you are outside the loop”;

}

              

 

Output:
number is 1

number is 2

number is 3

number is 4

number is 5

number is 6

number is 7

number is 8

number is 9

number is 10

you are outside the loop

Line 5:

  • Integer type loop variable “number” is declared and initialized with value 1.

Line 6:

  • There is a condition that loop will execute if value of number variable is less than or equal to 10.

Line 7:

  • Start of loop

Line 9:

  • Value of loop variable number is incremented.

 

Test Your Understandings
1. If the given condition is false then no statement execute in while section? True / False
Answer - Click Here:
True
while(number<=10);

{

cout<<“number is “<<number<<endl;

number++;

}

2. What is the error in code above?

Answer - Click Here:
Error: while(number<=10);

Correct: while(number<=10)

 

Fazal Rehman Shamil Click Here to Know More
Instructor, Researcher, Blogger, SEO Expert, Poet and Publisher of International Journal Of Software, Technology & Science ISSN : 2616 - 5325
Dear Professors and Resarchers!You are welome to Cite these tutorials in your research or slides etc. Please don't forget to mention the reference of website. Copy Paste of text is strcitly forbidden. Images can be reuse because images are protected with watermark.

Leave a Reply

Your email address will not be published. Required fields are marked *