C++ Array Programming: Comprehensive Guide and Case Studies

Introduction to Arrays

  • Definition: An array is a variable that can store multiple values of the same data type.
  • Inadequacy of Individual Variables: Instead of declaring five separate variables for marks (e.g., int mark1, mark2, mark3, mark4, mark5), which is time-consuming, a programmer can simplify the process using an array.
  • Declaration Syntax: An array is declared using the square bracket [] operator.
    • Syntax: Type <array_Name> [size];
    • Example: int tests[5];

Memory Allocation and Indexing

  • Memory Structure: When a declaration like int tests[5]; is made, the system allocates contiguous memory locations.
  • Elements:
    • The first element is at location test[0] (index 0 / subscript 0).
    • Subsequent elements follow as test[1], test[2], test[3], and test[4].
  • Conceptual Representation: If the array holds the values 10,5,12,−1,510, 5, 12, -1, 5, they are mapped as follows:
    • test[0] = 1010
    • test[1] = 55
    • test[2] = 1212
    • test[3] = −1-1
    • test[4] = 55

Array Definition Components

  • Code Example: int tests[5];
  • int: This is the data type of the individual array elements.
  • tests: This is the identifier or name of the array.
  • 5: Residing within the [], this is the size declarator. It indicates the total number of elements the array can hold.

Array Initialization and Input/Output

  • Initialization: This refers to setting values at the time of declaration without using cin.
    • Example: int tests[5] = {10, 5, 12, -1, 5};
  • Input Data: Inputting data into an array uses the cin >> command with a specific subscript.
    • Example (Manual): cin >> tests[0]; cin >> tests[1];
    • Example (Using a Loop): cpp for (x = 0; x < 5; x++) { cin >> test[x]; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  • Output Data: Printing data uses the cout << command.
    • Example (Using a Loop): cpp for (x = 0; x < 5; x++) { cout << test[x]; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Example Program: Floating Point Numbers

  • Objective: Write a program that accepts 5 floating-point numbers and prints them.
  • Code Implementation:
# include <iostream.h>
void main()
{
    float nom[5]; // declaration
    int x;
    //Input Data
    for(x=0;x<5;x++)
    {
        cout <<" please insert any number : "; 
        cin>> nom[x];
    } 
    // Output Data 
    cout <<" The number that has been input \n";
    for(x=0;x<5;x++) 
    {
        cout<<nom[x]<<endl;
    }
}
  • Sample Execution:
    • Inputs: 15,−8,4,10,−2015, -8, 4, 10, -20
    • Output Display:       15       -8       4       10       -20

Arrays of Characters and Strings

  • String Initialization: A character array can be initialized using a string in double quotes " ".
    • Example: const int SIZE = 6; char fName[SIZE] = "Henry";
  • The Null Terminator: When storing a string, you must leave room for the null terminator \0 at the end of the array.
  • Explicit Initialization: If initializing character-by-character, the \0 must be added explicitly.
    • Example: char fName[6] = { 'H', 'e', 'n', 'r', 'y', '\0'};
  • Index Mapping for "Henry":
    • [0]: H
    • [1]: e
    • [2]: n
    • [3]: r
    • [4]: y
    • [5]: \0

Parallel and Multi-Dimensional Arrays

  • Example Problem: Input name, Test 1 mark, and Test 2 mark for 5 students. Calculate and print the average for each student.
  • Code Implementation:
#include <iostream.h>
void main ()
{
    // declaration of variables
    char name[5][10]; // 2D array for names
    int test1[5], test2[5], average[5], x;

    // Input
    for (x=0; x<5; x++)
    {
        cout<< "insert the name "; 
        cin>>name[x]; 
        cout <<"insert test 1 "; 
        cin>>test1[x]; 
        cout <<"insert test 2 "; 
        cin>>test2[x]; 
        average[x]=(test1[x]+test2[x])/2; // calculate average
    }

    // Output
    cout<<"LIST OF STUDENTS AND AVERAGE"<<endl;
    for (x=0; x<5; x++)
    {
        cout<<name[x]<<"\t"<<average[x]<<endl;
    }
}

Program Comparison and String Handling

  • Character Input Handling:
    • Single character: char name; cin >> name; (e.g., stores 'A').
    • Character array: char name[6]; cin >> name; (e.g., stores "BROWN").
  • Comparison Logic:
    • For a single character: if (scheme[x] == 'A') (uses single quotes).
    • For a string/word: if (scheme[x] == "PENSION") (uses double quotes).
  • Alternative for Names: Instead of char name[5][10], one can use string name[5] by including the library #include <string.h>.

Practical Application: Rainfall Data Analysis

  • Scenario: The Meteorology Department of Perak needs to track rainfall for four weeks in 10 flood-prone areas.
  • Requirements:
    • A 2D array to store area names.
    • 1D arrays to store rainfall data for each week.
    • Calculation of average rainfall per area.
  • Code Structure:
# include<iostream.h>
void main()
{
    int i, bilkaw=10, week1[10], week2[10], week10[10], week4[10], pur[10]; 
    char nama[10][20]; 

    for(i=0; i<bilkaw; i++)
    {
        cout<<"please enter area name"; 
        cin.get(nama[i],20); // Capture area name with spaces
        cin.ignore(); // Clean buffer
    }

    for(i=0; i<bilkaw; i++)
    {
        cout<<"please enter rainfall data for four weeks for area"<<nama[i]<<endl;
        cin>>week1[i]>>week2[i]>>week10[i]>>week4[i]; 
        pur[i]=(week1[i]+week2[i]+week10[i]+week4[i])/4; 
    } 

    cout<<"Rainfall Data in 10 Areas"<<endl;
    for(i=0; i<bilkaw; i++)
    {
        cout<<nama[i]<<"\t"<<pur[i]<<endl;
    }
}
  • Identified Areas Example: Gugusan Manjoi, Bandar Manjung.

Student Graduation Information Problem

  • University Context: KSI University Graduation 2017.
  • Statistics:
    • 800 Master students.
    • 100 PhD students.
  • Required Data Fields:
    • Name
    • Matrics No (Matrics_No)
    • Level (Master or PhD)
    • Category (Local or International)
    • Sponsorship (Yes/No)
  • Requested Outputs:
    1. Count of Local Master students.
    2. Count of Local PhD students.
    3. Count of International Master students.
    4. Count of International PhD students.
    5. Total number of Sponsored Students.
  • Specific Examples Provided:
    • Ali, Matrics 123456, PhD, Local, Sponsored: Yes.
    • Lara, Matrics 222222, Master, Local, Sponsored: No.

Summary of Essential Array Operations

  • Declaration: Defining the data type and size.
  • Initialization: Assigning starting values.
  • Input: Populating the array with cin.
  • Output: Displaying array contents with cout.
  • Calculation: Processing elements (e.g., finding totals or averages).