Write a program which finds the factorial of a number entered by the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "stdafx.h"
#include <iostream>


int main(){
	int x;
	int y;
	y = 1;
	std::cin >> x;
	for (y = 1; y < x; y++)
		x = x*y;
	std::cout << x;
}

I know x*y is wrong but I don't know how to make it multiply by all the numbers before?  
Last edited on
I don't know how to make it multiply by all the numbers before?
A nested for loop.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

edit: Oops.
Last edited on

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

int main(){
int x;
cin>>x;
int answer = 1;  //initiliaze by one (not 0 because then the result would always be 0)
for (int i=2; i<=x; i++){
    answer = answer*i;    //multiply answer by all the numbers from 2 two x
}
cout<<answer;
}
Last edited on
Topic archived. No new replies allowed.