Chapter 5 Exercises
Exercise 1. Create a program that shows multiples of 5 between the numbers 0 and 100 using a for loop.
Solution:
public class Main {
public static void main(String[] args) {
//Create a for loop
//i = 0 since it's our first value,
//then we put 100 as the maximum value.
//Finally we add i++ to indicate that the value increases by 1.
for (int i = 0; i<=100; i++) {
//Now we want to show the numbers that are multiples of 5.
//So we add an if.
if (i%5==0) {
System.out.println(i);
}
}
}
}
Exercise 2. Create a program that shows multiples of 5 between the numbers 0 and 100 using a while loop.
Solution:
public class Main {
public static void main(String[] args) {
//It's necessary to create the variable before writing the while loop.
int i=0;
//Now let's go with the while loop.
//While the value is less than or equal to 100, our program will execute
while (i<=100) {
//We use an if to show only multiples of 5.
if (i%5==0) {
System.out.println(i);
}
// We use i++ so our variable increases by one.
i++;
}
}
}
Exercise 3. Show numbers between 320 and 160 counting down by twenty using a for loop.
Solution:
public class Main {
public static void main(String[] args) {
for (int i =320; i>=160; i-- ) {
if (i%20==0){
System.out.println(i);
}
}
}
}
π‘ Initialize the control variable: The control variable in a Java loop is a variable that is used to count or keep track of the number of times the loop has executed. It helps decide when the loop should stop.
Exercise 4. Show numbers between 320 and 160 counting down by twenty using a while loop.
Solution:
public class Main {
public static void main(String[] args) {
int i = 320;
while (i>=160) {
if (i%20==0) {
System.out.println(i);
}
i--;
}
// In this case we have placed i-- below the if line
// This is because the program reads from top to bottom.
// If we had placed i-- before the if, the first value considered would be 319.
// Therefore we would have lost the value 320
}
}
π‘ Update the control variable: Modify the control variable in each iteration so that the loop can advance and eventually end.
Exercise 5. Create a program that asks for a password to open a suitcase. The password is 7678. If it’s correct, it opens. But if after 5 attempts it’s not achieved, it locks.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// First we create our password.
int password = ****;
//We create a scanner since we'll have to input data via keyboard.
Scanner exercise = new Scanner(System.in);
//We use a for to have 5 attempts.
//We add i++ so the attempts go one by one.
for (int i = 0; i<5; i++ ) {
System.out.println("Enter a password");
//We input data via keyboard
int attempt = exercise.nextInt();
//Now we use our conditional.
if (attempt == password) {
System.out.println("Suitcase opened");
//It's necessary to put a System.exit if we guess the password correctly
//This way the program will close.
System.exit(0);
} else System.out.println("Incorrect data");
}
//Outside the loop, after the five attempts, we add the following line:
System.out.println("You ran out of attempts");
}
}
Exercise 6. Create a program that shows the multiplication table for 8.
Solution using for:
public class Main {
public static void main(String[] args) {
for (int i=1; i<=10; i++ ) {
System.out.println(i +" x " + 8 + " = " + (i*8));
}
}
}
Solution using while:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i<10) {
i++;
System.out.println(i +" x " + 8 + " = " + (i*8));
}
}
}
Exercise 7. Create a program that calculates the arithmetic mean of numbers entered via keyboard until a negative number is entered. (The negative number doesn’t count for the average).
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner(System.in);
//The arithmetic mean is the division of the total sum by the number of values.
//So we're going to create two variables.
double totalSum = 0;
double totalData = 0;
//We need to create a variable that holds the value each time we enter a number.
int number = 0;
//We create the average variable.
double average = 0;
//We assign zero value to all variables since that's what they're worth for now.
//We create the while only for when our entered number is greater than 0.
while (number>=0) {
System.out.println("Enter a number");
number = exercise.nextInt();
// This while considers all entered numbers.
// But the last one has negative value and we don't want to use it.
// So we put in an if to only count positive values.
if (number>=0) {
totalData++;
totalSum = totalSum + number;
}
}
average = totalSum/totalData;
System.out.println("Total sum is = " + totalSum);
System.out.println("The number of digits entered is " + totalData);
System.out.println("The average is: = " + average);
}
}
Exercise 8. Create a program that shows the square and cube of the 5 numbers following a number entered via keyboard.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner(System.in);
System.out.println("Enter a number");
int number = exercise.nextInt();
//We use a for. The first value is number +1.
// The last value should be less than or equal to number +5
for (int i= number +1; i<=number+5;i++) {
System.out.println("The number is: " + i + ", its square is " + i*i + ", the cube is " + i*i*i);
}
}
}
Exercise 9. Create a program where we enter 10 numbers via keyboard and it tells us how many are even and how many are odd.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
// We create two variables to count the number of even and odd numbers.
int evens = 0;
int odds = 0;
// We create a for loop that allows us to enter ten data points
for (int i= 0; i<10;i++) {
System.out.println("Enter a number");
int data = exercise.nextInt();
// Now using an if, we make it add 1 to either evens or odds
// It can be done in two ways. Adding ++ or doing: variable = variable +1
if (data%2==0) {
evens = evens +1;
} else odds++;
}
//Now we simply show the total sum of both even and odd numbers.
System.out.println("Total even numbers: " + evens);
System.out.println("Total odd numbers: " + odds);
}
}
Exercise 10. We make exercise 5 a bit more complicated. Create a program that asks for a password to open a suitcase. The password is 7678. If it’s correct, it opens. But if after 5 attempts it’s not achieved, it locks. If you enter a number with more or less than 4 digits, the program will tell you that the password must have 4 digits and won’t count it as an attempt.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int password = ****;
int attemptsUsed = 0;
Scanner exercise = new Scanner(System.in);
while (attemptsUsed<5) {
System.out.println("Enter a password");
int attempt = exercise.nextInt();
if (attempt > 999 && attempt < 100000 ) {
attemptsUsed ++;
}
if (attempt <= 999 || attempt >= 100000 ) {
System.out.println("The password must have four digits");
}else
//Now we use our conditional.
if (attempt == password) {
System.out.println("Suitcase opened");
//It's necessary to put a System.exit if we guess the password correctly
//This way the program will close.
System.exit(0);
} else System.out.println("Incorrect password");
}
//Outside the loop, after the five attempts, we add the following line:
System.out.println("You ran out of attempts");
}
}
Exercise 11. Create a program where a base and an exponent are entered, and that shows the result.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.println("Enter the base");
int base = exercise.nextInt();
System.out.println("Enter the exponent");
int exponent = exercise.nextInt();
//We also create a result variable that for now has the same value as the base.
int result = base;
// When we raise something to the square we multiply base by base, so one multiplication.
// When raising it to the cube we multiply base by base by base. Two multiplications.
// When raising it to 4, it's three operations. So always one less than the exponent.
// Therefore this will be our for.
for (int i = 0; i<exponent -1;i++) {
result = result*base;
}
System.out.println("The result is " + result);
}
}
Exercise 12. Create a program where we enter a number via keyboard and it tells us whether it is prime or not.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.println("Enter a number");
int num = exercise.nextInt();
//A prime number is one that can only be divided by 1 and itself.
//Therefore we're going to make a loop with an int i, that goes one by one.
//From 1 to the number itself.
//We make our number divide by i each time
//We create an int counter.
//Each time our number is divisible by i, the counter will add 1.
//If the counter is 2 it means it's divisible by 1 and itself. Prime.
//If the counter is greater than two then it won't be prime.
int counter = 0;
for (int i = 1; i<=num; i++) {
if(num%i==0) {
counter++;
}
}
if (counter <=2) {
System.out.println ("It's prime");
} else System.out.println ("It's not prime");
}}
Exercise 13. Create a program that adds the next 100 numbers to a number entered via keyboard.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.println("Enter a number");
int num = exercise.nextInt();
int sum = 0;
for (int i = num+1; i<=num+100;i++) {
System.out.println(i);
sum = sum+i;
}
System.out.println("The total sum is " + sum);
}
}
π‘ Avoid infinite loops: Verify that the loop condition will change at some point so that the loop doesn’t run indefinitely.
Exercise 14. Create a program that asks for two numbers. Then, show the numbers between them, starting with the first one and advancing by 7.
Solution using for:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.println("Enter number a");
int numA = exercise.nextInt();
System.out.println("Enter number b");
int numB = exercise.nextInt();
for (int i = numA; i<=numB;i+=7) {
System.out.println(i);
}
}
}
Solution using while:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.println("Enter number a");
int numA = exercise.nextInt();
System.out.println("Enter number b");
int numB = exercise.nextInt();
int currentValue=numA;
while (currentValue<=numB) {
System.out.println(currentValue);
currentValue += 7;
}
}
}
π‘ Use break and continue in moderation: Use break to exit the loop early and continue to skip to the next iteration, but do it carefully to keep your code clear and understandable.
Exercise 15. Enter 10 numbers via keyboard and calculate the average of odd numbers and the largest of the even numbers.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
int data;
double sumOdds = 0;
double numberOfOdds = 0;
int largestEven = 0;
for (int i=1; i <=10;i++) {
System.out.println("Enter number " + i);
data = exercise.nextInt();
if (data%2!=0) {
numberOfOdds ++;
sumOdds = sumOdds + data;
} else
if (data>largestEven ) {
largestEven = data;
}
}
System.out.println("The largest even number is " + largestEven);
System.out.println("The average of odd numbers is " + (sumOdds/numberOfOdds));
}
}
Exercise 16. Program that asks for numbers until the sum is 1000. Then, show that sum on the screen.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
int sum = 0;
while (sum < 1000) {
System.out.println("Enter a number");
int data = exercise.nextInt();
sum = sum + data;
}
System.out.print("The final amount is " + sum);
}
}
Exercise 17. We create a program where we enter a number via keyboard. Then, the program calculates all multiples of 3 up to that number, adds them up, and displays the result on the screen.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.println("Enter a number");
int num = exercise.nextInt();
int sum = 0;
for (int i=1;i<=num;i++){
if (i%3==0) {
System.out.println(i);
sum = sum+i;
}
}
System.out.println("The total sum is " + sum);
}
}
Exercise 18. Create a program that shows all numbers from 1 to 1000 that are not multiples of the number entered via keyboard.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.println("Enter the multiple");
int multiple = exercise.nextInt();
for (int i=1;i<=1000;i++) {
if (i%multiple!=0) {
System.out.println(i + " is not a multiple of " + multiple );
}
}
}
}
Exercise 19. Write a program that asks the user for a text string and a specific character, then counts and shows how many times that character appears in the string.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.print("Enter a text string: ");
String sentence = exercise.nextLine();
System.out.print("Enter the character to count: ");
char letter = exercise.next().charAt(0);
int counter = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == letter) {
counter++;
}
}
System.out.print("The number of times repeated is " + counter);
}
}
Exercise 20. Create a program that counts the vowels in a phrase entered via keyboard.
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exercise = new Scanner (System.in);
System.out.println("Enter the phrase");
String string = exercise.nextLine();
int counter = 0;
for (int i = 0; i < string.length(); i++) {
char character = Character.toLowerCase(string.charAt(i));
if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') {
counter++;
}
}
System.out.println(counter);
}
}
π‘ Define a clear exit condition: Establish a condition that allows the loop to end at an appropriate time to avoid infinite loops.