How to write a C++ program.
Additive persistence is a property of the sum of the digits of an integer. The sum of the digits is found, and then the summation of digits is performed creating a new sum. This process repeats until a single integer digit is reached. Consider the following example:
1. The beginning integer is 1234
2. Sum its digits is 1+2+3+4 = 10
3. The integer is now 10
4. The sum of its digits is 1 + 0 = 1
5. The integer is 1. When the value reaches a single digit, we are finished. This final integer is the additive root
Program Specifications
The program should run as follows.
1) Gather input as a redirection from a file input.txt. The program ends under one of the following circumstances a. the next gathered integer is a negative number. b. if all the integers from the file have been processed.
2) If the given integer is a single digit, report its additive persistence as 0 and its additive root as itself on a single line as two space separated numbers
3) For each multidigit, non-negative, integer output on a single line the two space separated numbers: a. the integer's additive persistence b. the integer's additive root
How to write a C++ program.
Code
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void digSum(int n)
{
int sum = 0;
while(n > 0 || sum > 9)
{
if(n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
if(n==sum)
cout <<"0 "<<sum<<endl;
else
cout <<"1 "<<sum<<endl;
}
int main() {
//Create a dynamic array to hold the values
vector<int> numbers;
//Create an input file stream
ifstream
in("/Users/Akhilaperumalla/Desktop/readme.txt",ios::in);
/*
As long as we haven't reached the end of the file, keep reading
entries.
*/
int number; //Variable to hold each number as it is
read
//Read number using the extraction (>>) operator
while (in >> number) {
//Add the number to the end of the
array
numbers.push_back(number);
}
//Close the file stream
in.close();
/*
Now, the vector<int> object "numbers" contains
both the array of numbers,
and its length (the number count from the file).
*/
//Display the numbers
cout << "Numbers:\n";
for (int i=0; i<numbers.size(); i++) {
if(numbers[i] < 0)
break;
else
digSum(numbers[i]);
}
//cin.get(); //Keep program open until "enter" is
pressed
return 0;
}
Screenshot of input file
Screenshot of output:
Get Answers For Free
Most questions answered within 1 hours.