Global arrays

Hi guys, have a question to ask here.It seems that my sum function can't fetch the modified values from global array B after scan function has been called. But it would be okay if I declared the arrays inside main. I thought global variables can retain their values upon modification between functions?

#include <stdio.h>
int a[5]={12,13,14,15,16};
int b[5];
void scan (int b[], int size);
void sum(int a[],int b[]);
int main(void)
{

scan(b,5);
sum(a,b);
return 0;
}




void scan (int b[], int size)
{
int i,j[5];
for(i=0;i<size;i++)
{ printf("Enter the element of the target array: \n");
scanf("%d", &j[i]);
b[i]=j[i];
}

}

void sum(int a[],int b[])
{
int i, j;
int total1=0,total2=0;
double sumo;
for(i=0;i<5;i++)
{ total1=total1+a[i];
}
for(j=0;j<5;j++)
{ total2=total2+b[i];
}
sumo = 1.0*total1/total2;

printf("Total1 = %d\n", total1);
printf("Total2 = %d\n", total2);
printf("Sum = %lf\n", sumo);

}
Hi,

Before I start next time you might want to wrap you code inside code tags ([ code ] your code [ /code ], without the spaces). This makes it easier for us to read your code samples and help you! :D

You problem in your second for loop inside the function void sum(int a[],int b[]).

Your code:
1
2
3
for(j=0;j<5;j++)
{ total2=total2+b[i];
}


see in the for loop for( j =0; j <5; j++) you have declared and initialised a variable name j, however in the next line total2=total2+b[ i ];, you use i to invoke a location in your array (at this point i == 5, which is outside the bounds of your array and thus points to junk data).

The above line should be using j not i to point to the location in the array. Like this: total2=total2+b[ j ];.

I hope this helps!

P.S: I'm not quite sure what the variable double sumo; is supposed to represent so I'm not going to comment on it.

P.P.S: You might want to consider using cout<< and cin>> for printing to the screen and taking user interface. see: http://www.cplusplus.com/doc/tutorial/basic_io/ for a good tutorial in their use.

P.P.P.S: I might have gone a little format crazy with this one, so apologies if its not clear. If it isn't I'll be happy clarify. :D
Last edited on
Thanks :)!! Can't believe I missed that lol.

It's my first time posting in this forum, sry for missing out the code tags.

Topic archived. No new replies allowed.