Deitel C++ How To Program 9th Edition Chapter 4 Exercise 4.34

13 Jul 2024 - Syed Muhammad Shahrukh Hussain

Write a program to calculate factorial of a non negative number.

Terminal

Input number:4
24

Solution

#include <iostream>

using namespace std;

int main() {
  int n;
  int factorial = 1;

  cout << "Input number:";
  cin >> n;
  if (n < 0) {
    cout << "Please input non-negative number" << endl;
    return 0;
  }
  for (int i = 0; (n - i) >= 1; i++) {
    factorial *= ( n - i );
  }
  cout << factorial << endl;
  return 0;
}

Sources