Answer the question
In order to leave comments, you need to log in
Why doesn't the for loop decrement the value in prefix form?
Why does such a loop for(int i = f; i > 0; --i)
not reduce the value i
to 1 loop pass, although it is in prefix form?
The decrement only fires after the loop has been passed 1 time.
PS the task was about factorial, I solved it like this for(int i = (f-1); i > 0; i--)
, but I'm still interested - the previous version should have worked too
Answer the question
In order to leave comments, you need to log in
1. In the for loop, there is no difference between the postfix or prefix decrement/increment form for the counter variable.
2. The first pass of the loop is carried out with the initial value i. Then the counter variable changes and the second pass of the loop will already have the value i1, and so on.
3. In your case, everything was done correctly:
exl@exl-Lenovo-G560e:~/SandBox > cat test.cpp
#include <iostream>
int main() {
int f = 15;
for(int i = --f; i > 0; --i)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
exl@exl-Lenovo-G560e:~/SandBox > g++ test.cpp
exl@exl-Lenovo-G560e:~/SandBox > ./a.out
14 13 12 11 10 9 8 7 6 5 4 3 2 1
exl@exl-Lenovo-G560e:~/SandBox > cat test.cpp
#include <iostream>
int main() {
int f = 15;
for(int i = f--; i > 0; --i)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
exl@exl-Lenovo-G560e:~/SandBox > g++ test.cpp
exl@exl-Lenovo-G560e:~/SandBox > ./a.out
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
any operand that you supply as the third argument will be executed at the very end of the loop.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question