The logic is very complicated, let’s think about it a little bit. You have terms that start at 2 and evolve from 2 to 2. So in the loop let’s call this termo
instead of i
as called to give more semantics to what we are doing since the loop is part of the problem domain is not just a mechanism to scan a data collection.
Let’s go two for two on one for
which is simpler than a while
.
Let’s start the factorial where it always starts which is 1. And we will apply the calculation of it always using two steps (you can do in one but complicates the understanding).
Before finding the factorial of the current term we need to find the factorial of the previous term because to show jumps of 2 in 2, but to calculate no, has to calculate all factorial, after all the factorial is always based on its previous factorial, can not skip one of the numbers. Then I count with the previous term and soon after you find that I do with the current one. And that’s it, I have the necessary factorial.
As I am accumulating I don’t need to calculate all factorial again, I already have the value of the previous term, so just repeat this step. So:
#include<stdio.h>
int main() {
int fat = 1;
for (int termo = 2; termo <= 20; termo += 2) {
fat *= termo - 1;
fat *= termo;
printf("%d\n", fat);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I’m not sure if it should end in 20, but if it’s 20 terms jumping from 2 to 2, and not just until the 20th. term, just make the loop go up 40.
First you need to find a criterion. The progression clearly shows it is not arithmetic. Having a clear definition of what needs to be done gives to look at the code, which is confusing.
– Maniero
I suggest you do the table test to understand what is happening. At the end of the
for
the value ofx
will be 1, and in the next iteration ofwhile
, it will start at 3 (i.e., you are calculating the factorial 3 several times). It’s also unclear if 20! is the highest value to be calculated, or if there are 20 terms (which would end the sequence at 40! , a number with more than 47 digits and which causes overflow in the results)– hkotsubo
Note that you modify the value of x within your command
for
. When exiting the loop the variablex
will always be worth 1.– anonimo
A hint: you don’t need this
for
. If the idea is to show 2!, then 4!, 6! and so on, you don’t have to calculate everything from the beginning. If you have already calculated 2!, just multiply by 3 and 4 to get 4!, then just multiply by 5 and 6 to get 6! and so on– hkotsubo
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero