3 9 6 1 8 [ ]
Plus Two Computer Applications (Commerce) · Chapter 02

Arrays

4 sections
Interactive array & string workbench
15 review questions
2.1

Array and its Need

2.1

Why an Array?

An array is a collection of elements of the same type placed in contiguous memory locations, referred to by a single variable name. Consider storing the scores of 20 students: doing it with 20 separate variables quickly becomes unmanageable, and scaling that approach to 1000 students turns into a long, repetitive block of declarations and input statements.

int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t; float avg; cin>>a>>b>>c>>d>>e>>f>>g>>h>>i>>j>>k>>l>>m>>n>>o>>p>>q>>r>>s>>t; avg = (a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t)/20.0;

An array solves this by allocating one block of memory for the whole group, with each element reached through its position, called the index or subscript.

2.1.1

Declaring Arrays

An array must be declared before use, just like an ordinary variable:

data_type array_name[size]; // example int num[10]; // 10 integers, indexed num[0] .. num[9] int score[1000]; // scores of 1000 students

In C++, indexing always starts at 0, so an array of size n is indexed from 0 to n−1. num[0] is read as “num zero” — a shorthand for “the num array subscripted by zero.”

2.1.2

Memory Allocation for Arrays

The memory reserved for an array depends on its type and size:

total_bytes = sizeof(array_type) × size_of_array // example: float a[10]; → 4 × 10 = 40 bytes

Elements sit at consecutive addresses — e.g. a 4-byte integer array starting at address 1000 places num[0] at 1000–1003, num[1] at 1004–1007, and so on.

2.1.3

Array Initialisation

Elements can be initialised at declaration, with the values listed inside braces:

int score[5] = {98, 87, 92, 79, 85}; char code[6] = {'s', 'a', 'm', 'p', 'l', 'e'}; float wgpa[7] = {9.60, 6.43, 8.50, 8.65, 5.89, 7.56, 8.22};

Values are stored in the order written — the first fills index 0, the second fills index 1, and so on. If fewer values are given than the declared size, the remaining numeric elements are set to 0 (a char array pads with the space character ' ' instead). When an initialiser list is present, the size itself can be omitted and is inferred from the count of values:

int num[] = {16, 12, 10, 14, 11}; // size 5, inferred
2.1.4

Accessing Elements & Traversal

An individual element is reached with the array name and a subscript — a variable, constant, or any integer expression:

score[0] = 95; score[1] = score[0] - 11; cin >> score[2]; sum = score[0] + score[1] + score[2] + score[3] + score[4];

Using a loop control variable as the subscript is far more scalable, letting a single statement step through every element in sequence:

sum = 0; for (i=0; i<5; i++) sum = sum + score[i];

Traversal means visiting every element of an array at least once to perform some operation — displaying all elements, summing them, or finding the largest are all examples. Program 2.1 below reads five scores and prints them back in reverse, by running the index from 4 down to 0:

int i, score[5]; for (i=0; i<5; i++) // reads the scores cin >> score[i]; for (i=4; i>=0; i--) // prints them in reverse cout << "score[" << i << "] is " << score[i] << endl;

To find the largest element, a variable is initialised to the first element and then compared against each remaining element in turn, replacing itself whenever a larger value turns up — try this and the reverse-order display in the workbench below.

2.2

String Handling Using Arrays

2.2

Why a Character Array?

A string is a sequence of characters, but C++ has no fundamental data type built specifically to hold one. A single char variable can only ever store one character, so a name like "Niketh" — six characters — needs a char array instead:

char my_name[10]; char my_name[10] = {'N', 'i', 'k', 'e', 't', 'h'};

Unlike arrays of other types, a character array enjoys a special privilege: once declared, its name behaves like an ordinary string variable, so cin >> my_name; reads a whole word into it in one statement — this shortcut does not work for arrays of int or float.

char my_name[10]; cout << "Enter your name: "; cin >> my_name; cout << "Hello " << my_name;
2.3

Memory Allocation for Strings

2.3

The Null Character

When a string is stored in a character array, C++ automatically appends a null character '\0' right after the last letter, marking where the string ends. So the memory needed for a string is always one byte more than its visible length — "Niketh" has six letters but occupies seven bytes.

Index0123456
my_nameNiketh\0

A character array can also be initialised directly from a string literal, and if the size is left unspecified it is inferred from the string's length plus one byte for the terminator:

char my_name[10] = "Niketh"; // 10 bytes reserved, 3 left unused char str[] = "Hello World"; // 12 bytes: 11 characters + '\0'
2.4

Input/Output Operations on Strings

2.4

The White-Space Problem with cin

Reading a string with cin >> my_name; works only until a space appears — cin treats white space as a separator between data items. So an input like "Maya Mohan" is read as two separate items, and only "Maya" ends up stored.

char my_name[20]; cin >> my_name; // input "Maya Mohan" → only "Maya" is stored
2.4.1

gets() and puts()

C++ provides two console functions, declared in <cstdio>, that work around this limitation:

gets(array_name) → reads a full line, spaces includedputs(string_data) → prints a string followed by a new line
#include <cstdio> char my_name[20]; gets(my_name); // captures "Maya Mohan" in full puts("hello"); puts(my_name);

Even though a string is normally handled as a whole with cin/cout or gets/puts, any individual character can still be reached by its subscript — my_name[0] is the first letter, and the terminating '\0' can be located the same way. Program 2.6 uses exactly this to count vowels, iterating with a for loop until the null character is reached:

for (int i=0; str[i] != '\0'; i++) switch (str[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': vow++; }

Note the deliberate absence of a break after each vowel case — since every matching case does the same thing, they simply fall through to the single shared statement.

Try It Yourself

Array & String Workbench

Pick an operation, supply the data, then press Run to see the array laid out in memory boxes alongside a step-by-step trace of how the loop processes it.

for(i=0;i<5;i++) cin>>a[i];

Enter up to 8 integers separated by commas.

a[5] = {12,3,6,1,8}
Self-Assessment

Question & Answer Review

Tap a question to reveal the answer — a quick way to check understanding of arrays and string handling before moving to Chapter 3.

01What is an array, and why is it preferred over using many separate variables?
An array is a collection of elements of the same type stored in contiguous memory locations under one variable name. It avoids declaring and managing a huge number of individual variables when a large quantity of similar data must be processed, and it allows a loop to step through every value using the subscript.
02What are the elements of a ten-element array numbered from?
From index 0 to index 9 — C++ array subscripts always start at zero.
03How is an individual array element accessed?
Using the array name followed by the element's index (subscript) in square brackets, e.g. score[2].
04If AR is an array, which element does AR[7] refer to?
The eighth element of the array — the one stored at index 7, since indexing begins at 0.
05Given int a[3]={2,3,4};, what is the value of a[1]?
3 — the second value in the initialiser list fills index 1.
06Given int a[]={1,2,4};, what is the value of a[1]?
2. Omitting the size is fine when an initialiser list is supplied — the compiler infers the size (3, here) from the number of values.
07Printing every element of an array is an example of which operation?
Traversal — visiting each element of the array at least once to perform an operation on it.
08How is the memory allocated for an array computed?
total_bytes = sizeof(array_type) × size_of_array — the size of one element multiplied by the number of elements.
09What does the declaration int studlist[1000]; mean?
It declares an integer array named studlist that can hold 1000 elements, indexed studlist[0] through studlist[999].
10Why can't cin >> name; correctly read a string containing spaces, such as "Sachin Tendulkar"?
Because cin treats white space as a separator between data items, so it stops reading at the first space; only "Sachin" would be stored, and "Tendulkar" would be left unread (or read into whatever comes next).
11Which console function reads a full line of text, spaces included, into a character array?
gets(array_name), declared in <cstdio>.
12What character does C++ automatically place at the end of a stored string, and why?
The null character '\0', used as a terminator that marks where the string ends; it is why a string's memory requirement is always one byte more than its visible length.
13How many bytes does char str[] = "Hello World"; allocate?
12 bytes — 11 characters in "Hello World" plus 1 byte for the terminating '\0'.
14What does puts() do, and how does its output differ from a plain cout statement?
puts(string_data) displays a string on the screen and automatically moves to a new line afterward; a cout << statement does not add a line break unless endl or "\n" is included explicitly.
15Why is there no break after the vowel cases 'a', 'e', 'i', 'o' in Program 2.6's switch block?
Because every one of those cases should trigger the same action, they are deliberately left to fall through to the shared statement vow++; attached to the last case ('u'), avoiding the need to repeat the same line five times.