Search

Arrays

                Array provides easy way to represent our data in C program. 



If we want to store marks of 100 students, then declaring 100 different int type of variables is not a good idea in C. C language provides facility to solve this issue using concept of “Array”. An array is collection of variables with same datatype.


In C language Arrays are of two types:
  • One-dimensional arrays
  • Multidimensional arrays

Syntax of Array

Array variable must be declared before its first use in C program. The general syntax of declaring one-dimensional array is as under:

data_type array_name[size_of_array];


where 
  • data_type may be any valid C data type like int, char, float, etc
  • array_name is valid variable name as per C language
  • size_of_array indicates maximum number of elements that array can store




Sample Programs





#include<stdio.h>
int
 main()
{
 int i=0, number[5];
 for(i=0; i<5; i++) // This loop tracks array index 
 {
  printf("Enter your Number[%d]:",i);
  scanf("%d",&number[i]);
 }
 //Logic to print number array.
 for(i=0; i<5; i++) // This loop tracks array index 
 {
  printf("Number[%d]:%d \n", i, number[i]);
 }
 return 0;
}




Output of the program:

Enter your Number[0]:2
Enter your Number[1]:4
Enter your Number[2]:6
Enter your Number[3]:8
Enter your Number[4]:10
Number[0]:2
Number[1]:4
Number[2]:6
Number[3]:8
Number[4]:10






#include<stdio.h>
int main()
{
 int i, arr1[5];
 for(i=0; i<5; i++)
 {
  printf("Enter Element[%d]:", i);
  scanf("%d",&arr1[i]);
 }
 printf("Array elements in reverse order are:\n");
 for(i=4; i>=0; i--)
 {
  printf("Element[%d]: %d \n", i,arr1[i]);
 }
}




Output of the program:

Enter Element[0]:1
Enter Element[1]:2
Enter Element[2]:3
Enter Element[3]:4
Enter Element[4]:5
Array elements in reverse order are:
Element[4]: 5
Element[3]: 4
Element[2]: 3
Element[1]: 2
Element[0]: 1




No comments:

Post a Comment