Topics

6/recent/ticker-posts

Arrays in c language


arrays:

 

DEF: Array is a collection of similar type of elements, that can share common name.

 

Syntax to declare array:

 

            data_type   array_name  dimension

           

            [] à Single dimension array

            [][] à Two dimensional array

[][][]  à three dimensional array

 

Arrays are of two types:

 

1)     1. Single dimensional arrays  à it is only one dimension

2)     2. Multi Dimensional arrays  à it contains more than one dimension

 

Working with single dimension arrays:

 

 

            Syntax :

                        data_type  array_name [n];

 

            nà no of elements.

 

            Eg:

                        int a[5];

                        int  b[];  à Invalid

 

            memory map for the above

           

 

 

 

 

 

 

Size of array = no.of elements * sizeof(data_type);

In the above example

Sizeof of array = 5 * 2 = 10 bytes

           

Memory allocation for the arrays is a sequential manner.

 

Accessing array elements :




                       

Assigning values to array elements :

 

 

a[5]= 60; à invalid, it raises memory exception.

 

 

Initializing array

 

            int a[5]={1,2,3,4,5};  à Valid

int a[ ]={1,2,3,4,5};  à Valid

int a[5]={1,2,3,4};  à Valid, fifth value may be garbage

            int a[5]={1,2,3,4,5,6};  àInvalid, since no of elements are more than size of

 the array.

 

Reading array elements from key board:

 

            for(i=0;  i<n ; i++)

            {

                        scanf(“%d”,&a[i]);

            }

 

Displaying array elements:

 

for(i=0;  i<n ; i++)

            {

                        printf(“%d”,a[i]);

            }

 

 

 

Program to read and display array elements:

 

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

int main()

{

int a[50];

int n,i;

            printf("\nEnter how many elements");

            scanf("%d",&n);

            if(n<1 || n>50)

            {

               printf("\n Invalid no of elements");

               exit(0);

            }

 

            printf("\nEnter the elements");

            for(i=0;i<n;i++)

            {

               scanf("%d",&a[i]);

            }

 

            printf("\nElements are ");

            for(i=0;i<n;i++)

            {

               printf("%d  ",a[i]);

            }

getch();

}

 The output has been given here in the above image or figure..

Post a Comment

0 Comments