How can I add the digits of my input ysing array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can I add the digits of my input ysing array?

Like if I input 42 the answer will be 6 ( 4 + 2 ).

12th Oct 2016, 2:27 PM
Ian Soriano
Ian Soriano - avatar
2 Answers
+ 2
Without array: int n, sum; cin >> n; sum = 0; while (n > 0) { sum += n % 10; n /= 10; } cout << sum << endl; With array: int i, n, sum; int digits[16] = {0}; cin >> n; i = 0; while (n > 0) { digits[i] = n % 10; i++; n /= 10; } digits[i] = -1; sum = 0; i = 0; while (digits[i] != -1) { sum += digits[i]; i++; } cout << sum << endl;
12th Oct 2016, 2:44 PM
Zen
Zen - avatar
0
how do I start if it's like this: int sumDigits(int n) { }
12th Oct 2016, 2:49 PM
Ian Soriano
Ian Soriano - avatar