Array in C Programming
[email protected] | CCIS – DIT | Mariano Marcos State University
Introduction to Arrays
• Definition: A collection of elements of the same data type stored in
contiguous memory locations.
• Purpose: Useful for storing multiple values under a single variable name.
Example:
int numbers[5]; // An array of 5 integers
Why Use Arrays?
• Organized Storage: Groups similar items, such as test scores.
• Simplifies Manipulation:
• Easily loop through data.
Example:
int scores[3] = {90, 85, 70}; // Store 3 test scores
Declaring and Initializing Arrays
• Declaration: type arrayName[size];
• Initialization at Declaration:
int scores[5] = {10, 20, 30, 40, 50}; // Initializes all 5 elements
• Partial Initialization: Uninitialized elements are set to zero (if global).
int scores[5] = {10, 20}; // Only first two elements initialized
Accessing Array Elements
• Syntax: arrayName[index];
• Example:
int scores[5] = {90, 85, 70, 60, 50};
printf("%d", scores[0]); // Outputs 90 (first element)
Modifying Array Elements
• Syntax: Assign new values using indices.
Example:
int scores[5] = {90, 85, 70, 60, 50};
scores[3] = 75; // Updates the fourth element to 75
Length of Array in C
• The Length of an array in C refers to the
number of elements in the array. It
must be specified at the time of
declaration. It is also known as the size
of an array that is used to determine the
memory required to store all of its
elements
• The sizeof() operator is a compile-time
unary operator that calculates the size
of the variables and datatypes. It
returns an integer value that represents
the size of the expression or a variable
in bytes.