Alternative to if else?
Oct 7, 2017 at 8:48pm UTC
SOi wrote this code for the recursive method and I really wanted to know if I can do this problem without using if else. what would be the appropriate replacement for if else statement?
Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include<iostream>
#include<cmath>;
using namespace std;
int re(int n);
float b(int n);
int main() {
int a;
cout << "Please entet a positive number\n" ;
cin >> a;
cout << re(a) << endl;;
cout << b(a) << endl;
system("pause" );
return 0;
}
float b(int n) {
if (n == 1) {
return 2;
}
else {
return pow((-1.0), n)*sqrt(n)*b(n - 1);
}
}
int re(int n){
if (n == 1) {
return 3;
}
else if (n == 0) {
return -2;
}
else {
return 2 *re(n - 1) + 3* re(n - 2);
}
}
Last edited on Oct 8, 2017 at 12:03am UTC
Oct 8, 2017 at 1:21am UTC
1 2 3 4 5 6 7
#include <cmath>
double b( int n ) // invariant: positive n
{ return n == 1 ? 2 : std::pow( -1.0, n ) * std::sqrt(n) * b(n-1) ; }
int re( int n ) // invariant: non-negative n
{ return n == 1 ? 3 : ( n == 0 ? -2 : 2 * re(n-1) + 3 * re(n-2) ) ; }
Oct 8, 2017 at 2:52am UTC
Thank you very much!
Topic archived. No new replies allowed.