Initialize One-Dimensional Array in C Programming

There are four different ways to initialize one-dimensional array in c programming.

1. Initialize array at the time of declaration

One way is to initialize one-dimentional array is to initialize it at the time of declaration. You can use this syntax to declare an array at the time of initialization.

int a[5] = {10, 20, 30, 40, 50};

a[0] is initialized with 10, a[1] is initialized with 20 and so on.

2. Initialize all elements of an array with 0 (zero)

C program does not assign any default value to declared variables. Same is true for the elements of an array. When we declare an array, all of its elements get initialized with garbage value. If you don’t want to get all elements initialized with garbage, you can initialize them with value 0 (zero). You can do this with the help of this syntax.

int a[5] = {0};

With the following syntax, a[0] to a[5] all are initialized with value 0 (zero).

Important Point: You can initialize an array with 0 (zero) only.

If you want to initialize elements with value 10, this syntax will not work.

int a[5] = {10}; //This will not initialize all statements with 10

3. Initialize to define the size of an array

Till now, we declare an array with size. Although, it is also possible to define the size of an array by initializing elements of the array. You can use this syntax for this.

int a[] = {10, 20, 30, 40, 50};

Remember: if you are not defining size inside [ ] brackets, you must initialize the array (it will define array’s size).

If you will not define size of an array inside [ ] brackets, and you are also not initializing the array while declaring. Compiler will show an error “size of array is unknown or zero” and program will not compile.

int a[]; //This will cause an error.

4. Initialize array elements individually

Array is a group of variables, each variable is called element of the array. You can initialize all elements separately as you initialize any other variable. See following syntax.

int a[5];
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;

This is the most useful approach to initialize one-dimentional array in c programming. Most of the time, array elements are initialized with this method as per the requirement of the program.

Dr. Yogendra Pal

Ph.D. (IIT Bombay), M.Tech., B.Tech. (CSE) Dr. Yogendra Pal finished his Ph.D. from Educational Technology department at IIT Bombay. Mr. Pal holds B.Tech. and M.Tech. Degrees in Computer Science and Engineering. His interests include programming, web development, graphic design and educational technology.

This Post Has 3 Comments

  1. hi sir , is it avaliable progrmmingand web videos avaliablle in english

  2. Ta sir

    1. Thank you

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close Menu


Close Panel
Skip to toolbar