Introduction to Arrays in C Programming
Fundamental Concepts
- Basic Data Types:
int
, float
, char
, double
, etc.
- Variable Declaration: Example:
int a = 5;
- Variable
a
of type int
is assigned a value of 5
Memory Representation of Variables
- Memory Layout: Memory can be visualized as a tape of bytes
- Storing an
int
Variable: Typically takes 4 bytes
- Example:
int a = 5;
takes 4 bytes in memory
- Address allocation example: starting from 100 to 103
Binary Representation
- Integer to Binary: Decimal 5 in 32-bit binary is 000...0101
- Stored across 4 bytes or 32 bits
Limitations of Single Variables
- Single Value Storage: A variable stores one value at a time
- Example:
int a = 5;
updates to int a = 6;
overwrites 5
Intro to Arrays
- Need for Arrays: Efficiently store multiple values
- Example: Storing roll numbers of 60 students
- Avoid multiple variable declarations
Array Declaration
- Syntax:
datatype arrayName[size];
- Example:
int rollNumbers[60];
- Size Constraint: Size must be a constant
- Invalid Declarations:
int a[];
or int a[n];
(without pre-defined constant n
)
Types of Arrays
- 1D Arrays: Single row of elements
- 2D Arrays: Matrix-like structure
- Multi-dimensional Arrays: Generally not covered in this session
Array Initialization
- Compile-Time (Static): Specify values during declaration
- Example:
int a[5] = {6, 2, 4, 3, 0};
- Stores values in continuous memory locations
- Address: base address + index * data type size
- Run-Time (Dynamic): Specify values during program execution
- Use loops and standard input functions like
scanf
Array Memory Allocation
- Consecutive Memory Allocation: Memory allocated in continuous blocks
- Example:
int a[5];
allocates 20 bytes (5 elements * 4 bytes each)
Fixed Size Limitation
- Fixed Size: Size declared at compile time cannot be changed at run time
- Example:
int a[5];
cannot store 6 elements
- Dynamic Arrays: Concept to overcome fixed size (discussed later)
Accessing Array Elements
- Random Access: Efficiently access any element using index
- Example:
a[2]
to access the third element
- Formula: Base address + (index * data type size)
- Element Indexing: Typically starts at 0
Example Code for Run-Time Initialization
#include <stdio.h>
int main() {
int a[5];
printf("Enter the elements of the array:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &a[i]);
}
return 0;
}
Summary
- Arrays are fixed-size, sequenced collections of same data-type
- Methods to declare, initialize, and access arrays
- Fixed size is both a feature and a limitation
- Random access allows efficient retrieval of elements
- Detailed explanation of 1D arrays, brief mention of 2D and multi-dimensional arrays
Next Steps
- Detailed discussion on run-time initialization, traversal, and operations on 1D arrays
- Introduction to 2D arrays and their memory access patterns