§ — — Computer Programming 1
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:
Element address formula:
element address = array address + (sizeof(element) × index)
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
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
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'
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];
#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
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);
}
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
Add more scores to the array (update the size too) and watch the average and max update.
Done with this module? Track it — your progress shows on the subject list.
Up next
Lesson 6: Functions→←Previous: Lesson 4: Program Control Structures