c program regarding loops - loops

program wherein there shouldn't be negatives in the equation and it will end when 0 as input
#include <stdio.h>
int main() {
double number, sum = 0;
int average;
int count;
do {
printf("Enter a number: ");
scanf("%lf", &number);
count++;
if (number > 0)
sum += number;
average = sum / (count);
} while (number != 0);
printf("Average is %.1lf", average);
return 0;
}

In your program you are counting all numbers independent on whether they are positive or negative
do {
printf("Enter a number: ");
scanf("%lf", &number);
count++;
//...
Also it does not make a sense to calculate the average within the do while loop.
average = sum / (count - 1);
And it is unclear why the variable average has the type float instead of double.
float average;
And you forgot to initialize the variable count.
Pay attention to that the user can enter neither positive number.
And as it follows from the title of your question you are going to enter integer numbers not double.
The program can look the following way
#include <stdio.h>
int main( void )
{
double sum = 0.0;
double average = 0.0;
size_t count = 0;
while( 1 )
{
printf( "Enter a number: " );
int number;
if ( scanf( "%d", &number ) != 1 || number == 0 ) break;
if ( number > 0 )
{
sum += number;
++count;
}
}
if ( count != 0 ) average = sum / count;
printf( "Average is %f\n", average );
return 0;
}

Firstly, you didn't initialize your count variable. That said, you should increment the count variable only when a non negative value is encountered. Unrelated but I'd recommend you calculate the average outside the loop, as below:
#include <stdio.h>
int main()
{
double number, sum = 0;
float average;
int count = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &number);
if (number > 0)
{
sum += number;
count++;
}
} while (number != 0); //should it stop with 0 or 1? assuming 0
average = sum / count;
printf("Average is %.1lf\n", average);
return 0;
}

First of all, always enable your compiler's warnings. I use -Wall -Wextra -pedantic with gcc and clang. This would have caught the first of the problems listed below if nothing else.
There are many problems.
count is not initialized.
Negative numbers aren't included in the sum as you claim, but they do affect the average because you increment count for negative numbers too.
The assignment asks for you to loop until you get zero, but you loop until you get -1.
The formula for average isn't sum / (count - 1).
average is calculated over and over again for no reason.
You don't handle the case where no inputs are entered, leading to a division by zero.
average is a float, which is odd since you it's built from double values.
You should check the value returned by scanf for errors or end of file.
You don't emit a line feed after your output.
#include <stdio.h>
int main(void) {
int count = 0.0;
double sum = 0.0;
while (1) {
printf("Enter a number: ");
double number;
if ( scanf("%lf", &number) < 1 ) // Invalid input or EOF.
break;
if ( number == 0.0 )
break;
if ( number < 0.0 )
continue;
count++;
sum += number;
}
if (count) {
double average = sum / count;
printf("Average is %.1lf\n", average);
} else {
printf("Nothng to average\n");
}
return 0;
}

Related

Sum and average for n numbers with -1 as exit integer

Hello I have a small problem with my code and I want to understand it. My task is to write a program that take the sum and average for n numbers with while loops or nested while loops with if conditions, when you want to exit the code you should enter -1. The code is down below. The problem I have is that I can't get it to exclude the -1 from the calculation. What am I doing wrong. And it is suppose to be a simple code.
int main(void) {
int count;
float sum, average, number;
sum = 0;
count = 0;
printf("Calculate sum and average (-1 to quit)\n");
while (number!=-1) {
scanf("%f", &number);
sum = sum + number;
count = count + 1;
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
in the while block, you read the number and then add it to your average calculation, and only then after the iteration repeats you're checking if it's different than -1 to stop the iteration:
there are obviously different ways to solve it:
one way can be to use while(true) and in the while block after you read the number add an if statement to compare it with -1 and break out of the loop
while (true) {
scanf("%f", &number);
if (number == -1) break;
sum = sum + number;
count = count + 1;
}
Reordering the different steps could solve this:
int main(void) {
int count;
float sum, average, number=0.0f;
sum = 0;
count = -1;
printf("Calculate sum and average (-1 to quit)\n");
while (number!=-1) {
sum = sum + number; // first time no effect with 0
count = count + 1; // first time "no effect" counting to 0
scanf("%f", &number); // will not be counted or summed if -1
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
Think it through with immediatly entered -1:
sum is 0+0, suitable for no numbers being added up
count is -1+1==0, suitable for no numbers
dividing by 0 should be avoided, but that is a separate issue
Think it through with one number:
number is read in with sum==0 and count==0
is not -1, so loop iterates again
sum and count are updated meaningfully
-1 one is entered
loop ends without processing -1
By the way, comparing a float for identity is risky. You would be safer if you could compare more "generously", e.g. while (number>-0.5).
I think you should take the input at the last of the loop as it will get check in the next iteration. And when -1 comes up it will not be added.
#include <stdio.h>
int main(){
int count=0;
float sum=0, average=0, number=0;
printf("Calculate sum and average (-1 to quit)\n");
while(number!=-1){
sum = sum + number;
count = count + 1;
scanf("%f", &number);
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
Code needs to test number as -1 before including it in the summation. OP's code test almost does this right. OP's code test for -1 before number is even assigned leading to undefined behavior (UB).
float number;
while (number!=-1) { // UB!
Also good to test the return code of scanf() for success.
while (scanf("%f", &number) == 1 && number != -1) {
sum = sum + number;
count = count + 1;
}

Average of Numbers in a Loop

In my C Program, I want to get the average of the sum of numbers being entered until the program stops. What should I add to check the average? Thank you!
#include <stdio.h>
int main (void)
{
int x;
int sum = 0;
int average;
int testEOF;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%d", &x);
if (testEOF !=EOF)
sum +=x;
} while (testEOF !=EOF);
printf ("\nTotal: %d\n", sum);
printf ("\nAverage: %d\n", average);
return 0;
//main
}
As other people explained, you have to initialize sum and count, they are never given their initial values. No need to initialize average and x because you assign sum/count to average and users will assign any value to x.
You have to put everything you want your if statement to do in {...}. But you didn't. Your if statement only does sum +=x and does not work for count++ and average = sum / count. So your program increases the value of count even after EOF. So you found 14/6 rather than 14/5.
You checked testEOF != EOF twice. One is in the if statement, other is in do-while.
I put the code below:
#include <stdio.h>
int main (void){
float x;
float sum = 0;
float count = 0;
float average;
float testEOF;
printf("Enter your numbers: <EOF> to stop.\n");
while(1){
testEOF = scanf("%f", &x);
if (testEOF ==EOF){
break;
}
sum +=x;
count++;
average = sum / count;
}
printf ("\nTotal: %f\n", sum);
printf ("\nAverage: %.2f\n", average);
return 0;
}
#include <stdio.h>
int main (void)
{
float x;
float sum;
float count;
float average;
float testEOF;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%f", &x);
if (testEOF !=EOF)
sum +=x;
count++;
average = sum / count;
} while (testEOF !=EOF);
printf ("\nTotal: %f\n", sum);
printf ("\nAverage: %.2f\n", average);
return 0;
}
This is now almost correct. The only thing is that the number is not getting divided by the number of values entered.
Example:
2
3
3
3
3
Sum is 14
Average: 2.3 (should be 2.8)
This seems that count is being added by 1 every time I get the average.
Well if you want your output to be printed with decimal point you can do the following , in that case
for inputs like 0, 1, 1 the out would be 0.666667 otherwise it will be simply 0 ignoring the decimal part.
the while part can be optimized as suggested by #David C. Rankin
double sum = 0;
double average = 0;
unsigned int count = 0;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%d", &x);
if (testEOF != EOF)
{
sum += x;
count++;
}
} while (testEOF != EOF);
printf ("\nTotal: %f\n", sum);
average = sum / count;
printf ("\nAverage: %f\n", average);

Why are my values for sum and count being lost each loop?

I'm getting a consistent divide by zero error, even though each loop should be populating the variables. Code below:
#include <stdio.h>
void calculateAverage()
{
int grade, count, sum;
double average;
sum = 0;
count = 0;
grade = 0;
average = 0.0;
int coolvalue = 0;
while (coolvalue==0)
{
scanf("%d", &grade);
if (grade == -1)
{
sum, sizeof(double);
count, sizeof(double);
average = (sum / count);
printf("%lf", &average);
break;
}
else
{
if ((grade > 100) || (grade < -1))
{
printf("Error, incorrect input.\n");
break;
}
else
{
sum = +grade;
count = count + 1;
return count;
return sum;
}
}
}
coolvalue = 1;
}
int main(void)
{
while (1)
calculateAverage();
while (1) getchar();
return 0;
}
Even while using return, I'm not able to properly increment the value of sum or count.
There are multiple issues in your code.
scanf("%d", &grade); - you don't check the value returned by scanf(). It returns the number of values successfully read. If you enter a string of letters instead of a number, scanf("%d") returns 0 and it does not change the value of grade. Because of this the code will execute the rest of the loop using the previous value of grade. You should restart the loop if the value returned by scanf() is not 1:
if (scanf("%d", &grade) != 1) {
continue;
}
Assuming you enter 10 for grade this block of code executes:
sum = +grade;
count = count + 1;
return count;
return sum;
sum = +grade is the same as sum = grade. The + sign in front of grade doesn't have any effect. It is just the same as 0 + grade.
You want to add the value of grade to sum and it should be sum += grade. This is a shortcut of sum = sum + grade.
return count makes the function complete and return the value of count (which is 1 at this point) to the caller. The caller is the function main() but it doesn't use the return value in any way. Even more, your function is declared as returning void (i.e. nothing) and this renders return count incorrect (and the compiler should warn you about this).
return sum is never executed (the compiler should warn you about it being dead code) because the function completes and the execution is passed back to the caller because of the return count statement above it.
Remove both return statements. They must not stay here.
If you enter -1 for grade, this block of code is executed:
sum, sizeof(double);
count, sizeof(double);
average = (sum / count);
printf("%lf", &average);
break;
sum, sizeof(double) is an expression that does not have any effect; it takes the value of sum then discards it then takes the value of sizeof(double) (which is a constant) and discards it too. The compiler does not even generate code for it.
the same as above for count, sizeof(double);
average = (sum / count);:
the parenthesis are useless;
because both sum and count are integers, sum / count is also an integer (the integral result of sum / count, the remainder is ignored).
you declared average as double; to get a double result you have to cast one of the values to double on the division: average = (double)sum / count;
if you enter -1 as the first value when the program starts, count is 0 when this code is executed and the division fails (division by zero).
printf("%lf", &average); - you want to print the value of average but you print its address in memory. Remove the & operator; it is required by scanf() (to know where to put the read values). It is not required by printf(); the compiler generates code that passes to printf() the values to print.
break; - it passes the execution control after the innermost switch or loop statement (do, while or for). It is correct here and makes the variable coolvalue useless. You can simply remove coolvalue and use while (1) instead.
All in all, your function should look like:
void calculateAverage()
{
int sum = 0;
int count = 0;
int grade = 0;
double average = 0.0;
while (1) {
if (scanf("%d", &grade) != 1) {
// Invalid value (not a number); ignore it
continue;
}
// A value of -1 signals the end of the input
if (grade == -1) {
if (count > 0) {
// Show the average
average = (double)sum / count;
printf("Average: %lf\n", average);
} else {
// Cannot compute the average
puts("You didn't enter any value. Cannot compute the average.\n");
}
// End function
return;
}
if ((grade < -1) || (100 < grade)) {
puts("Error, incorrect input.\n");
// Invalid input, ignore it
continue;
}
sum += grade;
count ++;
}
}
Quite a few corrections need to be made.
The while loop in the calculateAverage() function. That's an infinite loop buddy, because you are not changing the value of that coolValue variable anywhere inside, instead you make it 1 only when it exits the loops, which it never will.
So, use while(1) {...}, and inside it, check for the stopping condition, i.e, if (grade == -1) { ... } and inside it calculate and print the average and return. This will automatically break the while.
You're not checking if the input grade is actually a valid integer or not. Check the value of scanf for that, i.e, use if (scanf("%d", &grade) != 1) { ... }
The expression sum = +grade; is just another way of writing sum = 0+grade which in turn is nothing but sum = grade. Replace this with sum += grade;. This is the right way to write a shorthand for addition.
Two return statements..a very wrong idea. First of all, a function can have just one return(in an obvious way I mean, at once). Secondly, the function calculateAverage() is of return-type void. there's no way how you can return double value from it. So remove these two statements.
I have attached the code below which works. Also do go through the output which I have attached.
CODE:
#include <stdio.h>
void calculateAverage()
{
int grade, count = 0, sum = 0;
double average;
printf("\nenter the grades... enter -1 to terminate the entries\n.");
while (1) {
printf("\nEnter the grade: ");
if (scanf("%d", &grade) != 1) {
printf("\nInvalid characters entered!!!");
continue;
}
else if(((grade > 100) || (grade < -1))) {
printf("\nInvalid grade entered!!!");
continue;
}
else {
if (grade == -1) {
average = sum/count;
printf("\nAverage value of grades: %.3lf",average);
return;
}
else {
sum += grade;
count++;
}
}
}
}
int main(void)
{
calculateAverage();
return 0;
}
OUTPUT:
enter the grades... enter -1 to terminate the entries.
Enter the grade: 50
Enter the grade: 100
Enter the grade: 60
Enter the grade: -1
Average value of grades: 70.000
Perhaps it is better for the function to be of type double instead of void. Although it is not my favorite solution it is close to what you want.
#include <stdio.h>
double calculateAverage(void)
{
double average;
int sum = 0, count=0, grade;
while (1)
{
scanf("%d", &grade);
if ((grade > 100) || (grade < -1))
printf("Error, incorrect input.\n");
else if (grade != -1)
{sum = sum+ grade; count = count + 1;}
else
break;
}
if (count==0)
average=-1.0; //none valid input. Notify the main()
else
average=(double)sum/count;
return average;
}
int main(void)
{
double result;
result= calculateAverage();
if (result!=-1.0)
printf("\n average= %lf",result);
else
printf("No grades to calculate average");
getchar();
return 0;
}

Calculating the average of user inputs in c

disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.

How do I adjust this code to allow for an unspecified number of positive integers

I am completely new to programming and I'm currently taking a Intro to programming course. I need to adjust the below code to allow for an unspecified number of positive integers. I've looked this up and it seems to not take the average correctly. Please help. Thank you.
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
double avg;
/* Initialize variables */
count = 0;
sum = 0;
avg = 0.0;
// Loop through to input values
while (count < 20)
{
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum = sum + value;
count = count + 1;
}
else {
printf("Value must be positive\n");
}
}
// Calculate avg. Need to type cast since two integers will yield an
// integer
avg = (double) sum/count;
printf("average is %lf\n ", avg );
return 0;
}
You can use infinite loop and check for negative value and the return result of scanf as conditions to break.
Sample code looks like:
for(;;)
{
printf("Enter a positive Integer\n");
if(scanf("%d", &value) == 1 )
{
if (value >= 0) {
sum = sum + value;
count = count + 1;
}
else {
printf("Value must be positive\n");
break;
}
}
else
{
break;
}
}
Also, your initialization code is ok, but can be done cleaner this way (there is no need to separate between declaration and initialization - you can group them into one line):
int count = 0, value = 0, sum = 0;
double avg = 0;

Resources