Introduction to Loops
8
Introduction to Programming
Iteration Control Structure • Doing something more than once – Do until a condition happens – Do as long as a condition happens • Parts of a Loop – Conditional (Boolean) Expression – Body of Loop • Repeat body until conditional is false
Introduction to Programming
Iteration Control Structure 3 Types: • While loop • Do-while loop • For loop
Introduction to Programming
While Loop
Simplest loop in C
Syntax: while (cond) { [statements] }
Semantics: • Continue as long as cond is true: • When cond false, on to next statement • If cond false first time, block isn't executed
Introduction to Programming
Example 1: Using While Loop • Problem: Compute the sum of the numbers between 1 to 10, inclusive. int sum = 0, counter=1; while(counter <=10) { sum = sum + counter; counter++; } Introduction to Programming
Example 2: Using While Loop int main(void) { int number; scanf("%d",&number); while (number >= 0 ) { printf("%d\n", number *2 ); scanf("%d" , &number); } printf("done! \n"); return 0; } Introduction to Programming
Do-While Loop • Always do block at least once • Repeat as long as condition is true do{ [statements] } while (condition); • Notice the semicolon at the end • If condition is false, block done at least once Introduction to Programming
Continue and Break Statements • continue – Ignore rest of loop – Go back to top of loop • break – Ignore rest of loop – Break out of loop
Introduction to Programming
Example: Using Break count = 1; while (count<=10) { scanf("%d",&number); if (number<0) break; count = count+1; } Introduction to Programming
Example: Nested loops #include <stdio.h> int main() { int x ,y; x = 0; do{
y = 0; do{ printf("*"); y = y+1; }while (y < 5);
printf("\n"); x = x+1; }while(x <3); return 0; }
/*y++;*/
/* x++ */ Introduction to Programming
Programming Exercise (while, do-while) • Write a C program that displays at the left margin of the screen a solid triangle of asterisks whose side is an integer value given by the user. For example, if side is 3, the program displays the following patterns, one below the other. Enter number of sides: 3 * ** *** Introduction to Programming
Programming Exercise (while, do-while) • Write a C program that displays at the left margin of the screen a solid triangle of asterisks whose side is an integer value given by the user. For example, if side is 3, the program displays the following patterns, one below the other. Enter number of sides: 3 *** ** * Introduction to Programming