Sample Midterm Exam Instructor: Mojallal CS 110
Question: Sum of Digits (100 points)
Using only the techniques and methods taught in CS110, write a C++ program that reads
from an input file called numbers.txt and writes the results to an output file called digitsum.txt.
The input file contains a single positive integer (with any number of digits). Your program
must compute the sum of the digits of that integer using a loop (not string manipulation),
and output a meaningful message with the original number and the computed digit sum.
Requirements:
• Read one positive integer from the input file.
• Use integer math to compute the digit sum (e.g., using % and / operators).
• Write a meaningful message to the output file showing the original number and the
result.
Assumptions:
(i) Only the main algorithm requires header documentation (a comment describing the
digit-summing logic).
(ii) The input file contains exactly one positive integer.
(iii) The integer can be stored in a variable of type int.
Sample Input File (numbers.txt):
2947
Expected Output File (digitsum.txt):
The sum of the digits of 2947 is: 22
The answer is provided on the next page.
Page 1
Sample Midterm Exam Instructor: Mojallal CS 110
Solution
# include < iostream >
# include < fstream >
using namespace std ;
int main () {
ifstream inputFile ( " numbers . txt " );
ofstream outputFile ( " digitsum . txt " );
if (! inputFile ) {
cout << " Error : Could not open input file . " << endl ;
return 1;
}
if (! outputFile ) {
cout << " Error : Could not open output file . " << endl ;
return 1;
}
int number ;
inputFile >> number ;
int originalNumber = number ;
int digitSum = 0;
/*
* Algorithm to calculate sum of digits :
* Repeatedly extract the last digit using modulo 10 ,
* add it to the total , and remove the last digit using division .
*/
while ( number > 0) {
int digit = number % 10;
digitSum += digit ;
number = number / 10;
}
outputFile << " The sum of the digits of "
<< originalNumber << " is : " << digitSum << endl ;
inputFile . close ();
outputFile . close ();
return 0;
}
Page 2