6 Arrays And Strings

C Programming · Unit 6

Arrays and Strings

Exam-focused notes for Arrays and Strings (C Programming, BIT102): what the TU syllabus asks and how it has actually been tested, with 13 solved past questions from this unit.

Arrays and Strings in short

Arrays store many values of the same type under one name. Strings are arrays of characters. Together they handle lists, tables and text.

Arrays and Strings: notes

One-dimensional arrays

An array is a group of variables of the same type stored in continuous memory. Each item is an element, reached by an index that starts at 0.

int marks[5];            /* declaration: marks[0] to marks[4] */
marks[0] = 70;
int a[5], sum = 0;
for (int i = 0; i < 5; i++) {
    scanf("%d", &a[i]);
    sum += a[i];
}
printf("Sum = %d\n", sum);

C does not check array bounds. Using a[5] for a size-5 array gives undefined behaviour.

Two-dimensional arrays

A two-dimensional array stores data in rows and columns, like a table or matrix. It is declared as type name[rows][cols].

int m[2][3] = { {1, 2, 3}, {4, 5, 6} };
for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++)
        printf("%d ", m[i][j]);
    printf("\n");
}

Elements are stored row by row in memory. This is called row-major order. Matrix addition adds a[i][j] + b[i][j] for each position.

Multi-dimensional arrays

C allows arrays with three or more dimensions. A 3D array int x[2][3][4] is two tables, each with 3 rows and 4 columns. It holds 2 x 3 x 4 = 24 elements.

int cube[2][2][2] = { { {1, 2}, {3, 4} }, { {5, 6}, {7, 8} } };
printf("%d\n", cube[1][0][1]);   /* 6 */

The size of the array in bytes is the product of all dimensions times the size of one element.

What this unit covers

  • One-dimensional arrays
  • Two-dimensional arrays
  • Multi-dimensional arrays
  • Array initialization and access
  • String definition and declaration
  • String functions from string.h
  • String manipulation and palindrome checking
  • Pattern generation using arrays

String definition and declaration

2081 · 10 marks

What is string?Explain any three string function in "string.h" header file in C with example.Write a program to check whether a word is palindrome or not.[2+3+5]

Show solved answer

String, String Functions, and Palindrome Check


1. What is String? [2 marks]

A string in C is a sequence of characters stored in a character array and terminated by a null character (\0). C does not have a built-in string data type; instead, strings are represented as arrays of type char.

Declaration:

char name[] = "Hello";
// Stored as: H e l l o \0

The null character \0 marks the end of the string and is automatically added when a string literal is used.


2. Three String Functions in string.h [3 marks]

i) strlen() - String Length

Returns the number of characters in a string, excluding the null character.

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "Hello";
    printf("Length = %d", strlen(str));  // Output: 5
    return 0;
}

ii) strcpy() - String Copy

Copies the content of one string (source) into another string (destination).

#include <stdio.h>
#include <string.h>
int main() {
    char src[] = "Nepal";
    char dest[20];
    strcpy(dest, src);
    printf("Copied string: %s", dest);  // Output: Nepal
    return 0;
}

iii) strcmp() - String Compare

Compares two strings lexicographically.

  • Returns 0 if both strings are equal
  • Returns a negative value if first string is less than second
  • Returns a positive value if first string is greater than second
#include <stdio.h>
#include <string.h>
int main() {
    char s1[] = "apple";
    char s2[] = "apple";
    if (strcmp(s1, s2) == 0)
        printf("Strings are equal");   // Output: Strings are equal
    else
        printf("Strings are not equal");
    return 0;
}

3. Program to Check Whether a Word is Palindrome or Not [5 marks]

Logic: A word is a palindrome if it reads the same forwards and backwards. Example: "madam", "level", "racecar"

We compare the string with its reverse. If they are equal, it is a palindrome.

#include <stdio.h>
#include <string.h>

int main() {
    char word[100], rev[100];
    int len, i, j;
    int isPalindrome = 1;  // Assume true initially

    printf("Enter a word: ");
    scanf("%s", word);

    len = strlen(word);

    // Reverse the word manually
    for (i = 0, j = len - 1; i < len; i++, j--) {
        rev[i] = word[j];
    }
    rev[len] = '\0';  // Add null terminator

    // Compare original and reversed word
    if (strcmp(word, rev) == 0) {
        printf("\"%s\" is a Palindrome.\n", word);
    } else {
        printf("\"%s\" is NOT a Palindrome.\n", word);
    }

    return 0;
}

Sample Output:

Case 1:

Enter a word: madam
"madam" is a Palindrome.

Case 2:

Enter a word: hello
"hello" is NOT a Palindrome.

Explanation of Key Steps:

StepDescription
strlen(word)Finds the length of the entered word
Reverse loopCopies characters from end to start into rev[]
rev[len] = '\0'Properly terminates the reversed string
strcmp(word, rev)Compares original and reversed; returns 0 if equal
Open this answer on its own page →

0 · 5 marks

How is string defined in C program? Write a program to check if a given string is a palindrome or not. [5]

A string in C is defined as a one-dimensional array of characters terminated by a null character (\0). Unlike some other languages, C does not have a built-in string data type. Syntax: Examples of string declaration and initialization: The null character \0 marks the end of the string and is auto...

Open this answer on its own page →

One-dimensional arrays

2080 · 10 marks

What is an array? How an array can be passed as function argument? Write a program to arrange an array having 10 integer numbers in ascending order using function.[10]

--- An array is a collection of elements of the same data type stored in contiguous (adjacent) memory locations, all sharing a common name and accessed individually using an index (subscript). Declaration Syntax: Example: Key Properties: Property Detail ------ Index range 0 to size - 1 Memory Con...

Open this answer on its own page →

0

Array Definition and Differentiation

--- An array is a collection of elements of the same data type stored in contiguous (adjacent) memory locations, all sharing a common name and accessed individually using an index (subscript). General Syntax (C): Example: Here, all 5 integers are stored one after another in memory and accessed as...

Open this answer on its own page →

Two-dimensional arrays

2079 · 5 marks

Write a program to find the sum of diagonal elements of n*n matrix. [5]

For an n×n matrix, there are two diagonals: - Principal (Main) Diagonal: elements where row index == column index → a[i][i] - Secondary (Anti) Diagonal: elements where row + column = n-1 → a[i][n-1-i] Note: If an element lies on both diagonals (center of odd-sized matrix), it should be counted on...

Open this answer on its own page →

2081.2 · 5 marks

Write a program to add two 3×3 matrices. [5]

--- Step Description ------------------- Step 1 Declare three 3x3 integer arrays: A, B, and C Step 2 Use nested for loops to read elements of matrix A Step 3 Use nested for loops to read elements of matrix B Step 4 Add corresponding elements: C[i][j] = A[i][j] + B[i][j] Step 5 Print the resulting...

Open this answer on its own page →

Pattern generation using arrays

2079 · 5 marks

Write a program to display the following pattern using the string "NEPAL". NNNNENENENEPNEPNEPNEPANEPANEPANEPALNEPALNEPAL[5]

The pattern reaches us as the run-on string NNNNENENENEPNEPNEPNEPANEPANEPANEPALNEPALNEPAL, so the first job is to break it back into rows. Splitting it into consecutive prefixes of "NEPAL" gives and joining these five rows back together reproduces the given string character for character. The pat...

Open this answer on its own page →

2078 · 5 marks

Write a program to generate the following pattern of integers.

1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1

[5]

Show solved answer

Pattern Generation Program

Pattern Analysis

Looking at the pattern carefully:

1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

Each row i prints numbers from 1 to i, then back from i-1 to 1.


C Program

#include <stdio.h>

int main() {
    int n, i, j;

    printf("Enter the number of rows: ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++) {
        /* Print increasing part: 1 to i */
        for (j = 1; j <= i; j++) {
            printf("%d ", j);
        }

        /* Print decreasing part: i-1 down to 1 */
        for (j = i - 1; j >= 1; j--) {
            printf("%d ", j);
        }

        printf("\n");
    }

    return 0;
}

Output (for n = 5)

1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

Step-by-Step Explanation

Row (i)Increasing PartDecreasing PartFull Row
11(none)1
21 211 2 1
31 2 32 11 2 3 2 1
41 2 3 43 2 11 2 3 4 3 2 1
51 2 3 4 54 3 2 11 2 3 4 5 4 3 2 1

Logic Summary:

  • Outer loop controls the row number i from 1 to n
  • First inner loop prints j from 1 to i (ascending)
  • Second inner loop prints j from i-1 to 1 (descending)
  • Total numbers in row i = 2i - 1
Open this answer on its own page →

2077 · 5 marks

Write a program to generate the following pattern of Integers.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

[5]

Show solved answer

Program to Generate Integer Pattern

Understanding the Pattern

Looking at the pattern carefully:

1
1 2 1
1 2 1 2 3 1
1 2 3 1 2 3 1 2 3 4 1
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 5 1
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

Pattern Logic:

  • Row i contains i groups
  • Each group in row i prints numbers from 1 to i
  • Except the last group which prints 1 to i (for last row) or ends with the row number

C Program

#include <stdio.h>

int main() {
    int n = 5;  // Number of rows
    int i, j, k;

    for (i = 1; i <= n; i++) {
        // Print i groups of (1 to i)
        for (j = 1; j <= i; j++) {
            for (k = 1; k <= i; k++) {
                printf("%d ", k);
            }
        }
        printf("\n");
    }

    return 0;
}

Output

1
1 2 1 2
1 2 3 1 2 3 1 2 3
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

Alternative Pattern (Pyramid Style)

#include <stdio.h>

int main() {
    int n = 5;
    int i, j, k;

    for (i = 1; i <= n; i++) {
        // Each row: groups from 1..1, 1..2, ..., 1..i
        for (j = 1; j <= i; j++) {
            for (k = 1; k <= j; k++) {
                printf("%d ", k);
            }
        }
        printf("\n");
    }

    return 0;
}

Output:

1
1 1 2
1 1 2 1 2 3
1 1 2 1 2 3 1 2 3 4
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Key Concepts Used

ConceptDescription
Outer loopControls the row number (i from 1 to n)
Middle loopControls number of groups per row (j from 1 to i)
Inner loopPrints numbers 1 to i (or 1 to j) in each group
Nested loopsThree levels of nesting required

Note: The exact pattern depends on interpretation of the question. Both versions use the same three-nested-loop logic which is the core concept being tested.

Open this answer on its own page →

Multi-dimensional arrays

2078 · 5 marks

What do you mean by multi-dimensional array? Write a program to display the sum of two mxn matrices. [5]

Show solved answer

Multi-Dimensional Array

Definition

A multi-dimensional array is an array that has more than one dimension (index). It can be thought of as an array of arrays. The most common form is the two-dimensional (2D) array, which represents data in rows and columns (like a matrix).

General syntax in C:

data_type array_name[size1][size2]...[sizeN];

For a 2D array (matrix):

int matrix[m][n];  // m rows and n columns

Elements are accessed using two indices: matrix[i][j] where i is the row index and j is the column index.


Program to Display the Sum of Two M x N Matrices

#include <stdio.h>

int main() {
    int m, n, i, j;
    int A[10][10], B[10][10], C[10][10];

    // Input dimensions
    printf("Enter number of rows (m): ");
    scanf("%d", &m);
    printf("Enter number of columns (n): ");
    scanf("%d", &n);

    // Input elements of matrix A
    printf("\nEnter elements of Matrix A (%dx%d):\n", m, n);
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("A[%d][%d]: ", i, j);
            scanf("%d", &A[i][j]);
        }
    }

    // Input elements of matrix B
    printf("\nEnter elements of Matrix B (%dx%d):\n", m, n);
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("B[%d][%d]: ", i, j);
            scanf("%d", &B[i][j]);
        }
    }

    // Calculate sum: C = A + B
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    // Display the result matrix C
    printf("\nSum Matrix C = A + B:\n");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Sample Output

Enter number of rows (m): 2
Enter number of columns (n): 2

Enter elements of Matrix A (2x2):
A[0][0]: 1
A[0][1]: 2
A[1][0]: 3
A[1][1]: 4

Enter elements of Matrix B (2x2):
B[0][0]: 5
B[0][1]: 6
B[1][0]: 7
B[1][1]: 8

Sum Matrix C = A + B:
6    8
10   12

Key Points

ConceptDetail
Declarationint A[10][10] declares a 2D array
AccessA[i][j] accesses element at row i, column j
Nested loopsOuter loop for rows, inner loop for columns
Addition ruleC[i][j] = A[i][j] + B[i][j] for each element
Open this answer on its own page →

2077 · 5 marks

What do you mean by multi-dimensional array? Write program logic to add and display the sum of two m x n matrices. [5]

Show solved answer

Multi-Dimensional Array

Definition

A multi-dimensional array is an array that has more than one dimension (index). It can be thought of as an array of arrays. The most common form is the two-dimensional (2D) array, which represents data in rows and columns (like a matrix or table).

General Syntax (C language):

data_type array_name[size1][size2]...[sizeN];

For a 2D array (matrix of m rows and n columns):

int A[m][n];

Elements are accessed using two indices: A[i][j] where i is the row index and j is the column index.


Program Logic to Add Two m x n Matrices and Display the Sum

Algorithm / Logic

  1. Declare three m x n matrices: A, B, and C (for the result).
  2. Input all elements of matrix A.
  3. Input all elements of matrix B.
  4. For each element at position [i][j], compute C[i][j] = A[i][j] + B[i][j].
  5. Display the resultant matrix C.

C Program

#include <stdio.h>

int main() {
    int m, n;
    int A[10][10], B[10][10], C[10][10];
    int i, j;

    /* Step 1: Input dimensions */
    printf("Enter number of rows (m): ");
    scanf("%d", &m);
    printf("Enter number of columns (n): ");
    scanf("%d", &n);

    /* Step 2: Input elements of Matrix A */
    printf("\nEnter elements of Matrix A (%d x %d):\n", m, n);
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("A[%d][%d] = ", i, j);
            scanf("%d", &A[i][j]);
        }
    }

    /* Step 3: Input elements of Matrix B */
    printf("\nEnter elements of Matrix B (%d x %d):\n", m, n);
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("B[%d][%d] = ", i, j);
            scanf("%d", &B[i][j]);
        }
    }

    /* Step 4: Add the two matrices */
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    /* Step 5: Display the resultant matrix C */
    printf("\nSum Matrix C = A + B:\n");
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Sample Output

Enter number of rows (m): 2
Enter number of columns (n): 2

Enter elements of Matrix A (2 x 2):
A[0][0] = 1   A[0][1] = 2
A[1][0] = 3   A[1][1] = 4

Enter elements of Matrix B (2 x 2):
B[0][0] = 5   B[0][1] = 6
B[1][0] = 7   B[1][1] = 8

Sum Matrix C = A + B:
6    8
10   12

Key Points

ConceptDetail
StorageElements stored in row-major order in memory
AccessA[i][j] accesses element at row i, column j
ConditionBoth matrices must have the same dimensions (m x n) for addition
Time ComplexityO(m x n) for addition
Open this answer on its own page →

String manipulation and palindrome checking

2077 · 5 marks

Write a C program to check whether a given string is palindrome or not. [5]

A palindrome is a string that reads the same forwards and backwards. Example: "madam", "racecar", "level" --- --- Step Description ------------------- 1 Read the string from the user 2 Find the length using strlen() 3 Compare str[0] with str[len-1], str[1] with str[len-2], and so on 4 If any pair...

Open this answer on its own page →

String functions from string.h

2081.2 · 5 marks

List any five types of functions for string manipulation with their uses. [5]

--- S.N. Function Use / Purpose ------------------------------- 1 strlen() Returns the length of a string (number of characters excluding null character \0) 2 strcpy() Copies one string into another string 3 strcat() Concatenates (joins/appends) one string at the end of another string 4 strcmp() ...

Open this answer on its own page →