Arrays and Strings
Programming in C тАУ Part 3: Arrays and Strings
Class 12 ┬╖ Computer Science ┬╖ Unit 4: Programming in C
All programs below were compiled and run, and the outputs are real.
Navigation: тЖР Part 2: Control Structures and Loops ┬╖ Part 3 ┬╖ Part 4: Functions, Structures and Unions тЖТ
Table of Contents
- Arrays
- One-Dimensional Arrays
- Common Array Programs
- Two-Dimensional Arrays and Matrices
- Strings
- String Functions
- Common String Programs
- Quick Revision Table
- Practice Questions
1. Arrays
An array is a collection of variables of the same data type stored in continuous (adjacent) memory locations and accessed by one common name and an index (subscript).
Why arrays? To store 100 marks you would otherwise need 100 separate variables. An array stores them under one name, and a loop can process them all.
| Type | Subscripts | Example |
|---|---|---|
| One-dimensional | 1 | int marks[5]; |
| Two-dimensional | 2 (rows and columns) | int m[3][3]; |
| Multi-dimensional | 3 or more | int a[2][3][4]; |
Important: the index starts at 0. An array
a[5]has elementsa[0]toa[4]. There is noa[5]. C does not check the limits, so going outside the array silently damages other data.
2. One-Dimensional Arrays
data_type array_name[size];
int marks[5]; /* declaration */
int num[5] = {10, 20, 30, 40, 50}; /* initialization */
int x[] = {1, 2, 3}; /* size taken from the list: 3 */
If fewer values are given than the size, the rest become 0 (int a[5] = {1, 2}; gives 1, 2, 0, 0, 0).
#include <stdio.h>
int main(void)
{
int age[] = {18, 12, 19, 20, 16, 16, 17}; /* size decided by the values */
int n = sizeof(age) / sizeof(age[0]); /* number of elements */
int i;
printf("Number of elements = %d\n", n);
printf("First element age[0] = %d\n", age[0]);
printf("Last element age[%d] = %d\n", n - 1, age[n - 1]);
for (i = 0; i < n; i++)
printf("age[%d] = %d\n", i, age[i]);
return 0;
}
Output:
Number of elements = 7
First element age[0] = 18
Last element age[6] = 17
age[0] = 18
age[1] = 12
age[2] = 19
age[3] = 20
age[4] = 16
age[5] = 16
age[6] = 17
#include <stdio.h>
#define N 5
int main(void)
{
int marks[N], i;
for (i = 0; i < N; i++) { /* index runs from 0 to N-1 */
printf("Enter mark %d: ", i + 1);
scanf("%d", &marks[i]);
}
printf("The marks are: ");
for (i = 0; i < N; i++)
printf("%d ", marks[i]);
printf("\n");
return 0;
}
Sample run:
Enter mark 1: 72
Enter mark 2: 85
Enter mark 3: 64
Enter mark 4: 90
Enter mark 5: 78
The marks are: 72 85 64 90 78
3. Common Array Programs
Sum and average
#include <stdio.h>
int main(void)
{
int i, sum = 0;
int num[5] = {5, 10, 15, 20, 25};
for (i = 0; i < 5; i++) {
printf("%d\t", num[i]);
sum = sum + num[i];
}
printf("\nSum of 5 numbers is: %d\n", sum);
return 0;
}
Output:
5 10 15 20 25
Sum of 5 numbers is: 75
#include <stdio.h>
int main(void)
{
int age[10], i, sum = 0;
float avg;
for (i = 0; i < 10; i++) {
printf("Enter age %d: ", i + 1);
scanf("%d", &age[i]);
sum = sum + age[i];
}
avg = sum / 10.0f; /* 10.0 gives a decimal result */
printf("Average age = %.2f\n", avg);
return 0;
}
Sample run:
Enter age 1: 17 18 16 19 17 18 20 16 17 18
Enter age 2: Enter age 3: Enter age 4: Enter age 5: Enter age 6: Enter age 7: Enter age 8: Enter age 9: Enter age 10: Average age = 17.60
Counting with a condition
#include <stdio.h>
#define N 20
int main(void)
{
int age[N], i, count = 0;
for (i = 0; i < N; i++) {
printf("Enter age of student %d: ", i + 1);
scanf("%d", &age[i]);
}
for (i = 0; i < N; i++) {
if (age[i] >= 20 && age[i] <= 25)
count++;
}
printf("Students aged 20 to 25 = %d\n", count);
return 0;
}
Sample run:
Enter age of student 1: 18 21 22 25 26 19 20 23 24 30 27 21 22 28 25 20 19 24 23 31
Enter age of student 2: Enter age of student 3: Enter age of student 4: Enter age of student 5: Enter age of student 6: Enter age of student 7: Enter age of student 8: Enter age of student 9: Enter age of student 10: Enter age of student 11: Enter age of student 12: Enter age of student 13: Enter age of student 14: Enter age of student 15: Enter age of student 16: Enter age of student 17: Enter age of student 18: Enter age of student 19: Enter age of student 20: Students aged 20 to 25 = 12
Largest element
#include <stdio.h>
int main(void)
{
int i, n, num[100], max;
printf("How many numbers (maximum 100)? ");
scanf("%d", &n);
if (n < 1 || n > 100) {
printf("Invalid size\n");
return 1;
}
for (i = 0; i < n; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &num[i]);
}
max = num[0]; /* assume the first is the largest */
for (i = 1; i < n; i++) {
if (num[i] > max)
max = num[i];
}
printf("Largest number = %d\n", max);
return 0;
}
Sample run:
How many numbers (maximum 100)? 5
Enter number 1: 34 78 12 95 41
Enter number 2: Enter number 3: Enter number 4: Enter number 5: Largest number = 95
Linear search
#include <stdio.h>
int main(void)
{
int a[50], n, i, key, found = 0;
printf("How many elements (maximum 50)? ");
scanf("%d", &n);
if (n < 1 || n > 50)
return 1;
for (i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &a[i]);
}
printf("Enter the number to search: ");
scanf("%d", &key);
for (i = 0; i < n; i++) {
if (a[i] == key) {
printf("%d found at position %d (index %d)\n", key, i + 1, i);
found = 1;
break;
}
}
if (!found)
printf("%d is not in the array\n", key);
return 0;
}
Sample run:
How many elements (maximum 50)? 5
Enter element 1: 10 25 30 45 50
Enter element 2: Enter element 3: Enter element 4: Enter element 5: Enter the number to search: 45
45 found at position 4 (index 3)
Records in an array
#include <stdio.h>
int main(void)
{
int age[10], i;
int count1 = 0, count2 = 0;
for (i = 0; i < 10; i++) {
printf("Enter age of employee %d: ", i + 1);
scanf("%d", &age[i]);
}
for (i = 0; i < 10; i++) {
if (age[i] >= 60)
count1++;
else if (age[i] < 35)
count2++;
}
printf("Employees aged 60 or more = %d\n", count1);
printf("Employees aged below 35 = %d\n", count2);
return 0;
}
Sample run:
Enter age of employee 1: 65 30 45 62 28 36 70 55 33 60
Enter age of employee 2: Enter age of employee 3: Enter age of employee 4: Enter age of employee 5: Enter age of employee 6: Enter age of employee 7: Enter age of employee 8: Enter age of employee 9: Enter age of employee 10: Employees aged 60 or more = 4
Employees aged below 35 = 3
Sorting (bubble sort)
Neighbouring elements are compared and swapped if they are in the wrong order. After each pass the next largest (or smallest) value reaches its place.
#include <stdio.h>
int main(void)
{
int a[10], i, j, temp;
for (i = 0; i < 10; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &a[i]);
}
for (i = 0; i < 9; i++) {
for (j = i + 1; j < 10; j++) {
if (a[i] < a[j]) { /* swap to put the larger value first */
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Numbers in descending order:\n");
for (i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Sample run:
Enter number 1: 45 12 78 3 56 91 23 67 8 34
Enter number 2: Enter number 3: Enter number 4: Enter number 5: Enter number 6: Enter number 7: Enter number 8: Enter number 9: Enter number 10: Numbers in descending order:
91 78 67 56 45 34 23 12 8 3
4. Two-Dimensional Arrays and Matrices
A two-dimensional array stores data in rows and columns like a table or matrix.
int m[3][4]; /* 3 rows, 4 columns: 12 elements */
int a[2][3] = { {1, 2, 3}, {4, 5, 6} };
Element m[i][j] is in row i, column j, and both indexes start at 0. A nested loop is used to process it: the outer loop for rows, the inner loop for columns.
Reading and displaying a matrix
#include <stdio.h>
int main(void)
{
int matrix[3][4], i, j;
printf("Enter the elements of a 3x4 matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++)
scanf("%d", &matrix[i][j]);
}
printf("\nThe matrix is:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++)
printf("%d\t", matrix[i][j]);
printf("\n");
}
return 0;
}
Sample run:
Enter the elements of a 3x4 matrix:
1 2 3 4 5 6 7 8 9 10 11 12
The matrix is:
1 2 3 4
5 6 7 8
9 10 11 12
Row-wise sum
#include <stdio.h>
int main(void)
{
int j, k, sum;
int num[3][4] = {{1, 2, 3, 4}, {8, 10, 11, 5}, {9, 6, 2, 8}};
printf("Data stored\t\t Row sum\n");
for (j = 0; j < 3; j++) {
sum = 0;
for (k = 0; k < 4; k++) {
printf("%d\t", num[j][k]);
sum = sum + num[j][k];
}
printf("= %d\n", sum);
}
return 0;
}
Output:
Data stored Row sum
1 2 3 4 = 10
8 10 11 5 = 34
9 6 2 8 = 25
Transpose
The transpose of a matrix swaps its rows and columns, so b[j][i] = a[i][j].
#include <stdio.h>
#define SIZE 3
int main(void)
{
int a[SIZE][SIZE], i, j;
printf("Enter the elements of a %dx%d matrix:\n", SIZE, SIZE);
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++)
scanf("%d", &a[i][j]);
}
printf("\nTranspose of the matrix:\n");
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++)
printf("%d ", a[j][i]); /* row and column swapped */
printf("\n");
}
return 0;
}
Sample run:
Enter the elements of a 3x3 matrix:
1 2 3 4 5 6 7 8 9
Transpose of the matrix:
1 4 7
2 5 8
3 6 9
Addition
Matrices of the same size are added element by element.
#include <stdio.h>
int main(void)
{
int m1[3][3], m2[3][3], i, j;
printf("Enter the elements of the first 3x3 matrix:\n");
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
scanf("%d", &m1[i][j]);
printf("Enter the elements of the second 3x3 matrix:\n");
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
scanf("%d", &m2[i][j]);
printf("\nSum of the two matrices:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%d\t", m1[i][j] + m2[i][j]);
printf("\n");
}
return 0;
}
Sample run:
Enter the elements of the first 3x3 matrix:
1 2 3 4 5 6 7 8 9
Enter the elements of the second 3x3 matrix:
1 1 1 2 2 2 3 3 3
Sum of the two matrices:
2 3 4
6 7 8
10 11 12
Multiplication
For A (r1 ├Ч c1) and B (r2 ├Ч c2), multiplication is possible only if c1 = r2. The result has size r1 ├Ч c2, and c[i][j] = sum of a[i][k] ├Ч b[k][j].
#include <stdio.h>
int main(void)
{
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int c[2][2], i, j, k;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
c[i][j] = 0;
for (k = 0; k < 2; k++)
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
printf("Product matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++)
printf("%d\t", c[i][j]);
printf("\n");
}
return 0;
}
Output:
Product matrix:
19 22
43 50
5. Strings
A string is a group of characters ending with the null character '\0'. C has no string data type, so a string is stored in a char array.
char name[10] = "Nepal"; /* stored as N e p a l \0 */
char city[] = "Pokhara"; /* size 8: 7 letters + '\0' */
Always keep one extra element for
'\0'. A string of 5 letters needs an array of at least 6.
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[] = "Nepal"; /* '\0' is added automatically */
char b[] = {'N', 'e', 'p', 'a', 'l', '\0'}; /* same string, written out */
printf("a = %s, b = %s\n", a, b);
printf("sizeof(a) = %zu (includes '\\0')\n", sizeof(a));
printf("strlen(a) = %zu (without '\\0')\n", strlen(a));
return 0;
}
Output:
a = Nepal, b = Nepal
sizeof(a) = 6 (includes '\0')
strlen(a) = 5 (without '\0')
Reading a string
| Function | Reads | Note |
|---|---|---|
scanf("%s", s) | One word, stops at a space | No & needed for an array name |
fgets(s, size, stdin) | A full line with spaces | Safe; keeps the \n at the end |
gets(s) | A full line | Removed from standard C; unsafe |
#include <stdio.h>
int main(void)
{
char line[60], word[30];
printf("Enter a sentence: ");
fgets(line, sizeof line, stdin); /* reads the whole line, spaces included */
printf("fgets stored: %s", line); /* line already ends with '\n' */
printf("Enter a word: ");
scanf("%29s", word); /* stops at the first space */
printf("scanf stored: %s\n", word);
return 0;
}
Sample run:
Enter a sentence: Nepal is beautiful
fgets stored: Nepal is beautiful
Enter a word: Himalaya Mountains
scanf stored: Himalaya
6. String Functions
These are declared in string.h.
| Function | Purpose | Example | Result |
|---|---|---|---|
strlen(s) | Length (without '\0') | strlen("Rajesh") | 6 |
strcpy(d, s) | Copies s into d | strcpy(a, "Ram") | a = "Ram" |
strcat(d, s) | Joins s to the end of d | strcat(a, "Rai") | "RamRai" |
strcmp(a, b) | Compares two strings | strcmp("cat", "cat") | 0 |
strcmp() returns 0 if equal, a negative value if the first is smaller (comes earlier in the dictionary), and a positive value if the first is larger.
Warning: the destination of
strcpy()andstrcat()must be big enough, or memory is overwritten.
#include <stdio.h>
#include <string.h>
int main(void)
{
char n[] = "Everest";
int length;
length = strlen(n);
printf("string = %s\n", n);
printf("length = %d\n", length);
return 0;
}
Output:
string = Everest
length = 7
#include <stdio.h>
#include <string.h>
int main(void)
{
char first[30] = "Rajesh";
char last[30] = "Hamal";
char copy[30];
int r;
/* strlen() */
printf("Length of \"%s\" = %zu\n", first, strlen(first));
/* strcpy(destination, source) */
strcpy(copy, first);
printf("Copied string = %s\n", copy);
/* strcat(destination, source) */
strcat(first, " ");
strcat(first, last);
printf("Joined string = %s\n", first);
/* strcmp() returns 0 if equal, negative or positive otherwise */
r = strcmp("apple", "banana");
if (r < 0)
printf("\"apple\" comes before \"banana\"\n");
else if (r == 0)
printf("Both strings are equal\n");
else
printf("\"apple\" comes after \"banana\"\n");
printf("strcmp(\"cat\", \"cat\") = %d\n", strcmp("cat", "cat"));
return 0;
}
Output:
Length of "Rajesh" = 6
Copied string = Rajesh
Joined string = Rajesh Hamal
"apple" comes before "banana"
strcmp("cat", "cat") = 0
Functions from ctype.h
| Function | Purpose |
|---|---|
toupper(c) / tolower(c) | Convert one character to upper / lower case |
isalpha(c) / isdigit(c) | Is it a letter / a digit? |
isupper(c) / islower(c) | Is it an upper / lower case letter? |
Turbo C note:
strrev(),strupr(),strlwr()andstrcmpi()appear in many old notes, but they are not standard C. The program below does the same jobs with a loop, so it works on any compiler.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char s[30];
int i, len;
printf("Enter a word: ");
scanf("%29s", s);
len = strlen(s);
printf("Uppercase: ");
for (i = 0; i < len; i++)
putchar(toupper(s[i]));
printf("\nLowercase: ");
for (i = 0; i < len; i++)
putchar(tolower(s[i]));
printf("\nReversed : ");
for (i = len - 1; i >= 0; i--)
putchar(s[i]);
printf("\n");
return 0;
}
Sample run:
Enter a word: Everest
Uppercase: EVEREST
Lowercase: everest
Reversed : tserevE
7. Common String Programs
Palindrome string
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[30], rev[30];
int i, len;
printf("Enter a word: ");
scanf("%29s", s);
len = strlen(s);
for (i = 0; i < len; i++) /* build the reversed string */
rev[i] = s[len - 1 - i];
rev[len] = '\0';
if (strcmp(s, rev) == 0)
printf("%s is a palindrome\n", s);
else
printf("%s is not a palindrome\n", s);
return 0;
}
Sample run:
Enter a word: madam
madam is a palindrome
Correction: a palindrome test that reverses the string into the same variable and then compares it with itself is always "true". Compare the characters from both ends, as done above.
Counting vowels
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char line[100];
int i, vowels = 0, consonants = 0;
char c;
printf("Enter a sentence: ");
fgets(line, sizeof line, stdin);
for (i = 0; line[i] != '\0'; i++) {
c = tolower(line[i]);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
vowels++;
else if (isalpha(c))
consonants++;
}
printf("Vowels = %d, Consonants = %d\n", vowels, consonants);
return 0;
}
Sample run:
Enter a sentence: Programming in C is fun
Vowels = 6, Consonants = 13
Sorting names alphabetically
#include <stdio.h>
#include <string.h>
int main(void)
{
char names[20][30], temp[30];
int n, i, j;
printf("How many names (maximum 20)? ");
scanf("%d", &n);
if (n < 1 || n > 20)
return 1;
for (i = 0; i < n; i++) {
printf("Enter name %d: ", i + 1);
scanf("%29s", names[i]);
}
for (i = 0; i < n - 1; i++) { /* bubble sort */
for (j = 0; j < n - 1 - i; j++) {
if (strcmp(names[j], names[j + 1]) > 0) {
strcpy(temp, names[j]);
strcpy(names[j], names[j + 1]);
strcpy(names[j + 1], temp);
}
}
}
printf("\nNames in alphabetical order:\n");
for (i = 0; i < n; i++)
printf("%s\n", names[i]);
return 0;
}
Sample run:
How many names (maximum 20)? 5
Enter name 1: Ram
Enter name 2: Sita
Enter name 3: Hari
Enter name 4: Bishnu
Enter name 5: Anita
Names in alphabetical order:
Anita
Bishnu
Hari
Ram
Sita
8. Quick Revision Table
| Topic | Key point |
|---|---|
| Array | Same-type elements in continuous memory, one name |
| Index | Starts at 0; last index is size тИТ 1 |
| 2-D array | a[row][col]; process with nested loops |
| Matrix addition | Same size; add element by element |
| Matrix multiplication | Columns of A = rows of B |
| String | char array ending with '\0' |
strlen strcpy strcat strcmp | Length, copy, join, compare |
scanf("%s") vs fgets | One word vs full line |
9. Practice Questions
Short-answer questions
- What is an array? Why is it used? (NEB Q8)
- Write the syntax to declare and initialize a one- and a two-dimensional array.
- What is a string? Why is
'\0'needed? - Differentiate between
scanf("%s")andfgets(). - Explain
strlen(),strcpy(),strcat()andstrcmp()with examples. (NEB Q8)
Programming questions (exam favourites)
- Read 10 numbers, then find the largest, the smallest and the average.
- Search for a number in an array and print its position.
- Sort 10 numbers in ascending order.
- Add, transpose and multiply two 3├Ч3 matrices.
- Check whether a string is a palindrome.
- Count the vowels, or the words, in a sentence.
- Arrange 5 names in alphabetical order.
Navigation: тЖР Part 2: Control Structures and Loops ┬╖ Part 3 ┬╖ Part 4: Functions, Structures and Unions тЖТ
Prepared for NEB Class 12 Computer Science exam revision.