You are here:

C/arrays in c programming language

Advertisement


Question
QUESTION: hi,
I was reading a c programming book and as a beginner, i was lost by the codings. could u explain to me the meaning of this line by line?

# include <stdio.h>

int main(void)

{
 
 int a1[10], a2[10];
 int i;

 for (i=1 ;i<11;i++) a1[i-1] = i ;  /*start the analysis
         from this line pls
         */

 for (i = 0; i<10; i++) a2[i] = a1[i];

for  (i = 0; i<10; i++) printf("%d", a2[i]);

return 0;

}

pls, i urgently need to know why the first two for looops.

ANSWER: In the first loop, the array a1[] is getting populated.
The array index starts from 0.
But the loop index is starting from 1.
So, a[i-1] is used so, that array is populated from 1 less than the loop index, that is 0. And value 1 greater than the array index is kept in the array a[1].
And in the 2nd loop, all values of a1 is copied to a2.

---------- FOLLOW-UP ----------

QUESTION: why populate the array index so that it is 1 less than the loop index? what is the reason for populating the a1 array? i want to know why it is necessary to populate the a1 array first before equating it to the a2 array.

Answer
1. why populate the array index so that it is 1 less than the loop index?
ANS: Array index starts from 0. But, the loop is starting from 1.
        So, start of the array index is 1 less than the start of the loop index.

2. what is the reason for populating the a1 array?
ANS: If you don't write anything before using the variable, then what will it have?
        It might contain some value, which you don't know & didn't expected! (this is called garbage value).
        So, every variable should be initialized before using (and so is the a1 array).

3. i want to know why it is necessary to populate the a1 array first before equating it to the a2 array.
ANS: If you want to populate a2 using a1, then a1 needs to have the correct values. That's why a1 is initialized first.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.