Link to home
Start Free TrialLog in
Avatar of bydysawd
bydysawd

asked on

Array initialisation with a loop

How is it possible to initialise an int type array using a loop. I tried the following, but it dosnt display the whole array, only the last element value.

#include<stdio.h>

int a[10];
int i, x;

main()
{

for(i=0; i<10; i++)
  {
  a[i];
  }

printf("array contents: %d", a[i]);

return 0;

}
ASKER CERTIFIED SOLUTION
Avatar of marcjb
marcjb
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Answers2000
Answers2000

Damn, marcjb types faster

What do you want to initialize it to, each array item to the loop index then :-



     for(i=0; i<10; i++)
       {
       a[i] = i ; /* set the i'th element of a[], that is a[i], to i */
       }

The reason that "a[i];" compiles is that it is valid C, but does nothing.  You are probably aware that in C that it is possible to ignore the return values of functions, example :-

x = somefunc() ;
or
somefunc() ;

are both valid.

This rule also applies to expressions :-

e.g. these are both valid
x = 3 * 5 ;
3 * 5 ;

the second calculates 3*5 but then throws away the result.  Simiarly your code gets the pre-existing value of a[i], but then does nothing.


The next problem is the printf in your program.  At the end of the loop (the first }) i is 10.  Therefore your printf prints the item 10 of a, only.  As a only has items 0 to 9, this could potentially cause a crash, but also is definitely not what you want, therefore

either



     for(i=0; i<10; i++)
       {
       a[i] = i ;
       }

    for (x=0; x<10;x++)
    {
      printf( "Item %d of array is %d", x, a[x] ) ;
    }


or



     for(i=0; i<10; i++)
       {
       a[i] = i ;
      printf( "Item %d of array is %d", i, a[i] ) ;
       }

Avatar of bydysawd

ASKER

Thanks for your prompt reply.

Your programs works, however I wanted each element in the array to increment by one, and then the 'stdout' to show each array content:

array 1: 0
array2: 1
etc

Sorry I did not state the question clearer..but thanks a lot !
The bit under "either" in my comment is that you need.

Array indexes always start from 0 in C by the way
Answers2000's suggestion of:

for(i=0; i<10; i++)
 {
 a[i] = i ;
 }

in the initialization of the array will place the values
a[0] = 0, a[1] = 1, etc...  into the array.