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, what happened?
for(i=i-1; i>=0; i--) {
printf("%d", BinArray[i]);
}
return 0;
}
CodePudding user response:
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]);
}
CodePudding user response:
In the first loop, num reduced by half for every step, so it became smaller and smaller, but the index i became bigger and bigger, so the bits were ordered from high (starting at index 0) to low. In the second loop, the index started at big and reduced to 0, so the bits were printed out from low (left) to high (right). If you want to print out the bits from high to low, you need to start the index at 0 for the second loop and increase it to the last bit position, as below.
for(num = 0; num < i; num ) { /* assume num will not be used again */
printf("%d", BinArray[num]);
}