Different ways to initialize an array in C Programming

Arrays in C

The following C programming code performs simple operations on arrays. It initializes an array by two different ways and prints out the result of the array initialization.

In C, an array can be initialized using aggregates, which are a collection of values enclosed in braces ({}) and separated by commas.

Another way to initialize array by using a loop which allows you to set the initial values of an array using a more flexible and dynamic approach. The basic idea is to use a loop to assign values to each element of the array based on some condition or calculation.

This approach is particularly useful when you need to initialize an array with values that are not known at compile-time or that need to be calculated based on some condition or input.

Read more about arrays in our article: Arrays in C Programming

#include <stdio.h>

#define N 10

void oneWay(void);
void anotherWay(void);

int main(void) {
  printf("noneWay:n");
  oneWay();
  printf("nantherWay:n");
  anotherWay();
}

//Array initialized with aggregate
void oneWay(void) {
  int vect[N] = {1,2,3,4,5,6,7,8,9,0};
  int i;

  for (i=0; i<n; i++)
    printf("i = %2d  vect[i] = %2dn", i, vect[i]);
}

//Array initialized with loop
void anotherWay(void) {
  int vect[N];
  int i;

  for (i=0; i<n; i++)
    vect[i] = i+1;
  for (i=0; i<n; i++)
    printf("i = %2d  vect[i] = %2dn", i, vect[i]);
}

The output of this program is:

oneWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 0

antherWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 10

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post