Basic array questions

I was doing some school work and I got most of them, but am struggling with these two(still not super good at using arrays properly).
question 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int foo (void) 
{ 
	int i, j, k;
	int grid[4];
		 
	for (i = 0; i < 4; i++) 
	{ 
		grid[i] = 2; 
		for (j = 1; j < = 3; j++)  
				grid[j] = grid[i]+ 3; 
	} 
	return (grid[1]); 
} 
foo returns : ?

// this doesn't make much sense to me . So where do the loops end and begin. //What is grid[1]. Is it looking for i j or ks value? grid[i] is always equal //to 2. This makes no sense. 


question 2

Write the code to fill the array declared below with the numbers 1 – 20

int a[4][5];

Hint: Loops would make this easy

Code :
// any hints on where to start?

Being a two dimensional array, one loop would iterate through the first index set, and an inner loop would iterate through the second set.

Pseudo code:
1
2
3
4
5
6
loop {
	loop {
		i ++;
		a[j][k] = i;
	} k++
} j++


Examining the end result would show this in the array:
a[0][0] = 1, [1] = 2, [2] = 3, [3] = 4, [4] = 5
a[1][0] = 6, [1] = 7, [2] = 8, [3] = 9, [4] = 10
a[2][0] = 11, [1] = 12, [2] = 13, [3] = 14, [4] = 15
a[3][0] = 16, [1] = 17, [2] = 18, [3] = 19, [4] = 20

This is more for the second question, but knowing this, you can tackle the first. Expanding it out and filling it in as you go through the loops will help you conceptualize arrays.

Any of this help?
Last edited on
Yah that makes sense. Thanks. But in the second question they say int a[4][5] doesnt that have something to do with it as well? The highest your loops went up to was a[3][0]

Also what loops should i be using? for loops? Thanks.
Last edited on
Tried it out with for loops. Does this look okay?
1
2
3
4
5
6
7
8
9
10
11
12
13
int foo (void)
{
	int i,j,k;
	int a[4][5];
	for(j=0;j<4;j++)
	{
		for(k=0;k<5;k++){
		a[j][k]=i
		}
	}
}

	return i;
Last edited on
My loops went to a[3][4]. You may recall that an arrays index starts at 0, not 1. So a[4] includes a[0], a[1], a[2], and a[3] (four components).

Regarding your code logic, make sure to increase the value of i for each iteration per the assignment. Give it a run to see the rest for yourself, but I think you got it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int foo (void)
{
	int i,j,k;
	int a[4][5];
	for(j=0;j<4;j++)
	{
		for(k=0;k<5;k++){
		i++
			a[j][k]=i
		
		}
	}

	return i;

Ok I fixed and here is my answer for the second part.
I still dont understand how to do the first question though :(
Last edited on
Topic archived. No new replies allowed.