Learn Java Easy. Chapter 5 Exercises

🔁 Java Loop Exercises Solved Step by Step | Topic 5

Topic 5 Exercises

Exercise 1. Create a program that shows multiples of 5 between numbers 0 and 100 using a for loop.

Solution:

public class Main {

      public static void main(String[] args) {

                //We create a for loop

                //i = 0 since it's our first value,

               //then we put 100 as maximum value.

              //Finally we add i++ to indicate that the value increases by one. for (int i = 0; i<=100; i++) {

              //Now we want to show 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 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 we 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 in steps of twenty and backwards 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 used to count or track the number of times the loop has executed. It helps decide when the loop should stop.

Exercise 4. Show numbers between 320 and 160 in steps of twenty and backwards 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 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 the loop can advance and eventually terminate.

Exercise 5. We create a program that asks for a password to open a suitcase. The password is 7678. If 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 = 7678;

              //We create a scanner since we'll have to enter data via keyboard.

              Scanner exercise = new Scanner(System.in);

              //We use a for to have 5 attempts.

              //We add i++ so attempts go one by one. 

               for (int i = 0; i<5; i++ ) {

                       System.out.println("Enter a password");

               //We enter 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

                       //So the program will close.

                                 System.exit(0);

                        } else System.out.println("Wrong 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 of 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 one is entered. (The negative number doesn’t count for the mean).

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 figure.

          int number = 0;

         //We create the mean variable. double mean =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 figure is greater than 0.

         while (number>=0) {

                   System.out.println("Enter a number"); 
                   number = exercise.nextInt();

         // This while takes into consideration all entered figures.

         // But the last one has negative value and we don't want to use it.

         // So we put an if to only count positive values.

                    if (number>=0) { totalData++;

                            totalSum = totalSum + number;

                    }

              }

              mean = totalSum/totalData; System.out.println("Total sum is = " + totalSum);

              System.out.println("The number of figures entered is "  + totalData);

              System.out.println("The mean is: = " + mean);

     }

}

Exercise 8. We create a program that shows the square and cube of the next 5 numbers after one 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 in which 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 quantity of even and odd numbers. int even = 0;

                 int odd =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 through an if, we make it add 1 to even or odd numbers

                       // It can be done in two ways. Adding ++ or doing: variable = variable +1

                          if (data%2==0) { 

                                even = even +1;

                          } else odd++;

                   }


                 //Now we simply show the total sum of both even and odd numbers.

                 System.out.println("Total even numbers: " + even);   
                 System.out.println("Total odd numbers: " + odd);

        }

}

Exercise 10. We complicate exercise 5 a bit. We create a program that asks for a password to open a suitcase. The password is 7678. If 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 it won’t count as an attempt.

Solution:

import java.util.Scanner; 

public class Main {

       public static void main(String[] args) {

              int password = 7678;

              int attemptsTried = 0;

              Scanner exercise = new Scanner(System.in);

               while (attemptsTried<5) { 

                       System.out.println("Enter a password");

                       int attempt = exercise.nextInt();

                       if (attempt > 999 && attempt < 100000 ) { 

                                attemptsTried ++;

                        }

                         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

                      //So 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 in which we enter a base and an exponent, and it 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 i.e. one multiplication.

            // When raising it to the cube we multiply base by base, by base. Two multiplications.

            // When raising it to 4, there are three operations. I.e. 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. We create a program in which we enter a number via keyboard and it tells us if it’s 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 inserted 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 the loop doesn’t execute indefinitely.

Exercise 14. Create a program that asks for two numbers. Then, show the numbers between them, starting with the first 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 currentData=numA;

              while (currentData<=numB) {

                      System.out.println(currentData); currentData += 7;

               }

       }

}

💡Use break and continue moderately: Use break to exit the loop early and continue to jump to the next iteration, but do so carefully to keep your code clear and understandable.

Exercise 15. Enter 10 numbers via keyboard and calculate the mean of odd numbers and the largest of 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 quantityOdds = 0; 
               int largestEvens = 0;

               for (int i=1; i <=10;i++) {

                    System.out.println("Enter number " + i); data = exercise.nextInt();

                     if (data%2!=0) { quantityOdds ++;

                    sumOdds = sumOdds +data;

                     } else

                     if (data>largestEvens ) { largestEvens = data;

                     }

                }

            System.out.println("The largest of the evens is " + largestEvens);    
            System.out.println("The mean of the odds is " + (sumOdds/quantityOdds));

      }

}   

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 figure is " + sum);

       }
  
}

Exercise 17. We create a program in which we enter a number via keyboard. Then, the program calculates all multiples of 3 up to that figure, adds them and shows 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 phrase = exercise.nextLine();

          System.out.print("Enter the character to count: "); 

          char letter = exercise.next().charAt(0);
    
           int counter = 0;

           for (int i = 0; i < phrase.length(); i++) { 

                  if (phrase.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 chain = exercise.nextLine(); int counter = 0;

              for (int i = 0; i < chain.length(); i++) {

                     char character = Character.toLowerCase(chain.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 terminate at an appropriate time to avoid infinite loops.

Did you like it? Don’t keep it to yourself — share it like juicy gossip! 😏