Array in C

              ARRAY IN C


Array is a collection of variables having similar data-type . C programming language provides a data structure called array. 

Here are the syntax of the array is : 

data-type  variable name [size of array];

Declaration: Here are the declaration of the array is :-

            int marks [30];

Here, int specifies the type of the variable , marks specifies the name of the variable, 30 Specifies the size of array and ([ ]) bracket tells the compiler that we are dealing with an array. 

Example of Array :

#include <stdio.h>

void main()

int arr[5]=(10,20,30,40,50); 

int i;

printf("Content of the array-\n");

// initial value of the i is 0 as the array indexing always start from zero

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

{

printf("Value at arr[%d] is %d\n",i,arr[i]);

}

}


OUTPUT:

Content of the array -

Value at arr[0] is 10

Value at arr[1] is 20

Value at arr[2] is 30

Value at arr[3] is 40 

Value at arr[4] is 50

Initialization:- It is possible to initialize an array during declaration.To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays.

You can initialize an array in C either one by one or using a single statement as follows -

- int num[6] = {3,8,4,9,6,7}; 

- int n [] = {8,4,6,0,9};

- float [ ] = {12.1, 11.9, 16.1, 19.4};

The number of values between braces {} cannot be larger than the number of elements that we declare for the array between square brackets [ ].

This will initialize the num array with value  at all index. We may also ignore the size of the array:

int num[] = {8,4,6,0,9};

The above statement assigns the 6th element in the array with a value of 7. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. 

This arrangement of array elements in memory is shown below is the pictorial representation of discussed above - 



/* sorting an array elements*/

#include<stdio.h>

#include<conio.h> 

void main() 

{

int a[3],i,j,temp;

printf ("Enter an array elements : \n"); 

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

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

}

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

{

for (j=i+1;j<5;j++)

if (a[i]>a[j]);  /*ascending sorting */

temp=a[i]; 

a[i]=a[j]; 

a[j]=temp; 

}

}

}

printf ("An array elements : \n");

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

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

}

 getch(); 

}


Output 

Enter an array elements :

1

2

3

4

5

An array elements :

5

4

3

2

1


[Program finished]























Comments

Popular posts from this blog

Basic Computer 🖥️💻 Organisation

Introduction of computer 🖥️🖥️🖱️