Only homogeneous data type can be stored in the array, so it is called Homogeneous data type.
If we want to buy 7 numbers, int num1,num2,num3,num4,num5,num6,num7; Let's give that.
This is how the array is rendered,
int num[7];
7 integer value can be stored inside this num variable.
From this we can see that instead of creating 7 separate variables, we can create an array variable and use the memory of this variable.
These 7 elements are stored sequentially in memory.
We can access this array element only by index.
The index value starts from 0.
Declaring Array
Syntax
data_type array_name[size];
data_type -> refers to data types like int,float,char...
array_name -> This represents a variable name.
size -> This should be an integer value.
Initializing Array
Method 1:
int arr[5]={10,20,30,40,50};
The variable arr[5] first creates 5 locations and stores the given values in them.
Method 2:
int arr[10]={10,20,30};
First, the variable arr[10] creates 10 locations, of which it stores the value in three locations and returns zero in the other locations.
Method 3:
int arr[2]={10,20,30,40,50};
Only spaces can be created in arr[2], but here there are 5 values. If this happens, the computer will give us a warning message. From this, it can be seen that the value given in it should not be more than the size of the array.
Method 4:
int arr[]={10,20,30};
Thus, since we initialize the array without giving the size, the compiler will take the memory according to the given value.
Look at the image given above. In it memory is given as 1000, 1004, 1008. Because integer data type takes 4 bytes to store a value.
The first integer value ranges from 1000 to 1003. The next value ranges from 1004 to 1007. The next value ranges from 1008 to 1011.
This is how memory is allocated to every element in Array.
Now let's see how to get value from User using array.
To store value in Array,
An array variable called num can store 5 integer values.
int num[5];
for(i=0;i<5;i++)
{
scanf("%d",&num[i]);
}
To display the value in the Array,
It can display the 5 integer values in the array variable called num.
int num[5];
for(i=0;i<5;i++)
{
printf("%d",num[i]);
}
Programme:
#include<stdio.h>
int main()
{
int num[5];
printf("Enter the 5 values:");
for(i=0;i<5;i++)
{
scanf("%d",&num[i]);
}
printf("Display Values");
for(i=0;i<5;i++)
{
printf("%d",num[i]);
}
return 0;
}
Output:
Enter the 5 values:
10
20
30
40
50
Display Values:
10
20
30
40
50