Hello, I did do a search and found two posts on the same program, but they didn't quite get me working like I'd like.
The assignment: The user will enter either an integer to be averaged or a sentinel of 999 indicating that no more numbers are to be entered. When the sentinel is entered, the program will exit the repetition loop. It will then compute and display the average of numbers entered.
My program works well ( I think) so far, but I would like for the program to loop back and allow the user to input another integer should they decide to type an invalid character rather than an integer. Currently the program stops if scanf !=1 and averages the numbers correctly.
There are no comments yet, and the prompts are not finished as this is how I test my programs currently.
Code:
#include <stdio.h>
int main()
{
int uInput;
int count = 0;
int sum = 0;
int sentinel = 999;
float average;
printf("purpose, %d \n\n", sentinel);
printf("enter you first number\n");
while (scanf("%d", &uInput)==1)
{
if (uInput == sentinel)
break;
printf("enter another integer or %d to average the values\n", sentinel);
sum += uInput;
count ++;
printf("the sum is now %d\n", sum);
}
if ( count != 0)
{
average= sum/count;
printf("%d numbers input, %d sum, %.3f average", count, sum, average);
}
else
printf ("No valid integers were entered, please restart the program and try again");
//The section below is to stop the program until a key is pressed.
fflush(stdin); //clears the input area so you can pause
printf("\n\n\nPress any key to exit the program."); //prints the message
getchar(); //force the computer to pause until you press a key
return 0; //returns a value of 0 if the program works correct
}
I also have been told that last section is garbage, but our instructor said we have to include those lines.
I can create external functions if this would be easier, but have only written one simple program using pointers and addressing. Any help is greatly appreciated! Thanks in advance!