Chapter+4_Ex+4.8

Exercise 8 Write a program that displays the sum of digits of any non-negative integer. Two ways to do this. My first way is ridiculously complicated and time wasting. code format="cpp" using namespace std; int power(int base,int p);//creating a power function, because math.h doesn't do anything correctly int main(int argc, char *argv[]) {   int number,n,x;//2 integers cout<<"Input an integer: "; cin>>number;//get user's number cout<0,x>0;n*=10,x++){//loop to determine how many digits are there
 * 1) include
 * 2) include

if(n0;x--){ divider = power(10,x);//set the digit to divide temp = (number%divider/power(10,x-1))+temp;//sum the number from the last result looped }

cout<0;p--){//keep on multiplying itself by the "power" times x=x*base; }   return x;//return the result } }

code

The second way: code format="cpp" using namespace std;
 * 1) include
 * 2) include
 * 3) define endl cout<>num;//user input integer endl;//new line if (num <0){//check if user input is positive cout<<"number is negative, plz type a positive input"; endl; }           else{

while(num>0){//summing digits using loop cout<<num%10; sum += num%10; num = num/10; }                             }    cout<<"sum of digits is: "<<sum;//output result cin.ignore(100,'\n');//ignore user input so that program doesn't end cin.get;//program end as user terminates

system("PAUSE"); return EXIT_SUCCESS; }

code

code

code