Loading...
Loading...

C Arrays Tutorial

Arrays in C are used to store multiple values of the same data type. This tutorial covers the basics of single-dimensional and multi-dimensional arrays, along with practical examples.

1. What is an Array?

An array is a collection of variables that share the same data type and are stored sequentially in memory.

2. Declaring an Array

To declare an array in C, specify the data type, array name, and size:

#include <stdio.h>

int main() {
    int numbers[5]; // Declaration of an array with size 5

    return 0;
}

The above code declares an integer array of size 5.

3. Initializing an Array

Arrays can be initialized at the time of declaration:

#include <stdio.h>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5}; // Array initialization

    return 0;
}

The values are assigned to the array elements in sequence.

4. Accessing Array Elements

Array elements are accessed using their index, starting from 0:

#include <stdio.h>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};

    printf("First element: %d\\n", numbers[0]); // Accessing the first element

    return 0;
}

Use the index to read or write data to specific array elements.

5. Multi-dimensional Arrays

C supports multi-dimensional arrays, like 2D arrays:

#include <stdio.h>

int main() {
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    printf("Element at [1][2]: %d\\n", matrix[1][2]); // Accessing element

    return 0;
}

2D arrays are commonly used for matrices or tables.

6. Conclusion

Arrays are essential for handling lists of data. Practice with both single-dimensional and multi-dimensional arrays to master their usage.

0 Interaction
461 Views
Views
40 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home