Explain difference b/w the two codes
How does the compiler interpret the position of the initialization
in both the cases.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
//Finding the factorial
#include <iostream>
#include <cmath>
using namespace std;
long fact(int n)
{if (n<0)
return 0;
int f(1);
while (n>1)
f *= n--;
return f;
}
int main()
{ int x;
cin >> x;
cout << fact(x);
system ("pause");
return 0;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
//Finding the factorial
#include <iostream>
#include <cmath>
using namespace std;
long fact(int n)
{if (n<0)
return 0;
while (n>1)
int f(1);
f *= n--;
return f;
}
int main()
{ int x;
cin >> x;
cout << fact(x);
system ("pause");
return 0;
}
|
Last edited on
In the second example the while statement has no braces, it would just loop initializing f, and there would be an error because f is out of scope.
If you mean to say to put the code like this, The code isn't giving me the factorial. :/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
//Finding the factorial
#include <iostream>
using namespace std;
long fact(int n)
{if (n<0)
return 0;
while (n>0)
{int f(1);
f *= n--;
return f;}
}
int main()
{ int x;
cin >> x;
cout << fact(x);
system ("pause");
return 0;
}
|
Last edited on
Any initialization expression should be before while loop.
Topic archived. No new replies allowed.