Array in C

array

Array in C

An array is a variable that can store multiple values of same data type.

For example, if we want to store 100 integer numbers, we can create an array.

        
int num[100];     
        
    
Array in C

How to declare an Array?

An array is declared by using Data Type, Array Name, and Array Size

Syantx of Array Declaration

        
dataType arrayName[ArraySize];       
        
    

Example

        
int num[10];        //Declared an Array, num of integer data type and its size is 10. 
float salary[45];   //Declared an Array, salary of floating point data type and its size is 45. 
double data[250];   //Declared an Array, data of double data type and its size is 250. 
        
    

How to access array elements?

We can access elements of an array by indexes.

Suppose we declared an array num[100] as above. The first element is num[0], the second element is num[1], the third element is num[2], and so on.

How to initialize an array?

An array can be initialized during declaration as

            
 int num[10] = {20, 60, 48, 57, 89, 8, 12, 45, 76, 1};
            
        

Here

            
num[0] is 20
num[1] is 60
num[2] is 48
num[3] is 57
num[4] is 89
num[5] is 8
num[6] is 12
num[7] is 45
num[8] is 76
num[9] is 1
            
        

Here a simple program that takes input from user and store it in an Array and then prints the elements stored in Array.

Program

            
#include <stdio.h>

int main()
{
    int num[5];
    printf("Enter 5 integers: ");
                    
    // taking input from user and storing it in an array
    for(int i = 0; i < 5; ++i)
    {
        scanf("%d", &num[i]);
    }
                    
    printf("Displaying integers: \n");
                    
    // printing elements of an array
    for(int i = 0; i < 5; ++i)
    {
        printf("%d\n", num[i]);
    }
                    
    return 0;
}     
            
        

Output

            
Enter 5 integers: 10 25 6 89 12
Displaying integers:
10
25
6
89
12    
            
        



Join Our Social Media Connections

Post a Comment

0 Comments