Array In C Language





Page Content


To understand the concept of arrays effectively, let's examine the following program:

#include <stdio.h>

int main() {
    int current_value;
    current_value = 5;
    current_value = 10;
    printf("current_value = %d\n", current_value);
    return 0;
}
Output:
current_value = 10

Upon running this program, it will output current_value = 10. Why? Because, upon assigning the value 10 to current_value, the previous value of current_value (which was 5) gets overwritten. This demonstrates that ordinary variables, as used in this example, can only hold one value at a time.


However, there are scenarios where we need to store multiple values simultaneously within a single variable. Let's consider an example:

Suppose we want to organize the percentage marks obtained by 100 students in ascending order. We face two options to manage these marks in memory:


(a) Multiple Variables Approach : Create 100 separate variables, each designated to store the percentage marks of one student.
int marks1;
int marks2;
int marks3;
int marks4;
int marks5;
...
int marks96;
int marks97;
int marks98;
int marks99;
int marks100;
(b) Array Approach : Construct a single variable (referred to as an array or subscripted variable) with the capability to hold all 100 values.
  int marks[100];
  



What is an Array or define array in c?


Array is a collection of similar type of elements which have contiguous memory allocation.These similar quantities could be percentage marks of 100 students, or salaries of 300 employees, or ages of 50 employees.

For example, assume the following group of numbers, which represent percentage marks obtained by five students.

int stu_per[6] = { 48, 88, 34, 23, 96, 88}


Here we are going to write a program which will collect the marks of all subjects those are declared indivisully without an array.

#include <stdio.h>

int main() {
    // Marks of each subject
    int subject1 = 85;
    int subject2 = 90;
    int subject3 = 78;
    int subject4 = 88;
    int subject5 = 92;
    int subject6 = 80;

    // Calculate the sum of marks
    int total_marks = subject1 + subject2 + subject3 + subject4 + subject5 + subject6;

    // Print the sum of marks
    printf("Total marks: %d\n", total_marks);

    return 0;
}
Output:
Total marks: 513


Note : Before to convert above program into array program let's understand basic concepts of array.


Array declaration and Initialization example

    // Integer array
    int intArray[5] = {1, 2, 3, 4, 5};
    // Character array
    char charArray[5] = {'a', 'b', 'c', 'd', 'e'};
    // Float array
    float floatArray[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
    // Double array
    double doubleArray[5] = {1.111, 2.222, 3.333, 4.444, 5.555};
    // Long array
    long longArray[5] = {1000000000, 2000000000, 3000000000, 4000000000, 5000000000};
    // Short array
    short shortArray[5] = {1, 2, 3, 4, 5};
    // Unsigned Integer array
    unsigned int unsignedIntArray[5] = {1, 2, 3, 4, 5};
    // Unsigned Long array
    unsigned long unsignedLongArray[5] = {1000000000, 2000000000, 3000000000, 4000000000, 5000000000};
    // Unsigned Short array
    unsigned short unsignedShortArray[5] = {1, 2, 3, 4, 5};
    // Boolean array (not native to C, using int to represent)
    int boolArray[2] = {1, 0}; // 1 for true, 0 for false



Type of Declaration and initialization of array in c

In C programming, you can declare and initialize an array in various ways. Here are some common methods:


  1. Static Initialization: Declare and initialize the array with predefined values at the time of declaration.
        int arr1[5] = {1, 2, 3, 4, 5};
        
  2. Dynamic Initialization: If you're initializing the array dynamically, you can use a loop or other logic to assign values.
        int arr2[5];
        for (int i = 0; i < 5; i++) {
        arr2[i] = i + 1;
        }
        
  3. Partial Initialization: You can partially initialize an array, and the remaining elements will be automatically initialized to 0.
        int arr3[5] = {1, 2}; // arr3[0] = 1, arr3[1] = 2, arr3[2] = 0, arr3[3] = 0, arr3[4] = 0
        
  4. Designated Initializers (C99 and later): You can specify which elements of the array you want to initialize.
        int arr4[5] = {[0] = 1, [2] = 3}; // arr4[0] = 1, arr4[1] = 0, arr4[2] = 3, arr4[3] = 0, arr4[4] = 0
        
  5. String Initialization: Arrays can be initialized with strings. Strings in C are arrays of characters.
        char str[] = "Hello"; // str[0] = 'H', str[1] = 'e', ..., str[4] = 'o', str[5] = '\0'
        


Here we are going to write a program which will collect the marks of all subjects those are declared using array in c example.

#include <stdio.h>

int main() {
    // Marks of each subject
    int i,subjects[6] = {85, 90, 78, 88, 92, 80};

    // Calculate the sum of marks
    int total_marks = 0;
    for ( i = 0; i < 6; i++) {
        total_marks =total_marks+ subjects[i];
        
        //Another way to declare above statement
        //total_marks += subjects[i];
    }

    // Print the sum of marks
    printf("Total marks: %d\n", total_marks);

    return 0;
}
Output:
Total marks: 513


Another way to do the above program using #define keyword.

#include <stdio.h>

#define NUM_SUBJECTS 6

int main() {
    // Marks of each subject
    int i,subjects[NUM_SUBJECTS] = {85, 90, 78, 88, 92, 80};

    // Calculate the sum of marks
    int total_marks = 0;
    for ( i = 0; i < NUM_SUBJECTS; i++) {
        total_marks += subjects[i];
    }

    // Print the sum of marks
    printf("Total marks: %d\n", total_marks);

    return 0;
}
Output:
Total marks: 513


Here are some important points about arrays in C:

  • Arrays are a data structure that can be used to store a collection of data of the same type.
  • Arrays are declared using the type arrayName[size]; syntax, where type is the data type of the elements in the array, arrayName is the name of the array, and size is the number of elements in the array.
  • Arrays are indexed starting from 0, so the first element in an array is at index 0, the second element is at index 1, and so on.
  • Arrays can be accessed using the arrayName[index] syntax, where index is the index of the element you want to access.
  • Arrays can be manipulated using a variety of C operators, such as the + operator for addition, the - operator for subtraction, the * operator for multiplication, and the / operator for division.
  • Arrays can be passed to functions as arguments.
  • Arrays can be returned from functions.
  • Arrays can be used to store data in a variety of applications, such as storing the scores of a game, storing the names of students in a class, or storing the coordinates of points on a map.


Here are some additional tips for using arrays in C:

  • When declaring an array, make sure to choose a size that is large enough to accommodate all of the data that you need to store.
  • When accessing an element in an array, make sure that the index is within the bounds of the array.
  • When manipulating arrays, use caution to avoid errors.


Arrays can be a powerful tool when used correctly. However, they can also be a source of errors if not used carefully.



For understanding the arrays properly, let us consider the following:

#include <stdio.h>

int main() {
  // This is a regular variable that can store only one value at a time.
  int x = 5;

  // We can assign a new value to x, which will overwrite the old value.
  x = 10;

  // We can print the value of x.
  printf("x = %d\n", x);

  // In this case, x will print 10.

  // Now, let's say we want to store the marks of 100 students.
  // We could create 100 separate variables, one for each student.
  // However, this would be very inefficient and difficult to manage.

  // Instead, we can use an array.
  // An array is a variable that can store multiple values of the same type.
  // In this case, we can create an array to store the marks of 100 students.

  // The following code declares an array of 100 integers.
  int marks[100];

  // We can now store the marks of the students in the array.
  // For example, we can store the mark of the first student by using the following code.
  marks[0] = 95;

  // We can also print the marks of the students in the array.
  // For example, we can print the mark of the first student by using the following code.
  printf("The mark of the first student is %d\n", marks[0]);

  // In this case, the mark of the first student will print 95.

  // Arrays are a very powerful tool that can be used to store and manipulate data.
  // They are used in many different programming languages, including C, C++, Java, and Python.
}



The array "marks" declared and initialized in the program?

#include<stdio.h>
void main()
{
   int i;
   int marks[5] = {11, 12, 13, 14, 15}; // Declaration as well as Assignment
   // we can retrieve it using loop
   for (i = 0; i < 5; i++)
   {
      printf("%d\n", marks[i]);
   }
}
Output:
11
12
13
14
15


The array "marks" declared and initialized in the program using another way?

#include<stdio.h>

void main()
{
   int i;  
   int marks[5];// Declaration
   
   marks[0] = 11;// Assignment
   marks[1] = 12;
   marks[2] = 13;
   marks[3] = 14;
   marks[4] = 15;

   // we can retrieve it using loop
   for (i = 0; i < 5; ++i)
   {
      printf("%d\n", marks[i]);
   }
}
      
Output:
11
12
13
14
15


Array Program where we are taking user input elements as well as size of array?

#include<stdio.h>

void main()
{
   int i, size;
   int marks[50]; // Declaration
   printf("Enter the size of an array :\n ");
   scanf("%d", &size);
   printf("Enter the %d elements :\n", size);
   for (i = 0; i < size; ++i)
   {
      scanf("%d", &marks[i]);
   }

   printf("\n\nThe Values Entered By You :\n");
   // we can retrieve it using loop
   for (i = 0; i < size; ++i)
   {
      printf("%d\n", marks[i]);
   }
}     
Output:
Enter the size of an array :
2
Enter the 2 elements :
12
50
             
             
The Values Entered By You :
12
50


Bounds Checking in c

In C, there's no built-in check to ensure that the index used for an array stays within the array's size. If you try to access or store data using an index that's larger than the array size, it'll just go to some other part of the memory, possibly overwriting important data or even the program itself. This can cause the program to behave unpredictably or even crash without any warning.

For example, in the provided program, the array num has size 40, but the loop tries to access elements up to index 100. This can lead to serious issues.

So, it's entirely up to the programmer to make sure that they don't go beyond the array's size. The compiler won't give any error messages for this, so it's essential for the programmer to be careful about array bounds.

# include <stdio.h>
int main( )
{
int num[ 40 ], i ;
for ( i = 0 ; i <= 100 ; i++ )
num[ i ] = i ;
return 0 ;
}


here's an example program in C that demonstrates error handling when working with arrays to ensure array indices stay within bounds:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int size,i;
    int array[MAX_SIZE];

    // Prompt user to enter the size of the array
    printf("Enter the size of the array (up to %d): ", MAX_SIZE);
    scanf("%d", &size);

    // Validate array size
    if (size <= 0 || size > MAX_SIZE) {
        printf("Invalid array size. Please enter a size between 1 and %d.\n", MAX_SIZE);
        return 1; // Return 1 to indicate error
    }

    // Prompt user to enter array elements
    printf("Enter %d elements:\n", size);
    for ( i = 0; i < size; i++) {
        scanf("%d", &array[i]);
    }

    // Display array elements
    printf("\nArray elements:\n");
    for ( i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    return 0; // Return 0 to indicate success
}

Output:
Enter the size of the array (up to 100): 5
Enter 5 elements:
101
102
103
104
105

Array elements:
101 102 103 104 105


Multi Dimensional Array

A two-dimensional array, also known as a 2D array, is an array data structure that stores elements in a grid-like format with rows and columns. Unlike a one-dimensional array, which is a linear collection of elements, a two-dimensional array organizes elements into rows and columns to represent a grid, table, or matrix.


Implimentation of two dimentional array in c

  • Representing game boards, such as chess, checkers, or Sudoku.
  • Storing and analyzing data from sensor arrays, such as weather stations or medical devices.
  • Implementing algorithms like dynamic programming for problems involving grids or tables.
  • Creating 2D representations of geographical maps or floor plans.
  • Storing and manipulating pixel data in computer graphics and digital art.
  • Modeling and simulating physical systems with spatial dimensions, such as fluid dynamics or particle systems.

Declaration of two dimentional array in c

data_type array_name[row_size][column_size];

Here's an example of how you would declare a two-dimensional array of integers:

int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns

In this declaration:
  • int is the data type of the elements in the array (in this case, integers).
  • matrix is the name of the array.
  • 3 represents the number of rows in the array.
  • 4 represents the number of columns in the array.



    #include<stdio.h>
    int main()
    {
      // printf("%d ", *(arr + (i*cols) + j)) 
      // for pointer memory calculation[col=like 3]
      //1234 +(0*4*3)+0*4 => First Element [Here 4 is Datatype]
      int i,j,arr[3][3]={{1,2,13},{14,5,116},{7,8,15}};
      // retrive two Dimentional array
      for( i=0;i<3;i++)
      {
        for( j=0;j<3;j++)
        {
          printf("%d \t",arr[i][j]);
         // printf("%x \t",arr[i][j]);
          
        }
        printf("\n");
      }
    }         
      
        
Output:
              1       2       13
              14      5       116
              7       8       15
              
              --------------------------------
              Process exited after 0.04745 seconds with return value 10
              Press any key to continue . . .
        
Example:5

    #include<stdio.h>
    int main()
    {
    int i,j,size,vir[3][3];
    printf("Enter the size of an  array: ");
    scanf("%d",&size);
    printf("Enter the %d elements :\n",size*size);
    for( i=0;i <size;i++)//row
    {
    for( j=0;j <size;j++)//column
    { 
    scanf("%d",&vir[i][j]);
    }
    }
    
    printf("Output\n");
    for( i=0;i <size;i++)//row
    {
    for( j=0;j <size;j++)//column
    {printf(" %d \t",vir[i][j]);}
    printf("\n");
    }
    }
         
        
Output:
              Enter the size of an  array: 2
              Enter the 4 elements :
              10
              30
              65
              67
              Output
               10      30
               65      67
              
              --------------------------------
              Process exited after 13.98 seconds with return value 2
              Press any key to continue . . .
        
Example:6

    #include<stdio.h>
    int main()
    {
    int i,j,size,vir[3][3];
    printf("Enter the size of an  array: ");
    scanf("%d",&size);
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {
     scanf("%d",&vir[i][j]);
    }
    }
    
    printf("Transpose is\n");
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {printf(" %d \t",vir[j][i]);
    }
    printf("\n");
    }
    }
      
                
        
Output:
          Enter the size of an  array: 3
          65
          45
          23
          23
          45
          67
          54
          23
          32
          Transpose is
           65      23      54
           45      45      23
           23      67      32
          
          --------------------------------
          Process exited after 18.48 seconds with return value 3
          Press any key to continue . . .
        
Example:7

    #include<stdio.h>
    int main()
    {
    int i,j,size,vir[3][3], vir1 [3][3];
    printf("Enter the size of an  array: ");
    scanf("%d",&size);
    printf("enter the element for the first matrix \n");
    for( i=0;i<size;i++)//row
      {
    
       for( j=0;j<size;j++)//column
        {
          scanf("%d",&vir[i][j]);
        }
        }
      printf("enter the element for the second matrix \n");
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {
     scanf("%d",&vir1 [i][j]);
    }
    }
    
    printf("The matrix 1 is\n");
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {printf(" %d \t",vir[i][j]);
    }
    printf("\n");
    }
    printf("The matrix 2 is\n");
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {
    printf(" %d \t",vir1[i][j]);
    }
    printf("\n");
    }
    }
        
                
        
Output:
          Enter the size of an  array: 2
          enter the element for the first matrix
          1
          2
          3
          4
          enter the element for the second matrix
          23
          45
          67
          89
          The matrix 1 is
           1       2
           3       4
          The matrix 2 is
           23      45
           67      89
          
          --------------------------------
          Process exited after 18.47 seconds with return value 2
          Press any key to continue . . .
        
Example:8

    #include<stdio.h>
    int main()
    {
    int i,j,size,vir[3][3], vir1 [3][3],vir2[3][3];
    printf("Enter the size of an  array: ");
    scanf("%d",&size);
    printf("enter the element for the first matrix \n");
    for( i=0;i<size;i++)//row
      {
    
       for( j=0;j<size;j++)//column
        {
          scanf("%d",&vir[i][j]);
        }
        }
      printf("enter the element for the second matrix \n");
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {
     scanf("%d",&vir1 [i][j]);
    }
    }
    
    printf("The matrix 1 is\n");
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {printf(" %d \t",vir[i][j]);
    }
    printf("\n");
    }
    printf("The matrix 2 is\n");
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {
    printf(" %d \t",vir1[i][j]);
    }
    printf("\n");
    }
    
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {
    vir2[i][j]=vir[i][j]+vir1[i][j];
    }
    }
    printf("The sum is\n");
    for( i=0;i<size;i++)//row
    {
    
    for( j=0;j<size;j++)//column
    {printf(" %d \t",vir2[i][j]);
    }
    printf("\n");
    }
    }
              
        
Output:
          Enter the size of an  array: 2
          enter the element for the first matrix
          10
          20
          30
          40
          enter the element for the second matrix
          100
          200
          300
          400
          The matrix 1 is
           10      20
           30      40
          The matrix 2 is
           100     200
           300     400
          The sum is
           110     220
           330     440
          
          --------------------------------
          Process exited after 26.59 seconds with return value 2
          Press any key to continue . . .
        
Example:9

    #include <stdio.h>

    #define SIZE 3 // Size of the matrix
    
    int main()
    {
        int A[SIZE][SIZE]; // Matrix 1 
        int B[SIZE][SIZE]; // Matrix 2
        int C[SIZE][SIZE]; // Resultant matrix
        
        int row, col, i, sum;
    
    
        /* Input elements in first matrix from user */
        printf("Enter elements in matrix A of size %dx%d: \n", SIZE, SIZE);
        for(row=0; row<SIZE; row++)
        {
            for(col=0; col<SIZE; col++)
            {
                scanf("%d", &A[row][col]);
            }
        }
    
        /* Input elements in second matrix from user */
        printf("\nEnter elements in matrix B of size %dx%d: \n", SIZE, SIZE);
        for(row=0; row<SIZE; row++)
        {
            for(col=0; col<SIZE; col++)
            {
                scanf("%d", &B[row][col]);
            }
        }
    
        /*
         * Multiply both matrices A*B
         */
        for(row=0; row<SIZE; row++)
        {
            for(col=0; col<SIZE; col++)
            {
                sum = 0;
                /*
                 * Multiply row of first matrix to column of second matrix
                 * and store sum of product of elements in sum.
                 */
                for(i=0; i<SIZE; i++)
                {
                    sum += A[row][i] * B[i][col];
                }
    
                C[row][col] = sum;
            }
        }
    
        /* Print product of the matrices */
        printf("\nProduct of matrix A * B = \n");
        for(row=0; row<SIZE; row++)
        {
            for(col=0; col<SIZE; col++)
            {
                printf("%d ", C[row][col]);
            }
            printf("\n");
        }
    
        return 0;
    }
    
            
        
Output:
          Enter elements in matrix A of size 3x3:
          1
          2
          3
          4
          5
          6
          7
          8
          9
          
          Enter elements in matrix B of size 3x3:
          10
          20
          30
          40
          50
          60
          70
          80
          90
          
          Product of matrix A * B =
          300 360 420
          660 810 960
          1020 1260 1500
          
          --------------------------------
          Process exited after 17.9 seconds with return value 0
          Press any key to continue . . .