Understanding Arrays in C Programming

Sep 12, 2024

Arrays in C Programming

Introduction

  • Welcome back to the C programming series.
  • Today, we will learn about arrays in C.
  • Arrays allow storing multiple data items in a single variable.

What is an Array?

  • An array is a collection of similar types of data.
  • Example: To store the ages of 100 people, instead of creating 100 variables, we can use a single array.

Declaring an Array in C

  • Syntax for array declaration:
    data_type array_name[array_size];
    • data_type: Type of data stored (e.g., int, float).
    • array_name: Identifier for the array.
    • array_size: Number of elements the array can hold.
  • Example: int age[5];
    • Declares an array of integers to store the ages of 5 people.
  • Note: Size and data type cannot be changed after declaration.

Assigning Values to an Array

  • Values are assigned using the equal to operator (=).
  • Example: age = {21, 29, 25, 32, 17};
  • If the number of elements is lesser than declared size, remaining elements default to 0.

Array Indexing

  • Each element in an array is associated with an index, starting from 0.
    • Example: age[0] accesses the first element.
  • Accessing elements:
    • To print elements, use:
      printf("%d", age[index]);

Individual Assignment of Values

  • Values can also be assigned individually using their index:
    • Example: age[0] = 21;
  • Input from the user can also be stored in arrays using scanf.

Modifying Array Elements

  • Changing the value of an array element is straightforward:
    • Example: age[2] = 26;

Using Loops with Arrays

  • Instead of writing multiple scanf or printf statements, we can use loops.
  • Example for input:
    for (int i = 0; i < 5; i++) {
        scanf("%d", &age[i]);
    }
    
  • Example for output:
    for (int i = 0; i < 5; i++) {
        printf("%d", age[i]);
    }
    

Common Mistake - Out of Bounds Access

  • Be cautious about accessing array elements out of bounds. Example: If an array of size 5 is accessed with index 5, it results in unexpected behavior.

Programming Task

  • Create a program to compute the average marks of a student:
    • Use an array to store marks of 5 subjects.
    • Compute total and average marks.
  • Solutions available in GitHub repository.

Conclusion

  • Review concepts learned in this video.
  • Engage with the content: comment on the programming squeeze question.