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"> 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">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 4 – Chapter 3 Repetition.

Similar presentations


Presentation on theme: "Week 4 – Chapter 3 Repetition."— Presentation transcript:

1 Week 4 – Chapter 3 Repetition

2 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

3 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

4 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); }

5 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


Download ppt "Week 4 – Chapter 3 Repetition."

Similar presentations


Ads by Google