Group
Flow Control in C++
Objective
1. Prompt the user to enter a positive integer.
2. Initialize a variable to store the factorial result, starting with 1.
3. Use a loop to multiply the factorial result by each integer from 1 to N.
4. Display the final factorial result.
5. Test the program with different values of N.
Calculate the factorial of a number using a loop.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Main function - the entry point of the program
int main() {
int N, factorial = 1; // Declare the variable N to store user input and factorial initialized to 1
// Ask the user to enter a positive integer
cout << "Enter a positive integer: ";
cin >> N; // Read the user input and store it in N
// Use a for loop to calculate the factorial of the number
for (int i = 1; i <= N; ++i) {
factorial *= i; // Multiply factorial by each integer from 1 to N
}
// Display the result of the factorial
cout << "The factorial of " << N << " is: " << factorial << endl;
return 0; // Return 0 to indicate that the program executed successfully
}
Output
Enter a positive integer: 5
The factorial of 5 is: 120