This program will determine the count, minimum, maximum, sum and average of all valid numbers entered. It will stop asking for new values when zero is entered and don't accept negative values. After asking for 1st number it just stops working. I will be very happy if anyone can give me some tips how to write it more efficiently and some for just coding.
#include <stdio.h>
#include <stdlib.h>
void display(void);
void menu(void);
int main(void)
{
display();
menu();
system("pause");
return 0;
}
void display(void)
{
printf("program will determine the count, minimum, maximum, sum and average of all valid numbers entered.\n");
return;
}
void menu(void)
{
int count;
float min = 0;
float max = 0;
float sum;
float avg;
float user = 0;
int index;
printf("Please enter the number ==> ");
do
{
// I think I scew up here plz check it.
scanf("%f", user);
if (user > 0)
{
if (user > max)
{
max = user;
}
if (user < min)
{
min = user;
}
}
else
{
printf("Please enter a positive number");
}
sum += user;
count = index;
index++;
} while (user != 0);
avg = sum / count;
printf("The minimum number ==> %f", min);
printf("The maximum number ==> %f", max);
printf("The number of enteries ==> %i", count);
printf("The sum of all values ==> %f", sum);
printf("The average of all values ==> %f", avg);
}
scanf("%f", user); should be scanf("%f", &user);
You'd not want to increase these if input - user is not correct:
sum += user;
count = index;
index++;
Moreover, your count is not being computed correctly. To be specific, you're calculating 1 less than actual count. So put this block inside if statement like this
if (user > 0)
{
if (user > max)
{
max = user;
}
if (user < min)
{
min = user;
}
sum += user;
count = index + 1;
index++;
}
else
{
printf("Please enter a positive number");
}
Be cautious when using %i. %d and %i are same when used in printf but not in scanf.
printf("The number of enteries ==> %d", count); //Notice %d
This line is wrong:
scanf("%f", user);
You are not storing the input into user. You can fix it like this:
scanf("%f", &user);
Here's your error:
scanf("%f", user);
The %f format specifier to scanf expects the address of a float, i.e. a float *. All function parameters in C are pass by value, meaning that changing a parameter isn't reflected in the calling function. By passing a pointer, the function can dereference the pointer to write to the location it points to.
So change the function call to pass in the address of user:
scanf("%f", &user);
Related
Question and example
I am trying to code a program that would ask the user to input a number, and then ask if the user wants to continue. If the response is "yes" then the program will ask for the user input again. If the response is "no" then the program will stop and give the user the maximum and minimum value that the user input during the program running.
This is my take on the problem, its still incomplete and probably very wrong
#include <stdio.h>
int main()
{
float value, command, max, min;
int a[100];
printf("Please enter the value: ");
scanf("%f",value);
printf("Do you want to continue?: ");
scanf("%f",command);
if (!strcmp(command, "yes")){
printf("Please enter the value: ");
scanf("%f",value);
printf("Do you want to continue?: ");
scanf("%f",command);
}
if (!strcmp(command, "no")){
max = a[0];
min = a[0];
for(int i=1; i<n; i++)
{
if(a[i]>max)
{
max = a[i];
}
if(a[i]<min)
{
min = a[i];
}
}
}
printf("The maximum value is %f, and the minumum is %f",max,min);
return 0;
}
To handle an arbitrary number of inputs, use a loop and test for a new minimum and maximum within.
The scanf conversion specification %f needs the address of value.
We can't scan the command string into a float.
The given output format for the numbers we get with the printf conversion specification %g.
E. g.:
#include <float.h>
#include <stdio.h>
#include <string.h>
int main()
{
float value, max = FLT_MIN, min = FLT_MAX;
char command[4];
do
{
printf("Please enter the value : "); scanf("%f", &value);
if (value > max) max = value;
if (value < min) min = value;
printf("Do you want to continue : "); scanf("%3s", command);
} while (strcmp(command, "no") != 0);
printf("The maximum value was %g and the minumum is %g\n", max, min);
}
Note that the example code is not safe for wrong input.
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!!!
}
So, I have to write a program to ask the user for an integer, and then that integer will determine how many more entries the user gets before adding all the numbers that were entered. So, if the first entered integer is "5", then the user can enter 5 more integers. Those 5 integers are then added together at the end and displayed. I have written a program with for loops, but for some reason, it is only adding first 4 integers and not the 5th one. Here is the code:
int main() { //declare main function
int c=0,n,i; //declare integers
int sum=0;
printf("\nEnter an integer: "); //ask user for input and create a label
scanf("%d",&n);
if (n>=0) { //use if statement
for (i=0;i<n;i++) //use for loop inside if statement to account for negative integers
{
sum+=c;
printf("Enter an integer: ");
scanf("%d",&c);
}
}
else {
printf("Wrong number. You can only enter positive integers!");
}
printf("The sum of the %d numbers entered is: %d",i,sum);
return 0;
}
Just change the position of
sum+=c;
to after the scanf it should work.
It is good to split the program. use functions. Not everything in the main function.
int getInteger(void)
{
char str[100];
int number;
while(!fgets(str, 100, stdin) || sscanf(str, "%d", &number) != 1)
{
printf("Wrong input. Try again:") ;
}
return number;
}
int main()
{
int nsamples;
long long sum = 0;
printf("Enter number of samples:");
while((nsamples = getInteger()) <= 0)
{
printf("Try again, entered number must be >= 0\n");
}
printf("Enter numbers:\n");
for(int i = 1; i <= nsamples; i++)
{
printf("Sample no %d:", i);
sum += getInteger();
}
printf("The sim is: %lld\n", sum);
}
So I'm trying to use a isdigit() to check for non numeric values and for some reason when I put in a integer i get a floating exception error and my generated printf statement "invalid input". I am quite confused on why when i enter a digit it goes into my if statement where it is only true if it is NOT an integer
#include <stdio.h>
#include <ctype.h>
int main()
{
int hour=0, minute=0, total=0, maxDiveTime=0, counter=0, average=0;
printf ("Enter dive times in the format of HH:MM (hours:minutes), Enter \\0 to stop\n");
while (scanf("%d:%d",&hour, &minute) != '\0')
{
if ((!isdigit(hour)) || (!isdigit(minute)))
{
printf("Invalid Input\n");
break;
}
else
{
if (((hour*60)+minute) > (maxDiveTime))
{
maxDiveTime = ((hour*60)+minute);
}
total = total + (hour*60) + minute;
counter ++;
}
}
average = total/counter;
printf("The total divetime is %d:%d\n", total/60, total%60);
printf("The average divetime is %d:%d\n", average/60, average%60);
printf("The max divetime is %d\n", maxDiveTime );
return 0;
}
First, the reason for the floating exception is that count in expression total/count is zero when you break when entering the loop the first time or when you do not enter the loop at all. So check count before calculating something. Second, scanf returns the number of values successfully read in, which should be 2 in your case. Third, isdigit expects a character, i.e. something like '0', not an integer ranging from 0 to something. When scanf with %d succeeds, you have already successfully read in a number (and nothing else).
int main()
{
int hour=0, minute=0, total=0, maxDiveTime=0, counter=0, average=0;
printf ("Enter dive times in the format of HH:MM (hours:minutes), Enter \\0 to stop\n");
while (scanf("%d:%d",&hour, &minute) == 2)
{
if (((hour*60)+minute) > (maxDiveTime))
{
maxDiveTime = ((hour*60)+minute);
}
total = total + (hour*60) + minute;
counter ++;
}
if (count > 0) {
average = total/counter;
printf("The total divetime is %d:%d\n", total/60, total%60);
printf("The average divetime is %d:%d\n", average/60, average%60);
printf("The max divetime is %d\n", maxDiveTime );
}
return 0;
}
So my program asks for name and numbers, then tallies up the number of even entries and odd entries, then giving a total of all the even entries and a total for all the odd.
It all works except the calculations, it tells me I have all odd entries and only values them as 1 when adding them up.
I feel like it has something to do with my variables and referencing in my calc function
#include <stdio.h>
int number = 1;
int evencount, oddcount;
int eventotal, oddtotal;
int main () {
char name[256];
printf("Enter your name \n");
scanf("%s", name);
printf("Enter numbers within 1-100 \n");
printf("Enter 0 to quit\n");
calc(number);
printf("%s,the numbers you have entered are broken down as follows: \n", name);
printf("%d odd entries \n", oddcount);
printf("%d even entries\n", evencount);
printf("You entered even numbers with a total value of %d \n", eventotal );
printf("You entered odd numbers with a total value of %d \n", oddtotal);
return 0;
}
int calc (int input) {
while (number != 0) {
scanf("%d", &number);
if (input%2 == 1) {
oddcount++;
oddtotal += input;
}
else {
evencount++;
eventotal += input;
}
};
}
scanf("%d", &number);
if (input%2 == 1) {
{
oddcount++;
oddtotal += input;
}
I think you probably want number % 2 rather than input % 2,
oddtotal += number rather than oddtotal += input, etc.
In your calc function, you're mixing up input, which is a parameter, and number, which is a global.
Using a global here for your input variable is bad form, and in fact you don't need to pass anything into this function.
Also, better to use do..while instead of while since the loop must run at least once:
You're also using the function before it's declared, so you should have a function prototype. And since calc doesn't need to return anything, set its return type to void.
#include <stdio.h>
int evencount, oddcount;
int eventotal, oddtotal;
void calc();
int main()
{
...
calc();
...
}
void calc()
{
int number;
do {
scanf("%d", &number);
if (number%2 == 1) {
oddcount++;
oddtotal += number;
} else {
evencount++;
eventotal += number;
}
} while (number != 0);
}