I want the code to automatically know which way to iterate through the loop without manually adding the '>' or '<' sign. I am using the logic that if the setup part of the loop is smaller than the value in the test expression, then the sign used will '<' and will be '>' vice versa.
The current way I have gone around this is by wrapping the for loop in an if statement, however this looks incredibly bulky and I feel there must be a better way.
The following is the code I am currently using:
i = -1;
if ((i*i*i)<(i * i * (i + i + i + i + i))){
for (integer = i * i * i; integer < i * i * (i + i + i + i + i);integer += i * i * i * i * i) {
printf("%d",integer);
printf("\n");
}
}
else {
for (integer = i * i * i; integer > i * i * (i + i + i + i + i);integer += i * i * i * i * i) {
printf("%d",integer);
printf("\n");
}
}
And here is an example which looks simpler:
if (-1<-5){
for (integer = -1; integer < -5;integer += -1) {
printf("%d",integer);
printf("\n");
}
}
else{
for (integer = -1; integer > -5;integer += -1) {
printf("%d",integer);
printf("\n");
}
}
2 Answers 2
You have a really complicated example with variables, and a simpler one with literals. The literal one is only going to use one branch. So let's do a simple one with variables. Let's say you want to iterate from a to b, but you don't know which is larger. Well, first of all, unless I'm missing something, if a>b, then you'll want integer -= increment
in the second branch, while your code has integer += increment
in both. So before your for-loop, define a variable direction
equal to the sign of b-a
(that is, if b-a >0
then direction = 1
, if b-a<0
then direction = -1
). Then do:
for(integer = a; (b-integer)*direction > 0; integer += direction*increment)
-
2\$\begingroup\$ Good advice. I'd write it
int delta = (a < b ? +1 : -1);
and thenfor (i = a; i != b; i += delta) { ... }
\$\endgroup\$Edward– Edward2017年11月16日 17:11:35 +00:00Commented Nov 16, 2017 at 17:11 -
\$\begingroup\$ @Edward this seemed to work fine until I came across the initiator being a minus number \$\endgroup\$user8786494– user87864942017年11月22日 17:50:58 +00:00Commented Nov 22, 2017 at 17:50
I am not going to repeat @Accumulation's solution but instead point out another aspect. By introducing only 2 variables you can make the complicated example look like the simple one:
i = -1;
int a = i * i * i;
int b = a * i * i;
// With i * i * (i + i + i + i + i) => i * i * (5 * i) = 5 * i * i * i = 5 * a
if (a < 5 * a) {
for (integer = a; integer < 5 * a; integer += b) {
printf("%d",integer);
printf("\n");
}
} else {
for (integer = a; integer > 5 * a; integer += b) {
printf("%d",integer);
printf("\n");
}
}
if (-1<-5){
This will NEVER be true However, this:if ((i*i*i)<(i * i * (i + i + i + i + i))){
will be true if 'i' is >0 and false otherwise \$\endgroup\$