Thread: Factorial program

  1. #1
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688

    Factorial program

    Hi Guys I am trying to make a program that reads in 10 values, calculates
    the factorial values ie: !5 = 5 * 4 * 3 * 2 * 1 then prints them out in a tabular format. I have got the basis of it down but its giving me the incorrect output.

    The program does compile. I think my mistake, is variable 'b' which holds the calculated value should really be an array as well? Or am I thinking the logic totally wrong?

    Here is what I have come up with:

    Code:
    #include <iostream>
    #include <iomanip>
    
    // main function - begins program execution ////////////////////////////////////
    //
    int main ( void )
    {
       const int ARRAY_SIZE = 10;
       
       int fact[ ARRAY_SIZE ] = { 0 };
       int b = 1;
       
       std::cout << "Enter a number: ";
       
       for ( int i = 0; i < ARRAY_SIZE; i++ )
       {
          std::cin >> fact[ i ];
       
          for ( int x = 1; x <= fact[ i ]; x++ )
          {
             b = b * x;
          }
       }
       
       std::cout << "Number" << std::setw( 12 ) << "FACTORIAL\n\n";
       
       for ( int i = 0; i < ARRAY_SIZE; i++ )
       {
          std::cout << fact[ i ] << std::setw( 17 ) << b << std::endl;
       }
       
       std::cin.get(); // freeze console output window
       std::cin.ignore();
          
       return 0; // return value from int main
    }
    Double Helix STL

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Yes, b needs to be stored in an array as well.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Factorial Computation Program
    By ts9818a in forum C++ Programming
    Replies: 3
    Last Post: 05-11-2008, 07:01 PM
  2. Need help with a program, theres something in it for you
    By engstudent363 in forum C Programming
    Replies: 1
    Last Post: 02-29-2008, 01:41 PM
  3. Replies: 4
    Last Post: 02-21-2008, 10:39 AM
  4. Writing code for a program in C
    By Sure in forum C Programming
    Replies: 7
    Last Post: 06-11-2005, 01:33 PM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM