Definition :-
An Array is a group (or collection) of the same data types .
For an example an int array holds the elements of int types while float array holds the elements of float types .
How to declare an Array ?
datatype Array_name[array_size];
For example,
float salary[5];
Keynotes :
1: Arrays have 0 as the First index, not 1. In this example , salary[0] is the First element.
2: If the size of an array is n , to access the last element, the n-1 index is used.
In this example, salary[4]
3: Suppose the starting address of salary[0] is 2120d. then, the address of the salary[1] will be 2124d.
Similarly, the address of salary[2] will be 2128d and so on.
This is because the size of a float is 4 bytes.
How to initialize an array?
int salary[5] = { 10000 , 12000 , 12300 , 20000 , 21000 };
You can also initialize an array like this .
int salary[] = { 10000 , 12000 , 12300 , 20000 , 21000 };
here ,
salary[0] is equal to 10000
salary[1] is equal to 12000
salary[2] is equal to 12300
salary[3] is equal to 20000
salary[4] is equal to 21000
Example 1: ARRAY Input/Output
// Program to take 5 values from the user and store them in an Array
// Print the elements stored in the Array
#include<stdio.h>
void main(){
int salary[5];
int i,n;
printf("Enter 5 salaries: ");
// Taking input and storing it in an Array
for ( i = 0; i < 5; i++)
{
scanf("%d",&salary[i]);
}
printf("Displying salaries: ");
// Printing elements of an Array
for ( i = 0; i < 5; i++)
{
printf("%d \n",salary[i]);
}
}
OUTPUT :-
Enter 5 salaries : 10000 12000 12300 20000 21000
Displaying salaries :
10000
12000
12300
20000
21000
Here, we have used a for loop to take 5 inputs from the user and store them in an array.
Then , using another for loop, these elements are displayed on the screen.
There are two types of C-Arrays
1: One dimensional array
2: Multi-dimensional array
Multi-dimensional array contains , Two dimensional, Three dimensional upto 'n' dimensional array.
Nice bhau
ReplyDelete