+ 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?
4 Réponses
+ 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);
}
+ 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 👍
0
Mohamed ELomari why is that working?
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);
}