In today’s class we have learnt about comparisons and sorting. The following practice help me go through the knowledge I absorbed. And this set of exercise reinforce my knowledge in dealing with nested loops and control embedded in loops.
Code 1
The first code is about finding the maximum and the minimum in an input array. It can be used in finding the most remarkable value for different data. Trace Table on Class Website.
import java.util.*;
public class Practice4 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] myArray=new int [1000];
System.out.print("Please tell me how much number you
are going to put in:");
int n;
n=input.nextInt();
for(int i=0;i<n;i++){
myArray[i]=input.nextInt();
}
int max=myArray[0];
int min=max;
for(int i=0;i<n;i++){
if(myArray[i]>max){
max=myArray[i];
}
if(myArray[i]<min){
min=myArray[i];
}
}
System.out.println("The maximum number is "+max+".");
System.out.println("The mainimum number is "+min+".");
}
}
Input & Output
Flowchart
Code 2
The second code is used to calculate the average for a group of numbers. It can be used to find out the average for a large amount of data. Trace Table on Class Website.
import java.util.*;
public class Practice5 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int num=0,total=0,count=0;
for(;num>=0;){
System.out.println("Please enter a number which is
greater or equal to 0 in order to calculate the
average:");
num=input.nextInt();
if(num>=0){
total+=num;
count++;
}
}
System.out.println("The average is "+total/count+".");
}
}
Input & Output
Flowchart
Code 3
The third code is about sorting an array. It can be used to arrange a group of data from the largest to the smallest or the smallest to the largest. Trace Table on Class Website.
import java.util.*;
public class Practice6 {
public static void main(String[] args){
int num[] ={15,30,25,85,40,90,50,65,20,60};
int temp;
System.out.println("Before sorting:");
for(int i=0;i<=9;i++){
System.out.print(num[i]+" ");
}
for(int i=0;i<=8;i++){
for(int j=0;j<=8;j++){
if(num[j]<num[j+1]){
temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
System.out.println();
System.out.println("After sorting:");
for(int i=0;i<=9;i++){
System.out.print(num[i]+" ");
}
}
}
Input & Output
Flowchart