+ 2

Getting the whole range of results from a For loop in C

#include <stdio.h> int main(){ int i = 13, n; for (i; i > 0; i = i/2) { n = i%2; } } The n variable should be "1011", but if I try to use it outside the For loop its value is only "1". Anybody has a solution for using the int n outside its scope with the "1011" value?

13th Oct 2019, 3:01 PM
Alessandro Palazzolo
Alessandro Palazzolo - avatar
4 Answers
+ 2
#include <stdio.h> int main(){ int i = 13, n = 0; for (i; i > 0; i = i/2) { n = (n * 10) + i%2; } printf("n: %d", n); }
13th Oct 2019, 3:16 PM
MO ELomari
MO ELomari - avatar
+ 1
Replace `n = i % 2;` with `printf("%d", i % 2);` That will output '1011'. But if you want value of <n> to become 1011 (in int form), well that's another story. (Edit - 2) I just took a closer look and seems the sample code isn't giving the correct result. The binary representation of 13 (decimal) is supposed to be 1101 and not 1011 (11 decimal). Mohamed ELomari Please kindly revise the solution 👍
13th Oct 2019, 3:15 PM
Ipang
0
Mohamed ELomari why is that working?
13th Oct 2019, 4:06 PM
Alessandro Palazzolo
Alessandro Palazzolo - avatar
0
i just gave him the answer he want it (The n variable should be "1011", but if I try to use it outside the For loop its value is only "1") ( already know that this is not the binary representation of 13 ) here is an improved solution to get the correct binary representation: #include <stdio.h> int main(){ int i = 13, n = 0, r = 0; for (;i > 0; i = i/2) { r = (r * 10) + i%2; } while(r) { n = (n * 10 ) + r % 10; r /= 10; } printf("n: %d", n); }
15th Oct 2019, 8:29 AM
MO ELomari
MO ELomari - avatar