neogz

Niz- unos-ispis-suma neparnih / rekurzija

Apr 2nd, 2014
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5.  
  6.  
  7.  
  8. // unos pomoću rekurzije
  9. void unos(int niz[], int max)
  10. {  
  11.     if (max == 0) cin >> niz[max];
  12.     else {
  13.         cin >> niz[max];
  14.         unos(niz, max - 1);
  15.     }
  16. }
  17. void ispis(int niz[], int max)
  18. {  
  19.     if (max == 0) cout << niz[max]<<"\t";
  20.     else {
  21.         cout << niz[max] << "\t";
  22.         ispis(niz, max - 1);
  23.     }
  24. }
  25. //suma neparnih elemenata
  26. int sne(int niz[], int max)
  27. {
  28.     // bazni slucaj tj, ako je brojac < 0 vrati nulu
  29.     if (max < 0)return 0;
  30.     else {  //ako je neparan saberi
  31.         if (niz[max] % 2 == 1) return niz[max] + sne(niz, max - 1);
  32.         else return sne(niz, max - 1);
  33.     }
  34. }
  35. //suma elemenata sa neparnim indexom
  36. int sni(int niz[], int max)
  37. {
  38.     if (max == 0)return 0;
  39.     else{
  40.         if (max % 2 == 0)return sni(niz, max - 1);
  41.         else return niz[max] + sni(niz, max - 1);
  42.     }
  43. }
  44.  
  45. int main()
  46. {
  47.     const int max = 7;
  48.  
  49.     int niz[max];
  50.  
  51.     cout << "Unesite vrijednosti vaseg niza: \n";
  52.     unos(niz,max-1);
  53.     cout << endl;
  54.  
  55.     cout << "Vas niz je: \n";
  56.     ispis(niz, max - 1);
  57.     cout << endl;
  58.  
  59.     cout << "Suma neparnih elemenata niza je: " << sne(niz, max-1) << endl;
  60.     cout << "Suma elemenata sa neparnim indexom je: " << sni(niz, max - 1) << endl;
  61.  
  62.     system("pause >nul");
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment