Learn Arrays In C

Definition of Array:

An array is a collection of elements of the same data type stored in continuous memory locations.

Consider a case where we want to store roll numbers of 10 students. Roll numbers are integers. We can use 10 separate variables to store roll numbers of each student or we can use array to do the same.

Why to use array?

  • Array can store elements of same data type together.
  • Accessing the items in array becomes very convenient compared to accessing from each separate variable.
  • We do not have to remember the variable names as array can store them sequentially.
The basic idea of array is to represent many instances in one variable.

Syntax:

// Array declaration by specifying size
int arr1[100]; 
 

// declare an array of user specified size 
int n = 100; 
int arr2[n]; 

// Initializing array with elements 
int arr[] = {1, 2, 3, 4}  // Here the compiler creates an array of size 4. 
  
 
// We can also do the above as  "int arr[4] = {1, 2, 3, 4}" 


// Declaration by specifying size and initializing 
int arr[6] = {1, 2, 3, 4} 
  
/* Here the compiler creates an array of size 6, initializes first  
 4 elements as specified by user and rest two elements as 0. 

Above is same as  "int arr[] = {1, 2, 3, 4, 0, 0}" 

*/

How to access array elements?

Array elements are accessed using an integer index. It starts from 0 and goes up to arraySize minus 1.

For Example:
int main() 
{ 
int arr[5]; 
arr[1] = 10; 
arr[5/2] = -5; 
arr[1/2] = 2; // this is same as arr[0] = 2 
arr[3] = arr[2]; 

printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]); 

return 0; 
} 

/* Output of above code:


2 10 -5 -5


/*

C Examples For Practice

  1. C program to add integers of two arrays
  2. C program to check whether the number is present in the array or not
  3. C program to find maximum number in an array
  4. C program to print array in reverse order
  5. C program to check whether the character is present in the string or not

Comments