Add n Integers to an non fixed Array - c

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];

Related

C Program returns garbage value for avg

When running this program using pointers and arrays to calculate the grade point average from the user input, it outputs a garbage value. How can I alter the code so that the output is correct?
void Insert_Grades(int *array)
{
int grades[4];
int i;
for (int i = 0; i < 4; i++)
{
printf("Enter grade %d: ", i + 1);
scanf("%d", &grades[i]);
}
array = grades;
}
void Calculate_Avg(int *array)
{
int i;
float avg;
float sum = 0;
for (i = 0; i < 4; i++)
{
sum += *(array + i);
}
avg = sum / 4;
printf( "Grade point average is: %f ", avg);
}
int main()
{
int grades[4];
int i;
printf("Enter the number of grades:\n");
Insert_Grades(grades);
Calculate_Avg(grades);
printf("\n");
return 0;
}
you cant assign arrays.
This operation assigns local pointer array with reference of the local array grades. For the extral world this operation means nothing.
array = grades;
You need to copy values instead.
memcpy(array, grades, sizeof(grades));
or
for (size_t index = 0; index < 4; index++)
array[index] = grades[index];
There are multiple problem in your code:
in function Insert_Grades, value are read into the local array grades. The last instruction array = grades has no effect because it only modifies the argument value, which is just local variable, a pointer to int that now points to the first element of grade array.
This explains why the program outputs garbage because the array grades defined in the main() function is uninitialized and is not modified by Insert_Grades().
You could copy the array grade to the caller array pointed to by array, but it seems much simpler to use the array pointer to read the values directly where they belong.
the variable i is defined multiple times, with nested scopes.
you should test the return value of scanf() to detect invalid or missing input.
Here is a modified version:
#include <stdio.h>
void Insert_Grades(int *array, int count) {
for (int i = 0; i < count; i++) {
printf("Enter grade %d: ", i + 1);
if (scanf("%d", &array[i]) != 1) {
fprintf(stderr, "invalid input\n");
exit(1);
}
}
}
float Calculate_Avg(const int *array, int count) {
float sum = 0;
for (int i = 0; i < count; i++) {
sum += array[i];
}
return sum / count;
}
int main() {
int grades[4];
int count = sizeof(grades) / sizeof(*grades);
float avg;
printf("Enter the grades:\n");
Insert_Grades(grades, count);
avg = Calculate_Avg(grades, count);
printf("Grade point average is: %.3f\n", avg);
return 0;
}

I need help creating a program in c that prints average and count of user inputed values

This program must fill a constant array of doubles with user inputs. It must keep count of all digits excluding chars when they are input. 0s count. After compilation it will accept inputs but the program immediately terminates. Right now it will only output the average but the count should be tracked as of now. I'm unfamiliar with c so any help would be appreciated.
#include <stdio.h>
#define SIZE 1000
double avgNoZero(double array[], int size);
int main (int argc, char **argv) {
double array[SIZE];
double number;
double average;
int count = 0;
while (scanf("%lf", & number == 1) && (count < SIZE)) { //I'm receving warnings about number being an int
array[count++] = number;
}
average = avgNoZero(array, count);
printf("%f\n", average);
return 0;
}
double avgNoZero(double array[], int size) {
int i;
//int count = 0;
double sum = 0;
for(i = 0; i < size; i++) {
sum += array[i];
/*if (array[count] != 0 ) { //I'm unsure where the part that checks for non zero should be.
sum += array[i];
} */
}
return sum / size;
}
At least this one problem
// while (scanf("%lf", & number == 1) && (count < SIZE))
while (scanf("%lf", & number) == 1 && (count < SIZE))
Good that OP has some warnings enabled and reported them.
I'm receving warnings about number being an int

Calculating Arithmetic and Geometric mean by introducing numbers until 0 is pressed

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;
}

While loop with user input validation to fill array, then search array for largest number.

I am working on a program that will accept user input to fill an array and then quit when the user enters q. Next the array is passed to a function that finds the largest value in the array. My program seems like it would work, but I believe that user input for the array is incorrect and I am not sure how to solve it.
#include <stdio.h>
#define SIZE 30
int maxnum(int userarray[], int maxx);
int main()
{
int i;
int nums[SIZE];
int largest;
printf("Type integer numbers (up to 30), followed by q to quit:\n");
while(scanf("%d", &nums[i]) == 1)
{
for(i = 0; i < SIZE; i++)
{
//blank
}
}
largest = maxnum(nums, SIZE);
printf("The largest number is: %d\n", largest);
return 0;
}
int maxnum(int userarray[], int maxx)
{
int i;
int maxnumber;
maxnumber = userarray[0];
for(i = 1; i < maxx; i++)
{
if(maxnumber < userarray[i])
{
maxnumber = userarray[i];
}
}
return maxnumber;
}
First i is unitialized.
Then your inner for loop is strange (why someone would do that??) and sets i to SIZE in the end, which is not good.
I don't give more details, but the value of i is trash all the time because of those 2 mistakes it should be:
int i = 0;
while((i<SIZE) && (scanf("%d", &nums[i]) == 1))
{
i++;
}
so you read one by one, and protect against array out of bounds by the second condition.
After that you're passing NUMS
largest = maxnum(nums, SIZE);
whereas the array could contain fewer valid values. Just pass
largest = maxnum(nums, i);
Here is another solution for your problem.
In main() function
int n,i=0;
while(scanf("%d",&n) == 1){
nums[i++] = n;
}
n = maxnum(nums, i);
printf("The largest number is: %d\n", n);
Note : Initialize the value of i=0, Then input and update nums[] array
In maxnum() function
for(i = 0; i < maxx; i++) {
if(maxnumber < userarray[i]){
maxnumber = userarray[i];
}
}
Note: Start i=0 and find the max mumber and return the value

Dynamic Programming - Minimum Coin caching

Earlier I posted a question about the coin vending machine problem (the minimum number of coins required). Turns out the issue was a typo in a for loop, so now the program works. The original question was this:
As the programmer of a vending machine controller your are required to compute the minimum number of coins that make up the required change to give back to customers. An efficient solution to this problem takes a dynamic programming approach, starting off computing the number of coins required for a 1 cent change, then for 2 cents, then for 3 cents, until reaching the required change and each time making use of the prior computed number of coins. Write a program containing the function ComputeChange(), that takes a list of valid coins and the required change. This program should repeatedly ask for the required change from the console and call ComputeChange() accordingly. It should also make use of “caching”, where any previously computed intermediate values are retained for subsequent look-up.
The issue is that the code makes use of recursion, so it takes quite a long time to evaluate large values. Making use of caching should improve the issue, but I have no idea how to go about it. The code can be found below.
#include <stdio.h>
#include <limits.h>
int computeChange(int[],int,int);
int min(int[],int);
int main(){
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(cur)/sizeof(int);
int v;
printf("Enter a value in euro cents: ");
scanf("%d", &v);
printf("The minimum number of euro coins required is %d", computeChange(cur, v, n));
return 0;
}
int computeChange(int cur[], int v, int n){
if(v < 0)
return INT_MAX;
else if(v == 0)
return 0;
else{
int possible_mins[n], i;
for(i = 0; i < n; i++){
possible_mins[i]=computeChange(cur, v-cur[i], n);
}
return 1+min(possible_mins, n);
};
}
int min(int a[], int n){
int min = INT_MAX, i;
for(i = 0; i < n; i++){
if((a[i]>=0) && (a[i]< min))
min = a[i];
}
return min;
}
With your existing code:
#include <stdio.h>
#include <limits.h>
int computeChange(int[],int,int);
int min(int[],int);
void initChange ();
int change [MAX]; //used for memoization
int main(){
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(cur)/sizeof(int);
int v;
initChange ();
printf("Enter a value in euro cents: ");
scanf("%d", &v);
printf("The minimum number of euro coins required is %d", computeChange(cur, v, n));
return 0;
}
void initChange () {
int i =0;
for (i = 0; i < MAX; i++) {
change[i] = INT_MAX;
}
}
int computeChange(int cur[], int v, int n){
if(v < 0)
return INT_MAX;
else if(v == 0)
return 0;
else{
if (change[v] == INT_MAX) {
int possible_mins[n], i;
for(i = 0; i < n; i++){
possible_mins[i]=computeChange(cur, v-cur[i], n);
}
change[v] = 1 + min(possible_mins, n); // memoization
}
return change[v];//you return the memoized value
};
}
int min(int a[], int n){
int min = INT_MAX, i;
for(i = 0; i < n; i++){
if((a[i]>=0) && (a[i]< min))
min = a[i];
}
return min;
}
I already posted a solution using loops in your previous question. I will post it again here:
So the below is the code snippet for your problem using memoization and dynamic programming. The complexity is O(Val*numTypesofCoins).
In the end, change[val] will give you the min number of coins for val.
int main (void) {
int change [MAX];
int cur[]={1,2,5,10,20,50,100,200};
int n = sizeof(a)/sizeof(int);
int val; //whatever user enters to get the num of coins required.
printf("Enter a value in euro cents: ");
scanf("%d", &val);
for (i=0; i <= val; i++) {
change[i] = INT_MAX;
}
for (i=0; i < n; i++) { // change for the currency coins should be 1.
change[cur[i]] = 1;
}
for (i=1; i <= val; i++) {
int min = INT_MAX;
int coins = 0;
if (change[i] != INT_MAX) { // Already got in 2nd loop
continue;
}
for (j=0; j < n; j++) {
if (cur[j] > i) { // coin value greater than i, so break.
break;
}
coins = 1 + change[i - cur[j]];
if (coins < min) {
min = coins;
}
}
change[i] = min;
}
}

Resources