0% found this document useful (0 votes)
3 views3 pages

C++ While Loop Examples and Syntax

Uploaded by

lysarith09
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

C++ While Loop Examples and Syntax

Uploaded by

lysarith09
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

While Loop:

Syntax:
while(Logic-Expression){
Statements;
}
Example 1: គណនាផលបូក sum = 1+2+3+…+n (n>=1)
C++ Code:
#include<iostream>
using namespace std;

int main(){
//While Loop
//sum = 1+2+3+...+n (n>=1)
//Variable Declaration
int x, n, sum;
//Read n
cout << "Read n:";
cin >> n;//5
//If Else
if(n >= 1){
//n>=1
//Calculate sum = 0
sum = 0;
x = 1;
//Using while loop
while (x <= n)
{
sum += x;//0+1+2+3+4+5
x++;//1+1=2+1=3+1=4+1=5+1=6
}
cout << "Sum: " << sum;//1+2+3+4+5
}else{
//n<1
cout << "n must be greater than or equal 1";
}
return 0;
}
Output:
Example 2: គណនាផលបូក sum = 1+3+5+…+(2n-1) (n>=1)
#include<iostream>
using namespace std;

int main(){
//While Loop
//sum = 1+3+5+...+(2n-1)) (n>=1)
//Variable Declaration
int x, n, sum;
//Read n
cout << "Read n:";
cin >> n;//3
//If Else
if(n >= 1){
//n>=1
//Calculate sum = 0
sum = 0;
x = 1;
//Using while loop
while (x <= n)
{
sum += ((2*x)-1);//0+1+3+5
x++;//1+1=2+1=3+1=4
}
cout << "Sum: " << sum;//1+3+5
}else{
//n<1
cout << "n must be greater than or equal 1";
}
return 0;
}
Output:

Example 3: គណនាផលគុណ factorial = 1*2*3*…*n =n! (n>=0)


#include<iostream>
using namespace std;

int main(){
//While Loop
//factorial = 1*2*3*...*n (n>=0)
//Variable Declaration
int x, n, factorial;
//Read n
cout << "Read n:";
cin >> n;//3
//If Else
if(n >= 0){
//n>=0
//Calculate sum = 0
factorial = 1;
x = 1;
//Using while loop
while (x <= n)
{
factorial *= x;//1*1*2*3*4
x++;//1+1=2+1=3+1=4+1=5
}
cout << "factorial: " << factorial;//1*2*3*4
}else{
//n<0
cout << "n must be greater than or equal 0";
}
return 0;
}
Output:

You might also like