C++ Factorial Calculator Exercise Solution

In summary: FAC() << "\n";return 0;}In summary, the code prints out 1! = 1*2*3*...*(1-1)*1, and also prints out the factorial of the number that was inputted.
  • #1
erok81
464
0

Homework Statement



Write a C++ code factorial.cc that calculates the factorial of an integer by direct multiplication. Start with your code in exercise (3), and modify it so that it gets "n" from the user and prints out n! = 1*2*3*...*(n-1)*n. To do this, use a "for" loop:

Code:
int nfac;

nfac = 1;
for (int i = 0; i < n; i++)
  {
    ...
  }

and within the curly braces set the variable nfac appropriately

Homework Equations



None.

The Attempt at a Solution



I am 100% lost on this problem. We don't have a text and we didn't learn about nfac or how to do these types of calculations in class so I don't really have anything to go off of.

It says to start with my code from exercise 3 which is this. It works fine and I can mostly understand which lines do what.

Code:
#include <iostream>

using namespace std;
int main(void)
{
int n;

 cout << "enter a number:";
 cin >> n;
 cout << "your number was " << n << "\n";

return 0;
}

I don't have much past this. I've tried different combinations of things for last hour and a half but haven't gotten anything. Mainly because I zero idea where to put things. My latest guess was something like this.

Code:
#include <iostream>

using namespace std;
int nfac;

nfac = 1;
for (int i = 0; i < n; i++)

{
 cout << "enter a number:";
 cin >> n;
 cout << "your number was " << n << "\n";
return 0;
}


I know this is completely incorrect and am almost embarrassed to even post it, but I really have nothing at all. I think the cout line needs something that actually points it to what the factorial is?

As you can see it looks like I just slapped his hint in there and called it good, but I've tried everything and this is the closest/cleanest attempt I've gotten so far - even though it is wrong.
 
Physics news on Phys.org
  • #2
nfac isn't something that you would have learned about - it's just the name of a variable.

Do you know how to calculate the factorial of a number? For example, can you calculate 10!
 
  • #3
Yes, I can calculate that as long as it's on paper or a calculator...i.e. not through c++ :tongue:

Also after some more thought, I think I might be onto something.

Perhaps I need to use my solution to part (3) as I posted along with his hint, but rather than combining them into one sub routine, I need them as separate.

So I'd leave my solution to (3) alone except for the last cout where it returns the solution. Then under that as a new sub routine I can define how the nfac works and reference the calculation into the cout of my (3).

Am I on the right track?

I would need come up with the line for finding the factorial. Which is what I believe you are hinting at.
 
  • #4
You could create a function for the factorial, but you can do it in one statement in a for loop.

Some things to think about:
1. How is the factorial defined? (Think recursion...)
2. What does a for loop do?
3. How can you combine the two?

For you last example code, remember that a C++ file must* have a main function, e.g.
Code:
#include <iostream>
// plus any other libraries

using namespace std;

int main(void) // void if no inputs
{
    //do stuff
}

*Assuming it's not an include file like iostream, cmath, etc.
 
  • #5
On these kind of problems it's often helpful to write an algorithm in plain English, after this step is done the rest should be almost trivial.
 
  • #6
I am not familiar with the word subroutine, but I can sense you are going in the right direction. I would move this part of the code outside the for loop:

cout << "enter a number:";
cin >> n;

Since you have put this in the for-loop, it is going to repeat through the program n number of times. Put this before the for-loop. So now for what goes inside the for-loop. So you know how to figure out factorials in paper but it is the same in C++. Remember n! = 1*2*3*...*(n-1)*n. So once our user types in the value n you would know the limit of the for loop. You would need to multiply all the numbers up to the number n. That is what the for loop is for. Use the value of i to multiply to each value of what you get for n. Think of something like n = n+i. But instead of adding you would be multiplying. Hope this helps you.

Also don't forget the return 0; at the end of your main.
 
  • #7
I guess sub routine isn't the right word. I hesitated calling it that, but didn't know anything else to use. I meant each separate section of my code. So the int main is one and int nfac would be the other.

Code:
#include <iostream>

using namespace std;
int main(void)
{
int n;

 cout << "enter a number to be factorialized:";
 cin >> n;
 cout << "The factorial of "<< n << " is "<< nfac << endl; //I need to reference my factorial calculation here somehow??

return 0;
}

int nfac;

nfac = 1;
for(int i = 0; i < n; i++)
  {
   nfac = nfac*i
  }

I know to calculate the factorial I'd have something like Ivan92 said; n! = 1*2*3*...*(n-1)*n, but I am not sure how that translates to C++? I assume it goes in with the nfac part like I mentioned above.

In the first part I have a \n. We didn't learn what that did, just to type it in and try the code. Does that cause the original script to actually display the number in that problem?

Like I mentioned we didn't really learn much. Just about the entire lesson has been pasted in here. So you can see I don't have a lot to start with.

Thanks everyone for the help so far.
 
Last edited:
  • #8
When I try to compile it, it get this error.

Code:
factorial.cc:17: error: expected constructor, destructor, or type conversion before '=' token
factorial.cc:18: error: expected unqualified-id before 'for'
factorial.cc:18: error: expected constructor, destructor, or type conversion before '<' token
factorial.cc:18: error: expected constructor, destructor, or type conversion before '++' token

Do I need to define i somehow? It looks like all of my errors start before the i.
 
  • #9
All of your code starting with the line int nfac; should be moved so that it is inside the body of your main() function.

estro said:
On these kind of problems it's often helpful to write an algorithm in plain English, after this step is done the rest should be almost trivial.
This is good advice from estro. Let's start with that, and not worry about writing C++ code until you understand the algorithm you're going to use.
 
  • #10
Note that everything should be inside of the main function (unless otherwise told). So the last part after the 3rd to last bracket should be in main. Also I would have the cout result after the for loop. Also your cout should have the n instead of nfac.

Also I see you are using two int data types when you really only need one. So you don't need "int nfac; nfac = 1;" part. In the for loop, replace nfac with int n. After that, it should be working but I have not tested it myself.
 
  • #11
Ivan92 said:
Note that everything should be inside of the main function (unless otherwise told). So the last part after the 3rd to last bracket should be in main. Also I would have the cout result after the for loop. Also your cout should have the n instead of nfac.

Also I see you are using two int data types when you really only need one. So you don't need "int nfac; nfac = 1;" part. In the for loop, replace nfac with int n. After that, it should be working but I have not tested it myself.

I gave that a try and it reduced my errors down to two.

I'm using this now.

Code:
#include <iostream>

using namespace std;
int main(void)
{
int n;

 cout << "enter a number to be factorialized:";
 cin >> n;
 cout << "The factorial of "<< n << " is "<< "\n" << endl;

int nfac;
for(int i = 0; i < n; i++)
  
   int n = nfac*i;

return 0;
}

It compiles nicely with no errors - so we are getting close. However, my "answer" displays as "the factorial of 4 is " but nothing after is. The \n has to be there so maybe my calculation is wrong and isn't finding the factorial?


Mark44 said:
This is good advice from estro. Let's start with that, and not worry about writing C++ code until you understand the algorithm you're going to use.

Good idea. So I just did this in my head rather than writing it first. But here is what I was thinking before I started. Hopefully this is what you guys mean.

I need to be able to enter a number and find its factorial

Enter original number after terminal asks for number at prompt

Factorial is then calculated by 1*2*3*...*(n-1)*n

Factorial is displayed on terminal.
 
  • #12
I believe it is because the cout line needs to go after the for loop. I see what you are doing now. So replace the n in the for loop with nfac again (I know I told you to replace it with n. Sorry :embarrassed:) So it should look like this.

"int nfac=1;
for(int i = 0; i < n; i++)

{ int nfac = nfac*i;}

return 0;"

I added the = 1 part (just to be safe and make sure it doesn't have the default value of zero). I also added in those brackets. Its a good thing to have. Now after your for loop you should put your cout statement. The reason it is not displaying is because you are couting a new line. It should look something like this:

cout << "The factorial of "<< n << " is "<< nfac << endl;

You would be displaying what is the variable nfac instead of a new line.
 
  • #13
Okay here is what I have now.

Code:
#include <iostream>

using namespace std;
int main(void)
{
  int n;

  cout << "Enter a number to be factorialized:";
  cin >> n;  int nfac=1;
  for(int i = 0; i < n; i++)

    { int nfac = nfac*i;}

  cout << "The factorial of "<< n << " is " << nfac << endl;

  return 0;
}

If I run it like that I will always get an answer of 1.
I tried removing the 1 so I had int nfac; and got an answer of -4199132 no matter which number I entered.
 
  • #14
{ int nfac = nfac*i;}

Only declare each variable once. Don't re-declare it in every iteration of the loop!
 
  • #15
Also double check your loop counter start and end values. Are you sure you want to multiply by zero?

for(int i = 0; i < n; i++)
 
  • #16
uart said:
Only declare each variable once. Don't re-declare it in every iteration of the loop!

If I get rid of that line, it doesn't work. Hmm...

uart said:
Also double check your loop counter start and end values. Are you sure you want to multiply by zero?

Maybe that's my problem? Although that line was given in the lab, so I assumed that had to be there?
 
  • #17
Code:
import java.util.Scanner; 

public class Snippet {
	public static void main(String args[]) {
	int n,nfact;
	while(true){
Scanner in=new Scanner(System.in);
System.out.println("Enter n");
n=in.nextInt();
	nfact=1;
	[B][COLOR="DarkRed"][COLOR="Red"]for(int i=2;i<n+1;i++)
	{
	nfact=nfact*i;
	}
	[/COLOR][/COLOR][/B]System.out.println(" Factorial of " + n + "  is  " +nfact);
	
}
	}
	
}

This is the java version, please observe for loop !
 
  • #18
Ooooooooh!

After looking at yours and uart's tips:

uart said:
Only declare each variable once. Don't re-declare it in every iteration of the loop!
(and the mult. by zero comment)

I took off my second int fact changed my loop values and voila...

Code:
#include <iostream>

using namespace std;
int main(void)
{
  int n;

  cout << "Enter a number to be factorialized:";
  cin >> n;

  int nfac=1;
  for(int i=2; i < n+1; i++)

    { nfac = nfac*i; }

  cout << "The factorial of "<< n << " is " << nfac << endl;

  return 0;
}

Finally works!

Now to study why I made the mistakes.

Thanks again for the help everyone!
 
  • #19
On a side note; is there a way to get this to work?

for (int i = 0; i < n; i++)

Once I found my extra int, it would always = 0. Because that loop is multiplying by zero? That line is directly from the lab, so I wonder if it is supposed to work?
 
  • #20
Precisely! It starts from zero and multiplying zero will always get you zero. Sometimes professor will make a mistake.
 
  • #21
erok81 said:
On a side note; is there a way to get this to work?

for (int i = 0; i < n; i++)

Once I found my extra int, it would always = 0. Because that loop is multiplying by zero? That line is directly from the lab, so I wonder if it is supposed to work?

Code:
import java.util.Scanner; 

public class Snippet {
	public static void main(String args[]) {
	int n,nfact;
	while(true){
Scanner in=new Scanner(System.in);
System.out.println("Enter n");
n=in.nextInt();
	nfact=1;
	for (int i = 0; i < n; i++)

	{
	nfact=nfact*(i+1);
	}
	
System.out.println(" Factorial of " + n + "  is  " +nfact);
	
}
	}
	
}
 
  • #22
stallionx,
Your formatting makes this simple code very difficult to read. Here is my effort to improve the readability.
stallionx said:
Code:
import java.util.Scanner; 

public class Snippet 
{
   public static void main(String args[]) 
   {
      int n, nfact;
      while(true)
      {
         Scanner in = new Scanner(System.in);
         System.out.println("Enter n");
         n = in.nextInt();
         nfact = 1;
         for (int i = 0; i < n; i++)
         {
	nfact = nfact*(i+1);
         }
	
         System.out.println(" Factorial of " + n + "  is  " + nfact);
	
      }
   }
}
 
  • #23
I know this is a different problem, but I'm still stuck on the same concepts (this one isn't an assigned problem, but I think it will go a long in helping me understand these).

I am confused when to use brackets and a couple of other things.

Here is my original problem.

Code:
// this code is supposed to print out a list of sin(i)/i for i=0,1,2...,10.
// it is broken...

#include <iostream>


using namespace std;

int main()
{
  int x;
   
  cout << " here is a list of sin(i)/i versus i: " << endl; 
  for (i = 1; i <= 10; i++)
    cout << " sin(" << i << ")/i is ";

    if (i = 0) {
      // special case of i=zero. The correct limit as sin(x)/x as x->0 is 1.
      cout << "1\n";
    } else {
      x = sin(i)/i
      cout << x << endl;
    }

I modified it to this in an attempt to fix it.

Code:
// this code is supposed to print out a list of sin(i)/i for i=0,1,2...,10.
// it is broken...

#include <iostream>
#include <cmath>

using namespace std;

int main(void)
{
  int i;

  cout << " here is a list of sin(i)/i versus i: " << endl;
  for (i = 1; i <= 10; i++);
    cout << " sin(" << i << ")/i is ";

  if (i = 0);

    // special case of i=zero. The correct limit as sin(x)/x as x->0 is 1.
  cout << "1\n"<<;
}
    else
      {
  x = sin(i)/i;
      cout << x << endl;
    return;
      }

I think I might have made it worse though. So let me start off by saying when is is appropriate to use the brackets?

Any other tips or hints to fix this thing?
 
  • #24
erok81 said:
I know this is a different problem, but I'm still stuck on the same concepts (this one isn't an assigned problem, but I think it will go a long in helping me understand these).

I am confused when to use brackets and a couple of other things.

Here is my original problem.

Code:
// this code is supposed to print out a list of sin(i)/i for i=0,1,2...,10.
// it is broken...

#include <iostream>


using namespace std;

int main()
{
  int x;
   
  cout << " here is a list of sin(i)/i versus i: " << endl; 
  for (i = 1; i <= 10; i++)
    cout << " sin(" << i << ")/i is ";

    if (i = 0) {
      // special case of i=zero. The correct limit as sin(x)/x as x->0 is 1.
      cout << "1\n";
    } else {
      x = sin(i)/i
      cout << x << endl;
    }

I modified it to this in an attempt to fix it.

Code:
// this code is supposed to print out a list of sin(i)/i for i=0,1,2...,10.
// it is broken...

#include <iostream>
#include <cmath>

using namespace std;

int main(void)
{
  int i;

  cout << " here is a list of sin(i)/i versus i: " << endl;
  for (i = 1; i <= 10; i++);
    cout << " sin(" << i << ")/i is ";

  if (i = 0);

    // special case of i=zero. The correct limit as sin(x)/x as x->0 is 1.
  cout << "1\n"<<;
}
    else
      {
  x = sin(i)/i;
      cout << x << endl;
    return;
      }

I think I might have made it worse though. So let me start off by saying when is is appropriate to use the brackets?

Any other tips or hints to fix this thing?

I doubt that this will compile. Here are some problems I see.
1) There is code that isn't in the body of any function (all of the code from else on).
2) Your for loop is not doing anything useful. This is because the body of the for loop is null.
The statement for(i = 1; i <= 10; i++);
causes the loop control variable, i, to be set respectively to 1, 2, 3, ..., 10, and finally 11, which is the first value that is too large. At each step, nothing useful happens.

You should get in the habit of using braces - {} - to surround the body of for loops, while loops, if statements, else statements, and other control statements.

Here is a typical for loop.
Code:
for (i = 0; i < 10; i++)
{
   // Body of for loop
}

If the body of a for loop etc. consists of a single statement, you don't have to use braces, but I would STRONGLY recommend using them. Many people have been burned by not using braces, and then coming back to decide they need another statement in the body. If the loop body is surrounded by braces, no problem, but if not, only the first statement is considered by the compiler to be the loop body, even if your indentation suggests otherwise.

Here is a typical if - else statement
Code:
if (i == 1)
{
   // What's supposed to happen if i equals 1
}
else
{
   // What's supposed to happen if i is NOT equal to 1
}


3) if (i = 0);
There are at least two things wrong here.
a) You are using the assignment operator =, instead of the equals operator ==.
b) Using the assignment operator instead of the equals operator causes the value 0 to be stored in the location for i. The value of this assignment expression is 0, which is considered false in C and C++. (Anything nonzero is considered to be true.) As a result of the value of the expression being false, the null statement following the right parenthesis is not executed.
In short the statement if (i = 0); does exactly nothing.

4) You are not understanding that the computer executes your code sequentially line after line (unless you have a loop or branch structure - e.g., if - else). If you want to print
sin(1)/1 is <something>
sin(2)/2 is <something>
.
.
.
you are going to have to compute sin(1)/1, sin(2)/2, etc. BEFORE the print statement is finished executing.

This would do what you want:
Code:
for (i = 1; i <= 10; i++)
{
    cout << " sin(" << i << ")/i is " << sin(i)/i << endl;
}
There is no need for a special case for i == 0; the loop runs from i == 1 through i == 10 and then quits.
 
  • #25
Oh wow! Thank you for that detailed post. I'm pretty sure I just learned more from that post than I have over the week of classes. Now I think I get how this stuff is used.

While I am working through it all, I've got two last questions to clear up.

Brackets. Do I need to finally close it all?

Say I've got my original bracket after the int main() and then numerous open/closed brackets for my loops etc. Do I then need to have a closing one after everything to end my int main, or is that taken care of in the first set of functions (or whatever you want to call them).

My return 0; where does that go? I'm not fully understanding what it does. I've seen some examples where they have something other than 0.

Thanks again for taking the time to write all of that up!
 
  • #26
You main function looks like this: int main (void), it means that your function must return an integer. [you can change it to void main (void), then you will not need any return...]
Reading your question I have no choice but to recommend you reading some intro c++ book.
 
  • #27
erok81 said:
Oh wow! Thank you for that detailed post. I'm pretty sure I just learned more from that post than I have over the week of classes. Now I think I get how this stuff is used.

While I am working through it all, I've got two last questions to clear up.

Brackets. Do I need to finally close it all?
Yes, of course.

Let's get some terminology straight.
Brackets - [] - also redundantly called "square brackets".
Braces - {} - also called "curly braces".
Parentheses - ()

Each of these occurs in pairs. Leaving one off results in a compile-time error.

They are also used for different purposes.
Brackets are used around array indexes. E.g., list[7] denotes the element at index 7 in the array named list.

Braces are used to surround the bodies of functions and control structures (such as for, while, if, if else, switch, and so on. They are also used to surround blocks of code.

Parentheses are used to surround the arguments to a function, the test expression in if and while, and to cause a change in the usual order of evaluation.

erok81 said:
Say I've got my original bracket after the int main() and then numerous open/closed brackets for my loops etc. Do I then need to have a closing one after everything to end my int main, or is that taken care of in the first set of functions (or whatever you want to call them).
Every brace has to be one of a pair, so yes you need a closing brace.
erok81 said:
My return 0; where does that go? I'm not fully understanding what it does. I've seen some examples where they have something other than 0.
The return statement is typically, but not always, the last statement in main. The main function is called from the operating system, and the return statement sends a value back to the operating system. A value of 0 usually indicates that everything is hunky-dory. You can return some other value for whatever reason you decide.
erok81 said:
Thanks again for taking the time to write all of that up!
My pleasure! I'm happy to be able to share what I know.
 
  • #28
Mark44 said:
Every brace has to be one of a pair, so yes you need a closing brace.The return statement is typically, but not always, the last statement in main. The main function is called from the operating system, and the return statement sends a value back to the operating system. A value of 0 usually indicates that everything is hunky-dory. You can return some other value for whatever reason you decide.

Ah got it. That makes perfect sense. I am glad I know why/what it does now. In class it was just on the example and we should include it. Not a why.

Check it out. I left the if/else in there just to make sure I could get it work.

Code:
// this code is supposed to print out a list of sin(i)/i for i=0,1,2...,10.
// it is broken...

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
  int i;
  {
    cout << " here is a list of sin(i)/i versus i: " << endl;
  }

  for (i = 1; i <= 10; i++)
    {
      cout << " sin(" << i << ")/i is " << sin(i)/i << endl;
    }


  if (i == 0)
  {
    cout << "1\n"<< endl;
  }
  else
    {
        i = sin(i)/i;
        cout << i << endl;
      }
      return 0;
    }

And it works! I wish this was something I was turning in. I'm pretty excited now that I actually understand what I did rather than copy and pasting/fumbling through it all.

Thanks again for the help. I can't express how much help these last few posts have been. I was getting pretty discouraged with this stuff over the last couple problems I've done. So thanks. :approve:
 
  • #29
Oh and I'll be sure to keep my braces/brackets/parentheses straight next time. ;)
 
  • #30
Your code works now, but there is what is known as "dead code," code that will never execute; namely, the part where you check to see if i == 0.

Here is your code the way I would write it, with dead code removed, and superfluous braces removed.
Code:
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
   int i;
  
   cout << " here is a list of sin(i)/i versus i: " << endl;
   
   for (i = 1; i <= 10; i++)
   {
      cout << " sin(" << i << ")/i is " << sin(i)/i << endl;
   }

   return 0;
}

The braces you had around the first cout statement weren't necessary. They didn't hurt anything, but if they're not needed, why include them?

All of the if (i == 0) and so on was completely unnecessary. The for loop sets i to 1, 2, 3, ..., 10, and 11, and then continues on. At no point is i being set to 0, so why check for it?
 
  • #31
estro said:
You main function looks like this: int main (void), it means that your function must return an integer. [you can change it to void main (void), then you will not need any return...]


Actually, main implicitly returns 0 for C++, so (for the main function only) you may omit "return 0;"

void main(void) is not okay!

It is not what is specified by the standards.

The caller is expecting a return value, and that value should be 0 for success.

It could result in stack corruption.
 
Last edited:

1. What is a C++ factorial calculator exercise?

A C++ factorial calculator exercise is a programming problem that requires the creation of a program in the C++ programming language that calculates the factorial of a given number. The factorial of a number is the product of all the numbers from 1 to that number.

2. How do I solve the C++ factorial calculator exercise?

To solve the C++ factorial calculator exercise, you will need to use a loop to multiply each number from 1 to the given number. You can also use recursion, which is a programming technique where a function calls itself until a base case is reached. Both methods will result in the calculation of the factorial of the given number.

3. What is the purpose of the C++ factorial calculator exercise?

The purpose of the C++ factorial calculator exercise is to practice and improve your programming skills in the C++ language. It also helps you understand the concept of loops and recursion, which are important concepts in programming.

4. Can I use any programming language to solve the C++ factorial calculator exercise?

No, the C++ factorial calculator exercise specifically requires the use of the C++ programming language. While other programming languages may have similar exercises, they may use different syntax and logic.

5. Are there any tips for solving the C++ factorial calculator exercise?

Some tips for solving the C++ factorial calculator exercise include breaking down the problem into smaller, manageable steps, testing your code with different inputs, and seeking help from online resources or fellow programmers if you get stuck. It is also important to understand the concept of factorials and how loops and recursion work in C++.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
747
  • Engineering and Comp Sci Homework Help
Replies
8
Views
835
  • Engineering and Comp Sci Homework Help
Replies
24
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
Back
Top