Monday 3 July 2017

Summing the digits of a number in C++

Q: This is a simple ad-hoc problem which asks to sum up the digits of a number repeatedly until the sum is less than 10. We are required to stop the program when input given is 0.




Code


#include <iostream>
using namespace std;



int magic(int num){
 if(num<10) return num;
 int newnum=0;
 while(num>0){
  newnum+=(num%10);
  num/=10;
  }
 return magic(newnum);
 
 }

int main(){
 
 while(1){
  
  int temp;
  cin>>temp;
  if(!temp) break;
  cout<< magic(temp)<< "\n";  
  }
 
 return 0;
 }

No comments:

Post a Comment