We need to declare the array by saying data type of the array.
Each element of the array is of a particular data type. We can’t mix different data types in an array.
Elements in an array stored in contiguous memory locations
Declaring array
int num[5];
int num1[]={9,8,7,6,5};
int num2[5]={19,34,21,55,41};
float percentage[4]={12.4,13.2,15.6,8.3};
Displaying elements of array
First element of an array is stored at 0th position.
int i;
for(i=0;i<5;i++){
printf(" %d Number = %d \n",i,num[i]);
}
Displaying float variable
for(i=0;i<4;i++){
printf(" %d Number = %f \n",i,percentage[i]);
}
Char Array
Strings are known as character array.
Declaring char array.
char name[10]="plus2net";
Example
char name[]={'p','l','u','s','2','n','e','t','\0'};
int i=0;
while(name[i]!='\0'){
printf("%c ",name[i]);
i=i+1;
}
Output
p l u s 2 n e t
Asking user to input elements of an array
User will be asked to enter one by one number till 5th number is entered.
#include <stdio.h>
int main(void){
int num[5];
int i;
for(i=0;i<=4;i++){
printf("enter one number \n");
scanf("%d",&num[i]);
}
return 0;
}
Search for element after entering the data by user
#include <stdio.h>
int main(void){
int num[5];
int i;
int x;
int flag=0;
for(i=0;i<=4;i++){
printf("enter one number \n");
scanf("%d",&num[i]);
}
printf("Entry is over, now enter one number to search \n");
scanf("%d",&x);
for(i=0;i<=4;i++){
if(num[i]==x){
flag=1;
printf("The number is found = %d \n",num[i]);
}
}
if(flag !=1){
printf("Number is not found");
}
return 0;
}
Sum and average values of elements of an array
#include <stdio.h>
int main(void){
float sum,avg,num[5];
int i;
//float avg;
for(i=0;i<=4;i++){
printf("enter one number \n");
scanf("%f",&num[i]);
sum=sum+num[i];
}
printf("Sum = %f \n",sum);
avg=sum/5;
printf("Average = %f \n",avg);
return 0;
}
Output is here
enter one number
3
enter one number
6
enter one number
2
enter one number
8
enter one number
10
Sum = 29.000000
Average = 5.800000
Highest and lowest number in an array
Highest Number only.
#include <stdio.h>
int main(void){
int num[5]={12,14,11,15,11,10};
//int num[6]={-30,-32,-33,-28,-31,-35};
int hig_num=num[0];
int i;
for(i=0;i<6;i++){
if(num[i]>hig_num){
hig_num=num[i];
}
}
printf("Highest Number is %d",hig_num);
return 0;
}
Highest and lowest number
#include <stdio.h>
int main(void){
int num[6]={12,14,11,15,11,10};
//int num[6]={-30,-32,-33,-28,-31,-35};
int hig_num=num[0];
int low_num=num[0];
int i;
for(i=0;i<6;i++){
if(num[i]>hig_num){
hig_num=num[i];
}else{
low_num=num[i];
}
}
printf("Highest Number is %d ",hig_num);
printf("\nLowest Number is %d ",low_num);
return 0;
}