Week 3 – Repetition (ctd.) While, Do-While, For statements
Repetition: Looping Allows execution of statement or block of statements more than once Often used in programs to validate inputs or to process (transform) inputs In C programming language, can use While, Do-While, For statements A single statement or block of statements contained within {} can be repeatedly executed
While Statement (Pre-test Loop) Often want to test the condition before even executing a loop the first time For this use a While or For statement is appropriate; if you don’t know how many times code is to be repeated use a While statement While statement syntax: while (condition) stmt; /* statement is executed as long as condition is true (i.e. until condition is false) */
While Statement Example main() { int numstudents, mark, numread = 0; int total = 0; double avg; printf("Enter number of students: "); scanf("%d", &numstudents); while (numread < numstudents) { printf("Enter mark:"); scanf ("%d", &mark); total = total + mark; numread = numread + 1; } avg = total / numstudents; printf("Average of %d students is: %.2lf\n",numstudents,avg);
For Statement Used if we know how many times a block of code is to be repeated; for example if we want to calculate an average for each student in a class of 10 students we want to repeat it 10 times For statement syntax: for (execute once before entering loop; condition; execute before evaluating condition) stmt;
For Statement Example main() { int i, mark, total = 0; double avg; for (i = 1; i <= 5; i = i+1) { printf("Enter mark %d:",i); scanf ("%d", &mark); total = total + mark; } avg = total / 5; printf("Average of 5 students is: %.2lf\n",avg);
Do-While Statement (Post-test Loop) Often want to execute the statement(s) before testing the condition, even for the first time; i.e. the block of code in the do-while loop is always executed unconditionally the first time Often used for validating input Do - While statement syntax: do stmt; while (condition) /* statement is executed as long as condition is true (i.e. until condition is false) */
Do - While Statement Example main() { int numstudents = 0; do { if (numstudents < 0) printf("Invalid! Number must be >= 0\n"); printf("Enter number of students: "); scanf("%d", &numstudents); } while (numstudents < 0); printf("Number of students in class: %d\n", numstudents); }