27.7k views
3 votes
write a program that takes in a positive integer as input, and output a string of 1's and 0's representing the integer in binary. for an integer x; the algothm is as long as x is greater than 0 output x % (remainder is either 0 or 1 . x=x/2 in coral language

User Btevfik
by
5.0k points

2 Answers

3 votes

Here's a Python program that converts a positive integer to its binary representation:

The Code

def decimal_to_binary(num):

binary = ""

while num > 0:

remainder = num % 2

binary = str(remainder) + binary

num //= 2

return binary if binary else "0"

# Taking input from the user

number = int(input("Enter a positive integer: "))

binary_representation = decimal_to_binary(number)

print(f"The binary representation of {number} is: {binary_representation}")

This program defines a function decimal_to_binary that converts a positive integer into its binary representation by iteratively dividing the number by 2 and appending the remainders (0s or 1s) to form the binary string

User Gmlime
by
5.0k points
7 votes

Answer: Provided in the explanation section

Step-by-step explanation:

The full questions says:

write a program that takes in a positive integer as input, and output a string of 1's and 0's representing the integer in binary. for an integer x; the algothm is as long as x is greater than 0 output x % (remainder is either 0 or 1 . x=x/2 in coral language. Note: The above algorithm outputs the 0's and 1's in reverse order.

Ex: If the input is:

6

the output is:

011

CODE:

#include <stdio.h>

int main() {

int n;

scanf("%d", &n);

while (n > 0) {

printf("%d", n % 2);

n /= 2;

}

printf("\\");

return 0;

}

2

#include <stdio.h>

int main() {

int n;

scanf("%d", &n);

while (n > 0) {

printf("%d", n % 2);

n /= 2;

}

return 0;

}

cheers i hope this helped !!

User Sekou
by
4.6k points