Average of a row in a two-dimensional array in C? - c

I am having trouble making a program that uses a function call to find the average of the rows in a two dimensional array? I can't get it to work in a larger program. I made this program to try and figure out what I am doing wrong, but to no avail. Any outside help would be greatly appreciated! Here is the testing code:
#include <stdio.h>
double dAvg(double pt[][5],int rows);
int main(void){
int i;
//Initiallize array
double array[3][5]={{3.0,5.0,2.0,1.0,0.0},{4.0,8.0,6.0,3.0,3.0},{7.0,6.0,2.0,3.0,5.0}};
//Computes the average value per row of array
for(i=0;i < 3;i++){
printf("The average of row %d is %f",i,dAvg(array,3));
}
return 0;
}
double dAvg(double pt[][5],int rows){
int r,c;
double sum,avg;
//Calculate sum first
for (c=0,sum=0;c<5;c++){
sum += pt[r][c];
//Find average by dividing the sum by the number of numbers in a row
avg=sum/5;
return avg;
}
}
When I run the program, it just says that the program has stopped working, on top of that, I don't feel confident that I will actually work once that first issue is solved. I am quite new to multi-dimensional arrays and especially so for passing them to functions. Thanks again for any help!

Most errors were present in your dAvg function:
Namely:
You should not pass the entire 2D array if you only need one row there
You should pass the length of the array instead of hardcoding it everywhere (good practice, not a bug)
Your r was kept uninitialised therefore your indexing was not working
You were returning the average in every iteration therefore instead of summing the values you added the first and then you returned before adding the others.
double dAvg(double array[], size_t length){
size_t c;
double sum = 0;
// Calculate sum first
for (c = 0; c < length; c++){
sum += array[c];
}
// Find average by dividing the sum by the number of numbers in a row
return sum / (double) length;
}
int main(void){
int i;
//Initiallize array
double array[3][5] = {{3.0,5.0,2.0,1.0,0.0}, {4.0,8.0,6.0,3.0,3.0}, {7.0,6.0,2.0,3.0,5.0}};
//Computes the average value per row of array
for(i = 0; i < 3; i++){
printf("The average of row %d is %f\n", i, dAvg(array[i], 5));
}
return 0;
}

Related

Storing matrix colum sums and comparing them to find the largest

How do I store 1,2,3...n columns sums to a variable and than compare them to find the largest sum?
#include <stdio.h>
#include <math.h>
#define NUM_ITEMS 1000
int array[NUM_ITEMS];
int main(){
FILE* file;
int a[10][10];
int i,j, count = 0;
int n=0;
file = fopen("Matrica.txt", "r");
while(count < NUM_ITEMS && fscanf(file, "%d", &array[count]) == 1)
count++;
n = sqrt(count);
printf("Dimenzije matrice: %dx%d ",n,n);
rewind(file);
for(i=0;i<n;i++)
for(j=0;j<n;j++){
fscanf(file,"%d",&a[i][j]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\nElementi matrice: %d \n",a[i][j]);
}
}
int col[n];
for(j=0;j<n;j++){
for(i=0;i<n;i++){
col[i] += a[i][0];
}
}
printf("\nDBG:%d",col[0]);
fclose(file);
}
The task is to find dimensions of a[10][10], print out the elements of it and find the column that has biggest sum. What is the name for this var in English.
So far I've finished 2/3rds of the task.
Below is the code:
for(j=0;j<n;j++){
for(i=0;i<n;i++){
col[i] += a[i][0];
}
}
it is the code for calculating sum of the 1st column.
I don't know how to implement it to do what I want, because col[i] must have NULL values for sum to take it's place
or it will just print out a bunch a jibberish.
Note: col[0] was supposed to present column 1 , col[1] column 2 etc.
If I guessed correctly from the example you get only one 10x10 matrix from file, and now you want to sum elements in columns(vertically) not in rows(horizontally) try changing
col[i] += a[i][0]
to
col[i] += a[j][i]
Because with your code you were only adding first element of every row. First [] indicates row,second [] indicates column. What this slight change does is it sums every column element of row to its column index in col[i]. Because I don't know how your text file looks like I suppose you for sure get 10x10 matrix with valid elements.

I am now learning how to work with arrays and I'm struggling with my assigment to make a multiplication table and get the average

The assignment consist of creating a multiplication table where the product of the user inputted multiplicand and multiplier is stored in an array called myArray[12]. Then the Average function has to have two parameters (Array and multiplier), which returns the average of the elements in the array called myArray. I am also confused as to how make "average" a separate function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int num, i = 0, multiplier;
int myArray[12] = {};
double average;
printf("\n Enter a multiplicand: \n");
scanf("%d",&num);
printf("\n Enter the multiplier: \n");
scanf("%d", &multiplier);
for(i=1; i <= multiplier; ++i){
printf("%d * %d = %d \n", num, i, num*i);
}
myArray[i] = myArray[i] + num * 1;
average = myArray[i] / multiplier;
printf("%f\n", average);
return;
}
You are looping i from 1 to multiplier, so when you exit that loop, i will be equal to multiplier + 1. Then you set myArray[i], but myArray is only defined to have 12 elements, so something bad will happen if i is >= 12 at this point.
I think that what you're trying to do is:
Ask the user for two numbers, num and multiplier.
Calculate i * num for i values from 1 to multiplier.
Average those numbers.
Note: I think you have the roles of num and multiplier reversed in your example, but I'm using your terminology.
So you have a few things wrong here. First, you need to allocate enough space for to hold the values you're generating.
int *myArray = calloc(multiplier, sizeof (int));
Now myArray points to an int array of multiplier elements.
Next, you should move the assignment to myArray[i] inside of the loop. I think you just want to set it to i * num.
Finally, to calculate the average, you have to total up all the values in myArray and divide by multiplier. But you said you have to write this as a function. This function will have to take:
A pointer to the start of the array of values, which is myArray.
The number of values in the array, which is multiplier.
These are the two parameters that you were asked to use. You should define the function like this:
double calculate_average(int *array, int length) {
// Loop i from 0 to length here to add up array values,
// then divide by length.
}
Then in main:
double average = calculate_average(myArray, multiplier);

Imprecise average at run time

I am trying to solve a problem and I've run into a bit of an issue.
I have to find the running average of a series of numbers.
Example:
input 4 2 7
output 4 3 4.3333
Now here's the problem although I get the answer, it is not the precise answer.
Accepted Output: accuracy difference shown in the image
290.6666666667
385.4000000000
487.8333333333
477.4285714286
496.4444444444
...
523.8571166992
506.0454406738
495.3043518066
I can't find whats wrong. Some help would be highly appreciated.
#include<stdio.h>
main(){
int n;
printf("set:");
scanf("%d",&n);
float arr[n+1],resarr[n+1];
float sum=0;
for(int i=1; i<=n; i++){
scanf("%f",&arr[i]);
sum=arr[i]+sum;
float res= sum/(float)i;
resarr[i]=res;
}
int i=1;
while(i<=n) {
printf("%0.10f\n",resarr[i]);
i++;
}
return 0;
}
Here
for(int i=1; i<=n; i++){ }
you are trying to access out of bound array elements, this certainly causes undefined behavior as let's assume if n is 5 then you are accessing arr[5] also which doesn't exist.
C doesn't perform array boundary condition check, its programmer responsibility to not to access out of bound elements else it causes UB.
In C array index starts from 0 not from 1. So better start rotating loop from 0 to n. For e.g
for(int i=0; i<n; i++) {
scanf("%f",&arr[i]);
/* some code */
}
Code fails to achieve the desired accuracy as it is using float rather than double. #Some programmer dude
Typical float is precise to 1 part in 223. For printing to 0.0000000001, better to use double which is typically precise to 1 part in 253.
#include<stdio.h>
int main(void) {
//float arr[n + 1], resarr[n + 1];
//float sum = 0;
double arr[n + 1], resarr[n + 1];
double sum = 0;
...
// scanf("%f", &arr[i]);
scanf("%lf", &arr[i]);
...
// float res = sum / (float) i;
double res = sum / i; // cast not needed as `sum` is `double`
...
}
Iterating from 1 is not idiomatic in C. More common to iterate starting at 0.
size_t is best for array sizing and indexing. int may be too narrow. Of course with small arrays, it makes scant difference.
#include<stdio.h>
int main(void) {
printf("set:");
size_t n;
scanf("%zu", &n);
double arr[n], resarr[n];
double sum = 0;
for (size_t i = 0; i < n; i++) {
scanf("%lf", &arr[i]);
sum = arr[i] + sum;
double res = sum / (i+1);
resarr[i] = res;
}
for (size_t i = 0; i < n; i++) {
printf("%0.10f\n", resarr[i]);
}
return 0;
}
More robust code would check the input from the user it insure it is valid, allocate rather than use a VLA if n is allowed to be large, flush output before reading, etc.
Note that array arr[] is not needed, just a single double for the input and sum.

Learning c programming - passing array into function

May i know why is int count, biggest = -12000;? Why must it be -12000 and I do not understand this statement biggest = -12000
If I put biggest = 10000, it can still compile. Appreciate your advise as I am currently learning c programming. Can you please understand as clearly as possible? Thanks in advance!
#include <stdio.h>
#define MAX 10
int array[MAX], count;
int largest(int x[], int y);
int main()
{
/* Input MAX values from the keyboard. */
for (count = 0; count < MAX; count++)
{
printf("\nEnter an integer value:\n ");
scanf_s("&d", &array[count]);
}
/* Call the function and display the return value. */
printf("\n\nLargest value = %d\n", largest(array, MAX));
return 0;
}
/* Function largest() returns the largest value in an integer array */
int largest(int x[], int y)
{
int count, biggest = -12000;
for (count = 0; count < y; count++)
{
if (x[count] > biggest)
biggest = x[count];
}
getchar();
return biggest;
}
If you want to find the largest number in an array you compare all elements against the currently 'biggest' value. Whenever you find a value that's larger you put it in biggest.
To make sure that you find the proper value you must initialize biggest to a sensible value.
Your code initializes biggest to -12000, and therefore it will fail if all elements in the array have values lower than -12000 (unless you know something about the values in the array, but then that should be mentioned in a comment, to explain the unusual initialization value).
Sure it will compile, but that does not mean it will work correctly.
You could initialize biggest to the lowest integer value possible (INT_MIN),
int largest(int x[], int y)
{
int count, biggest = INT_MIN; // lowest integer value possible
for (count = 0; count < y; count++)
{
but a smart trick is to initialize it to the first value in your array.
int largest(int x[], int y)
{
int count, biggest = x[0]; // first value in your array
for (count = 1; count < y; count++) // starting with 2nd element
{
You can work this all out on a piece of paper with e.g. 3 array values, or step through your debugger and see what values the respective variables get.
Instead of assigning the value in starting to biggest, you can compare two elements of the array and after comparing it store maximum value in biggest and after it swap the numbers if greater it would be good approach.
if you use like:
if(x[count]>x[count+1])
biggest=x[count];
x[count]=x[count+1];
x[count+1]=biggest;
code above line in loop.
What you tried assigned a very high value to biggest. It's not a worthy idea.

Getting an average from values obtained by a sensor using C

Ok so I get this code to do the averaging : (written in C )
.
.
int sum[3];
int j;
int avg;
for(;;) //infinite loop
{
for(j=0;j<3;j++){
i = ReadSensor(); // function that keeps saving sensor values as int i
sum[j]=i;
}
avg=sum[0]+sum[1]+sum[2]+sum[3];
printf("Sonar: %d \r \n", avg >> 2);
}
.
.
Is this correct ? im shifting by 2 to divide by avg / 2^(2) which is 4
The problem is im expecting a value of about 15, however I get about 8--9 .. Im not sure why this is happening ?
Basically the sensor's readings fluctuate between 15-17, I want to get an average instead of printing noise values. Is my code correct ? Then why do I get wrong outputs !?
Looks like your script only captures three values (j=0, j=1, j=2), then divides by four.
You have a few problems, here are some suggestions:
You're iterating through the inside loop 3 times, however you're saying you have 4 sensors, you should change your for loop to: for (j = 0; j < 4; j++).
sum is an array of 3 elements, yet you're accessing an element 1 past the end of the array when calculating avg (sum[3]). This will cause undefined behaviour. sum should be declared as char sum[4] for this reason and the one above.
(Optional) sum does not need to be an array in the above example, it can simply be an int.
(Optional) If you want to divide an int by 4, use the division operator. The compiler should be better at optimizing the code for your particular architecture than you.
This is how your code could now look, depending on whether you need to keep an array or not:
int sum[4];
int total, j;
for (;;)
{
total = 0; /* reset at every iteration of the outside loop */
for (j = 0; j < 4; j++) {
sum[i] = ReadSensor();
total += sum[i];
}
printf("Sonar: %d \r \n", total / 4);
}
OR
int total, j;
for (;;)
{
total = 0; /* reset at every iteration of the outside loop */
for (j = 0; j < 4; j++)
total += ReadSensor();
printf("Sonar: %d \r \n", total / 4);
}
Isn't this
avg=sum[0]+sum[1]+sum[2]+sum[3];
should be
avg=sum[0]+sum[1]+sum[2];
as the loop as well declaration int sum[3]; means we are trying to store only 3 values.
Now if you want 4 and ok with divide operator. There are the new code which should replace the mentioned lines
int sum[4];
for(j=0;j<4;j++)
avg=sum[0]+sum[1]+sum[2]+sum[3]; // this part stays the same
The number of values read from sensor is required twice. First, to control the number of iterations of for loop. Second, as the divisor of sum. Introduce a variable (say, N) to capture that.
Also, the division by shifting does not sound right, because that restricts the number of readings from the sensor to power of two.
enum { N = 4 };
sum = 0;
for( j = 0; j < N; j++) {
i = ReadSensor(); // function that keeps saving sensor values as int i
sum += i;
}
avg = sum / N;
printf( "Sonar average: %d\n", avg );

Resources