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.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.