Professional Documents
Culture Documents
Announcements
Monday lab scheduled on 15th August will instead be held on Saturday, 20th August. Monday lab scheduled on 22nd August will instead be held on Saturday, 27th August. Wednesday lab scheduled on 31st August will instead be held on Saturday, 3rd September. Please approach your tutor for all lab related issues.
Lec-08 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 1
Recap
If statement
Multiple conditions Nested if
Loops
while statement
Lec-08
Acknowledgement
Many of the slides on loops (both while and for statements and the examples) have been borrowed from Dr. Arnab Bhattacharyas class notes of ESc101.
Lec-08
Recap: Loops
Print all numbers between 1 and 100 that are divisible by 7 Algorithm:
1. 2. 3. 4. 5. Initialize x to be 1. Check if x is divisible by 7 If yes, print the value of x Increment x (add 1 to x consider the next number) If x <= 100 go back to step 2
Lec-08
for statement
for (initialization ; condition; update) { statements } Condition evaluates to true/false (boolean) Statements in the loop are executed as long as condition is true. initialization sets the initial values of variables update changes the value of variables d h h l f i bl Value of condition, if initially true, must change at some appropriate later time to false,
Otherwise, infinite loop is created.
Lec-08 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 7
for loop
Print all numbers between 1 and 100 that are divisible by 7 for (x = 1; x <= 100; x = x + 1) { if ((x % 7) == 0) p printf (%d , x); ( ) }
Lec-08
Example: Factorial
int i, n, factorial = 1; i n scanf (%d, &n); for (i = 1; i <= n; i = i + 1) { factorial = factorial * i; } printf (Factorial of %d is %d\n, n, factorial);
Lec-08
10
Example: Factorial
int i, n, factorial = 1; i n scanf (%d, &n); i = 1; while (i <= n) { factorial = factorial * i; i = i + 1; } printf (Factorial of %d is %d\n, n, factorial);
Lec-08 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 11
Lec-08
12
Example: power
Compute xy Assume y to be natural number. answer = 1; for ( i = 1; i <= y; i = i + 1) { answer = answer * x; }
Lec-08
13
Any Questions?
Lec-08
15