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 2.3: Program Structure

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

Program that demonstrates program structure in C++

// Greatest common divisor program.
#include <iostream>
#include <assert.h>

int gcd(int m, int n)   // function declartion
{                       // block
    int r;              // declaration of remainder

    while (n != 0) {    // not equal
        r = m % n;      // modulo operator
        m = n;          // assignment
        n = r;
    }                   // end while loop

    return m;           // exit gcd with value m
}

int main()
{
    int x, y, g;

    std::cout << "\nProgram GCD C++";
    do {
        std::cout << "\nEnter two integers: ";
        std::cin >> x >> y;
        assert(x * y != 0); // precondition on GCD
        std::cout << "\nGCD(" << x << ", " << y << ") = "
             << (g = gcd(x, y)) << std::endl;
        assert(x % g == 0 && y % g ==0); // postcondition
    } while (x != y);
}

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_2_3_Program_Stucture"
ch_dir_stat = os.chdir(code_dir)
build_command = os.system("g++ gcd.cpp -w -o gcd")
exec_status = os.system("echo \"20 10 50 4 60 30 100 100\" | ./gcd")

Program GCD C++
Enter two integers: 
GCD(20, 10) = 10

Enter two integers: 
GCD(50, 4) = 2

Enter two integers: 
GCD(60, 30) = 30

Enter two integers: 
GCD(100, 100) = 100