Week 4 – Chapter 3 Repetition
Input Validation using If statement To process only valid inputs you could use an if statement to test for invalid inputs For example an invalid input for number of doughnuts sold would be any negative number if ( quantity <= 0 ) printf("Number of doughnuts must be > 0!\n"); else { … } Have to rerun program if input is invalid Would be better if program allows repetition: to repeatedly asks user to enter input until it is valid
Loop – Repetition of Code Often need to repeat execution of a group of statements – for example, for input validation or calculations In programming this repetition is called looping Can be accomplished in C by: while, do while and for statements while statement syntax: while ( condition ) statement; statement is repeatedly executed provided condition is true
While Example : Input validation … printf("Enter number of doughnuts: "); scanf("%d", &quantity); while ( quantity <= 0 ) { printf(“Must have 1 or more doughnuts!\n"); scanf ("%d", &quantity); }
While Example: Calculation of average … int count = 0; printf(“How many students? "); scanf("%d", &numberStudents); while ( count < numberStudents ) { printf("Enter mark:"); scanf("%d", &mark); classTotal = classTotal + mark; count = count + 1; } average = classTotal / numberStudents; printf("Class average: %.1lf\n", average); count++; warning! – must not be integer division