A problem when calculating the average of an array (c programming )?

Click For Summary

Discussion Overview

The discussion revolves around a programming problem in C related to calculating the average of an array filled with user-inputted values. Participants explore issues with variable initialization and memory allocation, as well as the implications of using different methods for array declaration.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant describes a problem with their program where the average calculation yields an unexpectedly large number, suggesting the issue lies in the summation process.
  • Another participant points out that the variable 'e' is being assigned to the array before the user inputs a value, which may lead to using uninitialized data.
  • A suggestion is made to directly store user input into the array instead of using an intermediate variable, which could prevent the use of garbage values.
  • There is a discussion about the use of runtime array declaration in C and its compatibility with various compilers, with some participants expressing confusion about this feature.
  • A participant expresses gratitude for the help received and seeks clarification on using dynamic memory allocation with `calloc` as suggested by their instructor, comparing it to their current method of declaring an array with a variable size.
  • Another participant notes the importance of spelling and presentation in programming, suggesting that minor errors can affect professionalism.

Areas of Agreement / Disagreement

Participants generally agree on the issues related to variable initialization and the method of inputting values into the array. However, there is no consensus on the best approach to array declaration and memory allocation, as some participants express confusion regarding the use of `calloc` versus variable-length arrays.

Contextual Notes

There are unresolved questions regarding the compatibility of variable-length arrays with older compilers and the implications of using different memory allocation methods in C programming.

Who May Find This Useful

Beginners in C programming, particularly those learning about arrays, memory management, and user input handling.

blue_tiger30
Messages
28
Reaction score
0
hi ,
I need to do the following
Write a program that asks the user to enter a number. Then create an array of this size. Fill the array with random numbers between 0 and 10. Calculate the average value.
I did the program but there is a problem in calculating the average .
can some one tell me why it went wrong and how to solve the problem , not just posting the right solution without explaining please :)
I noticed that the problem is mainly in the sum but I don't know why it goes to a large number
Code:
#include <stdio.h>
#include <stdlib.h>
void avgArray(int array[],int size);
int main(void) {
int n,i,e;
printf("please enter the size of the array you want to create = ");
scanf("%i",&n);
int array[n];
printf("size of array = %i\n",(int)(sizeof(array)/sizeof(array[0])));
int size = (int)(sizeof(array)/sizeof(array[0]));

for (i=0; i<n; i++) {
array[i]=e;
printf(" please enter the value for array [%i] element = ",i);
scanf("%i",&e);
printf(" the value stored in array [%i] elment is %i\n",i,e);
}
avgArray(array,size);
}

void avgArray(int array[],int size){
int i;
int n=0;// number of elements starts as 0 
int sum=0;// the sum of the elements at the start is =0
float avg;
for (i=0; i<size; i++) {
	n+=1;// number of elements 
	sum += array[i];
	avg=(float)sum/n;// casting , to make the devision of 2 integers as a float
}
printf("the avarage of %d  which is the sum of %d elements is %.2f\n",sum,n,avg);
}

what I get is

Code:
please enter the size of the array you want to create = 5
size of array = 5
 please enter the value for array [0] element = 1
 the value stored in array [0] elment is 1
 please enter the value for array [1] element = 8
 the value stored in array [1] elment is 8
 please enter the value for array [2] element = 4
 the value stored in array [2] elment is 4
 please enter the value for array [3] element = 2
 the value stored in array [3] elment is 2
 please enter the value for array [4] element = 3
 the value stored in array [4] elment is 3
the avarage of 2665607  which is the sum of 5 elements is 533121.38
 
Technology news on Phys.org
You are assigning the input 'e' to array BEFORE the user is asked to input the number. You should initialize variables before they are used to avoid having trash values possibly being used.
 
blue_tiger30 said:
hi ,
I need to do the following
Write a program that asks the user to enter a number. Then create an array of this size. Fill the array with random numbers between 0 and 10. Calculate the average value.
I did the program but there is a problem in calculating the average .
can some one tell me why it went wrong and how to solve the problem , not just posting the right solution without explaining please :)
I noticed that the problem is mainly in the sum but I don't know why it goes to a large number
Code:
#include <stdio.h>
#include <stdlib.h>
void avgArray(int array[],int size);
int main(void) {
int n,i,e;
printf("please enter the size of the array you want to create = ");
scanf("%i",&n);
int array[n];
printf("size of array = %i\n",(int)(sizeof(array)/sizeof(array[0])));
int size = (int)(sizeof(array)/sizeof(array[0]));

for (i=0; i<n; i++) {
array[i]=e;
printf(" please enter the value for array [%i] element = ",i);
scanf("%i",&e);
printf(" the value stored in array [%i] elment is %i\n",i,e);
}
avgArray(array,size);
}

void avgArray(int array[],int size){
int i;
int n=0;// number of elements starts as 0 
int sum=0;// the sum of the elements at the start is =0
float avg;
for (i=0; i<size; i++) {
	n+=1;// number of elements 
	sum += array[i];
	avg=(float)sum/n;// casting , to make the devision of 2 integers as a float
}
printf("the avarage of %d  which is the sum of %d elements is %.2f\n",sum,n,avg);
}

what I get is

Code:
please enter the size of the array you want to create = 5
size of array = 5
 please enter the value for array [0] element = 1
 the value stored in array [0] elment is 1
 please enter the value for array [1] element = 8
 the value stored in array [1] elment is 8
 please enter the value for array [2] element = 4
 the value stored in array [2] elment is 4
 please enter the value for array [3] element = 2
 the value stored in array [3] elment is 2
 please enter the value for array [4] element = 3
 the value stored in array [4] elment is 3
the avarage of 2665607  which is the sum of 5 elements is 533121.38

The main problem is in your loop where you store the numbers in the array.
Code:
for (i=0; i<n; i++) {
  array[i]=e;
  printf(" please enter the value for array [%i] element = ",i);
  scanf("%i",&e);
  printf(" the value stored in array [%i] elment is %i\n",i,e);
}
At the start of the loop, e is an uninitialized variable, meaning it has a garbage value. That's what you're storing in array[0]. It would be better to dispense with e and store the input directly in the array, like this:
Code:
for (i=0; i<n; i++) {
  printf(" please enter the value for array [%i] element = ",i);
  scanf("%i",&array[i]);
  printf(" the value stored in array [%i] elment is %i\n", i, array[i]);
}

Also, I don't understand why you're compiler let's you get away with declaring your array at runtime. Older compilers wouldn't let you do this. What compiler are you using?

Minor point, but you have several misspellings: "elment"--> element, "devision" --> division, "average" --> average. Your program will look more professional if its user interface doesn't have misspellings.
 
Last edited:
thanks SteamKing , its working now
thanks Mark44 , I didnt get your suggestion really if you could explain more please .
I'm a beginner in programming , our Dr told us to use cygwin (gcc compiler) so that we can know how the files are produced
thanks for the minor point , I didn't spell cheek the program yet
 
I left a line of code in my example that I didn't want to include, but forgot to delete it. I've fixed it in my post, but here it is again.
Code:
for (i=0; i<n; i++) {
  printf(" please enter the value for array [%i] element = ",i);
  scanf("%i",&array[i]);[/color]
  printf(" the value stored in array [%i] elment is %i\n", i, array[i]);
}
I think this is what you're asking about. My point was that instead of inputting to a variable (e) and then putting the value in the array, you can input to the array directly. The line of code in blue, above, does just that.

Is that what you were asking about?
 
Yah , because the code that you posted had the e in it and had an upper case i &array so I got confused and though that there was something that exceeds my knowledge :)
Thanks again for your help , I really appreciate it :)
I just have one more question if you or anyone would like to answer it :)
our Dr. told us to do this task using (int *array = (int *)calloc(n,sizeof(int))) but I really didn't understand how that works , so I used scanf("%i",&n);
int array[n];

is there any difference between them or is there a case where my way won't work, if yes can you show me how to use the first method
 
blue_tiger30 said:
Yah , because the code that you posted had the e in it and had an upper case i &array so I got confused and though that there was something that exceeds my knowledge :)
Thanks again for your help , I really appreciate it :)
I just have one more question if you or anyone would like to answer it :)
our Dr. told us to do this task using (int *array = (int *)calloc(n,sizeof(int))) but I really didn't understand how that works , so I used
scanf("%i",&n);
int array[n];
The way you declared your array is something I questioned before. The C compilers that I used a number of years ago wouldn't let you do this, since the compiler had to know at compile time how much space to allocate on the stack for the array, and that couldn't be known until the program ran (i.e., at run time). In other words, the compiler needs to set aside a block of memory for the use of array, but has no way of knowing whether you will enter 5 for n or 2000. So I still don't understand how that works in your program, using the gcc compiler.

There's a pretty big difference between how your instructor said to do the problem and what you did. His way uses the calloc standard library function to allocate a block of memory on the heap, which is a different part of memory than the stack. The calloc function allocates memory and clears it (sets each cell to zero).

The arguments to calloc are the number of cells to allocate (n here), and the size of each cell (the sizeof an int). Assuming an int is 4 bytes, and n is, say 5, calloc will allocate a block of 5 * 4 = 20 bytes of contiguous memory.

The value returned by calloc is the location of (a pointer to) the first byte of allocated memory. In the definition int *array = (int*) calloc(...);
the variable array is actually a pointer variable that is initialized to the location in memory that is returned by calloc.

This part -- int * array -- says that array is a pointer to an int.
This part -- (int *) calloc( ... ) -- takes the address returned by calloc and casts it as a pointer to an int. Before being used, every pointer has to be associated with some type, such as int, char, and so on. Many standard library functions return what are called "void pointers" (void *), which means that they are just plain addresses that aren't associated with any type. These pointers have to be cast to some type before they can be used.
blue_tiger30 said:
is there any difference between them or is there a case where my way won't work, if yes can you show me how to use the first method
 

Similar threads

  • · Replies 25 ·
Replies
25
Views
3K
Replies
20
Views
2K
  • · Replies 31 ·
2
Replies
31
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
47
Views
5K
  • · Replies 17 ·
Replies
17
Views
4K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 22 ·
Replies
22
Views
3K