I have to calculate the arithmetic and geometrical mean of numbers entered by the user in C language. The algorithm works fine, but I don't know how to do the enter numbers until 0 is pressed part. I have tried many things but nothing works. Here is what I have tried to do until now. Thanks for the help.
int main() {
int n, i, m, j, arr[50], sum = 0, prod = 1;
printf("Enter numbers until you press number 0:");
scanf("%d",&n);
while (n != 0) {
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum = sum + arr[i];
prod = prod * arr[i];
}
}
int armean = sum / n;
float geomean = pow(prod, (float)1 / n);
printf("Arithmetic Mean = %d\n", armean);
printf("Geometric Mean = %f\n", geomean);
getch();
}
Your code is asking for the number of values in advance and subsequently reading that many values. That's not what you were asked to do.
You need to ask for numbers in a loop and exit the loop when the number that you read is 0. You don't even need an array:
int n = 0, i, m, j, sum=0, prod=1;
while (1) {
int value;
scanf("%d",&value);
if (value == 0) {
break;
}
sum=sum+value;
prod=prod*value;
n++;
}
int armean=sum/n;
float geomean=pow(prod,(float) 1/n);
You have to break the for loop when value 0 entered; so you should check for arr[i].
While loop is not required.
Please go through below code; this could be help full:
#include <stdio.h>
int main()
{
int n, i, m, j, arr[50], sum=0, prod=1;
printf("Enter numbers until you press number 0:");
for(i=0; i<50; i++)
{
scanf("%d",&arr[i]);
if (arr[i] == 0)
{
break;
}
sum=sum+arr[i];
prod=prod*arr[i];
}
printf ("%d %d\n",sum, prod);
n = i+1;
int armean=sum/n;
float geomean=pow(prod,(float) 1/n);
printf("Arithmetic Mean = %d\n",armean);
printf("Geometric Mean = %f\n",geomean);
getch();
return 0;
}
what dbush said is right, you don't need array and are not asking the number in advance but what he did not tell is how can you find the number of values
int main()
{
int n, sum=0, prod=1, num;
printf("Enter numbers until you press number 0:\n");
for(n=0; ; n++)
{
scanf("%d",&num);
if(num==0)
break;
sum=sum+num;
prod=prod*num;
}
printf("sum is %d \n",sum);
printf("prod is %d \n",prod);
printf("n is %d \n",n);
float armean=sum/n; //why int?
float geomean=pow(prod,(float) 1/n);
printf("Arithmetic Mean = %d\n",armean);
printf("Geometric Mean = %f\n",geomean);
//getch(); why getch(), you are not using turboc are you?
}
There is no need for an array, but you should test if the number entered in 0 after reading it from the user. It would be better also to use floating point arithmetic to avoid arithmetic overflow, which would occur quickly on the product of values.
In any case, you must include <math.h> for pow to be correctly defined, you should test the return value of scanf() and avoid dividing by 0 if no numbers were entered before 0.
#include <stdio.h>
#include <math.h>
int main() {
int n = 0;
double value, sum = 0, product = 1;
printf("Enter numbers, end with 0: ");
while (scanf("%lf", &value) == 1 && value != 0) {
sum += value;
product *= value;
n++;
}
if (n > 0) {
printf("Arithmetic mean = %g\n", sum / n);
printf("Geometric mean = %g\n", pow(product, 1.0 / n));
getch();
}
return 0;
}
Related
I am trying to perform an easy calculation without beeing able to figure out the right approach to it: I am trying to obtain a specific amount of N values, reading the step number from user input, within a certain range included between min and max also read from the user input. Those N values must be evenly spaced between themselves.
For instance, this should be able to produce a set of N numbers including the lower range limit and the upper one. I need to use decimal min and max and integer number of step.
This is the code I am trying to use:
#include <stdio.h>
int main()
{
double min;
double max;
int step;
double table_array[step];
table_array[0] = min;
printf("Enter the minimum value: ");
scanf("%lf", &min );
printf("Enter the maximum value: ");
scanf("%lf", &max );
printf("Enter the evenly spaced step value: ");
scanf("%d", &step );
printf("\n----------------------------------\n");
int i;
int increment;
for (i = 0; i <= step; i++){
increment = (max - min) / step;
table_array[i+1] = table_array[i] + increment;
while (table_array[i] < max){
printf("%i %lf\n",i, table_array[i]);
}
}
return 0;
}
I need to improve the for cycle for sure. Any suggestions? I assume it can be even totally wrong since it is not running, or better yet it is running but not showing the right result
First of all, you need declare an array with specific size. Initially the array size is not valid as step will initially have garbage value. then you are trying to print i with %i need to change that one with %d. with your step you need to calculate the increment only once. and as your increment can be double number then just make sure that you are using a double type for increment. now how i calculate the increment as 2 number must be min and max then there must be step >= 2 . suppose max =20 min =10 and step=3 so the numbers will be 10,15,20. so increment = (max -min )/(step-1) = 5. now make some complex case . if step = 1 then min must be equal to max. we need to check this case explicitly. another case if max < min then just need to swap them.
here is the code:
#include <stdio.h>
int
main ()
{
double min;
double max;
int step;
printf ("Enter the minimum value: ");
scanf ("%lf", &min);
printf ("Enter the maximum value: ");
scanf ("%lf", &max);
printf ("Enter the evenly spaced step value: ");
scanf ("%d", &step);
double table_array[step + 5];
table_array[0] = min;
printf ("\n----------------------------------\n");
int i;
double increment;
if (max < min){
double temp;
temp = min;
min = max;
max = temp;
}
if (step == 1 && max == min) {
i = 0;
printf ("%d %.18lf\n", i, table_array[i]);
} else {
increment = (max - min) / (step - 1);
i = 0;
printf ("%d %.18lf\n", i, table_array[i]);
for (i = 1; i < step; i++){
table_array[i] = table_array[i - 1] + increment;
printf ("%d %.18lf\n", i, table_array[i]);
}
}
return 0;
}
#include <stdio.h>
#define SWAPI(min,max,type) do{type tmp; if(min > max) {tmp = max; max = min; min = tmp;}}while(0)
double *getnumbers(double *table, size_t nelements, double max, double min)
{
double step;
if(table && nelements > 1 )
{
SWAPI(min,max, double);
step = (max - min) / (nelements - 1);
for(size_t element = 0; element < nelements; element++, min += step)
{
table[element] = min;
}
}
else
{
table = NULL;
}
return table;
}
void printtable(double *table, size_t num)
{
for(size_t i = 0; i < num; i++)
{
printf("[%zu] = %f\n", i, table[i]);
}
}
int main(int argc, char* argv[])
{
double numbers[25];
if(getnumbers(numbers,2,3,6)) printtable(numbers, 2);
printf("\n");
if(getnumbers(numbers,15,3,6)) printtable(numbers, 15);
}
https://godbolt.org/z/odscs6
#include <stdio.h> // printf, scanf, putchar
#include <float.h> // FLT_EPSILON
#include <math.h> // fabs
int isequal(double, double);
int main(void) {
double min, max, step, nnum;
printf("Maximum: "), scanf("%lf", &max); // Get maximum
printf("Minimum: "), scanf("%lf", &min); // Get minimum
if (min > max) { // If invalid maximum, handle error
puts("Maximum cannot be over minimum");
return 1; // Returning 1 indicates program failure
}
printf("Step: "), scanf("%lf", &step); // Get step
nnum = (max - min)/step;
if (!isequal(nnum, (int) nnum) || step <= 0) { // If invalid step, handle error
puts("Invalid step");
return 1;
}
putchar('\n'); // Separate input from output
for (int i = 0; i <= nnum; i++) {
printf("%d. %lf\n", i + 1, min);
min += step; // We already know it will go into maximum evenly
}
return 0; // Returning 0 indicates program success
}
int isequal(double x, double y) { // fabs() = Float absolute value
return fabs(x - y) < FLT_EPSILON; // FLT_EPSILON = Smallest comparable float value
}
I'm trying to get this program to run properly. It prompts user for a nonzero integer, if a nonzero integer is not entered, the while loop should keep prompting user until a nonzero integer is entered.
Then, it takes the integer and uses that as the amount of double entries the user may enter. The program then calls a function that takes the maximum, minimum, and mean of these user-determined amount of double values.
My issue is that even if I enter a nonzero integer, it rejects it and loops the prompt a second time. But, it accepts the nonzero integer the second time. Code below. Thanks!
#include<stdio.h>
void mmm (int n);
int main()
{
int num;
printf("Enter a positive nonzero integer: ");
scanf("%d", &num);
while(num < 1);
{
printf("Invalid number!\n");
printf("Enter a positive nonzero integer: ");
scanf("%d", &num);
}
mmm(num);
return 0;
}
void mmm (int n)
{
double min, max, mean, sum, entry;
int i;
printf("***** MIN MAX and MEAN *****\n");
printf("Enter %d numbers separated by spaces: ", n);
sum = 0;
for(i = 1; i <= n ; i++)
{
scanf("%lf", &entry);
sum += entry;
if(i == 1)
{
max = entry;
min = entry;
}
if(max < entry)
max = entry;
if(min > entry)
min = entry;
}
mean = sum/n;
printf("Minimum, maximum, and mean of the %d numbers: %.2lf, %.2lf, %.2lf\n", n, min, max, mean);
}
OK I fixed this by implementing a do-while loop in main:
#include<stdio.h>
void mmm (int n);
int main()
{
int num;
do{
printf("Enter a positive nonzero integer: ");
scanf("%d", &num);
}
while (num <= 0);
mmm(num);
return 0;
}
I am bashing my head because I cannot figure out why my C code keeps printing the wrong average of a set of n numbers!
This is my code below:
int main()
{
int i;
int n;
int sum = 0.0;
int lowest;
int highest;
float average;
int range;
int middle;
double median;
printf("\nEnter the amount of numbers you want?\n");
scanf("%d",&n);
int numbs[n];
int temp[n];
for(i = 0;i < n; i++)
{
printf("\nEnter a number from 0 to 15: ");
scanf("%d",&temp[i]);
}
while (temp[i] < 0 || temp[i] > 15) than 15
{
printf("This number is not from 0 to 15! Please re-enter another number: ");
scanf("%d",&temp[i]);
}
numbs[i] = temp[i];
sum += numbs[i];
}
int sortt = 0, j, x;
for (x = 1; x < n; x++) {
for (j = 0; j < n - x; j++) {
if (numbs[j] > numbs[j + 1]) {
sortt = numbs[j];
numbs[j] = numbs[j + 1];
numbs[j + 1] = sortt;
}
}
}
lowest = numbs[0];
highest = numbs[n-1];
middle = n/2;
if (n % 2)
{
median = numbs[middle];
}
else
{
median = (numbs[middle - 1] + numbs[middle]) / 2.0;
}
average = sum/n;
range = highest - lowest;
printf("\nSum: %d", sum);
printf("\nAverage: %.2f", average);
printf("\nMedian: %.2f", median);
printf("\nRange: %d\n", range);
return 0;
}
This is my input and output below. You can see that 8 divided by 3 is not 2, it is 2.67! I've tried using double and float.
Input & Output:
You need to correct the following line:
average = sum/n;
to
average = (float)sum/n;
You have to cast your return value into float. Think about it as a function with the following definition:
float divide(int x,int y){
return x/y; // returns an integer instead of float.
}
While this definition:
float divide(int x,int y){
return (float)x/y; // creates a temporary float variable and returns it immediately as the returned value of the function.
}
In addition, declaring int sum=0.0 is definitely going to show you a warning when compiling with -Wall. Try to follow warnings that you get from your compiler and fix all of them before you run your program.
8 divided by 3 is 2, remainder 2. 8 and 3 are integers, and when you divide two integers, you use integer division with integer rules.
Also, this line might be confusing you:
int sum = 0.0;
Since sum is an int, this just sets sum to zero.
And:
average = sum/n;
Since both sum and n are integers, this is integer division. What you do with a result does not affect how that result is computed -- C's rules are complex enough already.
/*Here see you can intake all values as float instead */
#include <stdio.h>
#include <stdlib.h>
void main()
{
float i,n,a,b,sum,ave;
printf("This is a program to calculate the average of 'n' numbers \n");
printf("Of How many numbers do you want to calculate average \n");
scanf("%f", &n);
printf("Enter the first number \n");
scanf("%f", &a);
sum = a;
for (i=1;i<n;i++)
{
printf("Enter another number \n");
scanf("%f", &b);
sum = sum + b;
}
ave = (sum/n);
printf("The average of the %f number is %f", n, ave);
getchar();
}
I want to do this code that tells you the number of (n) integers that are bigger (or equal) than a (k) input.
So for example:
input:
4 15
12
6
15
24
output:
2
So the 4 is the number of integers the user is going to input and the 15 is the k number, now the output is the quantity of numbers that are bigger than k.
What I have of code is this:
#include<stdio.h>
int main()
{
int n, k, i;
int c, d;
scanf(" %d",&n);
scanf("%d", &k);
for(i=1;i<=n;i++)
{
scanf("%d",&c);
if (c[i]>k)
c[i]=d;
}
printf("%d", d);
return 0;
}
As you can see my code sucks, I don't know how to find the integers that are bigger than k and to print the quantity, not the numbers themselves. Any help is really appreaciated. Thanks.
Far less elegant solution, but one that keeps the value you need for some further use.. OldProgrammer did it much simpler and more pretty.
int main()
{
int num, s, i, cnt = 0;
printf("please input number of integers and int to compare with\n");
scanf("%d %d", &s, &num);
int arr[s];
for(i = 0; i < s; i++)
{
printf("Please input %d. number", i+1);
scanf("%d", &arr[i]);
}
for(i = 0; i < s; i++)
{
if(arr[i] >= num)
cnt++;
}
//at this point cnt holds the value you need
return 0;
}
Not sure why you are trying to reference c as an array. That is not needed. Try this:
int main()
{
int n, k, i, c;
int count = 0;
scanf(" %d",&n);
scanf("%d", &k);
for(i=1;i<=n;i++)
{
scanf("%d",&c);
if (c > k)
count++;
}
printf("%d", count);
return 0
}
Also, I would rename your variables to something more meaningful, such as numEntries, checkValue, etc.
I've been looking for a solution quite a while now, but did not manage to find anything.
I need a program which takes the users input (a random amount of integers) until EOF, sums them up and gives me back the average.
I tried it using an array but I am not sure whats my mistake here.
I managed to get it working with a fixed size array. But I need a flexible one.. Is this even possible?
Here is what I got so far:
#include <stdio.h>
int main()
{
int count = 3;
int numbers[count];
long sum;
float average;
int i;
for (i = 0; i < count; i++) {
while (scanf("%d", &numbers[i]) != EOF) {
sum += numbers[i];
}
}
average = (float)sum/count;
printf("Average of your numbers is: %.2f\n",average);
return 0;
}
If you're just trying to find the average then you don't need to actually store these numbers.
int count = 0;
int sum = 0;
int num = 0;
double avg = 0.0;
for(; scanf("%d", &num) != EOF; sum += num, count++)
;
avg = sum / count;
After checking with OP, he does not mind if the inputs are not stored in array. In that case, you may want to consider this:
int num=0;
int sum=0
int count=0;
do
{
printf("Enter number:");
scanf("%d", num);
sum += num;
count++;
printf("Proceed(y/n)?");
scanf("%c", proceed);
}while(proceed == 'y');
This code may be a little troublesome that you need to enter 'y' to continue inputing, but this may solve your current problem of inputting n inputs.
You will need to realloc the size of the array if you have filled the existing array. This should work:
#include <stdio.h>
#include <stdlib.h>
int main() {
int input;
int size = 0;
int* arr = NULL;
int* temp = NULL;
long sum = 0;
float average = 0;
do {
scanf("%d", &input);
size++;
temp = (int*) realloc(arr, sizeof(int)*size);
if(temp != NULL) {
arr = temp;
arr[size-1] = input;
}
sum += input;
} while(input != 0);
average = sum / size;
printf("sum: %lu\n", sum);
printf("average: %f\n", average);
return 0;
}
It does not have to be an array if all you're doing is adding up numbers
int number = 0;
int count = 0;
while(scanf("%d", &number)!=EOF)
{
sum += number;
count++;
}
Also this will never work because count is supposed to be a constant
int count = 3;
int numbers[count];