Exercise (Solutions)

E1

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

E2

Create different versions of a program that finds all the primes below 100. Create one version that uses the naive approach and another version that uses Sieve of Eratosthenes. It is enough to print out just the number of primes below 100. However make sure you have coded in such a way that 100 can be replaced by 1000 or 9999 or any other number and your program still works.

E3

Create a program which takes a number as input from Scanner and prints out the complete Fact for that number from 1 to 10. The program should have a main method which calls generateFacts method which takes a number as input and outputs the facts as Array of integers.
The main method will iterate over the returned array and prints it on to the console.

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

E8

Write a console program to define and initialize a variable of type byte to 1 and then successively multiply it by 2 and display its value 8 times. Explain the reason for the last result.

E9

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: 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 ""