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 () ;
}

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

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.

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.