6 Arrays

C Programming · Unit 6 · 6 hrs

Arrays

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

Arrays in short

This chapter introduces the array as a way of grouping many values of the same type under one name, and the character array, or string, as C's way of representing text.

Arrays: notes

Introduction to Array

An array is a collection of elements of the same data type, stored under a single variable name and accessed by position. Each element shares the array's name but is distinguished by an index, or subscript, and in C indexing always starts at 0, so in int age[10], the elements run from age[0] to age[9]. The number of subscripts an array uses decides its dimension: a one-dimensional array uses one subscript, a two-dimensional array uses two, and so on.

int marks[5] = {68, 85, 95, 63, 81};

Types of Array (Single Dimensional and Multidimensional)

A one-dimensional array stores a simple list of values with a single subscript, declared as data_type array_name[size];, for example int age[10]; or float salary[20];. A multidimensional array uses more than one subscript; a two-dimensional array, the most common case, is declared as data_type array_name[rows][columns];, where the first subscript is the row count and the second is the column count, for example int a[3][2]; for a table of 3 rows and 2 columns.

Declaration and Memory Representation of Array

An array must be declared, giving its type, name and size, before it is used, and its size must always be a positive integer. Once declared, its elements occupy contiguous (adjacent) memory locations, one after another, each taking as many bytes as its data type requires. For an array marks[10], the valid index range runs from a lower bound of 0 to an upper bound of size - 1, that is 9, and the size is the upper bound plus one. To process an array's elements, a loop is generally used with the loop variable playing the role of the subscript, starting from 0.

What this unit covers

  • Introduction to Array
  • Types of Array (Single Dimensional and Multidimensional)
  • Declaration and Memory Representation of Array
  • Initialization of array
  • Character Array and Strings
  • Reading and Writing Strings
  • Null Character
  • String Library Functions (string length, string copy, string concatenation, string compare)

Introduction to Array

2081 · 10 marks

What are the characteristics of array?Write a program to input age of 500 persons and display the following: a) Average age b) Age between 25 to 30[2+8]

Show solved answer

Characteristics of Array and Program for Age Analysis

Characteristics of Array [2 marks]

An array is a collection of similar data type elements stored in contiguous memory locations. Its main characteristics are:

  1. Homogeneous Elements: All elements in an array must be of the same data type (e.g., all int, all float).
  2. Contiguous Memory Allocation: Array elements are stored in consecutive memory locations.
  3. Index/Subscript Based Access: Each element is accessed using an index starting from 0 (lower bound = 0, upper bound = size - 1).
  4. Fixed Size: The size of an array is fixed at the time of declaration and cannot be changed during execution.
  5. Random Access: Any element can be directly accessed using its index in constant time.
  6. Single Variable Name: Multiple values are stored under one variable name with different indices.

Program to Input Age of 500 Persons [8 marks]

#include<stdio.h>
#include<conio.h>

void main()
{
    int age[500], i;
    int count = 0;          /* count of persons with age between 25 to 30 */
    float sum = 0, average;

    clrscr();

    /* Input age of 500 persons */
    for(i = 0; i < 500; i++)
    {
        printf("Enter age of person %d: ", i + 1);
        scanf("%d", &age[i]);
    }

    /* Calculate sum and count persons with age between 25 to 30 */
    for(i = 0; i < 500; i++)
    {
        sum = sum + age[i];

        if(age[i] >= 25 && age[i] <= 30)
        {
            count++;
        }
    }

    /* a) Calculate average age */
    average = sum / 500;

    printf("\n--- Results ---\n");

    /* Display average age */
    printf("\na) Average Age = %.2f", average);

    /* b) Display ages between 25 to 30 */
    printf("\n\nb) Ages between 25 to 30:\n");
    for(i = 0; i < 500; i++)
    {
        if(age[i] >= 25 && age[i] <= 30)
        {
            printf("Person %d : %d years\n", i + 1, age[i]);
        }
    }

    printf("\nTotal persons with age between 25 to 30: %d", count);

    getch();
}

Explanation of the Program

StepDescription
Declarationint age[500] declares an integer array of size 500 to store ages
Input LoopA for loop runs from i=0 to i<500 to input all 500 ages
Sum CalculationEach age is added to sum to find total
Condition Checkage[i] >= 25 && age[i] <= 30 checks if age falls in the range
Averageaverage = sum / 500 gives the average age
OutputAverage is displayed and ages in range 25-30 are printed with person number

Sample Output

--- Results ---

a) Average Age = 35.46

b) Ages between 25 to 30:
Person 3  : 27 years
Person 7  : 25 years
Person 12 : 30 years
...

Total persons with age between 25 to 30: 85
Open this answer on its own page →

2079 · 5 marks

Write a program to find the second largest number in the given array of numbers. [5]

  1. Read N numbers into an array. 2. Find the largest element first. 3. Then find the largest element among all elements that are NOT equal to the largest -- that gives the second largest. --- --- --- Step What happens ------------------- First loop Reads N numbers into arr[] Second loop Finds lar...
Open this answer on its own page →

2075 · 10 marks

Define array?What are the benefits of using array?Write a program to add two matrices using array.[1+2+7]

Show solved answer

Array: Definition, Benefits, and Matrix Addition Program


1. Definition of Array [1 mark]

An array is a collection of similar (same data type) elements stored in contiguous memory locations, referred to by a single variable name and accessed using an index (subscript).

Syntax:

data_type array_name[size];

Example:

int marks[5];  /* declares an array of 5 integers */

2. Benefits of Using Array [2 marks]

BenefitExplanation
Organized StorageMultiple values of the same type are stored under one variable name, keeping data organized.
Easy AccessAny element can be directly accessed using its index, e.g., arr[2].
Less CodeInstead of declaring many separate variables, a single array declaration handles all values.
Loop FriendlyArrays work efficiently with loops to process large amounts of data quickly.
Supports 2D DataTwo-dimensional arrays allow representation of matrices and tables naturally.

3. Program to Add Two Matrices Using Array [7 marks]

Logic:

  • Take two matrices A and B of the same size (r x c).
  • Add corresponding elements: C[i][j] = A[i][j] + B[i][j]
  • Display the resultant matrix C.

Program:

#include<stdio.h>
#include<conio.h>

void main()
{
    int A[10][10], B[10][10], C[10][10];
    int i, j, r, c;

    clrscr();

    /* Input: number of rows and columns */
    printf("Enter number of rows: ");
    scanf("%d", &r);

    printf("Enter number of columns: ");
    scanf("%d", &c);

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

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

    /* Addition of two matrices */
    for(i = 0; i < r; i++)
    {
        for(j = 0; j < c; j++)
        {
            C[i][j] = A[i][j] + B[i][j];
        }
    }

    /* Display the resultant matrix C */
    printf("\nResultant Matrix after Addition:\n");
    for(i = 0; i < r; i++)
    {
        for(j = 0; j < c; j++)
        {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }

    getch();
}

Sample Output:

Enter number of rows: 2
Enter number of columns: 2

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

Enter elements of Matrix B:
B[0][0] = 5
B[0][1] = 6
B[1][0] = 7
B[1][1] = 8

Resultant Matrix after Addition:
6       8
10      12

Explanation of Key Steps:

StepDescription
int A[10][10]Declares a 2D array to store matrix elements
Nested for loop for inputReads each element row by row using scanf
C[i][j] = A[i][j] + B[i][j]Adds corresponding elements of both matrices
Nested for loop for outputDisplays the result matrix in proper row-column format using printf and \t
Open this answer on its own page →

2074 · 5 marks

Write a program to find sum and average of 10 integer numbers stored in an array. [5]

Arrays use a loop variable as the subscript (starting from 0) to process elements. A one-dimensional array of size 10 has indices from arr[0] to arr[9]. Step Description ------------------- int arr[10] Declares a one-dimensional array of 10 integers (indices 0 to 9) First for loop Reads 10 intege...

Open this answer on its own page →

Types of Array

2080 · 5 marks

Write a program to read P*Q matrix of integers and find the largest integer of each row and display it. [5]

A two-dimensional array is declared as datatype arrayname[row][col]. Processing requires a nested loop where the outer loop corresponds to rows and the inner loop corresponds to columns. Each element can be accessed as a[i][j]. --- 1. Start 2. Read the number of rows P and columns Q 3. Read all e...

Open this answer on its own page →

2077 · 10 marks

What are the benefits of using arrays?Compare one dimensional array with two dimensional array.Write a program to find transpose of a matrix.[2+2+6]

--- (a) Benefits of Using Arrays An array is a collection of elements of the same data type stored in contiguous memory locations under a single variable name. Benefits of using arrays: 1. Easy data management: Multiple values of the same type can be stored under one variable name, making code cl...

Open this answer on its own page →

Character Array and Strings

2080 · 5 marks

Write a program to check whether the entered word is palindrome or not. [5]

A palindrome is a word (or string) that reads the same forwards and backwards. For example: madam, level, racecar are palindromes. 1. Accept a word (string) from the user. 2. Copy the original string into another variable. 3. Reverse the copied string using strrev(). 4. Compare the original and r...

Open this answer on its own page →

Initialization of array

2080 · 5 marks

Write a program to initialize an array of dimension 10 and sort the numbers within the array in ascending order. [5]

The program initializes an array of dimension 10, reads values from the user, and sorts them in ascending order using Bubble Sort. Bubble Sort Logic: Compare adjacent elements; if the left element is greater than the right, swap them. Repeat for n-1 passes. --- --- --- Step Description ----------...

Open this answer on its own page →

String Library Functions

2078 · 10 marks

Explain any three string functions.Write a program to check if two matrices are identical or not.[3+7]

(a) Three String Functions String functions are built-in functions available in the <string.h header file used to manipulate strings in C. --- Returns the number of characters in a string, excluding the null character \0. Syntax: int strlen(char s[]); Example: --- Copies the content of one string...

Open this answer on its own page →

2075 · 5 marks

Discuss any five string library functions. [5]

String library functions are built-in functions used to manipulate strings in C. Their prototypes are declared in the header file <string.h. --- This function returns the length of the string, i.e., the number of characters excluding the terminating null character (\0). It accepts a single argume...

Open this answer on its own page →