Learn about C Program to initialize all members of array with same number in the below code example.
Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
C Program to initialize all members of array with same number:
Generally initializing array with same numbers can be done easier for small sized array. It can be simply initialized putting values in flower brace that is shown below.
Method 1:
int array[5]={3,3,3,3,3};
Imagine array of size 20 or 1000 .This could be time consuming for initializing with same value ,so this could be achieved using loops. here are some methods.
Method 2:
#include<stdio.h>
int main()
{
int i,array[20];
for(i=0;i<20;i++)
{
array[i]=3;//declaring every index value with 3
}
for(i=0;i<20;i++)
{
printf("%d ",array[i]);
}
}
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
If elements in array to be declared with 0 value then that is easy task to be done. As static variable initializes its elements with 0 whereas any variable declared will be initialized with garbage values, hence static declaration is sufficient to initialize all values to zero
Method 3:
#include<stdio.h>
int main()
{
static int array[20];
int i;
for(i=0;i<20;i++)
{
printf("%d ",array[i]);
}
}
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
if an array is incompletely declared then automatically all other values of that array initializes to 0
Method 4:
#include<stdio.h>
int main()
{
int array[20]={1,2,3,4,5};
int i;
for(i=0;i<20;i++)
{
printf("%d ",array[i]);
}
}
1 2 3 4 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Also Read: