Loop

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Sample 1: Sum of First 10 Natural Numbers

int i, sum = 0;
for (i = 1; i <= 10; i++)
{
sum = sum + i;
}
cout << "\n The sum of first 10 natural numbers: " << sum << endl;

sum i i<=10 sum=sum+i i++


0 1 T 0=0+1=1 2
1 2 T 1=1+2=3 3
3 3 T 3=3+3=6 4
6 4 T 6=6+4=10 5
10 5 T 10=10+5=15 6
15 6 T 15=15+6=21 7
21 7 T 21=21+7=28 8
28 8 T 28=28+8=36 9
36 9 T 36=36+9=45 10
45 10 T 45=45+10=55 11
55 11 F
The sum of first 10 natural numbers: 55

Sample 2: Reverse Number: Let n=1234

int n, rev_n = 0, rem;

cout << "Enter an integer: ";


cin >> n;

while(n != 0) {
rem = n % 10;
rev_n = rev_n * 10 + rem;
n =n/10;
}
cout << "Reversed Number = " << rev_n;

Expected Output=4321

n rev_n rem while(n != 0) rem = n % 10 rev_n = rev_n * 10 + n =n/10


rem
1234 0 0 1234!=0=T 0=1234%10=4 0=0*10+4=4 1234=1234/10=123
123 4 4 123!=0=T 4=123%10=3 4=4*10+3=43 123=123/10=12
12 43 3 12!=0=T 3=12%10=2 43=43*10+2=432 12=12/10=1
1 432 2 1!=0=T 2=1%10=1 432=432*10+1=4321 1=1/10=0
0 4321 1 0!=0=F
Reversed Number = 4321
3. Triangle
int i, j, rows;

cout << " Input number of rows: ";


cin >> rows; // Read input for the number of rows from the user

let row=5
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; j++)
{
cout << "*";
}
cout << endl; }

i i <= rows j j <= i cout << "*"; j++ i++

1 1<=5=T 1 1<=1=T * 2 2
2<=1=F
2 2<=5=T 1 1<=2=T ** 2
2 2<=2=T 3
3 3<=2=F 3
3 3<=5=T 1 1<=3=T *** 2
2<=3=T 3
3<=3=T 4
4<=3=F 4
4 4<=5=T 1 1<=4=T **** 2
2 2<=4=T 3
3 3<=4=T 4
4 4<=4=T 5
5<=4=F 5
5 5<=5=T 1 1<=5=T ***** 2
2 2<=5=T 3
3<=5=T 4
4<=5=T 5
5<=5=T 6
6<=5=F 6
6 6<=5=F

*
**
***
****
*****
3. Fibonacci Series
int n1=0,n2=1,n3,i,number;
cout<<n1<<" "<<n2<<" ";
for(i=2;i<number;++i)
{
n3=n1+n2;
cout<<n3<<" ";
n1=n2;
n2=n3;
}
i i<number; n3=n1+n2; cout<<n3<<" "; n1=n2; n2=n3; ++i
2 2<10=T 0=0+1=1 1 2 3 5 8 13 21 34 1 1 3
3 3<10=T 1=1+1=2 1 2 4
4 4<10=T 2=1+2=3 2 3 5
5 T 3=2+3=5 3 5 6
6 T 5=3+5=8 5 8 7
7 T 8=5+8=13 8 13 8
8 T 13=8+13=21 13 21 9
9 T 21=13+21=34 21 34 10
10 F

You might also like