Advertisement
Josif_tepe

Untitled

Oct 10th, 2023
845
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.34 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int sum(int n) {
  5.     if(n <= 0) {
  6.         return 0;
  7.     }
  8.    
  9.     return sum(n / 10) + (n % 10);
  10. }
  11. int main() {
  12.     cout << sum(123) << endl;
  13.     return 0;
  14. }
  15.  
  16. // sum(123) = sum(12) + 3 = 3 + 3 = 6
  17. // sum(12) = sum(1) + 2 = 1 + 2 = 3
  18. // sum(1) = sum(0) + 1 = 0 + 1 = 1
  19. // sum(0) = 0
  20.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement