Arrays in C

Mannan Ul Haq
0

Arrays in C are used to store multiple elements of the same data type in a contiguous memory block. They provide a convenient way to work with collections of values and are widely used in programming. Arrays can be one-dimensional or multi-dimensional.


1. One-Dimensional Arrays:

A one-dimensional array, also known as a linear array, is a collection of elements of the same data type arranged in a single row.

Array Length = 4
First Index = 0
Last Index = 3

In C, each element in an array is associated with a number known as an array Index. We can access elements by using those indices.


Declaration and Initialization:

To declare a one-dimensional array in C, you need to specify the data type of the elements and the size of the array. The size represents the number of elements the array can hold. The syntax for declaring a one-dimensional array is as follows: 


dataType arrayName[arraySize];

 

Here, dataType refers to the type of data the array will store, such as int, char, float, etc. arrayName is the name given to the array, and arraySize denotes the number of elements the array can hold. 


After declaring the array, you can initialize it with different methods:


1. In C, its possible to initialize an array during declaration. For example:


int arr[5] = { 19, 10, 8, 7, 9 };

 

2. Another method to initialize array during declaration is:


int arr[] = { 19, 10, 8, 7, 9 };


Here, we have not mentioned the size of the array. In such cases, the compiler automatically computes the size. (alert-success)

 

3. Taking inputs from the user and store them in an array.

  • For this first of all initialize the size of array:
int arr[5]; or int arr[SIZE];

          Where SIZE is an constant variable.

  • Secondly, initialize the elements using loops:
for (index = 0; index < SIZE; index++)
    scanf("%d", &arr[index]);


For example:


#include <stdio.h>

#define SIZE 5 // Size of the array

int main()
{
    int arr[SIZE]; // Declare the array to store user input

    // Prompt the user to enter values for the array
    printf("Enter %d numbers:\n", SIZE);

    // Read user input and store it in the array
    for (int i = 0; i < SIZE; i++)
    {
        scanf("%d", &arr[i]);
    }

    return 0;
}


In C, unlike C++, you cannot use a variable to specify the size of an array at compile time. The size of an array must be a constant expression known at compile time. To resolve this issue, you can use a preprocessor macro to define the array size instead of a const variable. This preprocessor macro "#define" allows you to define constants. (alert-success)

 

Partial Initialization:

int list[25] = { 4, 7 };


  • Declares "list" to be an array of 25 components
  • The first two components are initialized to 4 and 7 respectively.
  • All other components are initialized to 0.

Accessing Elements:

Elements in a one-dimensional array can be accessed using the index.

Example:

 

int num = numbers[2]; // Accessing the element at index 2



Printing Array Elements:

We can print array using loop:

for (int index = 0; index < SIZE; index++)
    printf("%d ", arr[index]);


For example:


#include <stdio.h>

#define SIZE 5 // Size of the array

int main()
{
    int arr[SIZE]; // Declare the array to store user input

    // Prompt the user to enter values for the array
    printf("Enter %d numbers:\n", SIZE);

    // Read user input and store it in the array
    for (int i = 0; i < SIZE; i++)
    {
        scanf("%d", &arr[i]);
    }

    // Print the array elements
    printf("The array elements are: ");
    for (int i = 0; i < SIZE; i++)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}


Finding SIZE of Array:

To find the size of an array in C, you can use the sizeof operator. However, you need to be cautious when using sizeof with arrays, as it will return the size of the entire array in bytes, not the number of elements. To determine the number of elements, you can divide the total size of the array by the size of each individual element.

int arr[] = { 1, 3, 5, 7 };
int SIZE = sizeof(arr) / sizeof(arr[0]);

 


2. Two-Dimensional Arrays:

A two-dimensional array, also known as a matrix, is a collection of elements arranged in rows and columns. It can be visualized as a table or a grid.

Declaration and Initialization:

To declare a two-dimensional array in C, you need to specify the data type of the elements, the number of rows, and the number of columns. The syntax for declaring a two-dimensional array is as follows:

dataType arrayName[rowSize][columnSize];

Here, `dataType` represents the type of data the array will store, such as `int`, `char`, `float`, etc. `arrayName` is the name given to the array, `rowSize` denotes the number of rows, and `columnSize` represents the number of columns.


After declaring the array, you can initialize it with values using the following methods:

1. Initialize an array during declaration. For example:

int arr[2][3] = { 2, 4, 5, 9, 0, 19 };

 

0R
int arr[2][3] = { {2, 4, 5}, {9, 0, 19} };

Here, each set of curly braces represents a row, and the values inside them represent the elements of that row. The number of elements in each row should match the number of columns specified during the declaration. (alert-success)

2. Taking inputs from the user using loops:

for (int i = 0; i < ROWS; i++)
{
    for (int j = 0; j < COLUMNS; j++)
    {
        scanf("%d", &arr[i][j]);
    }
}

 

For example:


#include <stdio.h>

#define ROWS 3 // Number of rows in the array
#define COLUMNS 3 // Number of columns in the array

int main()
{
    int matrix[ROWS][COLUMNS]; // Declare the 2D array to store user input

    // Prompt the user to enter values for the array
    printf("Enter %d numbers for the 2D array:\n", ROWS * COLUMNS);

    // Read user input and store it in the 2D array
    for (int i = 0; i < ROWS; i++)
    {
        for (int j = 0; j < COLUMNS; j++)
        {
            printf("Element (%d, %d): ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }

    return 0;
}

 

Accessing Elements:

In a two-dimensional array, elements are accessed using both the row and column indices. The row index specifies the row's position, and the column index specifies the column's position. The indices start from 0.

To access an element, you can use the array name followed by the row and column indices in square brackets:

arrayName[rowIndex][columnIndex];

For example, to access the element in the second row and third column of a 2D array named `matrix`, you would use `matrix[1][2]` because the indices start from 0.


Printing Array Elements:

To print the elements of a two-dimensional array, you can use nested loops. The outer loop iterates over the rows, and the inner loop iterates over the columns.

for (int i = 0; i < rowSize; i++)
{
    for (int j = 0; j < columnSize; j++)
    {
        printf("%d ", arrayName[i][j]);
    }
    printf("\n"); // Move to the next line after printing each row
}

For example:

#include <stdio.h>

#define ROWS 3 // Number of rows in the array
#define COLUMNS 3 // Number of columns in the array

int main()
{
    int matrix[ROWS][COLUMNS]; // Declare the 2D array to store user input

    // Prompt the user to enter values for the array
    printf("Enter %d numbers for the 2D array:\n", ROWS * COLUMNS);

    // Read user input and store it in the 2D array
    for (int i = 0; i < ROWS; i++)
    {
        for (int j = 0; j < COLUMNS; j++)
        {
            printf("Element (%d, %d): ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }

    // Print the 2D array elements
    printf("The 2D array elements are:\n");
    for (int i = 0; i < ROWS; i++)
    {
        for (int j = 0; j < COLUMNS; j++)
        {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !