factorials??

This is a discussion on factorials?? within the C++ Programming forums, part of the General Programming Boards category; I'm a rookie at C++ and trying to learn on my own with a lot of tutorials. My question is, ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    60

    factorials??

    I'm a rookie at C++ and trying to learn on my own with a lot of tutorials. My question is, what is the best method of caculating and displaying the values of 1! to 10! using nested "for" statements? Thanks for any advice in advance.

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,812
    You don't really need nested for statments you only need one loop think about it.
    a = 1;
    for i = 0; i < 10; i++
    a = a * i
    print a
    [edit] thanks hunter ya jerk [/edit]
    Last edited by prog-bman; 03-15-2005 at 10:58 PM.
    Woop?

  3. #3
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>for i = 10; i < 10; i++
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  4. #4
    People Love Me
    Join Date
    Jan 2003
    Posts
    412
    Code:
    /************************************
    Calculates factorial of a number (n!)
    ************************************/
    int fact(int n){
    		int result=1;
    
    //Special cases: n==0 and n<0
    		if(n==0){return 1;}	//0! = 1
    		if(n<0)	{return 0;}	//Negative factorial is undefined
    
    //If the number is positive:
    		while(n>0){
    		 result *=n;
    		n--;
    			 }
    	 return result;
    }

  5. #5
    Registered User
    Join Date
    Aug 2002
    Location
    Hermosa Beach, CA
    Posts
    446
    Not entirely relevent, but this was always my favorite:

    Code:
    # include <iostream>
    using namespace std;
    
    template <int x>
    class factorial {
    public:
        enum { VALUE = x * factorial<x-1>::VALUE };
    };
    
    template <>
    class factorial<0> {
    public:
        enum { VALUE = 1 };
    };
    
    int main()
    {
        cout << "Factorial is " << factorial<10>::VALUE << endl;
        return 0;
    }
    The crows maintain that a single crow could destroy the heavens. Doubtless this is so. But it proves nothing against the heavens, for the heavens signify simply: the impossibility of crows.

  6. #6
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    You can do it with a recursive function as well, although personally I can't write a recursive function to save my life. There is a tutorial on this site covering recursive functions, but I would never have figured out the output of this without running it:

    Code:
    void printnum ( int begin )
    {
         cout<< begin;
    
         if ( begin < 9 )          
              printnum ( begin + 1 ); 
    
         cout<< begin;             
    }

  7. #7
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    Hi,


    I just thought I'd add a little bit although you probably get the picture now. I have written a complete code which computes n! from n=1 to n=10, like you have mentioned using a 'nested for loop'.

    There are easier ways to do it, but I am just doing what you have specified. Underneath is the entire code which can be copied and pasted into your programme straight away.

    Code:
    /************************************
    Calculates factorial of a number (n!)
    
            from n=1  to n=10
    ************************************/
    #include<iostream.h>
    
    
    int main()
    {
        cout<<"*******************************"<<endl;
        cout<<"Calculates n! from n=1 to n=10"<<endl;
        cout<<"*******************************"<<endl;
        cout<<""<<endl;
        
        int accum;
        
        for (int b=1; b<11; b++)
        {
        
                accum=1; //initialise accumulate
        
                for (int a=b; a>0; a--)
                    {
                            accum=accum*a;
                    }
             cout<<"The solution is: "<<accum<<endl;
         }    
            
            
         int stop;
         cin>>stop;
    }

  8. #8
    Registered User
    Join Date
    Mar 2005
    Posts
    60
    Thanks everybody for responding. To help me better understand, why did treenef initialize the sample code within the inner loop? I notice if I take this out, you get weird negative numbers. The code in question is:

    accum=1; //initialise accumulate

    Thanks

  9. #9
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Actually, it's the outer loop. The outer loop is for displaying the factorial from 1 to 10, and the inner loop is for calculating the factorial of i. Since the accumulator must be reset for each factorial you are calculating, it makes sense to reset it each time at the beginning of the outer loop.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  10. #10
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    Yes hunter is correct.

    I should have initialised accum before the nested for statements.
    And I should have reset accum at the end of the outer loop. However, I had written the code in a rush and since it worked fine I didn't notice that the logic was incorrect. Here is the ammended code.

    Oh and just a helpful hint S_ny 33 -
    it's always useful to convert code into flow charts to help you visualise what is going on, especially when it comes to nested statements.


    Code:
    /************************************
    Calculates factorial of a number (n!)
    
            from n=1  to n=10
    ************************************/
    #include<iostream.h>
    
    
    int main()
    {
        cout<<"*******************************"<<endl;
        cout<<"Calculates n! from n=1 to n=10"<<endl;
        cout<<"*******************************"<<endl;
        cout<<""<<endl;
        
        int accum;
        accum=1; //initialise accumulate
        for (int b=1; b<11; b++)
        {
        
                
                
                for (int a=b; a>0; a--)
                    {
                            accum=accum*a;
                    }
             cout<<"The solution is: "<<accum<<endl;
             accum=1;
         }    
            
            
         int stop;
         cin>>stop;
    }

  11. #11
    Registered User
    Join Date
    Mar 2005
    Posts
    60
    Treenef -- your code is fine and it was very helpful...thanks. The flowchart is a good idea because I think that is my problem when determining the proper outlay of the code. Thanks.

  12. #12
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>I should have initialised accum before the nested for statements.
    No, it's fine as it is - accum will always be initialized to 1 before being used, and it will be reset when the outer loop wraps around to the beginning again. Either way will work fine though.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  13. #13
    People Love Me
    Join Date
    Jan 2003
    Posts
    412
    Okay boys and girls, let's learn something really quick:

    You do not need 2 for loops to do something simple like factorials. Usually, 2 for loops would be used to anything involving a 2D array or something of that nature. Also for creating a map or tiles or representing anything in 2 dimensions:
    Code:
    for(int i=0; i<height; i++){
        cout << endl;
           for(int j=0; j<width; j++){
               cout << "*";
            }
    }
    But simple crap like factorials don't need nest for loops. It'll just be more confusing to read, and stupid.


    ......There's your daily dose of common sense.
    Last edited by Krak; 03-17-2005 at 11:06 PM.

  14. #14
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Quote Originally Posted by Krak
    Okay boys and girls, let's learn something really quick:

    You do not need 2 for loops to do something simple like factorials. Usually, 2 for loops would be used to anything involving a 2D array or something of that nature. Also for creating a map or tiles or representing anything in 2 dimensions:
    Code:
    for(int i=0; i<height; i++){
        cout << endl;
           for(int j=0; j<width; j++){
               cout << "*";
            }
    }
    But simple crap like factorials don't need nest for loops. It'll just be more confusing to read, and stupid.


    ......There's your daily dose of common sense.
    And, Krak, you should do some reading before posting. The factorial is being calculated in one loop, and the outer loop is to repeat the factorial operation from 1! to 10!. Not the most efficient method to be sure (a single loop from 1 to 10, printing the running product after each iteration as prog-bman suggested, would be ideal but more of a specific-case hack), but the logic is correct and intuitive.
    Last edited by Hunter2; 03-17-2005 at 11:38 PM. Reason: De-flame-ized the post.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  15. #15
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    Also for creating a map or tiles or representing anything in 2 dimensions:
    Wrong.

    2 variables for x and y, one for offset. 1 loop and faster than a 2D array.


    I should suspect the recursive version would be this:

    Code:
    unsigned long Factorial(int num)
    {
      static unsigned long totalvalue=num;
      if (num<2) return totalvalue;
    
      totalvalue*=(num-1);
      Factorial(num-1);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need suggestion on sum of factorials.
    By chhay in forum C Programming
    Replies: 27
    Last Post: 08-01-2008, 06:13 AM
  2. Problem with Recursion calculing Factorials
    By cvelasquez in forum C Programming
    Replies: 7
    Last Post: 12-14-2005, 08:23 AM
  3. Function To Find Factorials!!! Please Help
    By adzza69 in forum C++ Programming
    Replies: 22
    Last Post: 08-20-2004, 07:39 PM
  4. Program to calculate factorials
    By forzamilan in forum C++ Programming
    Replies: 1
    Last Post: 09-22-2001, 11:24 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21