Hello, I'm trying to teach myself to code and I've always found the best way to learn was through doing. However in my attempt to make a fairly straightforward program(my first) I have clearly done something horribly wrong. Can anyone offer guidance as to what key concept I've messed up?
Thanks :)
#include <iostream>
usingnamespace std;
int factorial(int f)//int f being the input number to be put through the program
{
int fac = f;//fac is the output
int x = f;
for(x = f; x=0; x-1)//x is to keep track of the loop
{
int fac = fac * x;
cout<<fac;//just to check what is being done(nothing)
}
return fac;
}
int main()
{
int y;
cin>> y;
int z = factorial(y);
cout<< z;
cin.ignore();
return 0;
}
The last expression in your for loop doesn't do anything. Did you mean x-=1 or --x?
Line 11 creates a new variable called fac each iteration of the loop that is different from the fac on line 7. Just use the fac you declared on line 7 inside the for loop.
#include <iostream>
usingnamespace std;
int factorial(int f)//int f being the input number to be put through the program
{
int fac = f;//fac is the output
int x = f;
for(x = f; x=0; x=x-1)//x is to keep track of the loop
{
fac = fac * x;
cout<<fac;//just to check what is being done(nothing)
}
}
int main()
{
int y;
cin>> y;
int z = factorial(y);
cout<< z;
cin.ignore();
return 0;
}
I did originally have it returning the value but i wanted to have the cout so i could check if my loop was working.
Why do you not need curly brackets around the while in the example above?
You need curly brackets (which indicate a compound statement) only when the block of code you wish to execute consists of multiple statements. If the code you wish to execute for a loop consists of only one statement, the brackets aren't needed, although some folks consider it good practice to include them anyway.
Learning C++ is part of a course I'm taking this semester, but in saying that the course caters for some who really shouldn't be touching a computer so we'll see what happens. Thanks for the advice you've been excellent