Chapter 8: Arrays

1. What is an Array?

  • Array is a collection of elements of the same type
  • All elements are stored in contiguous (next to each other) memory locations
  • Each element has an index starting from 0

2. 1D Arrays (One-Dimensional Arrays)

Syntax for Declaration:

C

Examples:

C

Important Rule: Size must be known at compile time (or use dynamic allocation – we’ll learn later).

3. Initializing Arrays

Way 1: Declare and Initialize at the same time

C

Way 2: Initialize partially (remaining get 0)

C

Way 3: Let compiler decide size

C

4. Accessing Array Elements

Use index inside square brackets [] Index starts from 0 to size-1

C

Example: Full Program – Storing and Printing Marks

C

Output:

text

Danger: Never access marks[5] – it is out of bounds → undefined behavior (crash or garbage value)

5. Taking Input in Array

C

6. Array Operations

A. Sum and Average of Array Elements

C

Output:

text

B. Linear Search in Array

Find if a number exists in the array.

C

C. Sorting Array (Bubble Sort – Simple Method)

C

Output:

text

7. Multidimensional Arrays (2D Arrays)

2D array is like a table (rows and columns).

Declaration:

C

Initialization:

C

Accessing:

C

Example: Print 2D Array (Matrix)

C

Output:

text

Today’s Homework

  1. Create an array of 10 integers. Take input from user and print them in reverse order.
  2. Write a program to find the largest and smallest number in an array.
  3. Create a 2D array (3×3) and calculate the sum of all elements.
  4. Write a program that takes 5 numbers in an array and checks if a particular number is present (search).
  5. Try to print this pattern using nested loops and arrays:
    text

You may also like...