Further example of loops
Let us consider how to count the number of values falling into certain ranges in a set of input data.
Here we combine the power of the while and if statements to achieve this.
#include <stdio.h>
/*Counts ranges in a sequence of integers*/
void main() {
int Next, TotalTo10, TotalTo20, TotalTo30, TotalOver30;
/*Initialisation*/
scanf("%d",&Next);
TotalTo10 = 0;
TotalTo20 = 0;
TotalTo30 = 0;
TotalOver30 = 0;
/*Loop*/
while (Next != -1) {
if (Next<=10)
TotalTo10 = TotalTo10 + 1;
else if (Next<=20)
TotalTo20 = TotalTo20 + 1;
else if (Next<=30)
TotalTo30 = TotalTo30 + 1;
else TotalOver30 = TotalOver30 + 1;
scanf("%d",&Next);
} /*Loop statement*/
printf("The total under 11 is %d\n", TotalTo10);
printf("The total under 21 is %d\n", TotalTo20);
printf("The total under 31 is %d\n", TotalTo30);
printf("The total over 30 is %d\n", TotalOver30);
}
Plain text version to compile
Exercises on this section.
Next - switch statements.
Back to Contents page.