Assignment
10
Write a C++ program to read an integer n and prints the
factorial of n.
Program
Code with explanation:
1.
#include
<iostream>
2.
using
namespace std;
3.
int
main()
4.
{
5.
int
n, i, fact = 1;
6.
cout
<< ” * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
\n”;
7.
cout
<< ” \t Accept number n to find Factorial \n “;
8.
cout
<< ” * * * * * * * * * * * * * * * * * * * * * * * * * * * * * \n \t”;
9.
cin
>> n;
10. for
( i = 1 ; i <= n ; i ++ )
11. {
12. fact
= fact * i;
13. }
14. cout
<< ” * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
\n”;
15. cout
<< ” \t Factorial of ” << n << ” is ”
<< fact << endl;
16. cout
<< ” * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
\n”;
17. return
0;
18. }
Explanation
of Code:
Line No. 1 and 2: include the Library file
and stander input – output functions.
Line No. 3: main function header.
Line No. 4 and 18: Begin and end of main
function respectively.
Line
No. 5: Declare
the three integer variables.
Line
No. 7 and 9: Accept
number n from user to find Factorial.
Line
No. 10 to 13: for
loop iteration form 1 to n.
We declare the variable fact with initialization
value 1. Calculate the factorial in variable fact.
For
example,
Factorial of 5 = 1 * 2
* 3 * 4 * 5.
So in for loop, we
use the variable i as a counter variable move the value from 1 to n and calculate
the factorial using expression fact = fact * i;
Line
No. 15: Display
the factorial of number n.
Line
No. 17:
return statement appropriate with main function return data type.
Program
Code for run:
#include
<iostream>
using
namespace std;
int
main()
{
int n, i, fact = 1;
cout << ” * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * \n”;
cout << ” \t Accept number n to
find Factorial \n “;
cout << ” * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * \n
\t”;
cin >> n;
for ( i = 1 ; i <= n ; i ++ )
{
fact = fact * i;
}
cout << ” * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * \n”;
cout << ” \t Factorial of ”
<< n << ” is ” << fact << endl;
cout << ” * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * \n”;
return 0;
}
Output
of Program:
* * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * *
Accept number n to find Factorial
* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
3
* * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * *
Factorial of 3 is 6
* * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * *