Arrays:

Array is a data type which is used to store multiple values of same data type in a single variable.


In C, if you want to store marks of ten students, you will have to declare ten variables. But if you use arrays, you do not have to declare ten variables. As data type of all these variables is same, you can use only one array to store them. You can set the number of elements in a

int marks[5] = {88, 89, 80, 90, 98};

Accessing Elements of Array:

We can use indexes to access elements of array.

array.c
#include <stdio.h>

int main(){
  int marks [5] = { 76, 55, 92, 65 };
  printf("%d\n", marks[0])
  printf("%d\n", marks[1])
  printf("%d\n", marks[2])
  printf("%d\n", marks[3])
  printf("%d\n", marks[4])
  return 0;
}

Problem:
It is easy to print when size of array is 10, 20, 30 or 100 items. But imagine if the size of array is 1 million items, is it good to print individual indexes like this? What we are doing here? We are printing the items over and over again. And we have seen that when we need to repeat our same block of code, we use loops.

array.c
#include <stdio.h>

int main(){
  int marks [5] = { 76, 55, 92, 65 };
     
  for(int i = 0; i < 5; i++){
    printf("%d\n", marks[i]);
  }
  return 0;
}

Taking input in arrays:

We can take input in arrays with the help of cin object and extraction in the same way we take input in out int or other variables. We can manually take input in arrays at specified indexes or we can use loop to take input in arrays.

array.c
#include <stdio.h>
  
int main(){
  int marks [5] ;
  for(int i = 0; i < 5;  i++){ 
    printf("Enter data at %d index ", i+1);
    scanf("%d",&marks[i]);
  }
  for(int i = 0; i < 5;  i++){ 
    printf("Marks : %d\n", marks[i]);
  }
}

Changing elements of array:

We can change the elements of array at any index we want.

array.c
#include <stdio.h>

int main(){
  int marks [5] = { 76, 55, 92, 65 };
  printf("%d\n", marks[0]);
  marks[0] = 100;
  printf("%d\n", marks[0]);
  return 0;
}

Note: If you do not specify the size of array, it is ok.


array.c
#include <stdio.h>

int main(){
  int marks [] = { 76, 55, 92, 65, 90 };
  printf("%d\n", marks[0]);
  printf("%d\n", marks[1]);
  printf("%d\n", marks[2]);
  printf("%d\n", marks[3]);
  printf("%d\n", marks[4]);
  return 0;
}

Note: Point: If we do not know the size of array, to which number we will run the loop?


Find size of array:

sizeof() operator as discussed earlier will give you the size of array. Size of array does not gives you the number of elements in array. As size of int is 4 bytes and we have three integers, so size of array will be 12 bytes. For this purpose, we will divide the size of array with the size of datatype.
int items = sizeof(array) / sizeof(datatype)

array.c
#include <stdio.h>

int main(){
  int marks [] = { 21, 89, 76 };
  int size = sizeof(marks)/sizeof(int);
  for(int i = 0; i < size;  i++){ 
    printf("%d\n",marks[i]);
  }
}