Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 3.12: Arrays and Pointers

Adapted from: “Object-Oriented Programming Using C++” by Ira Pohl (Addison- Wesley)

Program that demonstrates arrays and pointers in C++

// Simple array processing
#include <iostream>

using namespace std;

const int SIZE = 5;

int main()
{
    int a[SIZE];    // get space for a[0], ....., a[4]
    int i, sum = 0;

    for (i = 0; i < SIZE; ++i) {
        a[i] = i * i;
        cout << "a[" << i << "] = " << a[i] << "   ";
        sum += a[i];
    }
    cout << "\nsum = " << sum << endl;
}

Compile and Execute the Program

The above program is compiled and run using Gnu Compiler Collection (g++):

import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + "Cpp_Code/Chapter_3_12_Arrays_and_Pointers"
ch_dir_stat = os.chdir(code_dir)
build_command = os.system("g++ sum_arr1.cpp -w -o sum_arr1")
exec_status = os.system("./sum_arr1")
a[0] = 0   a[1] = 1   a[2] = 4   a[3] = 9   a[4] = 16   
sum = 30