Modularity 


Contents of this section:

  1. A program demonstrating modularity in C++

1. A program demonstrating modularity in C++

    Code Listing: Absolute.h

// File name: ~ftp/pub/class/cpluplus/Modularity/Absolute.h
// Purpose:   header file for Absolute.cpp

#ifndef _ABSOLUTE_H_    // Preprocessor directive to make sure that
			// the current header file is defined for
			// only once.
#define _ABSOLUTE_H_

int Abs(int i);         // Function prototype

#endif

Code Listing: Absolute.cpp

// File name: ~ftp/pub/class/cplusplus/Modularity/Absolute.cpp
// Purpose:   implementation of the Abs() function declared in
//            Absolute.h

#include "Absolute.h" // This header file contains the function prototype
int Abs(int i)
{
	if( i >= 0)
		return i;
	else
		return -i;
}

    Code Listing: Modularity.cpp

// File name:  ~ftp/pub/class/cplusplus/Modularity/Modularity.cpp
// Purpose:    Driver program for the finding-abslute-value program

#include "Absolute.h"
#include <iostream>
using namespace std;

int main()
{
	int number;
	int abs_number;

	cout << "This program finds the absolute value of an integer." << endl;
	cout << "Enter an integer (positive or negative): ";
	cin >> number;
	
	abs_number = Abs(number);
	cout << "The absolute value of " << number << " is " << abs_number;
	cout << endl;
	return 0;
}

    Running session:

mercury[157]% CC -LANG:std Absolute.cpp Modularity.cpp -o Modularity
Absolute.cpp:
Modularity.cpp:
mercury[158]% Modularity
This program finds the absolute value of an integer.
Enter an integer (positive or negative): -45
The absolute value of -45 is 45
mercury[159]% Modularity
This program finds the absolute value of an integer.
Enter an integer (positive or negative): 0
The absolute value of 0 is 0
mercury[160]% Modularity
This program finds the absolute value of an integer.
Enter an integer (positive or negative): 9
The absolute value of 9 is 9
mercury[161]% 


Last modified: Sunday, 25-Mar-2012 17:45:30 CST
Copyright 2000 Department of Computer Science, University of Regina.

 CS Dept Home Page

Teaching Material

C++ Index Page