3 Introduction Ⅱ

Introduction Ⅱ

Objective

  • Write programs using different loop structures and techniques.

Exercise 1*

Write a program to print the sum of all numbers from 1 to 100.

Solution
Numbers.java
public class Numbers {
  public static void main(String[] args) {
    int limit = 100;
    int sum = 0;
    for (int number = 1; number <= limit; number += 1) {
      sum += number;
    }
    System.out.println("The sum of the numbers from 1 to " + limit + " is " + sum);
  }
}

Exercise 2*

Write a program to swap two variables.

Solution
Swap.java
public class Swap {
  public static void main(String[] args) {
    int a = 5;
    int b = 10;
 
    System.out.println("a is " + a);
    System.out.println("b is " + b);
 
    int temp = a;
    a = b;
    b = temp;
 
    System.out.println("a is " + a);
    System.out.println("b is " + b);
  }
}

Exercise 3*

Write a program to compute the sum of the digits of an integer.

Input an integer: 25
The sum of the digits is: 7
Solution
SumDigits.java
import java.util.Scanner;
 
public class SumDigits {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("Input an integer: ");
    int number = scanner.nextInt();
 
    int sum = 0;
    while (number > 0) {
      sum += number % 10;
      number /= 10;
    }
    System.out.println("The sum of the digits is: " + sum);
 
    scanner.close();
  }
}

Exercise 4

Write a program to print the integers between 1 to 100 which are divisible by 3, 5, and by both 3 and 5.

Divisible by 3:
3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99
 
Divisible by 5:
5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100
 
Divisible by 3 and 5:
15, 30, 45, 60, 75, 90
Solution
FizzBuzz.java
public class FizzBuzz {
  public static void main(String[] args) {
    int limit = 100;
 
    System.out.println("Divisible by 3:");
    boolean first = true;
    for (int number = 1; number <= limit; number += 1) {
      if (number % 3 == 0) {
        if (first) {
          first = false;
        } else {
          System.out.print(", ");
        }
        System.out.print(number);
      }
    }
    System.out.println();
 
    System.out.println();
    System.out.println("Divisible by 5:");
    first = true;
    for (int number = 1; number <= limit; number += 1) {
      if (number % 5 == 0) {
        if (first) {
          first = false;
        } else {
          System.out.print(", ");
        }
        System.out.print(number);
      }
    }
    System.out.println();
 
    System.out.println();
    System.out.println("Divisible by 5:");
    first = true;
    for (int number = 1; number <= limit; number += 1) {
      if (number % 3 == 0 && number % 5 == 0) {
        if (first) {
          first = false;
        } else {
          System.out.print(", ");
        }
        System.out.print(number);
      }
    }
    System.out.println();
  }
}

Exercise 5

Write a program that accepts four integers from the user and prints equal if all four are equal, and not equal otherwise.

Input first number: 25
Input second number: 37
Input third number: 45
Input fourth number: 23
Numbers are not equal!
Solution
AllEqual.java
import java.util.Scanner;
 
public class AllEqual {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("Input first number: ");
    int a = scanner.nextInt();
 
    System.out.print("Input second number: ");
    int b = scanner.nextInt();
 
    System.out.print("Input third number: ");
    int c = scanner.nextInt();
 
    System.out.print("Input fourth number: ");
    int d = scanner.nextInt();
 
    if (a == b && b == c && c == d) {
      System.out.println("Numbers are equal!");
    } else {
      System.out.println("Numbers are not equal!");
    }
 
    // if (a != b || b != c || c != d) {
    //   System.out.println("Numbers are not equal!");
    // } else {
    //   System.out.println("Numbers are equal!");
    // }
 
    scanner.close();
  }
}

Exercise 6

Write a program that requests the user to type the time in seconds and displays it in the standard format of hours:minutes:seconds.

Time in seconds: 3725
The time is 01:02:05
Solution
TimeFormat.java
import java.util.Scanner;
 
public class TimeFormat {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int time = scanner.nextInt();
 
    int hours = time / 60 / 60;
    int minutes = time / 60 % 60;
    int seconds = time % 60;
 
    System.out.printf("%02d:%02d:%02d\n", hours, minutes, seconds);
 
    scanner.close();
  }
}

Exercise 7

Write a program that prompts for two numbers then prints the sum, difference, product, and quotient of those numbers as shown in the following sample output:

What is the first number? 10
What is the second number? 5
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2

The values received from the user will be strings. Ensure that you convert these values to numbers before doing the computation.

Solution
TwoNumbers.java
import java.util.Scanner;
 
public class TwoNumbers {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("What is the first number? ");
    int first = Integer.parseInt(scanner.next());
 
    System.out.print("What is the second number? ");
    int second = Integer.parseInt(scanner.next());
 
    System.out.println(first + " + " + second + " = " + (first + second));
    System.out.println(first + " - " + second + " = " + (first - second));
    System.out.println(first + " * " + second + " = " + (first * second));
    System.out.println(first + " / " + second + " = " + (first / second));
 
    scanner.close();
  }
}

Exercise 8

Write a program to evenly divide pizzas. Prompt for the number of people, the number of pizzas, and the number of slices per pizza. Ensure that the number of pieces comes out even. Display the number of pieces of pizza each person should get. If there are leftovers, show the number of leftover slices.

How many people? 8
How many pizzas do you have? 2
How many slices per pizza? 8
8 people with 2 pizzas.
Each person gets 2 slices of pizza.
There are 0 leftover slices.
Solution
PizzaSlices.java
import java.util.Scanner;
 
public class PizzaSlices {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("How many people? ");
    int people = scanner.nextInt();
 
    System.out.print("How many pizzas do you have? ");
    int pizzas = scanner.nextInt();
 
    System.out.print("How many slices per pizza? ");
    int slices = scanner.nextInt();
 
    int totalSlices = pizzas * slices;
    int slicesPerPerson = totalSlices / people;
    int leftoverSlices = totalSlices % people;
 
    System.out.printf("%d people with %d pizzas.%n", people, pizzas);
    System.out.printf("Each person gets %d pieces of pizza.%n",
                      slicesPerPerson);
    System.out.printf("There are %d leftover pieces.%n", leftoverSlices);
 
    scanner.close();
  }
}

Exercise 9

Write a program that generates multiplication tables for the numbers 0 through 12, using a nested loop.

0 * 0 = 0
0 * 1 = 0
...
12 * 11 = 132
12 * 12 = 144
Solution
MultiplicationTable.java
public class MultiplicationTable {
  public static void main(String[] args) {
    for (int i = 0; i <= 12; i++) {
      for (int j = 0; j <= 12; j++) {
        System.out.printf("%d * %d = %d%n", i, j, i * j);
      }
    }
  }
}

Exercise 10+

Write a program that takes two integer points from the user (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2) then calculates the distance between them using the formula:

distance=(x2x1)2+(y2y1)2\begin{align*} \text{distance} &= \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} \end{align*}
Enter 4 integer values for (x1, y1) and (x2, y2) respectively: 4 2 7 4
Distance between (4, 2) and (7, 4) is 3.61.
Solution
Distance2D.java
import java.util.Scanner;
 
public class Distance2D {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print(
        "Enter 4 integer values for (x1, y1) and (x2, y2) respectively: ");
    int x1 = scanner.nextInt();
    int y1 = scanner.nextInt();
    int x2 = scanner.nextInt();
    int y2 = scanner.nextInt();
 
    double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    System.out.printf("Distance between (%d, %d) and (%d, %d) is %.2f.%n", x1,
                      y1, x2, y2, distance);
 
    scanner.close();
  }
}

Exercise 11+

Write a program that keeps accepting numbers from the user until -1 is entered. The program then calculates the number of entered values, their sum, and their average. Format your output to show the average to 2 decimal places.

Enter a positive value or -1 to quit: 9
Enter a positive value or -1 to quit: 5
Enter a positive value or -1 to quit: 6
Enter a positive value or -1 to quit: 3
Enter a positive value or -1 to quit: 1
Enter a positive value or -1 to quit: -1
You entered 5 numbers. The sum is 24 and the average is 4.80.
Solution
LoopingAverage.java
public class LoopingAverage {
  public static void main(String[] args) {
    java.util.Scanner scanner = new java.util.Scanner(System.in);
 
    int sum = 0;
    int count = 0;
    int number = 0;
 
    System.out.print("Enter a positive value or -1 to quit: ");
    number = scanner.nextInt();
    while (number != -1) {
      sum += number;
      count += 1;
 
      System.out.print("Enter a positive value or -1 to quit: ");
      number = scanner.nextInt();
    }
 
    if (count > 0) {
      System.out.printf(
          "You entered %d numbers. The sum is %d and the average is %.2f.%n",
          count, sum, (double)sum / count);
    } else {
      System.out.println("You didn't enter any numbers.");
    }
 
    scanner.close();
  }
}