What is an Array? • A collection of elements of the same type stored in contiguous memory. • Example: int A[5];
Why Use Arrays? • Easier to manage large data sets. • Access elements using index. • Saves code repetition.
Declaring Arrays Syntax: type arrayName[size]; Example: int marks[10];
Initializing Arrays • int A[5] = {1, 2, 3, 4, 5}; • int A[5] = {1, 2}; // others default to 0
Accessing Array Elements • Access with index: A[0], A[1] • Example with loop: for(int i=0;i<5;i++) printf("%d", A[i]);
Example Program #include <stdio.h> int main(){ int marks[5]={90,80,70,85,75}; int sum=0; for(int i=0;i<5;i++) sum+=marks[i]; printf("Total = %d", sum); return 0; }
2D Arrays • Example: int M[3][3]; • Access: M[i][j]
Strings as Character Arrays • char name[10] = "John"; • Strings are arrays of characters ending with '\0'.
Applications of Arrays • Store student marks • Represent matrices • Implement lookup tables • Store strings
Limitations of Arrays • Fixed size • Memory wastage if unused • Cannot dynamically resize