Teacher’s Notes:
=======================================
You can offer this problem in your beginner course. If you do, it will probably connect to the first two modules above. I offer this problem when my students transition to learning JAVA so I count it towards Second Language Programming and Procedural Programming.
My solution below is somewhat condensed but can be expanded. For instance:
while(Math.pow(2,exponent++) <= number);
could be expressed as:
while(Math.pow(2,exponent) <= number);
exponent++;
This might be a good time to cover the CS order of operations if you haven't already.
Assignment:
=======================================
Binary Numbers Printer
Write a program that will prompt the user to enter a single base 10 number as a positive integer. After the user enters the number, the program will call a method that prints the binary representation of that number.
You can find a video explaining how the binary number system works at: https://www.youtube.com/watch?v=VI_oVXp9NWg
Sample Input 1:
Enter a number: 123
Sample Output 1:
Binary Version: 1111011
Sample Input 2:
Enter a number: 256
Sample Output 2:
Binary Version: 100000000
Solution (JAVA):
=======================================
import java.util.Scanner;
public class BinaryNumberMaker {
public static void printBinaryNumber(int number) {
//first find out the highest power of 2 that is just over this number
int exponent = 0;
while(Math.pow(2,exponent++) <= number);
exponent--;
while(exponent > 0)
if(Math.pow(2, --exponent) <= number) {
System.out.print("1");
number -= Math.pow(2,exponent);
}
else
System.out.print("0");
System.out.println();
}
public static void main(String[] args) {
System.out.print("Enter a number: ");
int base10Number = new Scanner(System.in).nextInt();
System.out.print("Binary Version: ");
printBinaryNumber(base10Number);
}
}