Table of Contents
In this article, we discuss the While in C++ programming language.
In the C++ programming language, the while loop used to executes the block of code repeatedly until the particular condition is satisfied.
Generally, loops are used to repeat a block of code
C++ language has three types of loops
In this post, we are going to learn the While in Cpp programming language. with example program
Syntax
| Syntax in while loop in C++ |
Flow diagram
| Flow diagram of While loop in C++ |
Test Expression is checked on each and every entry of the while loop
Program 1
This program used to display natural numbers 1 to 10
#include <iostream>
using namespace std;
int main()
{
int counter=1; // initialized variable
while(counter<=10) //Test expresiion
{
cout << counter<<"-> number of student" << endl; //Display statement
counter++; //Increment statement
}
return 0;
}
When the above code is executed it produces the following result
Programme 2
This program allows to enter a number and calculate the factorial of given number
#include <iostream>
using namespace std;
int main() {
int number, i = 1, factorial = 1;
cout<< "Enter a positive integer: ";
cin >> number;
while ( i <= number) {
factorial *= i; //factorial = factorial * i;
++i;
}
cout<<"Factorial of "<<number<<" = "<<factorial;
return 0;
}
When the above code is executed it produces the following result
Program 3
The program allows the user to enter a number and calculates sum of 1 to given number
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int num,sum=0;
cout << "Enter a positive integer" << endl;
cin>>num;
int i=1;
while(i<=num){
sum+=num; //sum=sum+num;
i++;
}
cout<<"The sum of 1 to "<<num<<" : "<<sum;
getch();
return 0;
}
When the above code is executed it produces the following result
Enter a positive integer 40 The sum of 1 to 40 : 1600
Multiply two numbers in Java using scanner| 5 different ways In this article, we will…
5 Different ways to Divide two numbers in Java using scanner In this article, we…
Learn 8 Ways to Subtract Two Numbers Using Methods in Java In this article, we…
10 ways to subtract two numbers in Java In this article, we will discuss the…
Java Code Examples – Multiply Two Numbers in 5 Easy Ways In this article, we…
How to Divide two numbers in Java| 5 different ways In this article, we will…
This website uses cookies.