Skip to study material
← Question index

QUESTION 04 · Array Basics

Explain array declaration and initialisation with examples.

5 marks

Answer in brief

An array declaration specifies its element type, name and size. Initialisation supplies starting values when the object is created.

Syntax and examples

int marks[4];
int scores[4] = {60, 70, 80, 90};
int values[] = {2, 4, 6};
int zeroes[4] = {0};

Meaning

marks has space for four integers. An ordinary automatic marks array without an initialiser does not have useful guaranteed starting values. scores receives all four listed values. The length of values is inferred as three from its initialisers. In zeroes, the first element is explicitly zero and the remaining elements are also zero-initialised.

Partial initialisation

int a[5] = {2, 4}; stores 2 and 4 in the first two positions and zero in the rest. Do not confuse this with int a[5]; at block scope, which does not initialise the ordinary automatic elements. Objects with static storage duration have their own default initialisation rules.

Assignment after declaration

Assign individual elements using a valid index, such as a[2] = 9;. Ordinary C arrays cannot be assigned as a whole using a = b. To copy elements between separate arrays, use a suitable loop or an appropriate library operation with correct bounds.

Size and complexity

Where the actual array declaration is visible, sizeof a / sizeof a[0] gives its element count for this ordinary array. It does not work as an array-length calculation on an adjusted array parameter. Initialising or copying n elements involves O(n) element work; one element assignment is O(1).

C program and output

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

int main(void)
{
    int a[5] = {2, 4};
    for (int i = 0; i < 5; ++i) { printf("%d\n", a[i]); }
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

2
4
0
0
0

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 →