C Programming: Arrays 🎯

beginner
8 min

C Programming: Arrays 🎯

Welcome to the world of C Programming! Today, we're diving into one of the most fundamental data structures - Arrays. By the end of this lesson, you'll have a solid understanding of arrays, their usage, and how they can help you build powerful applications. 💡

What are Arrays? 📝

In simple terms, an array is a collection of variables of the same type, stored in contiguous memory locations. Each variable in an array is called an element.

Declaring and Initializing an Array ✅

To create an array, we need to specify its type and the number of elements. Here's a simple example:

c
int numbers[5] = {1, 2, 3, 4, 5};

In this example, we've created an array named numbers that holds 5 integers (int). The values 1, 2, 3, 4, 5 are the initial values assigned to each element.

Accessing Array Elements 📝

To access an array element, we use its index. The first element in an array has an index of 0, the second has an index of 1, and so on.

c
int numbers[5] = {1, 2, 3, 4, 5}; printf("%d\n", numbers[2]); // Outputs: 3

Array Types 📝

One-Dimensional Arrays 📝

These are the most basic type of arrays. As the name suggests, they have one dimension.

Multi-Dimensional Arrays 📝

Multi-dimensional arrays allow you to store data in multiple rows and columns, much like a spreadsheet.

c
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; printf("%d\n", matrix[1][2]); // Outputs: 7

In this example, we've created a 3x4 matrix.

Array Sizes and Dynamic Memory Allocation 📝

In C, array sizes are fixed at the time of declaration. However, we can dynamically allocate memory for arrays using malloc().

c
int *numbers = (int *)malloc(5 * sizeof(int)); numbers[0] = 1; numbers[1] = 2; // ...

In this example, we've created an array of 5 integers dynamically.

Common Array Operations 📝

  • Finding the maximum element:
c
int numbers[5] = {1, 2, 3, 4, 5}; int max = numbers[0]; for (int i = 1; i < 5; i++) { if (numbers[i] > max) { max = numbers[i]; } } printf("%d\n", max); // Outputs: 5
  • Finding the average of elements:
c
int numbers[5] = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < 5; i++) { sum += numbers[i]; } printf("%f\n", (float)sum / 5); // Outputs: 3

Quiz 🎯

Quick Quiz
Question 1 of 1

What is an array in C Programming?

Quick Quiz
Question 1 of 1

What is the first element's index in a one-dimensional array?