954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Factorial Using loop

I'm brand new to C++ ,I've written following code for finding a number's factorial,Can you please let me know how to write it more elegantly ?

#include <iostream>
using namespace std ;

main ()
{
     int num = 0 ;                     // declaring variables
     double result = 1 ;
     long int i = 1;
     
     cout << " Please Enter a Number : " ; // taking input from user 
     cin >> num ;
     
     while ( i <= num )                  // factorial 
     {
           result *= i ;
           i++ ;
           }
         
         cout << num << " ! = " << result ;
         cin.get () ;
}
naseerhaider
Newbie Poster
13 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

You could use a for loop instead of a while loop since you know how many iterations you will perform.

kerp
Light Poster
30 posts since May 2010
Reputation Points: 9
Solved Threads: 5
 

That's pretty much it, except
1) main() is anint, so always use int main() .
2) Watch your formatting . Be consistent.
This section

while ( i <= num )                  // factorial 
     {
           result *= i ;
           i++ ;
           }
         
         cout << num << " ! = " << result ;
         cin.get () ;
}


should be

while ( i <= num )                  // factorial 
    {
         result *= i ;
         i++ ;
    }
         
    cout << num << " ! = " << result ;
    cin.get () ;
}

You are using SPACEs to indent -- excellent!! Switch to 4 though, not 5.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

That's pretty much it, except 1) main() is anint, so always use int main() . 2) Watch your formatting . Be consistent. This section

while ( i <= num )                  // factorial 
     {
           result *= i ;
           i++ ;
           }
         
         cout << num << " ! = " << result ;
         cin.get () ;
}

should be

while ( i <= num )                  // factorial 
    {
         result *= i ;
         i++ ;
    }
         
    cout << num << " ! = " << result ;
    cin.get () ;
}

You are using SPACEs to indent -- excellent!! Switch to 4 though, not 5.

Thanks for your reply .I shell try to follow above mentioned practice in future.

naseerhaider
Newbie Poster
13 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: