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

In summary: LOLIn summary, the conversation was about a program that asks the user to enter a number, creates an array of that size, fills it with random numbers, and calculates the average value. However, there was a problem with the calculation and the user asked for help in solving it. It was determined that the issue was with an uninitialized variable being used in the array creation loop. The user also mentioned using the Cygwin compiler and was reminded to spell check the program for a more professional appearance.
  • #1
blue_tiger30
29
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
  • #2
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.
 
  • #3
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:
  • #4
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
 
  • #5
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);
  [color="blue"]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?
 
  • #6
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
 
  • #7
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
 

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

1. What is an array in C programming?

An array in C programming is a data structure that can hold a fixed number of elements of the same data type. It is a collection of similar elements that are stored in a contiguous memory location, which can be accessed using an index.

2. What is the average of an array in C programming?

The average of an array in C programming is the sum of all the elements in the array divided by the total number of elements. It is commonly used to find the central value or mean of a set of data.

3. Why is there a problem when calculating the average of an array in C programming?

The problem arises when the sum of all the elements in the array is too large to be stored in the data type used for the calculation. This can result in an overflow error, leading to an incorrect average value.

4. How can I avoid this problem when calculating the average of an array in C programming?

To avoid the problem, you can use a larger data type or a different algorithm for calculating the average. Another solution is to break the array into smaller sub-arrays and calculate the average for each sub-array, then combine them to get the final average.

5. Can you provide an example code for calculating the average of an array in C programming?

Yes, here is an example code that calculates the average of an array using a for loop and a double data type:

```#include int main() { int arr[5] = {1, 2, 3, 4, 5}; int i, sum = 0; double avg; for (i = 0; i < 5; i++) { sum += arr[i]; } avg = (double)sum / 5; printf("The average is: %.2lf", avg); return 0;}```

This code first declares an array of size 5 and initializes it with some values. Then, it uses a for loop to calculate the sum of all the elements. Finally, it divides the sum by the total number of elements and prints the average with two decimal places.

Similar threads

  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
20
Views
1K
  • Programming and Computer Science
Replies
31
Views
2K
  • Programming and Computer Science
Replies
2
Views
968
  • Programming and Computer Science
Replies
17
Views
2K
  • Programming and Computer Science
Replies
1
Views
981
  • Programming and Computer Science
2
Replies
47
Views
4K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
4
Views
3K
  • Programming and Computer Science
Replies
12
Views
1K
Back
Top