Post on 20-Jan-2016
The while loopExecutes a block as long as the condition is true
general form: while (condition) { statement 1; statement 2; … statement n; }
The While Statement
Execution of a while loop
• Condition evaluated– If condition evaluates to false
• loop terminates – execution passes to first line of code outside loop
– If condition evaluates to true• Body of loop is executed
• Process is repeated from beginning
Sample While Statement
int main ( ) { int count; count = 1; while (count <=20) {
printf (“\n%d”, count); count ++;
}
return 0; }
Sample Program 5.1#include <stdio.h>
int main( void ) {int increment = 0;int counter = 0;
printf("Please enter the increment: ");scanf("%d", &increment);printf("\n\n");
while (counter < 20){
printf("%d ", counter+=increment);}
return 0;}
Compare the for Loop & while int count; for (count=1; count <=20; count++) { printf (“\n%d”, count); } ---------------------------------------------------- int count = 1; while (count <=20) { printf (“\n%d”, count); count++; }
Writing a while loop
Write the C code to print the odd numbers less than 20 using a while loop
void main () { int count = 1; while (count < 20) { printf (“\n%d”, count); count += 2; } }
Sample Program 5.2
//Rewrite this using a while loop
#include <stdio.h>
int main( void ) {int counter = 0, sign_change = 1;
for (; counter < 20; counter++) {printf("%d\n", counter*sign_change);sign_change *= -1;
}
return 0;}
Uses of the while loop
• Iterating until the a flag is set indicated the process should be terminated– sentinel
• Iterating until the user enters valid data– data validation
The while loop and a sentinel
printf (“Enter a test score (0 to finish)”);
printf (“The average will be calculated”);
scanf (“%d”, &score);
count = 0;
while (score != 0) {
count += 1;
total += score;
printf (“Enter next score”);
scanf (“%d”, &score);
}
//Calculate average – make sure count > 0
Sample Program 5.3#include <stdio.h>void main () {
int count = 0, total = 0, score = 0;float average = 0;printf("Enter a test score (0 to finish)");printf("\nThe average will be calculated");printf("\n\nEnter first score: ");scanf ("%d", &score);while (score != 0) {
total += score;printf ("Enter next score: ");scanf ("%d", &score);count += 1;
}if (count) {
average = (float)total / count;printf ("\nThe average score is %.2f", average);
}else
printf("\nNo scores entered.");}
The while loop and data validation
//Allow the user to enter a number between 1 and 10 //and validate their entry
printf(“Enter a number between 1 and 10: “); scanf(“%d”, &nbr);
while (nbr < 1 || nbr > 10) {printf(“Invalid data – please enter a number between 1 and 10);scanf(“%d”, &nbr);
}
Sample program 5.4#include <stdio.h>
void main () {int ctr = 0, nbr = 0, array[5];printf("The program will allow the user to enter 5 integers.");printf("\nThe numbers must be between 1 and 10.");printf("\nThe sum of the numbers will then be printed.");while (ctr < 5) {
printf("\n\nEnter number %d (between 1 & 10): ", ctr + 1);scanf("%d", &nbr);while (nbr < 1 || nbr > 10) {printf("\nSorry, the number must be between 1 & 10.");printf("\nEnter number %d (between 1 & 10): ", ctr + 1);scanf("%d", &nbr);}array [ctr] = nbr;ctr ++;
}nbr = 0;for (ctr = 0; ctr < 5; ctr++)
nbr += array[ctr];printf("\n\nThe sum is: %d", nbr);
}
Sample Program 5.5#include <stdio.h>
int main() {int option = 0;
printf("1. Find the largest value");printf("\n2. Find the smallest value");printf("\n3. Find the average");
printf("\n\nPlease make selection: ");scanf("%d", &option);
while ((option < 1) || (option >3)) {printf("Invalid selection, please re-enter (valid values are 1, 2, and 3): ");scanf("%d", &option);
}
printf("\nCongratulations, you entered a valid menu option!!!");
return 0;}
The do … while loopExecutes a block as long as the condition is true
general form: do { statement 1; statement 2; … statement n; } while (condition);
The do … while loop
Execution of a do…while loop
• Body of loop is executed
• Condition is executed– If condition evaluates to false
• loop terminates – execution passes to first line of code outside loop
– If condition evaluates to true• Process is repeated from beginning
Sample Program 5.6#include <stdio.h>void main ( ) {
float average = 0;int count = 0;int score = 0;int total = 0;printf ("Enter a test score: ");scanf ("%d", &score);do {
total += score;count += 1;printf ("Enter next score (0 to finish): ");scanf ("%d", &score);
} while (score != 0);average = (float)total/count;printf ("The average is %.2f", average);
}
Sample Program 5.7//Run the code and fix any errors//Would a while loop work better here than a do…while?#include <stdio.h>void main ( ) {
int choice = 0;
printf ("1 - Add a record");printf ("\n2 - Delete a record");printf ("\n3 - Change a record");printf ("\n\n Enter a selection: ");scanf("%d", &choice);do {
printf("Invalid selection, please re-enter (valid values are 1, 2, and 3): ");scanf("%d", &choice);
} while (choice != 1 || choice != 2 || choice != 3);printf("\nCongratulations, you entered a valid menu option!!!");
}
Comparing loops
• Tasks accomplished with for loop can be accomplished with while or do..while loop.
• For loop has initialization condition, & increment in one spot– increased readability
– generally easier to work with
• If # repetitions cannot be determined before iterations begin, must use while
Comparing loops
• Top-checking loops– Condition is evaluated PRIOR to first iteration
• Loop may never execute
• for loops
• while loops
• Bottom-checking loops– Condition is not evaluated until AFTER the first
iteration• Guaranteed at least one iteration
• do…while loops
Nested loops
• Any loop can be nested within any other loops• for within while
• while within for
• for within do … while
• do … while within for, within while,
• etc.
• Loops must be completely nested within each other
Example of while within for
int count1;
int count2;
for (count1 = 1; count1 < 10; count1++){
count2 = 0;
while (count2 <3) {
printf (“%d”, count2);
count2 ++;
}
}