0% found this document useful (0 votes)
2 views3 pages

Array

Uploaded by

RaghaviSelva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Array

Uploaded by

RaghaviSelva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is an Array?

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

 Think of it like a row of lockers: each locker (array element) stores one item (data value),
and all lockers are numbered (index).
 In C, array indices start from 0.

🔹 Declaration of Arrays
 To declare an array in C, we specify:
data_type array_name[size];

 data_type → type of elements (e.g., int, float, char)


 array_name → identifier (e.g., marks, numbers)
 size → number of elements (constant or macro, not variable in standard C)

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


float prices[10]; // array of 10 floats
char vowels[5]; // array of 5 characters

📌 Key points:

 Size must be a positive integer constant (e.g., 5, 100, #define SIZE 50).
 Memory is reserved for all elements at once.

🔹 Initialization of Arrays
We can assign values to array elements during declaration or later.

1. Compile-Time Initialization

Provide values inside {}:


int marks[5] = {90, 85, 76, 92, 88};

 Here, marks[0] = 90, marks[1] = 85, etc.

👉 If we provide fewer values:


int marks[5] = {90, 85}; // remaining elements set to 0

So, marks → {90, 85, 0, 0, 0}


👉 If size is omitted:
int marks[] = {90, 85, 76, 92, 88};

Compiler automatically sets size = 5.

2. Run-Time Initialization

We can assign values using a loop:


#include <stdio.h>

int main() {
int marks[5];
for (int i = 0; i < 5; i++) {
printf("Enter mark for student %d: ", i+1);
scanf("%d", &marks[i]); // run-time input
}

printf("Marks entered are: ");


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

🔹 Accessing Array Elements


We use the index:
marks[0] = 95; // changes first element
printf("%d", marks[2]); // prints third element

🔹 Memory Representation
 Arrays are stored in contiguous memory locations.
 If int marks[5]; and each int is 4 bytes → total 20 bytes are allocated continuously.
 marks[0] → base address;
marks[i] = base_address + (i × size_of_data_type).

#include <stdio.h>

int main() {

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


printf("Array elements are:\n");

for (int i = 0; i < 5; i++) {

printf("numbers[%d] = %d\n", i, numbers[i]);

return 0;

numbers[0] = 10

numbers[1] = 20

numbers[2] = 30

numbers[3] = 40

numbers[4] = 50

You might also like