learnbywatch
Play Video

Initialize One-Dimensional Array in C Programming

After watching this video you will be able to:

No data was found

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-dimensional array in c programming. Most of the time, array elements are initialized with this method as per the requirement of the program.

What is your goal?

No data was found

4 thoughts on “Initialize One-Dimensional Array in C Programming”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Micro Courses using this Video

No data was found
Scroll to Top
Scroll to Top