Lec 07 Iteration Loop
Lec 07 Iteration Loop
Autumn 2020
Iterations and
Loops – contd.
An Example
int main() {
int fact, i;
fact = 1; i = 1;
while ( i<10 ) { /* run loop –break when fact >100*/
fact = fact * i;
if ( fact > 100 ) {
printf ("Factorial of %d above 100", i);
break; /* break out of the while loop */
}
++i;
}
return 0;
3}
Test if a number is prime or not
int main() {
int n, i=2;
scanf (“%d”, &n);
while (i < n) {
if (n % i == 0) {
printf (“%d is not a prime \n”, n);
break;
}
++i;
}
if (i == n) printf (“%d is a prime \n”, n);
return 0;
}
More efficient??
int main() {
int n, i = 2, flag = 0;
double limit;
scanf (“%d”, &n);
limit = sqrt(n);
while (i <= limit) {
if (n % i == 0) {
printf (“%d is not a prime \n”, n);
flag = 1; break;
}
i = i + 1;
}
if (flag == 0) printf (“%d is a prime \n”, n);
return 0;
}
continue Statement
continue
Skips the remaining statements in the body of a
while, for or do/while structure while (expr)
Proceeds with the next iteration of the loop statement;
do {
while and do/while
statements;
Loop-continuation test is evaluated immediately } while (expr);
after the continue statement is executed
double x;
for (x=0.0; x<2.0; x=x+0.2)
printf(“%.18f\n”, x);
Nested Loops: Printing a 2-D Figure
repeat 3 times
repeat 5 times
print a row of 5 *’s
print *
Nested Loops
const int ROWS = 3; row = 1;
while (row <= ROWS) {
const int COLS = 5;
/* print a row of 5 *’s */ outer
... loop
col = 1;
row = 1;
while (col <= COLS) {
while (row <= ROWS) {
printf (“* “);
/*print a row of 5 *’s*/ inner
col++; loop
}
... printf(“\n”);
++row; ++row;
} }
2-D Figure: with for loop
Example:
while (i < n) {
for (k=1; k < m; ++k) {
if (k % i == 0) break;
}
i = i + 1; Breaks here
}
int main()
{
int low, high, desired, i, flag = 0;
scanf(“%d %d %d”, &low, &high, &desired);
i = low;
while (i < high) {
Example for (j = i+1; j <= high; ++j) {
if (j % i == desired) {
flag = 1;
break;
} Breaks here
}
if (flag == 1) break;
i = i + 1;
Breaks here
}
return 0;
}
The comma operator
Separates expressions
Syntax
expr-1, expr-2, …,expr-n
where, expr-1, expr-2,… are all expressions
Is itself an expression, which evaluates to the value of the
last expression in the sequence
Since all but last expression values are discarded, not of
much general use
But useful in for loops, by using side effects of the
expressions
Example
1. Read N
N
2. Read Xi 1
3. Compute Mean
N
x
i 1
i
The Problem
Thank You!