thien

BÀI 15

Mar 2nd, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.62 KB | None | 0 0
  1. Bài 15: Hãy viết chương trình tính tổng các chữ số của một số nguyên bất kỳ
  2.  
  3.  
  4.  
  5. CODE 1:
  6.  
  7. #include <iostream>
  8. using namespace std;
  9. int tong(int n)
  10. {
  11. return n?n%10+tong(n/10):0;
  12. }
  13. int main()
  14. {
  15. cout<<tong(2222);
  16. system("pause");
  17. }
  18.  
  19.  
  20.  
  21.  
  22. CODE 2:
  23.  
  24. #include <stdio.h>
  25.  
  26. int main () {
  27. int n, s ;
  28. printf ("\nEnter an integer : ") ; scanf ("%d", &n) ;
  29. if (n < 0)
  30. n = - n ;
  31. cal:
  32. s= 0 ;
  33. while (n) {
  34. s += n %10 ; n /= 10 ;
  35. }
  36. if (s >= 10) {
  37. n = s ; goto cal ;
  38. }
  39. printf ("\nResult = %d\n", s) ;
  40. return 0 ;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment