0

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 () ;
}
3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by naseerhaider
Featured Replies
  • 1

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

  • 1
    WaltP 2,905   5 Years Ago

    That's pretty much it, except 1) [ICODE]main()[/ICODE] is an [B]int[/B], so always use [ICODE]int main()[/ICODE]. 2) Watch your [url=http://www.gidnetwork.com/b-38.html]formatting[/url]. Be consistent. This section [code] while ( i <= num ) // factorial { result *= i ; i++ ; } cout << num << " ! = " << result … Read More

1

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

1

That's pretty much it, except
1) main() is an int, 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.

0

That's pretty much it, except
1) main() is an int, 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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.