Write a C++ programming to add repeatedly all digits of a given non-negative number until the result has only one digit

  • برمجة سي بلس بلس
  • برمجة

Write a C++ programming to add repeatedly all digits of a given non-negative number until the result has only one digit

Input: 58
Output: 4
Explanation: The formula is like: 5 + 8 = 13, 1 + 3 = 4.

Sample Output:

Initial number is 15 single digit number is 6

Initial number is 57 single digit number is 3

الأجوبة

#include <iostream>
using namespace std;

int addDigits(int num) {
        return num - (num - 1) / 9 * 9;
    }

int main(void)
{
    int n = 15;
    cout << "\nInitial number is "<< n << " single digit number is " << addDigits(n) << endl; 
    n = 57;
    cout << "\nInitial number is "<< n << " single digit number is " << addDigits(n) << endl; 
    return 0;   
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...