Arrays 1 - What Are Arrays in C Programming Explain and Also How To Declare and Initialise Them

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Here's a comprehensive explanation of arrays in C programming, including declaration

and initialization:

What are arrays in C?

● Arrays are collections of elements of the same data type, stored contiguously in memory.
● They provide an efficient way to manage multiple values under a single variable name.

Declaring arrays:

● Syntax: data_type array_name[size];


○ data_type: The type of data the array will hold (e.g., int, float, char)
○ array_name: The name you choose for the array
○ size: The number of elements the array can hold (must be a constant value)

Examples:

C
int numbers[5]; // Declares an array to hold 5 integers
float scores[10]; // Declares an array to hold 10 floating-point numbers
char letters[26]; // Declares an array to hold 26 characters

Initializing arrays:

● At declaration:
C
int ages[] = {25, 30, 35, 40}; // Declares and initializes with values

● After declaration:
C
int scores[5];
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
// ...

Important points:

● Zero-based indexing: Array elements are accessed using indices starting from 0, not 1.
The first element is array_name[0], the second is array_name[1], and so on.
● Out-of-bounds access: Attempting to access an element beyond the array's bounds
leads to undefined behavior, potentially causing program crashes.
● Arrays and pointers: Arrays are closely related to pointers, but they are not the same
thing. An array name represents the address of the first element in memory.

Common uses of arrays:

● Storing lists of values (e.g., student scores, product prices)


● Implementing mathematical matrices
● Representing strings (a string is essentially a character array)
● Handling data structures like stacks and queues

You might also like