ADVERTISEMENT
ADVERTISEMENT

What are the different types of arrays in C?

An array in C is a collection of elements of the same data type, stored in contiguous memory locations. In C, there are two types of arrays:

  • One Dimensional Array
  • Two Dimensional Array

 One Dimensional Array

A one-dimensional (1D) array is a linear list of elements of the same data type, such as integers or characters. The elements are stored in contiguous memory locations and can be accessed using a single index. The index of the elements in a 1D array starts from 0.

For Example

int numbers[5];
char name[20];

This declares an array of 5 integers, with the index ranging from 0 to 4. To access the third element of the array, you would use the syntax numbers[2].

Here's a sample program that demonstrates how to use an array to sum 5 numbers in C:

#include <stdio.h>
int main() 
{
    int numbers[5];
    int sum = 0;
    printf("Enter 5 numbers: ");
    for (int i = 0; i < 5; i++) 
    {
        scanf("%d", &numbers[i]);
    }

    for (int i = 0; i < 5; i++)
    {
        sum += numbers[i];
    }

    printf("Sum of the numbers: %d", sum);

    return 0;
}

Two Dimensional Array

A two-dimensional (2D) array is a table-like structure that stores data in rows and columns. The elements are stored in contiguous memory locations and can be accessed using two indices, one for the row and one for the column. The index of the elements in a 2D array starts from 0.

For Example

int m1[3][4];

This declares a 2D array with 3 rows and 4 columns, with the index ranging from 0 to 2 for rows and 0 to 3 for columns. To access the element at the second row and third column, you would use the syntax m1[1][2].

Here's a sample program that demonstrates how to input and print a 3x3 matrix using an array in C:

#include <stdio.h>
int main()
 {
    int matrix[3][3],r,c;
    printf("Enter the elements of the 3x3 matrix:");
    for ( r = 0; r < 3; r++) 
    {
        for (c = 0; c < 3; c++) 
       {
            scanf("%d", &matrix[r][c]);
        }
    }

    printf("The matrix is:");
    for (r = 0; r < 3; r++) 
    {
        for ( c = 0; c < 3; c++) 
        {
            printf("%d ", matrix[r][c]);
        }
        printf("");
    }

    return 0;
}

This program uses nested for loops to prompt the user to enter the elements of a 3x3 matrix, which are then stored in the array "matrix". The outer for loop iterates through the rows, while the inner for loop iterates through the columns. Then another nested for loop is used to print the matrix, where the outer for loop iterates through the rows, while the inner for loop iterates through the columns. 


ADVERTISEMENT

ADVERTISEMENT