output problem with loops
Feb 16, 2016 at 8:17pm UTC
PROBLEM:
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6, output the individual digits of 8030 as 8 0 3 0, output the individual digits of 2345526 as 2 3 4 5 5 2 6, output the individual digits of 4000 as 4 0 0 0, and output the individual digits of -2345 as 2 3 4 5.
OUTPUT:
The output that I want is the program to output: whatever number the user inputs and then the program outputs the same number, separating the digits in spaces; is it possible to code this with LOOPS?
Below is my sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/*
I included optional code in comment lines, I am confused on how to incorporate that type of code while implementing input and output file
*/
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
ofstream outputfile;
unsigned int one,two,three,four,five;
//unsigned int digit;
inFile.open("data.txt" );
outputfile.open("result.txt" );
cout<< "Please input digit: " ;
//cin>>digit;
inFile>>one;
if (one==3456);
cout<< "\n3 4 5 6" ;
outputfile<< "\n3 4 5 6" ;
if (two==8030);
//else if (two==8030);
cout<< "\n8 0 3 0" ;
outputfile<< "\n8 0 3 0" ;
if (three==2345526)
//else if (three==2345526)
cout<< "\n2 3 4 5 5 2 6" ;
outputfile<< "\n2 3 4 5 5 2 6" ;
if (four==4000);
//else if (four==4000);
cout<< "\n4 0 0 0" ;
outputfile<< "\n4 0 0 0" ;
if (five==-2345);
//else if (five==-2345);
cout<< "\n2 3 4 5" ;
outputfile<< "\n2 3 4 5" ;
inFile.close();
outputfile.close();
return 0;
}
Thank You
Last edited on Feb 16, 2016 at 8:18pm UTC
Feb 16, 2016 at 9:50pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int power(int base, int exp) {
int n = 1;
for (int i = 1; i <= exp; i++)
n = n * base;
return n;
}
void printDigits(int num) {
num = abs(num);
int digits = 0, temp = num;
while (temp != 0) {
digits++;
temp = temp / 10;
}
for (int i = 0; i < digits; ++i)
cout << (num % power(10, digits - i)) / power(10, digits - i - 1) << " " ;
}
E. g. 12345 - 5 digits
(12345 % 10^5) / 10^4 = (12345 % 100000) / 10000 = 12345 / 10000 = 1
(12345 % 10000) / 1000 = 2345 / 1000 = 2
(12345 % 1000) / 100 = 345 / 100 = 3
(12345 % 100) / 10 = 45 / 10 = 4
(12345 % 10) / 1 = 5 / 1 = 5
Alternatively you can convert number to string and then you can print digit by digit (char by char). E. g.
1 2 3
string s = to_string(num);
for (unsigned int i = 0; i < s.length(); i++)
cout << s[i] << " " ;
Last edited on Feb 16, 2016 at 9:55pm UTC
Topic archived. No new replies allowed.