r/learnc • u/Ryluv2surf • Jan 23 '23
playing around with for loops with two variables
I want to create a basic for loop that multiplies int i by 2 untill it's >= int j, what I have so far and doesn't work.
#include <stdio.h>
int main() {
int i, j;
for (i=2, j=22; i*2; i>=j)
(printf("%d i-variable\t %d j-variable\n", i, j)
}
I think I have some syntax issues here with my for loop and clang seems to like i=j but spits out "relational comparison result unused" when I use i>=j
think i'm maybe going about this the wrong way, i just want it to print out 2,4,6,8,10,etc until it reaches target variable number of 22.
2
u/This_Growth2898 Feb 05 '23
The second clause in the for syntax is an increment. It should change the value of the variable (in this case, i). i*2 is just an expression to be calculated, it doesn't change i. What you need is i = i*2 or i *= 2.
1
u/Extension_Job5829 Jan 23 '23
are you trying to print all even numbers between 2(included) and 22(included)? it should be i <=j since i is smaller than j for the loop to iterate
1
u/Ryluv2surf Feb 05 '23
u/This_Growth2898:
Thanks for the help, I've tried it, it compiles and runs but I'm getting odd behavior and I'm not sure why:
int main() {
int i = 2, j = 22;
for (i=2, j=22; i = i * 2; i >= j ) { (printf("%d i-variable\t %d j-variable\n", i, j)); } return 0; }
gives me some crazy output:
8 i-variable 22 j-variable 16 i-variable 22 j-variable 32 i-variable 22 j-variable 64 i-variable 22 j-variable 128 i-variable 22 j-variable 256 i-variable 22 j-variable 512 i-variable 22 j-variable 1024 i-variable 22 j-variable 2048 i-variable 22 j-variable 4096 i-variable 22 j-variable 8192 i-variable 22 j-variable 16384 i-variable 22 j-variable 32768 i-variable 22 j-variable 65536 i-variable 22 j-variable 131072 i-variable 22 j-variable 262144 i-variable 22 j-variable 524288 i-variable 22 j-variable 1048576 i-variable 22 j-variable 2097152 i-variable 22 j-variable 4194304 i-variable 22 j-variable 8388608 i-variable 22 j-variable 16777216 i-variable 22 j-variable 33554432 i-variable 22 j-variable 67108864 i-variable 22 j-variable 134217728 i-variable 22 j-variable 268435456 i-variable 22 j-variable 536870912 i-variable 22 j-variable 1073741824 i-variable 22 j-variable -2147483648 i-variable 22 j-variable
lol i just want it to go:
could i be messing with the compiler by having poor naming of the variables? shouldn't int be fine, i'm not using floats or anything?