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;
}
Related
Something is wrong. I'm trying to make a cade which can count number count of any natural number. Like number count of 2 is 1, 30 is 2, 456 is 3. My code is running for 1 digit numbers but not for two digit numbers.
#include<stdio.h>
void main(void)
{
int num,count,check;
float div;
printf("Enter a natural number\n");
scanf("%d", &num);
while (num<=0)
{
printf("Error\n");
printf("Enter a number\n");
scanf("%d", &num);
}
while(num>1)
{
count=1;
check=10;
div=num/check;
if(div<=1)
{
printf("Number count is\n%d", count);
break;
}
check = check*10;
count = count+1;
}
}
The problem with your solution is that after check and count are modified at the end of the loop, they are re-declared to 1 and 10 respectively at the beginning of the loop at every passage.
You need to move the declaration just before the while loop.
Also div doesn't need to be a float given that the decimal part of this number is irrelevant.
You could also use less variables by replacing check by 10 and
using num directly instead of temporarily storing results in div.
I think this might be a simpler solution
#include <stdio.h>
int main(){
int num = 0, digits = 0;
while (num <= 0)
{
printf("Enter a natural number\n");
scanf("%d", &num);
num == 0 ? printf("Error\n") : 0;
}
for( ; num > 0; digits++)
num /= 10;
printf("number of digits: %d\n", digits);
}
As num is continuously divided by 10, the decimal of the result gets truncated since num is an int while digits steadily increases.
It is time to learn to use a debugger. Using it would have immediately shown the major problem in your code: you reset the value of count and check inside the loop. So if you enter a number greater or equal to 10, you enter an infinite loop because you will consistently divide that number by 10 and find that the result is >= 1!
There is another less important problem: you use if(div<=1) when it should be if(div<1). Because 10/10 is 1 and has 2 digits...
After those fixes you should have:
...
check = 10;
count = 1;
while (num > 1)
{
div = num / check;
if (div < 1)
{
printf("Number count is\n%d", count);
break;
}
check = check * 10;
count = count + 1;
}
return 0; // main shall return an int value to its environment...
}
Which correctly gives the number of decimal digit on positive integers. But as you were said in comments, you should always test the return value of scanf (what is the user inadvertently types a t instead of 5 for example?).
That being said, this answer intends to show you what the problems were, but Keyne's solution is better...
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;
}
I'm just beginning C, and I am encountering a logic error when trying to output the average of numbers entered. I will provide the source code of the program below.
// integer_sequence_avg.c
// Inputs a sequence of integers then averages them and outputs the result after the sentinel value "9999" is entered.
#include <stdio.h>
int main(void) {
// initializaiton
int addend = 0;
int sum = 0;
int average;
unsigned int counter;
for (addend; addend != 9999; ++counter) {
printf("%s", "Enter an integer to be averaged. Enter \"9999\" when you want to receive the average: "); // prompt to enter integers to be averaged
scanf("%d", &addend); // scans input into variable to be added to sum
if (addend != 9999) {
sum += addend; // Adds addend to sum
}
}
if (counter != 0) {
average = sum / counter; // Calculates average
printf("\nThe average of the integers added was %d\n\n", average); // Outputs average of numbers entered
} else {
printf("\nNo integers were entered.\n\n"); // Outputs that no integers were entered
}
system("pause");
return 0;
}
logic error screenshot
https://i.stack.imgur.com/Fwwaa.png
counter is incremented without being initialized. This invoked undefined behavior.
counter is incremented even when addend != 9999 is false.
Return values of scanf() should be checked to see if it successfully read things.
Instead of this
unsigned int counter;
for (addend; addend != 9999; ++counter) {
printf("%s", "Enter an integer to be averaged. Enter \"9999\" when you want to receive the average: "); // prompt to enter integers to be averaged
scanf("%d", &addend); // scans input into variable to be added to sum
if (addend != 9999) {
sum += addend; // Adds addend to sum
}
}
Try this:
unsigned int counter = 0;
while ( addend != 9999 ) {
printf("%s", "Enter an integer to be averaged. Enter \"9999\" when you want to receive the average: "); // prompt to enter integers to be averaged
if (scanf("%d", &addend) != 1) break; // scans input into variable to be added to sum
if (addend != 9999) {
sum += addend; // Adds addend to sum
++counter;
}
}
The problem is here:
for (addend; addend != 9999; ++counter) {
where counter is not initialized before using.
The fix: unsigned int counter = 0;
The only thing to address beyond that is that the counter value is being incremented once beyond what it should, giving wrong results.
eg, for these inputs:
4+6+8+9
Average should be 27/4 == 6, but counter == 5 after only 4 entries,
Average is computed as 27/5 == 5
To address this
change average = sum / counter;
to average = sum / (counter - 1);
Beyond that, integer division results in rounding, so unless the numerator contains all of the prime factors of the denominator, the result will invoke integer rounding. If that is a concern, floating point variables should be considered.
I am stuck on the last part of my homework assignment and hope I can get some guidance on what to do. The assignment is simple, I create a program that asks a user to input test scores until they type in my sentinel value of -1. Then the output displays the average of all imputed scores, this is to be repeated 4 times then the program exits. Everything works except my counter value. The counter keeps counting imputed scores from both the previous and current loops instead of only the current loop. So in iteration 2 it is giving me the average of all inputs from the first loop and the current loop.
Note: I haven't learned about arrays or anything else super advance yet.
I already initialized the count variable to 0 but I am can't seem to figure out why it ins't resetting per each loop. I moved the count=0 after the loop and before the loop and that doesn't do anything.
#include <stdio.h>
float calculateAverage(float, float);
FILE *fp;
int main(void)
{
int i;
float avg, score, sum = 0, count = 0;
fopen_s(&fp, "csis.txt", "w");
printf("***Average of Inputed Grades***\n");
for (i = 1; i <= 4; ++i)
{
do
{
printf("\nEnter Test Scores or -1 for average\n");
scanf_s("%f", &score);
fprintf(fp, "\nEnter Test Scores or -1 for average\n%f\n", score);
if (score != -1)
{
sum = sum + score;
count++;
}
} while (score >= 0 && score <= 100 && score != -1);
avg = calculateAverage(sum, count);
printf("\nThe Average for the entered test scores is:%.2lf\n", avg);
fprintf(fp, "\nThe Average for the entered test scores is:%.2lf\n", avg);
}
fclose(fp);
getchar();
return 0;
}
float calculateAverage(float sum, float count)
{
float avg = sum / count;
return (avg);
}
Expected results should display the average of the imputed test scores only for the current iteration then reset itself upon the next iteration.
The sum and count variables aren't resetting after each iteration of the do...while loop because you don't explicitly do so. You do set them to 0 at the start of the function where they're first defined, but you don't reset them again anyplace else.
You need to set both to 0 before entering the do...while loop:
for (i = 1; i <= 4; ++i)
{
sum = 0;
count = 0;
do
{
...
Even better, define sum and count at this point (as well as avg and score) since they're not used outside of the for loop:
for (i = 1; i <= 4; ++i)
{
float sum = 0, count = 0, avg, score;
do
{
...
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.