These are questions that came from the course managed by RoboProf. Some of the pictures aren't available, but the questions should be understandable regardless.
| Here is an example of a RobotWorld. It's very simple, containing a wall of three cells starting at coordinates 19, 0 and going north (up the diagram). (The wall is in the lower right corner of the world.) | ![]() |
This was created by the following program, ShortWall.java.
public class ShortWall extends RobotWorld
{
public void setWorld()
{
wall(19, 0, "north", 3);
}
}
|
The instruction wall(19, 0, "north", 3) contains four arguments. These arguments vary the effect of the instructions. The first two arguments 19 and 0 specify the starting cell. The next argument, "north" is surrounded in quotes and specifies the direction (north/up) and the final argument specifies the length of the wall. Note that this instruction is exactly equivalent to
wall(19, 2, "south", 3);I.e. a wall starting at cell (19,2) and going down three squares will obviously be the same as a wall starting at (19,0) and going up three squares. The following two instructions also create the same wall.
wall(19, 0, "north", 1); wall(19, 1, "north", 2);By choosing the arguments appropriately, you can place a wall wherever you please. Experiment by changing the arguments and observing the effects.
| Adapt the program so that it creates a wall going east from coordinates 7, 6 for two cells. It should look like the RobotWorld on the right. N.B. the name of the class must match the name of the file, e.g. if your class is called EastWall the file must be called EastWall.java | ![]() |
When you have adapted the program, follow the instructions to compile and run it. When it is working, submit it. (Press the submit button and select the program file.) It will then be automatically marked. (The marking program may take a few minutes.)
This RobotWorld contains a square wall surrounding a beeper.
The beeper is represented by an orange circle and is placed at cell
(4,16) using the command beeper(4,16)The program WallRoundBeeper.java (see below) created this world |
![]() |
public class WallRoundBeeper extends RobotWorld
{
public void setWorld()
{
wall(2, 18, "east", 4); // topmost wall
wall(6, 18, "south", 4); // rightmost wall
wall(6, 14, "west", 4); // bottom wall
wall(2, 14, "north", 4); // left wall
// Now place a beeper in the centre
beeper(4, 16);
}
}
|
| Adapt the program (or write a new program) so that it creates a wall that surrounds four beepers as shown in the RobotWorld on the right. | ![]() |
| In this example a robot is created (the blue 'V' shape at coordinates 2, 2). If you compile and run the program (MoveRobot.java below) you will see the world to the right. | ![]() |
If you now press the run button (or press the step button many times) you will see the robot execute the instructions in the run() method and end up (see diagram). | ![]() |
public class MoveRobot extends RobotWorld
{
public void setWorld()
{
MovingRobot jim = new MovingRobot(); // create a new robot
// place it in the world at location 2, 2 facing east.
jim.place(2, 2, "east");
}
}
class MovingRobot extends Robot
{
public void run()
{
move();
move();
turnLeft();
move();
move();
turnOff();
}
}
|
When you run the program and press the run button, the run() method starts. The six instructions are carried out one after the other until the robot finishes. Note that the path that the robot takes is indicated by the red dots.
| Adapt the program so that the robot starts at location 4, 8 facing north. Use the same run() method. Where will the robot end up? |
public class OneWorld extends RobotWorld
{
public void setWorld()
{
LongRobot jane = new LongRobot(); // create a new robot
jane.place(5, 14, "south");
}
}
class LongRobot extends Robot
{
public void run()
{
turnLeft();
turnLeft();
turnLeft();
turnLeft();
move();
move();
turnOff();
}
}
|
public class SixWorld extends RobotWorld
{
public void setWorld()
{
wall(3, 14, "east", 5);
wall(3, 13, "south", 5);
wall(4, 9, "east", 4);
wall(5, 11, "east", 3);
wall(7, 10, "east", 1); // direction irrelevant when length is one.
}
}
|
public class BeeperWorld extends RobotWorld
{
public void setWorld()
{
wall(3, 14, "east", 5);
wall(3, 13, "south", 5);
wall(4, 9, "east", 4);
wall(5, 11, "east", 3);
wall(7, 10, "east", 1);
beeper(0,0);
Beep beepCatcher = new Beep();
beepCatcher.place(0, 4, "south");
}
}
class Beep extends Robot
{
public void run()
{
// First move to where the beeper is
move();
move();
move();
move();
pickBeeper(); // pick up the beeper
// Turn around
turnLeft();
turnLeft();
// Move up
move();
move();
putBeeper(); // drop the beeper at this cell.
// turn right
turnLeft();
turnLeft();
turnLeft();
move();
turnLeft();
turnOff();
}
}
|
Remember to divide the problem into more manageable subtasks.
public class FieldOBeepers extends RobotWorld
{
public void setWorld()
{
// create a rectangle of beepers
beeper(10,4);
beeper(11,4);
beeper(12,4);
beeper(13,4);
beeper(14,4);
beeper(10,5);
beeper(11,5);
beeper(12,5);
beeper(13,5);
beeper(14,5);
beeper(10,6);
beeper(11,6);
beeper(12,6);
beeper(13,6);
beeper(14,6);
beeper(10,7);
beeper(11,7);
beeper(12,7);
beeper(13,7);
beeper(14,7);
beeper(10,8);
beeper(11,8);
beeper(12,8);
beeper(13,8);
beeper(14,8);
Harvester fred = new Harvester();
fred.place(9, 4, "east");
}
}
class Harvester extends Robot
{
public void run()
{
}
}
|
N.B. your robot should finish ready to consume another row of beepers at square (9, 9).
Note that you should only supply the Robot class, the RobotWorld will be supplied by RoboProf.
public class Bouncer extends Robot
{
public void run()
{
// First move to an obstruction
while(frontIsClear())
move();
// turn around
turnLeft();
turnLeft();
// move forward two squares
move();
move();
turnOff();
}
}
|
NB you should submit a class that extends Robot (not RobotWorld). You can test your program by creating a Tester class that extends RobotWorld and has a setWorld() method that creates a new instance of your class and then places it in the world.
Note that your program will be tested by putting it into one or more unknown worlds and observing where it ends up.
If the robot reaches an obstruction and there's a beeper present, then it should stay there.
Give the Robot a run() method that will locate the beeper, pick it up and then bring it home (to the origin). You should leave the robot facing north.
Hints
public boolean wallToLeft()
{
turnLeft(); // turn to face the potential wall
if(frontIsClear()) // is there a wall there?
{
turnRight(); // go back to where we were
return false; // indicate that there was no wall
}
else // ... otherwise
{
turnRight();// go back to where we were
return true; // there is a wall.
}
}
|
This method can now be used to check if a robot has a wall to its left. (Note you'll also have to define the turnRight method for this to work.)
The following Robot has a run method that hugs a wall as long the way in front is clear.
public class WallHugger extends Robot
{
public void run()
{
// this while statement uses the logical AND
// operator to check two conditions at once
while(frontIsClear() && wallToLeft())
move();
turnOff();
}
}
|
| Hi There |
Here are some hints to help you create the program:
// Hello.java
// written by CDaly
public class Hello
{
public static void main(String [] args)
{
System.out.println("Hello");
}
}
|
e.g. A sample run would look like
Enter a number: 4 4 doubled is 8In this case the user entered 4, the computer doubled it to get 8 and printed the answer.
Here is an example program that reads a number from the keyboard and prints three times that number. Note that the Console class is used to read from the keyboard. To use the Console class, you should set the CLASSPATH to be G:\lang\java\classes\;..
// Input.java
// written by CDaly
public class Input
{
public static void main(String [] args)
{
System.out.print("Enter a number: ");
int n = Console.readInt();
System.out.println(n + " trebled is " + 3 * n);
}
}
|
| // Declare y | |
| int y; | |
| y = 5; | |
| y = 7; | |
| y = y + 3; |
| // Declare the variables | |||
| int x; | |||
| int y; | |||
| int sum; | |||
| x | y | sum | |
|---|---|---|---|
| x = 5; | |||
| y = x + 7; | |||
| y = y + x; | |||
| sum = x * 3 + y; | |||
I said "No".Note that in order to print a double quote you have to use a backslash in front it (\").
| // Declare the variables | |||
| int x; | |||
| int y; | |||
| x | y | ||
|---|---|---|---|
| x = -7; | |||
| x = x + 3; | |||
| y = 3 - 5 * x; | |||
| y = (3 - 5 * x) % 2; | |||
| y = (3 - 5 * x) / (y + 2); | |||
e.g. If the user enters 5, the program should print
1
// PassFail.java
// This program prints out "Pass" or "Fail" depending on the value of mark
public class PassFail
{
public static void main(String [] args)
{
int mark;
System.out.print("Enter a mark: ");
mark = Console.readInt();
if(mark >= 40)
System.out.print("Pass");
else
System.out.print("Fail");
}
}
|
You must write a program that asks the user for a mark and if the mark is greater than or equal to 55, then print "Honour" otherwise print "Not an honour"
E.g. a sample session might be
Enter a mark: 70 Honourthe other case would be
Enter a mark: 40 Not an honour
| Mark | 85 to 100 | 70 to 84 | 55 to 69 | 40 to 54 | 0 to 39 |
|---|---|---|---|---|---|
| Grade | A | B | C | D | F |
The program Grade.java takes a mark and converts it to the appropriate grade.
// Grade.java
// This program gets a mark from the user and prints the corresponding grade
public class Grade
{
public static void main(String [] args)
{
int mark;
char grade;
System.out.print("Enter a mark: ");
mark = Console.readInt();
if(mark >= 85)
grade = 'A';
else if(mark >= 70)
grade = 'B';
else if(mark >= 55)
grade = 'C';
else if(mark >= 40)
grade = 'D';
else
grade = 'F';
System.out.println("The grade is " + grade + ".");
}
}
|
You must write a program that asks the user for a mark and prints out the grade according to the following table
| Mark | 70 to 100 | 60 to 69 | 55 to 59 | 40 to 54 | 0 to 39 |
|---|---|---|---|---|---|
| Grade | 1 | 2 | 3 | P | F |
E.g. a sample session might be
Enter a mark: 40 The grade is P.
// Calculate fine from speed if(speed > 35) fine = 30; else if(speed > 50) fine = 55; else if(speed > 65) fine = 75;What value will be assigned to fine?
| for loop | Initial value of i | Final value of i | Number of times executed |
|---|---|---|---|
| for(i = 1; i <= 10; i = i + 1) | |||
| for(i = 1; i < 10; i = i + 1) | |||
| for(i = 2; i <= 8; i = i + 1) | |||
| for(i = 0; i <= 6; i = i + 1) | |||
| for(i = -5; i < 5; i = i + 1) | |||
| for(i = 7; i < 7; i = i + 1) | |||
| for(i = 4; i <= 5; i = i + 1) |
// Dashnum.java
// This program prints out the numbers 1 to 10 separated by a dash
public class Dashnum
{
public static void main(String [] args)
{
int i;
for(i = 1; i <= 10; i++)
System.out.print(i + "-");
}
}
|
Write a program that prints the numbers 10 to 20 with each number followed by an *.
I.e. your program should print
10*11*12 ... 19*20*
// Numbers.java
// This program prints out the numbers n to 20 separated by a blank
// where n has been entered by the user
public class Numbers
{
public static void main(String [] args)
{
int i, n;
System.out.println("Enter a number: ");
n = Console.readInt();
for(i = n; i <= 20; i++)
System.out.println(i + " ");
}
}
|
Write a program that gets a number n from the user and prints the numbers 1 to n. Each number should be separated by a blank (' ').
A sample run might look like this
Enter a number: 6 1 2 3 4 5 6
// Sum.java
//
// This program works out the sum of the numbers from 1 to 20
public class Sum
{
public static void main(String [] args)
{
int sum = 0;
int i;
for(i = 1; i <= 20; i++)
sum = sum + i;
System.out.println("The sum of the numbers 1 to 20 is " + sum);
}
}
|
By the way, we could have avoided the for loop by using the formula
1 + 2 + 3 + ... n = n * (n-1) / 2
which would result in the following simpler program
// Sum.cpp
//
// This program works out the sum of the numbers from 1 to 20
public class Formula
{
public static void main(String [] args)
{
System.out.println("The sum of the numbers 1 to 20 is " + 20 * (20+1) / 2);
}
}
|
A sample run might look like this
Enter two numbers: 6 10 The sum is 40Note: to get two numbers from the user you could have something like this
int lower, upper; lower = Console.readInt(); upper = Console.readInt();
A sample run might look like this
Enter two numbers: 2 4 The sum of the squares is 29Note that 22 + 32 + 42 = 29
Here are some hints
First of you need a for loop to go from n1 to n2 for(int i = n1; i <= n2; i++) then you need to accumulate the squared value into a variable. Maybe something like sum = sum + (i * i) You should first initialise sum to 0,
// This program prints out the numbers 1 to 10 using a while loop
public class While
{
public static void main(String [] args)
{
int j = 1;
while(j <= 10)
{
System.out.print(j + " ");
j++;
}
}
}
|
Write a program that uses a while loop to print the numbers 5 to 15 with each number followed by a '*'.
I.e. your program should print
5*6*7*8*9*10*11*12*13*14*15*
// This program finds the factors of a number.
// Note that a for loop could be used here as well.
public class Loop
{
public static void main(String [] args)
{
int num;
System.out.print("Enter a number: ");
num = Console.readInt();
int i = 2;
while(i < num)
{
// if there is no remainder => i is a factor
if(num % i == 0)
System.out.println(i + " is a factor");
i++;
}
}
}
|
The following program checks to see if a number is prime. If a factor is found, then there is no need to check for another factor, so we can leave the loop immediately (using the break statement).
// This program checks to see if a number is prime or not
public class Prime
{
public static void main(String [] args)
{
int num;
System.out.print("Enter a number: ");
num = Console.readint();
int i = 2; // Don't count 1 when checking for primes
while(i < num)
{
if(num % i == 0)
break; // found a factor, no need to stay in the loop.
i++;
}
// Now if we exited the loop normally, then i will not
// be less than num (it will be equal), otherwise we broke
// out of the loop and num is prime.
if(i == num)
System.out.println(num + " is prime");
else
System.out.println(num + " is not prime");
}
}
|
Write a program that gets a number n from a user, and prints "Prime" if the number is prime, or 'Nonprime' otherwise.
A sample run would be
Enter a number: 7 Prime
// written by CDaly
// this program demonstrates the use of && (the logical AND operator)
// Based on age, works out if the user is a teenager or not.
// You should test this program with various ages to ensure that it always works.
public class Teenager
{
public static void main(String [] args)
{
int age;
System.out.print("Enter your age: ");
age = Console.readInt();
if(age > 12 && age < 20)
System.out.print("You are a teenager");
else
System.out.print("You are not a teenager");
}
}
|
Note that the if statement could have been written using the || (the logical OR operator) as follows
if(age <= 12 || age >= 20)
System.out.println("You are not a teenager");
else
System.out.println("You are a teenager");
Note that the two statements are also interchanged. This is in fact an
application of De Morgan's law: you can interchange AND with OR if you
invert the logic of both cases (e.g. > becomes <=) and the logic
of the overall expression (achieved in this case by rearranging the
statements).
I.e. the following two conditions are logically inverse (if one is true, then the other is false and vice versa)
age <= 12 || age >= 20and
age > 12 && age < 20
It is sometimes useful to rearrange the logic in this way.
Now write a program that given a person's age works out if they are entitled to cheap travel on buses. To get cheap travel they must be under 16 or a pensioner (65 or over). Your program must use one if statement, and a logical operator (either && or ||)
A sample session might look like
Enter your age: 20 You must pay full fare.or
Enter your age: 70 You get cheap travel.
// CanWork.cpp
// written by CDaly
// this program keeps looping until the user enters a normal working
// age (18 to 65)
public class CanWork
{
public static void main(String [] args)
{
int age;
do {
System.out.println("Enter a working age: ");
age = Console.readInt();
} while(age < 18 || age > 65) ; // if not valid, ask again
System.out.println("You can work at " + age);
}
}
|
Write a program that asks for a nonteen age, i.e. (less than 13 or greater than 19). A sample session might look like
nonteen: 18 nonteen: 13 nonteen: 27 Thank you, 27 is a nonteen age.
// This program prints a square of asterisks
public class Square
{
public static void main(String [] args)
{
int size;
int i, j;
System.out.println("Size:");
size = Console.readInt();
// print all the rows
for(i = 0; i < size; i++)
{
// print one row of asterisks
for(j = 0; j < size; j++)
System.out.print('*');
// move to the next row
System.out.println();
}
}
}
|
Note that two index variables are required, one for each loop. In this case i is used as the index variable for the outer loop, and j is used for the inner loop.
Assuming that size is 5, then the inner loop will print a row of five asterisks. Then a new line is printed to move to the next row. The outer for loop will cause five rows to be printed.
Write a program that takes two numbers (r the number of rows and c the number of columns), and prints a rectangle of asterisks r rows by c columns.
A sample session would be
Enter the rows and columns: 2 4 **** ****
// This program prints a triangle of asterisks
public class Triangle
{
public static void main(String [] args)
{
int size;
int len, j;
System.out.println("Size:");
size = Console.readInt();
// print each row
for(len = 1; len <= size; len++)
{
for(j = 1; j <= len; j++)
System.out.print('*');
System.out.println(); // need a new line
}
}
}
|
If the value of size was 5, then this program would print
* ** *** **** *****The first time the inner loop is executed, len is 1, so only one asterisk is printed. The second time, len is 2 so two asterisks are printed and so on until len is five and five asterisks are printed.
A sample session would be
Size: 4 **** *** ** *
// initialises and prints out an array
public class ArrayPrint
{
public static void main(String [] args)
{
int [] age = {23, 19, 2, 6};
System.out.println("index\tage"); // index tab age. (Note tab is '\t')
for(int i = 0; i < age.length; i++)
System.out.println(i + "\t" + age[i]);
}
}
|
Change the declaration line of the program so that the array becomes 25, 7, 200, 2, 9.
I.e. the program should output
index age 0 25 1 7 2 200 3 2 4 9
public class ArrayInput
{
public static void main(String [] args)
{
int [] num = new int[4]; // declare an array of four integers
System.out.print("Enter four numbers: ");
int i;
for(i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
System.out.println(); // print a new line
// Another for loop prints them out
for(i = 0; i < num.length; i++)
System.out.print(num[i] + " ");
}
}
|
The above program prints each number with a space after it. Adapt the program so that each number is printed with an asterisk after it.
A sample program run would look like
Enter four numbers: 23 56 3 -1 23*56*3*-1*
public class ArrayDouble
{
public static void main(String [] args)
{
int [] num = new int[3];
System.out.print("Enter three numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
System.out.println(); // print a new line
// Multiply each number by 2 and print it out
for(int i = 0; i < num.length; i++)
System.out.println(num[i] * 2);
}
}
|
The above program prints two times each element. Adapt the program so that three times each element is printed
A sample program run would look like
Enter three numbers: 5 3 -1 15 9 -3
public class ArrayTwice
{
public static void main(String [] args)
{
int [] num = new int[3];
System.out.print("Enter three numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
System.out.println(); // print a new line
// Print each number twice (separated by a dash)
for(int i = 0; i < 3; i++)
System.out.println(num[i] + "-" + num[i]);
}
}
|
A sample program run would look like
Enter three numbers: 9 3 4 9-9-9 3-3-3 4-4-4
public class Arrayiere
{
public static void main(String [] args)
{
int [] num = new int[5];
System.out.print("Enter five numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
System.out.println(); // print a new line
// Print the array starting at the back
for(int i = num.length - 1; i >= 0; i--)
System.out.print(num[i] + " ");
}
}
|
The above program prints in reverse each element separated by a space. Adapt the program so that each number appears on a separate line.
A sample program run would look like
Enter five numbers: 19 3 4 7 4 4 7 4 3 19
public class ArraySum
{
public static void main(String [] args)
{
int [] num = new int[6];
System.out.print("Enter six numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
// calculate the sum of the all the elements
int sum = 0;
for(int i = 0; i < num.length; i++)
sum = sum + num[i];
System.out.println("The sum of all the numbers is " + sum);
}
}
|
Adapt the program so that it prints out the sum of floating point numbers. You will have to change the declarations of the array num and of sum from int to double. To read in a double, use the readDouble() method of Console.
A sample program run would look like
Enter six numbers: 19.6 3.2 4 7.0 4 5 The sum of all the numbers is 42.8
public class GetArray
{
// the read() method returns an array of integers
int [] read()
{
int len; // number of elements
// ask the user for a valid length ... keep looping til done
do {
len = Console.readInt("How many numbers (1-20)?\n");
} while(len < 1 || len > 20) ;
int [] num = new int[len]; // Declare an array of len elements
// Now get the required numbers
System.out.print("Enter " + num.length + " numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt();
System.out.println();
return num; // return the array
}
}
|
This method can now be used by a different class (in a different file). For example:
public class PrintArray
{
public static void main(String [] args)
{
// Create a GetArray object ...
GetArray getArray = new GetArray();
// now use the read method to get our desired array
int [] num = getArray.read();
// Now print out the array
for(int i = 0; i < num.length; i++)
System.out.println(num[i] + " ");
System.out.println();
}
}
|
Extend the program so that it prints out a histogram of all the numbers entered. i.e. for each number entered the corresponding number of asterisks is printed. a sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 2 5 1 7 0 3 ** ***** * ******* ***Hint: a nested for loop is needed that might look something like
for(i = 0; i < num.length; i++)
{
// print out the appropriate number of asterisks
for(j = 0; j < num[i]; j++)
System.out.print("*");
System.out.println(); // start a new line
}
public class EvenCount
{
public static void main(String [] args)
{
// Create a GetArray object ...
GetArray getArray = new GetArray();
// now use the read method to get our desired array
int [] num = getArray.read();
System.out.println();
// Now we've got the array, check each element to see
// is it even or not.
int count = 0;
for(int i = 0; i < num.length; i++) // scan all the elements
if(num[i] % 2 == 0) // is this element even ...
count++; // ... yes, increase the count
System.out.println("There are " + count + " even elements");
}
}
|
GetArray.java is available if required.
Adapt the program to count how many of the numbers are greater than 10. A sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 0 13 There are 3 numbers greater than 10
Note that this is a very common task for computers to perform. If a stockbroker has a list of 1000 prices, he might want to find the highest price. Humans can scan through a list of numbers, and concentrate on the largest. They try to remember only the largest number they have seen. The following (fairly standard) algorithm assumes that the first number is the maximum, and then scans through the remaining elements. If any is larger than the current maximum, then make that the new maximum.
public class MaxArray
{
public static void main(String [] args)
{
// Create a GetArray object ...
GetArray getArray = new GetArray();
// now use the read method to get our desired array
int [] num = getArray.read();
// Now we've got the array, find the max element
int max = num[0];
for(int i = 0; i < num.length; i++) // scan all the elements
if(num[i] > max) // is this element greater than max ...
max = num[i]; // ... yes, assign max to this element
System.out.println("Max element is " + max);
}
}
|
GetArray.java is available if required.
Adapt the program so that it finds the smallest element in the array. A sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 10 13 The smallest number is 5
// Find the index of the first element greater than 10
public class Index
{
public static void main(String [] args)
{
// Create a GetArray object ... and read in the array
int [] num = new GetArray().read();
int i;
boolean found = false; // assume not found
for(i = 0; i < num.length; i++) // scan all elements
if(num[i] > 10) // is this element greater than 10 ...
{
found = true;
break; // ... yes, leave the for loop
}
if(found)
System.out.println("The number with index " + i + " is first greater than 10");
else
System.out.println("No number is greater than 10");
}
}
|
GetArray.java is available if required.
Write a program that finds the index of the smallest element in the array. A sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 20 7 11 5 10 13 The number with index 3 is the smallest numberRemember that the first element of an array is zero, so the fourth element has index 3.
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 10 13 Numbers less than 10 are at indices: 1 3
public class MakeOdd
{
public static void main(String [] args)
{
// Create a GetArray object ... and read in the array
int [] num = new GetArray().read();
// Now we've got the array, find the odd numbers
for(int i = 0; i < num.length; i++)
if(num[i] % 2 == 0) // is this element even ...
num[i] = num[i] / 2; // ... yes, divide by 2
// finally print out the array
System.out.print("The modified array is ");
for(int i = 0; i < num.length; i++)
System.out.print(num[i] + " ");
}
}
|
GetArray.java is available if required.
Every even number is divided by two. If however, the number is divisible by 4, then it will still be even when divided by 2.
Adapt the program so that it keeps dividing the number until it finds an odd number.
Hint: You want to keep dividing by two while the number is even. However be careful of zero values. A sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 10 13 The modified array is 5 5 11 7 5 13You should think about this program and write down the modifications before you submit the program.
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 10 13 The modified array is 20 0 11 7 10 13Note that the smallest element, the 5, has become 0.
// This program efficiently counts the different digits that are entered
public class Count
{
public static void main(String [] args)
{
int [] count = new int[10];
int digit;
int i;
for(i = 0; i < 10; i++)
count[i] = 0; // set all counts to zero.
// Keep asking the user to enter digits
System.out.print("Enter digits (0 to 9)? (use -1 to stop): ");
do {
digit = Console.readInt();
if(digit >= 0 && digit < 10)
count[digit]++; // increase count for that digit
} while(digit != -1) ;// ... keep looping til done
// now print out the number of digits
System.out.println();
System.out.println("Digit\tNumber"); // \t is the TAB character
for(i = 0; i < 10; i++)
System.out.println(i + "\t" + count[i]);
}
}
|
Adapt the program so that it doesn't print out any number which doesn't occur (i.e. that has a zero count).
Enter digits (0 to 9)? (use -1 to stop): 2 2 9 2 2 7 -1 Digit Count 2 4 7 1 9 1I.e. the user entered four 2s, one 7 and one 9.