Iterative Statements
Iterative Statements
Output: 1 3 5 7 9
Eg3:
For i from 10 to 1 step -1 #[if step value negative – initial value > ending value]
Print i
Output: 10 9 8 7 6 5 4 3 2 1
Eg4:
For i from 10 to 1 step -2
Print i
I ->10,1,-2 -> 10 8 6 4 2
0 >= 1 False
Output:
Problems:
1. To find the sum of n numbers
2. To find the factorial of a given number
3. To print the multiplication table
4. To find the sum of squares for the given n numbers
5. To find the sum of cubes for the given n numbers
6. To find the sum of first 10 even nos.
2 + 4 + 6 +8 + 10 +12 + 14 + 16 + 18 + 20
Input n
Sum <- 0
For i from 2 to 2 * n step 2
Sum <- Sum + i
Print Sum
Or
Input n
Sum <- 0
Even <- 2
For i from 1 to n
Sum <- Sum + Even
Even <- Even + 2
1. Sum of n numbers:
Algorithm
Input n
Sum <- 0
For i from 1 to n step 1
Sum = Sum + i
Print Sum
Output: 6
n=5
n Sum = Sum + i i
5 0+1=1 1
5 1+2=3 2
5 3+3=6 3
5 6 + 4 = 10 4
5 10 + 5 = 15 5
5 6
Input n
Sum <- 0
For i from 1 to n step 1
Sum = Sum + i
Print Sum
Output: 1 3 5 10 15
I = 1 to 5,2
Algorithm:
Input n
Product <- 1
For i from 1 to n step 1
Product =Product * i
Print Product
n=5
n Product = Product * i i
5 1*1=1 1
5 1*2=2 2
5 2*3=6 3
5 6 * 4 = 24 4
5 24 * 5 = 120 5
5 6
1*2=2
2*2=4
……….
10 * 2 = 20
n=5
n Sum = Sum +i * i i
5 0+1*1=1 1
5 1+2*2=5 2
5 5 + 3 * 3 = 14 3
5 14 + 4 * 4 = 30 4
5 30 + 5 * 5 = 55 5
5 6
While statement:
While condition
o Statement 1
o Statement 2
o ……………
o Statement n
Eg1:
i <- 1
While i <= 10
Print i
i=i+1
Eg2:
i <- 1
While i <= 10
Print i
i=i+2
Eg3:
i <- 10
While i >= 1
Print i
i=i-1
Eg4:
i <- 10
While i >= 1
Print i
i=i-2