Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can someone explain me how the for loop reverses the elements in the array?

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!)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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]);
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading