Hey all,

First post here and hello to everyone.

I've been studying C for a few months now, and everythnig has been making sense and I'm enjoying the challenge of learning to progeam.

Ther is one thing that keeps eluding my understanding of arrays, and that's using a variable in a for loop such as this:

#include <stdio.h>

int main()
{
    int array[10];
	int i;
		
	for (i = 0; i < 10; ++i){
	array[i]=i;
	
	printf("%d\n", array[i]);
	}
	return 0;
	}

No matter how I look at this, I can't seem to grasp the function of the variable i in this bit of the code, array. I can see that the loop runs up to 9, that the value of i is being assigned to each element in the array as the loop runs, that the variable i is being used as the index for the array, but why is the i in the array part?

Apologies if this is so basic, but it's driving me mad. Strange thing is, I find pointers to be easier to grasp tham this one thing. lol

Cheers.

Sometimes you just have to look at something for a while before it clicks. Adding extra printf statments can sometimes help to see what is going on.

#include <stdio.h>

int main(void)
{
   int i, array[10];
   for ( i = 0; i < 10; ++i )
   {
      array[i] = i;
      printf("array[%d] = %d\n", i, array[i]);
   }
   return 0;
}

/* my output
array[0] = 0
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4
array[5] = 5
array[6] = 6
array[7] = 7
array[8] = 8
array[9] = 9
*/

Ahh, now I see it. :) I have a tendency to look too closely at things.

Thanks a million for that, it helps in the way you showed your example.

Cheers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.