fork download
  1. #include <stdio.h>
  2.  
  3. void decimalToBinaryWhile(int n) {
  4. if (n == 0) {
  5. printf("0");
  6. return;
  7. }
  8. int binaryNum[32]; // Array to store binary digits (32 bits is usually sufficient for an int)
  9. int i = 0;
  10.  
  11. // Use a while loop to get the remainders
  12. while (n > 0) {
  13. binaryNum[i] = n % 2; // Store the remainder
  14. n = n / 2; // Update the number by dividing by 2
  15. i++; // Increment index
  16. }
  17.  
  18. // Use a for loop to print the array in reverse order
  19. for (int j = i - 1; j >= 0; j--) {
  20. printf("%d", binaryNum[j]);
  21. }
  22. }
  23.  
  24. int main() {
  25. int number;
  26. printf("Enter a decimal number: ");
  27. scanf("%d", &number);
  28. printf("Binary equivalent: ");
  29. decimalToBinaryWhile(number);
  30. printf("\n");
  31. return 0;
  32. }
  33.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Enter a decimal number: Binary equivalent: 111111111111100