C++ functions: Modularizing Code

Modularizing makes the code easy to maintain and debug and enables the code to be reused.

Functions can be used to reduce redundant code and enable code reuse. Functions can also be used to modularize code and improve the program’s quality.

Listing 5.10, GreatestCommonDivisor.cpp, gives a program that prompts the user to enter two integers and displays their greatest common divisor. You can rewrite the program using a function, as shown in Listing 6.4.

Listing 6.4 GreatestCommonDivisorFunction.cpp

1 #include <iostream>
2
using namespace std;
3
4
// Return the gcd of two integers
5 int gcd(int n1, int n2)
6 {
7     
int gcd = 1; // Initial gcd is 1
8     int k = 2; // Possible gcd
9
10   
while (k <= n1 && k <= n2)
11    {
12       
if (n1 % k == 0 && n2 % k == 0)
13        gcd = k;
// Update gcd
14        k++;
15    }
16
17   
return gcd; // Return gcd
18 }

19
20
int main()
21 {
22   
// Prompt the user to enter two integers
23    cout << “Enter first integer: “;
24   
int n1;
25    cin >> n1;
26
27    cout <<
“Enter second integer: “;
28   
int n2;
29    cin >> n2;
30
31    cout <<
“The greatest common divisor for ” << n1 <<
32   
” and ” << n2 << ” is ” << gcd(n1, n2) << endl;
33
34   
return 0;
35 }

By encapsulating the code for obtaining the GCD in a function, this program has several advantages:

  1. It isolates the problem for computing the GCD from the rest of the code in the main Thus, the logic becomes clear and the program is easier to read.
  2. If there are errors on computing GCD, they will be confined in the gcd function, which narrows the scope of debugging.
  3. The gcd function now can be reused by other programs.

Listing 6.5 applies the concept of code modularization to improve Listing 5.17, PrimeNumber.cpp. The program defines two new functions isPrime and printPrimeNumbers. The isPrime function checks whether a number is prime and the printPrimeNumbers function prints prime numbers.

Listing 6.5  PrimeNumberFunction.cpp

1 #include <iostream>
2
#include <iomanip>
3
using namespace std;
4
5
// Check whether number is prime
6 bool isPrime(int number)
7 {
8   
for (int divisor = 2; divisor <= number / 2; divisor++)
9    {
10     
if (number % divisor == 0)
11      {
12         
// If true, number is not prime
13          return false; // number is not a prime
14      }
15    }
16
17   
return true; // number is prime
18 }

19
20
void printPrimeNumbers(int numberOfPrimes)
21 {
22   
const int NUMBER_OF_PRIMES = 50; // Number of primes to display
23    const int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
24    int count = 0; // Count the number of prime numbers
25    int number = 2; // A number to be tested for primeness
26
27   
// Repeatedly find prime numbers
28    while (count < numberOfPrimes)
29    {
30       
// Print the prime number and increase the count
31       if (isPrime(number))
32       {
33           count++;
// Increase the count
34
35           
if (count % NUMBER_OF_PRIMES_PER_LINE == 0)
36           {
37               
// Print the number and advance to the new line
38               cout << setw(4) << number << endl;
39           }
40       
else
41       cout << setw(4) << number;
42       }
43
44       
// Check if the next number is prime
45        number++;
46     }
47 }
48
49
int main()
50 {
51     cout <<
“The first 50 prime numbers are \n”;
52     printPrimeNumbers(
50);
53
54     
return 0;
55 }

We divided a large problem into two subproblems. As a result, the new program is easier to read and easier to debug. Moreover, the functions printPrimeNumbers and isPrime can be reused by other programs.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *