Skip to content

Instantly share code, notes, and snippets.

@sr229
Last active November 3, 2022 12:11
Show Gist options
  • Save sr229/ef736d9bd156ac4510d6c454ba46b2ba to your computer and use it in GitHub Desktop.
Save sr229/ef736d9bd156ac4510d6c454ba46b2ba to your computer and use it in GitHub Desktop.
Factorials in C++ (with Comments)
/**
* Copyright 2019 (c) Ralph Wilson Aguilar
* For CS-111
* Do not copy or redistribute without permission.
*/
#include <iostream>
int main ()
{
int factorial = 1, i, input;
std::cout << "Enter the number you want to make a factorial of: ";
std::cin >> input;
/*
* We use a Loop-based approach to get a number's factorial.
* To get a factorial, we must first iterate it to a iterator
* variable with a initialized value of 1.
*
* The loop below is multiplying factorial from 1 to input's value. Where
* we multiply from 1 to the input's value, this is also known as a range.
*/
for (i=1; i <= input; i++)
{
factorial = factorial * i;
}
std::cout << "The factorial of " << input << " is " << factorial << std::endl;
return 0;
}
#include <iostream>
int main ()
{
int factorial=1, i=1, input;
std::cout << "Input: ";
std::cin >> input;
// the way this loop works is that until i is less than or equal than
while (i <= input)
{
factorial = factorial * i;
// keep incrementing until our condition is met.
i++;
}
std::cout << "The factorial of " << input << " is " << factorial << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment