I am creating a program that uses a while loop to provide multiple pieces of information from input given by the user. One of these pieces is the smallest number entered. I can't get it to print anything but 0. Any idea why?
#include <stdio.h>
#include <stdlib.h>
int main()
{
float num, sum = 0, sm, lg = 0, count = 0, avg = 0;
printf("Please enter a series of numbers (-1 to terminate): ");
scanf("%f", &num);
while(num > -1){
sum += num;
if(lg < num)
lg = num;
if(sm > num)
sm = num;
scanf("%f", &num);
count++;
avg = sum / count;
}
printf("The sum of your numbers is: %.4f\n", sum);
printf("You entered %.4f numbers\n", count);
printf("The average of the numbers you entered is: %.4f\n", avg);
printf("The smallest number you entered is: %.4f\n", sm);
printf("The Largest number you entered is: %.4f", lg);
return 0;
}
ex entry- 15
43
22.5
57.6
-1
Output-
sum:138.1000
4 numbers entered
average: 34.5250
smallest: 0.0000
Largest: 57.6000
In your code, sm has an undefined value because you aren't initializing it. You can initialize it to something like a very large number (or, even better, INFINITY) so it can be properly compared. The same goes for lg: if you want it to work for negative values too, you should initialize it with a very small value (-INFINITY). You can use INFINITY by including math.h.
the posted code does not compile!
first, because it is missing the needed #include statements for the needed header files. Specifically:
#include <stdio.h>
Then regarding this code block:
if(sm > num)
sm = num;
on the first pass through the while() loop, the variable sm is not initialized so accessing its' contents is undefined behavior.
Also, if using visual studio in debug mode, then all the stack is cleared to 0, so no other value will ever be assigned to it. This is why the algorithm always returns 0
Here's what I regard as a workable program. It uses double rather than float; if you insist, you can change the types and (input) formats to suit your desires. It has no particular limit on the number of rows it will accept. It doesn't output anything if there were no inputs. There is absolutely no need to use an array for the calculations. It uses use +∞ and -∞ to initialize the smallest (min) and largest (max) values respectively. Even if the only input is +∞ or -∞ (spelled +Inf or -Inf, or +Infinity or -Infinity, optionally without the + sign, and with upper-case, lower-case or mixed-case spelling) the correct values are produced.
#include <stdio.h>
#include <math.h>
int main(void)
{
double min = +INFINITY;
double max = -INFINITY;
double sum = 0.0;
size_t cnt = 0;
double value;
while (scanf("%lf", &value) == 1)
{
sum += value;
cnt++;
if (value > max)
max = value;
if (value < min)
min = value;
}
if (cnt > 0)
{
printf("Count = %zu\n", cnt);
printf("Sum = %g\n", sum);
printf("Min = %g\n", min);
printf("Max = %g\n", max);
printf("Average = %g\n", sum / cnt);
}
return 0;
}
Given ten random values between -1E6 and +1E6:
989375.672
-826955.668
224850.463
-401605.702
-45457.787
259618.099
821069.496
-268408.724
-512449.113
-46404.246
the program produces the output:
Count = 10
Sum = 193632
Min = -826956
Max = 989376
Average = 19363.2
I should probably put a bit more control on the output formatting, but the %g option is quite useful for numbers with wide ranges. Given the input data, using %11.3f would work well (it was used to format the output from the random number generator I used).
Related
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;
}
Hello I have been working on a program in C that calculates numbers and it gives me back an average. Now I'm having issues implementing code that will ask a user to enter any number of pairs and calculate the average. Below is the code that I been working on. I'm able to change the while (count < 5)to 10 to get more pairs, but my goal is to ask a user to input any PAIR and THEN calculate the average (re iterating).
#include <stdio.h>
int main () {
int count;
double avg, value, weight, sum, sumw;
count = 0;
sum = 0;
sumw = 0;
avg = 0.0;
while (count < 5) {
printf("Enter value and it's weight:");
scanf("%lf %lf", &value, &weight);
if (weight >= 0) {
sumw = sumw + weight;
sum = sum + value * weight;
count = count + 1;
}
else { printf("weight must be positive\n");
}
}
avg = sum / sumw;
printf("average is %lf\n " , avg );
return 0;
}
**Second part ** On this on I'm not too sure how to make it to PAIRS plus calculate avg. ej: 2 1 , 2 4 , 4 4 etc.
#include<stdio.h>
void main()
{
int i,n,Sum=0,numbers;
float Average;
printf("\nPlease Enter How many pairs do you want?\n");
scanf("%d",&n);
printf("\nPlease Enter the elements one by one\n");
for(i=0;i<n;++i)
{
scanf("%d",&numbers);
Sum = Sum +numbers;
}
Average = Sum/n;
printf("\nAverage of the %d Numbers = %.2f",n, Average);
return 0;
}
but my goal is to ask a user to input any PAIR and THEN calculate the
Well, then you need to store the values somewhere. Recommendation: Have a struct for:
typedef struct
{
double value;
double weight;
} Pair;
Then as soon as you have got number of pairs to read from user, create an array of pairs:
Pair* pairs = malloc(number * sizeof(*pairs));
Very important: Every malloc should go with a free to avoid memory leaks. General recommendation: plan the free immediately when or even before mallocing.
Now inside your loop, you can fill the pairs:
scanf("%lf %lf", &pairs[i].value, &pairs[weight].weight);
Analogously, you can then use the pairs in the array in next loop or for whatever other purpose.
Side note:
if (weight >= 0)
{
// ...
}
else
{
// printf("weight must be positive\n");
}
If user gave negative input, you'll be just skipping some values (or or as in loop proposed, still retain the negative values!).
You might instead read inside a nested loop until value is valid. Additionally consider user providing non-numeric input, too! In that case, you couldn't read a double at all. So general rule is: Always check the result of scanf:
if(scanf("%lf %lf", &value, &weight) != 2 || value < 0 || weight < 0)
// ^
// assuming negative value not desired either
{
// user input was invalid!!!
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a gradebook program that I've been building, which works fine, but now I want to slot 3 new functions into the existing code. I can't wrap my brain around the logical path I need to take to make it work. I need a SIMPLE way to also get the highest, lowest, and average grades printed at the end. Here's my program...
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_GRADE_COUNT 200
int main() {
int grade[MAX_GRADE_COUNT];
int i;
int count = 0;
char continueResponse;
printf("Welcome to Gradebooker!\n\n");
for(i = 0; i < MAX_GRADE_COUNT; i++) {
printf("Please enter grade (0-100): ");
scanf(" %d", &grade[i]);
count++;
printf("Do you have more grades to enter?(Y/N): ");
scanf(" %c", &continueResponse);
if(toupper(continueResponse) != 'Y') {
printf("\n >> Thank you for using Gradebooker! <<\n");
break;
}
}
printf("\n\nCurrent Gradebooker listings: \n\n");
for(i = 0; i < count; i++) {
printf("\t%5d\n", grade[i]);
}
return 0;
}
The program would need to calculate the max, min and average in the second loop, like this:
int sum = 0;
int minimum = INT_MAX;
int maximum = 0;
for(i = 0; i < count; i++) {
printf("\t%5d\n", grade[i]);
sum += grade[i];
if(grade[i] < minimum) minimum = grade[i];
if(grade[i] > maximum) maximum = grade[i];
}
float average = (float)sum / count;
printf("min grade: %d\n", minimum);
printf("max grade: %d\n", maximum);
printf("average: %f\n", average);
The minimum starts with a value that is larger than all values in the list (INT_MAX for example is the largest possible value an int can take). Then, for each grade in the array, it replaces it with that grade, if it is smaller than the one currently in the minimum variable. That way minimum will in the end contain the smallest grade.
Same for maximum, but reversed.
For the average, it accumulates the sum of all grades (sum needs to be initialized to 0 at the beginning), and the divides it by the number of grades in the end. This gives an arithmetic mean in average.
Using float, it calculates the average as a floating point number (so the average can be non-integer). The (float)sum / count is needed so that it will first cast (convert) sum to a float, and so a floating point division on it. Otherwise, with sum / count is would do an integer division (which returns a rounded down integer), and store that as float in the average variable afterwards.
The idea for finding maximum value is: first declare a variable (lets say, MAXX) to store maximum value and initial it with as minimum value as possible and then iterate through the array and if any value in the array found greater then the current value of MAXX variable than update the value of MAXX with the value.
The idea for finding minimum value is: first declare a variable (lets say, MINN) to store minimum value and initial it with as maximum value as possible and then iterate through the array and if any value in the array found greater then the current value of MINN variable than update the value of MINN with the value.
Idea for finding avarage: Sum all the grade and then divide the sum with the number of grade.
See the implementation below for better understanding:
int max_grade = 0;//for storing maximum grade
/*
Minimum possible value should be initialize here.
Best option to write here is:
int max_grade = INT_MIN;
But to use INT_MIN <limits.h> file must be included.
*/
int min_grade = 10000000;//for storing maximum grade
/*
Maximum possible value should be initialize here.
Best option to write here is:
int min_grade = INT_MAX;
But to use INT_MAX <limits.h> file must be included.
*/
int total_grade = 0;//for counting all the grade
for(i = 0; i < count; i++) {
if(grade[i] > max_grade){
max_grade = grade[i];
}
if(grade[i] < min_grade){
min_grade = grade[i];
}
total_grade += grade[i];
}
printf("Max grade = %d\n" max_grade);
printf("Min grade = %d\n" min_grade);
printf("Avg grade = %d\n" total_grade/count);
I could not see all your code (it seemed to be cut off at the bottom), however the basically procedure to get an average, max and min in C is as follows:
int running_total = 0;
int count_grades = 0;
int max_so_far = 0;
int min_so_far = 999;
while( -1 ){ // infinite loop
// get input (a grade)
// if input is done, break
count_grades++;
running_total += iCurrentGrade; // (iCurrentGrade should be defined during input phase)
if( iCurrentGrade > max_so_far ) max_so_far = iCurrentGrade;
if( iCurrentGrade < min_so_far ) min_so_far = iCurrentGrade;
}
printf( "avg: %d min: %d max: %d\n", (int)(running_total / count_grades), min_so_far, max_so_far );
We have been learning about recursion vs iteration in C this week and we were required to make a program that recursively determines the value of the nth term of a geometric sequence defined by the terms a, ar, ar^2, ... ar^(n-q).
For the most part, I think I have it figured out, as it seems to display the correct values per run, but it doesn't manage to break the recursion when the tested value reaches zero. Also, if possible to get a better explanation of recursion, and some examples of when recursion would be preferred over iteration as I'm still struggling with the concept.
// 2/20/2018
//Lab 6 Solution for Page 369 PE 4 B
//including libraries to be used
#include <stdio.h>
#include <math.h>
int main() {
//Function prototype
double goAnswer(int *, double, double, double, double *, int);
//Declaring variables
int nValue = 0;
double ratio = 0;
double firstTerm = 0;
double answer = 0;
double addedAnswer = 0;
int count = 1;
//Setting up to ask for each value
printf("Please enter in the value of n: ");
scanf("%d", &nValue);
printf("Please enter in the ratio you'd like to use: ");
scanf("%lf", &ratio);
printf("Please enter in the first term to use: ");
scanf("%lf", &firstTerm);
addedAnswer = goAnswer(&nValue, ratio, firstTerm, answer, &addedAnswer,
count);
//Printing out the value of the first nth terms
printf("The value of all terms added together is: %lf\n", addedAnswer);
return 0;
}
//function header
double goAnswer(int *nValue, double ratio, double firstTerm, double answer,
double *addedAnswer, int count) {
if (nValue == 0){
return 0;
}
else{ //This part calculates the answer, prints the value to the screen,
adds the answer to a running sum, decreases the nValue by one and calls the
function again with the lower nValue
answer = firstTerm * pow(ratio, count);
printf("The value of term %d is: %lf\n", count, answer);
printf("This is the nValue: %d \n", *nValue);
*addedAnswer += answer;
nValue -= 1;
return (goAnswer(nValue, ratio, firstTerm, answer, addedAnswer,
(count + 1)));
}
}
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.