Tutorial on while loops in the
C programming language.
This is not something I need to go into much detail in this tutorial, but it basically takes the stdio header file and includes it during compilation so you can use functions from it.
Defining the main function.
Code:
int loopcount;
int hotdogs;
int total;
int average;
Define a bunch of variables.
Code:
total = 0;
loopcount = 0;
Set values for two of the variables we just defined.
In plain English, while the variable "loopcount" is less than five, do the following.
Code:
printf("Enter number of dogs eaten: ");
Display to user: "Enter number of dogs eaten:"
Get the user's input, then set that as the value for the hotdogs variable.
This will probably confuse a lot of people, but remember when we defined the total variable's value as ZERO? Well, this statement is just saying take the predefined value of total, add it to the hotdogs variable, and set the sum as the new value for total.
Code:
loopcount = loopcount + 1;
Same as what we just did. Take the earlier value of loopcount, and add one to it. BUT, since we're doing a while loop, the compiler will add one UNTIL the value of loopcount is five.
End while loop.
Takes the total variable and divides it by five, then it sets the quotient as the value for average.
Code:
printf("Total number of dogs eaten was %d", average);
getchar();
return 0;
}
Display to the user: "Total number of dogs eaten was <average goes here>"
Then waits for the user to press a key, which will terminate the program, and the return 0 part just tells the OS or observing program that the application terminated successfully.
Full code:
Code:
#include <stdio.h>
int main(void) {
int loopcount;
int hotdogs;
int total;
int average;
total = 0;
loopcount = 0;
while (loopcount < 5) {
printf("Enter number of dogs eaten: ");
scanf("%d", &hotdogs);
total = total + hotdogs;
loopcount = loopcount + 1;
}
average = total/5;
printf("Total number of dogs eaten was %d", average);
getchar();
return 0;
}
Hope you enjoyed this tutorial!