Untitled Document
Here are some practice programming problems. These are considerably simpler than the programs we write in the labs. These are not to be handed in, though you should feel free to ask questions about any of them outside of class. All of these ask for some input from the user. You should download the SimpleInput.java file, and use it as we did in class:
SimpleInput keyboard = new SimpleInput();
......int value = keyboard.nextInt();
Programs with if-statements:
- Write a program that reads two integers from the user and prints the smaller
of these. Do this by writing a method called
int min(int x, int y) that returns the smaller of its two arguments. If you are uncertain how to get started, you can download the following file, which has everything you need except for method min(). - If you had trouble getting started with (1.) and downloaded my file, write on your own a similar program that reads two integers and prints their product.
- Write a similar program that reads three integers and prints the smallest of these. Be careful with the logic here.
Programs with loops:
- Write a program that reads a number N and prints the numbers 1, 2, 3, up to N three times. The first time should use a while-loop, the second a do-loop and the third a for-loop.
- Write a program that reads a number N and prints the first N prime numbers. One thing your program will need is a method boolean isPrime(int x) that determines whether its argument is prime, and returns either true or false. We did this in class so if you are really stuck you can look back in your notes or in the programs I posted on February 23, but it would be better to work it out on your own. Note that in this version you need to count the primes as you find them: if N is 10, for example, you want to find the first 10 prime numbers rather than the prime numbers less than 10. A correct program for this will print 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 when you give it a value 10 for N.
- Write a program that reads in two integers and prints the largest number that divides evenly into both. In some math class you probably called this the "greatest common divisor" of the numbers.