FOC Unit 3: Array, String and Functions

 

  • Whenever we want to work with large number of data values, we need to use that much number of different variables.
  • As the number of variables are increasing, complexity of the program also increases and programmers get confused with the variable names.

To understand the concept of arrays, consider the following example declaration.
int a, b, c;
Here, the compiler allocates 2 bytes of memory with name ‘a’, another 2 bytes of memory with name ‘b’ and more 2 bytes with name ‘c’.

These three memory locations are may be in sequence or may not be in sequence.


Array:

There may be situations in which we need to work with large number of similar data values.

To make this work more easy,
C/C++ programming language provides a concept called “Array”.
Python: list

An array is a variable which can store multiple values of same data type at a time.

Definition

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

Array indices start from 0.

Types of Arrays

One-Dimensional (1D)int a[5];

Two-Dimensional (2D)int a[3][3];

Syntax

data_type array_name[size];

Example:

int num[5];

Initialization

int num[5] = {10, 20, 30, 40, 50};
Or
int num[] = {10, 20, 30, 40, 50}; // Size is auto-calculated

Accessing Elements

printf("%d", num[0]); // Access first element num[2] = 100; // Modify third element

Array with Loops

for (int i = 0; i < 5; i++) printf("%d ", num[i]);

Memory Representation:
Elements are stored sequentially in memory.
array[i] address = base_address + (i * sizeof(data_type))


2D Array Example

int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
printf("%d", matrix[1][2]); // Output: 6

2D Array with Loop

#include <stdio.h> int main() { int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; // Display elements using nested loops for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; }
🔹Limitations
Fixed size (cannot grow/shrink at runtime)
All elements must be of the same type
No built-in bounds checking

🔹 Applications
Storing lists, matrices, strings
Implementing data structures (stacks, queues)
Sorting and searching algorithms

Post a Comment

0 Comments