C Arrays

1. What is an Array?

  • An array is a collection of elements of the same data type stored at contiguous memory locations.

  • Arrays allow you to store multiple values using a single variable name.

Syntax:

data_type array_name[size];
  • data_type → type of elements (int, float, char, etc.)

  • array_name → name of the array

  • size → number of elements (must be a positive integer)


2. Declaring and Initializing an Array

Declaration Only

int numbers[5]; // array of 5 integers

Declaration with Initialization

int numbers[5] = {1, 2, 3, 4, 5};
  • You can omit the size if initializing:

int numbers[] = {1, 2, 3, 4, 5}; // size automatically 5

3. Accessing Array Elements

  • Array elements are accessed using index numbers starting from 0.

#include <stdio.h>

int main() {
int numbers[5] = {10, 20, 30, 40, 50};

printf("First element: %d\n", numbers[0]);
printf("Third element: %d\n", numbers[2]);

return 0;
}

Output:

First element: 10
Third element: 30

4. Modifying Array Elements

#include <stdio.h>

int main() {
int numbers[5] = {10, 20, 30, 40, 50};

numbers[1] = 25; // change second element
numbers[4] = 55; // change fifth element

for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Output:

10 25 30 40 55

5. Looping Through an Array

#include <stdio.h>

int main() {
int numbers[5] = {5, 10, 15, 20, 25};

for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, numbers[i]);
}

return 0;
}

Output:

Element at index 0: 5
Element at index 1: 10
Element at index 2: 15
Element at index 3: 20
Element at index 4: 25

6. Key Points

  1. Array indices start at 0 and go up to size - 1.

  2. All elements must be of the same data type.

  3. Use loops to process arrays efficiently.

  4. Declaring array with size 0 or negative size is invalid.

  5. Accessing an index outside the declared size causes undefined behavior.


7. Example – Sum of Array Elements

#include <stdio.h>

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

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

printf("Sum of array elements: %d\n", sum);
return 0;
}

Output:

Sum of array elements: 15

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *