01
What Is an Array?
An array is a fixed-size, sequenced collection of elements all of the same data type, stored in contiguous memory locations and accessed through a single name plus an index.
Key characteristics:
- All elements are the same type.
- Elements are indexed starting from 0.
- The index can be a variable, allowing loops to process every element efficiently.
- The array name refers to the address of the first element in memory.
Element address formula:
element address = array address + (sizeof(element) × index)
02
Declaring, Defining, and Accessing Arrays
Declaration Syntax
data_type array_name[size];
int scores[20]; // 20-element integer array
char name[30]; // 30-element character array
float averages[10]; // 10-element float array
Initializing at Declaration
int first_array[5] = {5, 3, 2, 7, 9};
int second_array[] = {11, 21, 75, 24, 5}; // size inferred
int third_array[15] = {3, 7, 4, 6, 1}; // remaining 10 → 0
Character Arrays (Strings)
A string in C is a character array terminated by '\0' (null character). The null terminator is added automatically from string literals.
char college[6] = "CCMIT";
// college[0]='C', college[1]='C', ..., college[5]='\0'
Accessing Elements
scores[0] // first element
scores[9] // tenth element (for a 10-element array)
scores[i] // element at variable index i
Reading into an array:
for (i = 0; i < 10; i++)
scanf("%d", &scores[i]);
Printing:
for (i = 0; i < 10; i++)
printf("%d\n", scores[i]);
Copying (element by element — arrays cannot be assigned directly):
for (i = 0; i < 25; i++)
second[i] = first[i];
03
Array Examples: Sorting and Counting
Bubble Sort — Ascending Order
#include <stdio.h>
#include <conio.h>
void main() {
clrscr();
int num[3] = {5, 3, 7};
int h, i, temp;
for (h = 0; h < 3; h++)
for (i = 0; i < h; i++)
if (num[i] > num[i + 1]) {
temp = num[i];
num[i] = num[i + 1];
num[i + 1] = temp;
}
for (i = 0; i < 3; i++)
printf("%d\n", num[i]);
getch();
}
Output: 3, 5, 7
Count Positive and Negative Values
void main() {
int a[50], n, count_neg = 0, count_pos = 0, i;
printf("Enter the size of the array: ");
scanf("%d", &n);
for (i = 0; i < n; i++) scanf("%d", &a[i]);
for (i = 0; i < n; i++) {
if (a[i] < 0) count_neg++;
else count_pos++;
}
printf("Negative numbers: %d\n", count_neg);
printf("Positive numbers: %d\n", count_pos);
}
04
Practice Exercises — Lesson 5
05
Try It: Arrays
Add more scores to the array (update the size too) and watch the average and max update.