When multiple variables of similar type are given one variable name with one subscript which can either represent a row or column, such a variable is called single sub-scripted variable or one dimensional array.
Declaration of 1-D array:
*size must be an integer constant i.e. greater than zero
Example:-
int x[5];
This will reserve space for 5 elements of array as,
float amount[4];
char name[7];
Wrong declarations:-
int x[]; //wrong
float amount[-2]; //wrong
int n=7;
char name[n]; //wrong
Initialization of 1-D array:
When an array is declared,its elements will be containing unknown values. We can give them values when they are declared, this is called initialization of array's elements.
Example:-
int x[5]={10,20,30,40,50};
This will initialize array with these values,
float amount[4]={12.5,45.8,67.8,34.5};
Another methods for initialization:-
int x[5]={10,20,30};
This will initialize array with these values,rest values will be zeroes
int x[5]={10,20,30,40,50,60,70};
This will produce compilation error as 7 values can't be placed in the space of 5.
int x[]={10,20,30,40,50};
This will automatically reserve space for 5 elements,with the initialization of these 5 values,
Declaration of 1-D array:
An array must be declared before they are used, so that space for them is allocated before use.
data_type variable_name[size];
*size must be an integer constant i.e. greater than zero
Example:-
int x[5];
This will reserve space for 5 elements of array as,
float amount[4];
char name[7];
Wrong declarations:-
int x[]; //wrong
float amount[-2]; //wrong
int n=7;
char name[n]; //wrong
Initialization of 1-D array:
When an array is declared,its elements will be containing unknown values. We can give them values when they are declared, this is called initialization of array's elements.
data_type variable_name={list of values separated by comma};
int x[5]={10,20,30,40,50};
This will initialize array with these values,
float amount[4]={12.5,45.8,67.8,34.5};
Another methods for initialization:-
int x[5]={10,20,30};
This will initialize array with these values,rest values will be zeroes
int x[5]={10,20,30,40,50,60,70};
This will produce compilation error as 7 values can't be placed in the space of 5.
int x[]={10,20,30,40,50};
This will automatically reserve space for 5 elements,with the initialization of these 5 values,
Accessing 1-D array's elements:-
To access first element we use x[0],for second element we use x[1] and so on.
Code:
#include<stdio.h> void main() { int x[10]; int i,n; printf("Enter number of elements"); scanf("%d",&n); for(i=0;i<n;i++) { printf("\nEnter x[%d]==> ",i); scanf("%d",&x[i]); } printf("\nArray's elements are==>"); for(i=0;i<n;i++) { printf("\n%d",x[i]); } getch(); }
Output:





No comments:
Post a Comment