The purpose of the program: Convert a decimal number into a binary number.
My Question: How does the for loop work here printing the elements in reverse in the array? What does for(i=i-1; i>=0; i--) mean?
(I would also appreciate it, if you give me some feedback about my code, and how to make it look good and better, Thanks!)
#include <stdio.h>
int main()
{
int i;
int num;
int BinArray[32];
printf("Enter a decimal number: ");
scanf("%d", &num);
for(i=0; num>0; i++){
if(num % 2 == 0)
BinArray[i] = 0;
else
BinArray[i] = 1;
num = num / 2;
}
// I don't understand how it prints the binary numbers in reverse
// (from right to left); what happened?
for(i=i-1; i>=0; i--) {
printf("%d", BinArray[i]);
}
return 0;
}
>Solution :
The variable i contains the number of elements entered in this loop
for(i=0; num>0; i++){
if(num % 2 == 0)
BinArray[i] = 0;
else
BinArray[i] = 1;
num = num / 2;
}
because after assigning a new value to an element of the array BinArray the variable i is incremented in the for loop i++.
So i - 1 points to the last element of the array BinArray. Starting from this last element up to the element with the index equal to 0 (because the variable i is decremented i--) all elements of the array are outputted in this for loop
for(i=i-1; i>=0; i--) {
printf("%d", BinArray[i]);
}