1 Replies - 3156 Views - Last Post: 01 February 2011 - 01:25 PM Rate Topic: -----

#1 mizquier  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 01-February 11

Factorial Problem, C++, using for loop and if statements

Posted 01 February 2011 - 01:21 PM

Write a program that prompts the user to enter an integer and then calculates the factorial of it.
Print your calculated value to the screen.

I am confused on the concept, sample code would be nice just to see where to go with this. I appreciate any help.

Thanks!
Is This A Good Question/Topic? 0
  • +

Replies To: Factorial Problem, C++, using for loop and if statements

#2 LivingNightmare  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 21
  • View blog
  • Posts: 129
  • Joined: 07-July 10

Re: Factorial Problem, C++, using for loop and if statements

Posted 01 February 2011 - 01:25 PM

Well, I won't give you the code, but here's a bit to go with.
You know that n! = n * (n - 1)! correct? and you also know that 1! = 1;

So you can have something like

fact -> 1
for i is equal to 1 - n do
   fact -> fact * i
end while



If you understand how this works, then making a C++ program to do this becomes trivial.
Or, if you want to do it in a functional way, one that mirrors the definition of a factorial, you can have

fact(n)
if n is equal 0 then
   return 1
otherwise
   return n * fact(n - 1)



Following this pseudo code should make the task relatively simple.

This post has been edited by LivingNightmare: 01 February 2011 - 01:28 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1