Skip to study material
← Question index

QUESTION 08 · Array Basics

Write a C program to read and display an array using loops.

5 marks

Answer in brief

A loop can read each array element using its address and then display each stored value using the same valid index range.

Algorithm

  1. Read the count n. Accept only 1 through 20.
  2. For i from 0 to n - 1, read a[i] and check the input.
  3. Use another loop over the same indices to display the elements.

Input and output expressions

scanf("%d", &a[i]) supplies the address of the selected int element so that scanf can store its value. printf("%d", a[i]) supplies the stored value for output. The address is needed for this input conversion; it is not the value to display.

Example trace

For count 3 and elements 8, -2 and 5, the first loop fills a[0], a[1] and a[2]. The second loop displays 8 -2 5 in the same order. No sorting takes place. A space is printed before every value after the first, followed by one newline at the end.

Input limits

This complete example accepts values between -10000 and 10000. Input tokens must fit int. It rejects a bad count, a failed conversion or a value outside the chosen range. The fixed capacity is 20, while n describes how many positions currently contain the list.

Time and space complexity

Reading n values requires n input operations and displaying them requires n output operations. The total work is proportional to 2n, giving O(n) time. The list storage is O(n) in a general-size version; counters add O(1) auxiliary space. This sample reserves a fixed array of 20 elements.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>

int main(void)
{
    int n, a[20];
    if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
        puts("Unsupported input"); return 1;
    }
    for (int i = 0; i < n; ++i) {
        if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
            puts("Unsupported input"); return 1;
        }
    }
    for (int i = 0; i < n; ++i) {
        if (i > 0) { putchar(' '); }
        printf("%d", a[i]);
    }
    putchar('\n');
    return 0;
}

Sample input and output

Input

3
8 -2 5

Output

8 -2 5

Related exam questions

Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q11(b) · 5 marks

    Write an algorithm to sum all elements in an array and find its time complexity.

    Paper P02 · page 2
  • June 2022 · Q3(a) · 7 marks

    What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.

    Paper P03 · page 1

View this category in the exam question bank →