While Loop Tutorial

Factor8™

Active Member
Reputation
0
Tutorial on while loops in the C programming language.


Code:
#include <stdio.h>

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.

Code:
int main(void) {

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.

Code:
while (loopcount < 5) {

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

Code:
scanf("%d", &hotdogs);

Get the user's input, then set that as the value for the hotdogs variable.

Code:
total = total + hotdogs;

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.

Code:
}

End while loop.

Code:
average = total/5;

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!
 
Factor8â„¢ said:
Code:
#include <stdio.h>

You don't really need to know what this means, but it basically takes the stdio header file and includes in during compilation so you can use functions from it.

False. You *do* need to know what that means. If you didn't, how would you know what functions and such are included in that header file? How would you know if you need a different header file? YOU NEED TO KNOW THIS. :yes3:
 
I didn't say you don't need to know what a header file is and what functions it includes, I said you don't need to know what that statement really means, but I explained it anyway.
 
Back
Top