Exercise (Solutions)

E1

Write a program to print out all even numbers below 30.

E2

Create a program which takes a number as input from Scanner and prints out the complete Table Fact for that number from 1 to 10. If the input given is 7 then the program would print:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
: all the way till
7 x 10 = 70

E3

Write a program to print out if a given number as a program argument is a multiple of 6 or not.

Hint: The program arguments are always given to the main method as a String. Even an integer is given as a String type. So you need to convert the String to int type to do this exercise. So how to convert a String to int type? You can use Integer.parseInt(args[0])
The above statement converts any integer-string that is received in the 0th index of the args to an int type.

Refer to the Integer javadoc: https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#parseInt-java.lang.String-

E4

The sum of all even numbers below 10 is 2+4+6+8 = 20

Find the sum of all even numbers below 100. Write a program with a for or while loop to solve this problem.

E5

Write a guessing game. When the program starts, it picks a number in random between 20-50 and keeps it in memory and asks the user to guess a number. The user inputs a number between 20 and 50 both number inclusive. The system will print out the following hints to help the user win:

  • If the number the user input is below the number in memory by more than 10 then, print out "Your guess is too low. Try again."
  • If the number the user input is below the number in memory by equal to or less than 10 then, print out "Your guess is low. Try again."
  • If the number the user input is above the number in memory by more than 10 then, print out "Your guess is too high. Try again."
  • If the number the user input is above the number in memory by equal to or less than 10 then, print out "Your guess is high. Try again."

Once the user guesses the correct number, then print out "Congratulations, you guessed it right in " + the number of the times the user took to guess the number correctly.

Hint:

  • Have a while loop to keep asking the user to input values when the guess is not correct.
  • Find the difference between the user input number and the random number and then have a series of if blocks for each scenario
  • To generate a random number between an upper and lower limit, you could use:

int randomNumber = (int) (Math.random() * (upperlimit - lowerlimit)) + lowerlimit;

javadoc for Math: https://docs.oracle.com/javase/9/docs/api/java/lang/Math.html

results matching ""

    No results matching ""