Contents
While loop In the C/C++ Language
While loop:
In the C++ language, while loop is the simplest loop. It uses when we cannot know about the number of iterations in advance. The syntax of while loop is:
while (condition){
statement(s);
}
- while: while is a keyword.
- condition: On the base of the condition, all loops are executed. Conditions are given as a relational expression.
- statement(s): Statement or statements are the instructions that execute when the condition will true.
Firstly the loop checks the condition. This loop executes one or more time while the condition remains true. Flowchart of the while loop is:
Working:
Firstly, the compiler will check the condition. If condition will true then the compiler will enter in the body of the loop and start to execute all the statements within the body. After this process, it again moves to the condition and checks again. This process will break when the condition will false. A loop that will never end called infinite loop.
Examples:
- Write a program that will print even numbers from 1 to 50.
#include < iostream >
using namespace std;
int main(){
int even = 1;
while(even <= 50 && even % 2 == 0 ){
cout << even << “\t” ;
even++;
}
return 0;
}
- Write a program that will print 1 to 5 numbers with their squar root.
#include < iostream >
using namespace std;
int main(){
int num = 1;
cout<< “num \t squar root”
while(num <= 5 ){
cout << num << “\t” << num * num;
n++;
}
return 0;
}
- Write a program that will print the following: 1 + 1/2 + 1/4 + 1/6 + … + 1/20.
#include < iostream >
using namespace std;
int main(){
int even = 1;
float result = 1;
while( even <= 20 ){
result = result + 1 / even ;
even = even +2;
}
cout << ” result is : ” << result ;
return 0;
}
- Write a program that will print the factorial a number that will get by a user as input using while loop.
#include < iostream >
using namespace std;
int main(){
int factorial = 1, num ;
cout << ” enter a number: “;
cin >> num ;
n = num ;
while( num > 0 ){
factorial = fatorial * num ;
num — ;
}
cout << “factorial of ” << n << ” is : ” << factorial ;
return 0;
}
If you have any type of query than contact us.
We start a new course that will about blogger website. We also have provided the Free online computer courses check them out and also visit our facebook page.