tdudzik

Sumy cyfr

Feb 3rd, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int suma_cyfr(int n) {
  6.     int suma = 0;
  7.  
  8.     if (n == 0) {
  9.         return 0;
  10.     }
  11.  
  12.     while (n > 0) {
  13.         suma += n % 10;
  14.         n /= 10;
  15.     }
  16.  
  17.     return suma;
  18. }
  19.  
  20. bool liczba_jest_jednocyfrowa(int n) {
  21.     return n < 10;
  22. }
  23.  
  24. int main() {
  25.  
  26.     int n, suma;
  27.     do {
  28.         cout << "Podaj nieujemną liczbę całkowitą: ";
  29.         cin >> n;
  30.  
  31.         if (n < 0) {
  32.             cout << "Liczba musi być nieujemna!" << endl;
  33.             continue;
  34.         }
  35.  
  36.         do {
  37.             suma = suma_cyfr(n);
  38.             n = suma;
  39.  
  40.             cout << "Wynik to: " << suma << endl;
  41.         } while (!liczba_jest_jednocyfrowa(n));
  42.     } while (n < 0);
  43.  
  44.     return 0;
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment