+ 1

Can anyone tell me why this code doesn't give me "factorial of a given number"? (I want to know the reason why it is not working

#include<stdio.h> int Main() { int fact; Scanf("%d", &fact) ; For (int i=1; i<=fact ; i++) { fact=fact*i; } Printf("Factorial: %d", fact) ; return 0; }

11th Jan 2023, 7:25 AM
SD Anime
7 Answers
+ 6
SD Anime There are many problems here. To start, you cannot capitalize - main - scanf - for - printf Also the logic of the loop doesn't work. Try putting a print statement in the loop so you can see what it's actually doing, it's a good way to find errors and solutions: for (int i=1; i<=fact ; i++) { fact=fact*i; printf("Factorial: %d\n", fact) ; } Start with fixing those then if it's still not working show your code again. And it's better to attach it (use insert at the bottom of your post) instead of posting it in. And for those who can't read, don't just post solutions! That's not helping, that's taking away someone's opportunity to gain knowledge, pride and the confidence of knowing they can learn to resolve issues themselves with a little help. This shouldn't be seen as an opportunity to show off. The poster is asking why the code isn't working, not for you to do the work for them.
11th Jan 2023, 7:50 AM
Scott D
Scott D - avatar
+ 2
Thanks
11th Jan 2023, 8:35 AM
SD Anime
+ 1
Logic isn't working, I don't know why?
11th Jan 2023, 9:26 AM
SD Anime
+ 1
SD Anime The problem is, in the for loop you have i<=fact. However, every time the loop repeats fact is bigger! So in the first iteration i<=fact which translates to i<=6. But when the second iteration (loop) starts now the for loop is: i<=fact which now translates to i<=12. And so on. So each time it loops i is farther away from fact which is getting exponentially bigger. Because of that generally it's safer to do factorial loops backwards: 6*5*4*3*2*1 One solution is to create another variable: int fact, copy; Scanf("%d", &fact) ; copy = fact ; for (int i=1; i<=copy ; i++) Then copy will not grow as fact does, it stays at the same value. Maybe try that, see if it helps. And use a known answer, for example input 6 should output 720 as the factorial. Then adjust your loop accordingly.
11th Jan 2023, 10:04 AM
Scott D
Scott D - avatar
+ 1
Awesome explanation bro
11th Jan 2023, 11:30 AM
Mohd Junaid
Mohd Junaid - avatar
0
Thanks Scott D
13th Jan 2023, 5:45 AM
SD Anime
0
SD Anime You're welcome, hope you solved it. If not feel free to ask questions. Also, you might want to check out C lesson 16.1, Recursive Functions.
13th Jan 2023, 6:58 AM
Scott D
Scott D - avatar