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!!!
}
Related
I have scanf in a array I need to print the highest array stored
the problem is it print 0 every print
#include <stdio.h>
int main()
{
int n; // To input how many set of number to be entered
int order_number; // To count the numbers being entered
int length; // To count how many numbers in the array to be used in the last print
int max; // max computations later in last print
float num[100], sum = 0.0, average;
printf("Enter how numbers to be counted: ");
scanf("%d", &n); // asks the user how many numbers to be entered
while (n > 100 || n < 1)
{
printf("The entered number could not handle 100 above or below 1\n"); // shows if the user enters below 1 and above 100
printf("Please enter a number again: "); // asks the user to enter a number again
scanf("%d", &n); // asks the user how many numbers to be entered
}
for (order_number = 0; order_number < n; ++order_number) // loop syntax for counting numbers being entered
{
printf("%d. Enter number: ", order_number + 1); // prints the counting number being entered
scanf("%f", &num[order_number]); // asks the user for a number then store to the array
sum += num[order_number]; // adds all the number from the array
}
average = sum / n; // computes the average by adding a group of numbers and then dividing by the count of those numbers.
printf("The average is %.2f\n", average);
// Problem start here
length = sizeof(num) / sizeof(num[0]);
max = num[100];
for (int i = 0; i < length; i++)
{
if (num[i] > max)
max = num[i];
}
printf("Largest element present in given array: %d\n", max);
return 0;
}
#include <stdio.h>
int main()
{
int n; // To input how many set of number to be entered
int order_number; // To count the numbers being entered
int length; // To count how many numbers in the array to be used in the last print
int max; // max computations later in last print
float num[100], sum = 0.0, average;
printf("Enter how numbers to be counted: ");
scanf("%d", &n); // asks the user how many numbers to be entered
while (n > 100 || n < 1)
{
printf("The entered number could not handle 100 above or below 1\n"); // shows if the user enters below 1 and above 100
printf("Please enter a number again: "); // asks the user to enter a number again
scanf("%d", &n); // asks the user how many numbers to be entered
}
for (order_number = 0; order_number < n; ++order_number) // loop syntax for counting numbers being entered
{
printf("%d. Enter number: ", order_number + 1); // prints the counting number being entered
scanf("%f", &num[order_number]); // asks the user for a number then store to the array
sum += num[order_number]; // adds all the number from the array
}
average = sum / n; // computes the average by adding a group of numbers and then dividing by the count of those numbers.
printf("The average is %.2f\n", average);
max = num[0];
for (int i = 1; i < n; i++) // computation on finding the highest number in the array using loop
{
if (num[i] > max)
max = num[i];
}
printf("The largest number in the array is %d\n", max);
return 0;
}
max = num[100]; - you are looking at the 101st element of a 100 element array, indexed from zero. If you're lucky, you don't get a segmentation fault or some other memory error, since you're looking past the end of the array, but you're still going to get something random that happened to be in that memory location.
To iterate over the array, you then use all elements of the array, since you limit the loop by length - rather than 'n', which you've set to the number of used elements in the array. So you're also including length - n elements at the end that were never initialised to a useful value.
i need to assign these values to the array but i keep receiving assignment to expression error, I'm wondering how I can assign values to those arrays. i try assigning the inputted value of arr into num but i believe I am missing something in that expression.
this codes job is to read the input of a temperature assign the input into a category of the type of day and give the average of the temperature
Enter a high temp reading (-99 to quit)> 100
Enter a high temp reading (-99 to quit)> 0
Enter a high temp reading (-99 to quit)> 50
Enter a high temp reading (-99 to quit)> -99
Hot days: 1
Pleasant days: 0
Cold days: 2
The average temperature was 50.00 degrees.
this is what an output should look like
#include <stdio.h>
int main(void){
//declare variables
int num[30];
int Cday[30];
int Pday[30];
int Hday[30];
int total;
int total_ave;
double ave;
int NHday=0;
int NPday=0;
int NCday=0;
int arr;
//ask input store into num, then decides if the number goes into which array
do{
printf("Enter a high temp reading (-99 to quit)>");
scanf ("%d", &arr);
num = arr;
if(arr == -99)
{
break;
}
else if(arr<=60 && arr>=0){
Cday = num;
}
else if(arr>=60 && arr<=84){
Pday = num;
}
else if(arr<=84 && arr>=200){
Hday = num;
}
}while(num >=0);
//calculating the average
total = sizeof(num);
for(int i = 0;i< total; i++){
total_ave = total_ave + num[i];
}
ave = total_ave / total;
//to print the amount of times each day was in a category
NHday = sizeof(Hday)/sizeof(Hday[0]);
NPday = sizeof(Pday)/sizeof(Pday[0]);
NCday = sizeof(Cday)/sizeof(Cday[0]);
//printing the final statement once all the values are calculated
printf("\nHot days:\t %d\n", NHday);
printf("Pleasant days:\t %d\n", NPday);
printf("Cold days:\t %d\n\n", NCday);
printf("The average temperature was %.2f degrees.", ave);
//stops compiling when -99 is entered not collected as information
//
//
return(0);
}
i would also appreciate to know if how i am calculating how many items are in the array with the NHday CDay and Pday Calculations is the correct way to do it.
i am also wondering if my calculation for the average is correct. any help is appreciated thank you.
You don't need arrays for the different types of days, just counter variables, which you increment based on the temperature range.
total should not be sizeof(num) for two reasons:
sizeof counts bytes, not array elements.
You only want the count of inputs, not the total size of the array. You can get the total by adding the counters of each type of day.
You don't have to put the temperatures in an array. Just add each day's temperature to the total_ave variable after the user enters it.
When you're calculating ave, you need to cast one of the variables to double so that floating point division will be used instead of integer division.
#include <stdio.h>
int main(void){
//declare variables
int num;
int total;
int total_ave = 0;
double ave;
int NHday=0;
int NPday=0;
int NCday=0;
//ask input store into num, then decides if the number goes into which array
while (1) {
printf("Enter a high temp reading (-99 to quit)>");
scanf ("%d", &num);
if(num == -99)
{
break;
}
else if(num<=60){
NCday++;
}
else if(num<=84){
NPday++;
}
else {
NHday++;
}
total_ave += num;
}
//calculating the average
total = NHday + NPday + NCday;
ave = (double)total_ave / total;
//printing the final statement once all the values are calculated
printf("\nHot days:\t %d\n", NHday);
printf("Pleasant days:\t %d\n", NPday);
printf("Cold days:\t %d\n\n", NCday);
printf("The average temperature was %.2f degrees.", ave);
return(0);
}
You are assigning arr value to num array without using index. Your while loop should be like
while(i<30){
printf("Enter a high temp reading (-99 to quit)>");
scanf ("%d", &arr);
if(arr==-99){
break;
}
num[i] = arr;
i++;
total++;
if(arr<=60 && arr>=0){
NCday++;
}
else if(arr>=60 && arr<=84){
NPday++;
}
else if(arr>=84 && arr<=200){
NHday++;
}
}
Now
total = sizeof(num);
This will give you the total size of num array which is 30*4=120 as int data type has 4 byte size.
If you are not filling all 30 values then you need to know the number of values your are going to use from that array. That's why I am incrementing total as I am inserting values in num array which will help later.
for(int i = 0;i< total; i++){
total_ave = total_ave + num[i];
}
ave = total_ave / total;
If you just want to know the count of cold, hot days then you can increment them in while loop and print those.
printf("\nHot days:\t %d\n", NHday);
printf("Pleasant days:\t %d\n", NPday);
printf("Cold days:\t %d\n\n", NCday);
And first initialize the variables.
int num[30];
int total=0;
int total_ave=0;
double ave;
int NHday=0;
int NPday=0;
int NCday=0;
int arr=0;
int i=0;
I've been trying to figure this out the last few days, but no luck. The objective is to find the sum, average, minimum, and maximum grades and display them.
Here is my code, everything except minimum, maximum and grade input seem to work
// Includes printf and scanf functions
#include <stdio.h>
int main(void) {
unsigned int counter; // number of grade to be entered next
int grade; // grade value
int total; // sum of grades entered by user
float average; // average of grades
int maxi; // Max grade
int mini; // min grade
int i;
int max;
int min;
maxi = 1;
mini = 1;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
//scanf("%d%d", &min, &max);
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
//scanf("%d",&counter);
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
break;
}
else {
total = total + grade;
average = (float)total / counter; // NOTE: integer division, not decimal
}
}
max = (grade < maxi) ? maxi : grade;
min = (grade > mini) ? mini : grade;
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
Output:
Enter number of grades: 2
5
7
Enter grade 1: 4
Enter grade 2: 3
Class average is: 3.500
Your maximum grade is 3
Your minimum grade is 1
Sum: 7
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade" then from there it calculates everything. Also, it seems that the Maximum is always the last grade that I enter and shows 1 as the minimum when no where in the input is 1. I am supposed to use a conditional operator for the max/min, I tried looking it up and reading the book, but they just use letters like a,b,c, etc. Which just confused me so I'm not sure if I did it wrong.
Could that be what is messing everything up? If it isn't what am I doing wrong?
Another thing is I'm thinking I need a While loop if I want to make the counter have an input from 1-100, is that right?
Edit: just realized I had to remove the scanf for max and min. Taht's why I had to inptu 2 nubmers first
There are two major problems, as I see it
The variable total is not initialized, so the first occurrence of total = total + grade; would invoke undefined behaviour.
You have to initialize it explicitly to 0.
The same variable grade is used for holding the repeated input. After the loop, grade will only hold the last input value.
You need to either use an array for storing inputs and comparison, or, compare and update the min and max as you go, inside the loop.
For future references, please seperate your code in different functions or add comments, since analyzing an unfamiliar code always takes much time.
min: Your problem here lies, that you're initializing your min value with 1. That value is most of the time below your input grades. If you want to initialize it, you should use a high number.
For example:
#include <limits.h>
int min = INT_MAX;
max: Your "grade" will be always the last typed grade, which you scanned. That's not what you want. It would be good, to save all values, which you get as input in an array or a list.
Also your codesnippet at the end
max = (grade<maxi) ? maxi : grade;
min = (grade>mini) ? mini : grade;
will just compare one grade. You need to compare all values, which you entered.
You could just put them in the for-loop.
gradeinput: You need to temporarily save your inputs in a datastructure like an array/list to use them in your program.
int x[counter];
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i);
x[i]=scanf("%d", &grade);
}
.. have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
This happens because OP's stdout is buffered and not one character at a time.
To insure output is seen before the scanf(), use fflush().
See What are the rules of automatic flushing stdout buffer in C?
printf("Enter number of grades: ");
fflush(stdout); // add
scanf("%d", &counter);
Rather than set the min = 1, set to a great value
maxi = 1;
mini = 1;
maxi = 0;
mini = 100;
// or
maxi = INT_MIN;
mini = INT_MAX;
Move the test for min/max in the loop to test each value and fold maxi, max into the same variable.
if (max > grade) max = grade;
if (min < grade) min = grade;
The first total + grade is a problem as total is uninitialized.
// int total; // sum of grades entered by user
int total = 0; // sum of grades entered by user
Unnecessary to calculate average each time though the loop. Sufficient to do so afterward.
Style: After the break; the else is not needed.
Good that code tests user input range. Yet the i-- is incorrect. If code is to break, just break. If code it to try again, the i-- makes sense, but then code should continue.
The comment // NOTE: integer division, not decimal is incorrect as (float) total / counter is FP division.
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n");
i--;
continue;
}
total = total + grade;
} // end for
average = (float) total / counter;
In general, casting should be avoided.
Advanced issue: Consider the situation if later on code was improved to handle a wider range of integers and used higher precision FP math.
The 1st form causes total to become a float (this could lose precision) and perhaps use float to calculate the quotient, even if average was a double. Of course the (float) cast could be edited to (double) as part of the upgrade, but that is a common failure about updates. Types may be changed, but their affected object uses are not fully vetted.
The 2nd form below causes total to become the same type as average and use the matching math for the type. Reduced changed needed as the types change. This form is also easier to review as one does not need to go back and check the FP type of average to see if a cast to float, double or even long double was needed.
average = (float) total / counter;
// or
average = total;
average /= counter;
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
You have two scanf before "Enter grade"
scanf("%d", &counter);
scanf("%d%d", &min, &max);
#include <stdio.h>
int main(void) {
int counter; // number of grade to be entered next
int grade; // grade value
int total=0; // sum of grades entered by user
float average; // average of grades
int i;
int max;
int min;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
} else {
if(i==1){
max = grade;
min = grade;
}
else{
max = (grade < max) ? max : grade;
min = (grade > min) ? min : grade;
}
total = total + grade;
average = (float) total / counter; // NOTE: integer division, not decimal
}
}
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
I've edited your Code as there were some mistakes. First, you were not initialising the total, which may make it take some garbage value. The second one is no need of using break as you are reducing the value of i.The third one is that you are updating the min and max outside the for loop, where the value of grade will be the last entered grade. And maxi and mini are not at all needed. The code was running perfectly without waiting for dummy values. Cheers!
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.
Hello Stack Community!
I am having trouble calculating the correct average for 10 integers.
The expected output average is supposed to be 140.0 with one integer value recognized as not a positive program by the compiler.
This is what I have compiled, and it recognized the negative integer but the average still comes to 150.0
Just trying to figure out what I am missing here.
Thanks!
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
double avg;
/* Initialize */
count = 0;
sum = 0;
avg = 0.0;
// Loop through to input values
while (count < 10)
{
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;
}
Values are: 100 100 100 100 -100 100 200 200 200 200
You want to read exactly 10 positive numbers, with count from 0 to 9.
After reading 100 100 100 100 -100 100 200 200 200 200 the value of count is 9 (because -100 neither added to the sum nor counted), which is less that 10 so the loop is executed one more time.
This time scanf() fails, so value remains unchanged; effectively you are reading another 200.
This is why the sum of the numbers is 1500 and the average 150.
AlexP found the explanation: you must check the return value of scanf(), otherwise, you will silently accept input that is not a number and reuse the last converted value.
Also note that the cast in avg = (double) sum/count; applies to sum and binds stronger than /. It is considered good style to make this more explicit by writing avg = (double)sum / count;
Here is a modified version of your program:
#include <stdio.h>
int main(void) {
/* variable definitions */
int count, value, sum;
double avg;
/* Initializations */
count = 0;
sum = 0;
avg = 0.0;
// Loop through to input values
while (count < 10) {
printf("Enter a positive Integer\n");
if (scanf("%d", &value) != 1) {
break;
}
if (value >= 0) {
sum = sum + value;
count = count + 1;
} else {
printf("Value must be positive\n");
}
}
// Calculate avg.
// Need to type cast to force floating point division instead of integer division
if (count > 0) {
avg = (double)sum / count;
printf("average is %f\n", avg);
}
return 0;
}
If I understand your problem correctly, this is what you want to do :
int last_known_positive_value = 0;
// Loop through to input values
while (count < 10)
{
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum = sum + value;
last_known_positive_value = value;
}
else {
printf("Value must be positive\n");
sum = sum + last_known_positive_value;
}
count = count + 1;
}
check-answer-here
There are a number of different ways to approach the problem. (1) you can read your values as a string with fgets and then call sscanf and gain the benefit of a NULL return from fgets indicating EOF and a test of the buffer containing only '\n' to indicate a user pressed [Enter] to signal end of input.
(2) you can read the values numerically with scanf and then check for EOF to indicate end of input, or some other predetermined sentinel.
Regardless of which you choose, the approach is basically the same. (a) make a call to the function you are using for input, (b) check the RETURN, and (c) validate the value input is within the required range, and handle the data.
You get the drift, on all input, check the return of your read function and handle any error or EOF condition, then validate the input is within the expected range.
A quick example using your code and reading numeric values with scanf could be something like:
#include <stdio.h>
int main (void) {
/* define/initialize variables */
int count = 0, value = 0, sum = 0;
double avg = 0.0;
while (1) { /* infinite loop to process input */
int rtn;
printf ("Enter a positive Integer ([ctrl+d] to quit): ");
if ((rtn = scanf ("%d", &value)) != 1) {
if (rtn == EOF) { /* always handle user cancellation of input */
putchar ('\n'); /* tidy up with POSIX line ending */
break; /* on to final calculation */
}
}
if (value < 0) /* check out of range */{
printf ("Value must be positive\n");
continue; /* try again */
}
sum = sum + value; /* compute sum */
count = count + 1; /* increment count */
}
/* Calculate avg. (typecast to avoid integer division) */
avg = count > 0 ? (double) sum/count : 0; /* protect div by zero */
printf ("\n (%d/%d) => average: %lf\n", sum, count, avg);
return 0;
}
Example Use/Output
$ ./bin/sumavg < <(echo "100 100 100 100 -100 100 200 200 200 200")
Enter a positive Integer ([ctrl+d] to quit):
<snip>
(1300/9) => average: 144.444444
One common thread running between all complete examples is to always handle a manual EOF generated by the user allowing them to cancel an individual input, or input as a whole (you decide based on your needs). On Linux the manual EOF is generated by [ctrl+d] on windoze [ctrl+z].
Look all answers over and let me know if you have any questions related to the above.
while (count < 10) {
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum += value;
count++;
}
else {
printf("Value must be positive\n");
count++;
}
}
This will increment "count" even if negative integer is inputted.
Thus you will get the desired average.