Loop_practice

advertisement
Sample problems:
For each of these sample problems, write an algorithm that indicates:
1. The variables to be declared.
2. The initialization to be done before the loop executes
3. The loop exit condition
4. Actions to be performed in the loop body
5. Actions that update the exit condition
Then finally write java code implementing the problem.
1. Pennies for Pay:
Write a program that calculates how much a person would earn
over a period of time if his or her salary is one penny the first day,
two pennies the second day, and continues to double each day.
The program should display a “table” showing the salary for each
day: and then show the total pay at the end of the period, in both
pennies and as a dollar amount.
for Example
Day 1:
Day 2:
Day 3:
1 cent
2 cents
4 cents
The program should accept as input the number of days worked,
and should NOT accept a number of days less than one.
o The variables to be declared.
o Total Earnings
o Number of Pennies earned Each Day
o Number of Days
o “Current Day”
o The initialization to be done before the loop executes
o Current Day = 1
o Read in The # of Days
o # of pennies earned each day starts at 1
o Total earnings =0
o The loop exit condition (current Day > # of days)
o Actions to be performed in the loop body
o Total Earnings += todays earnings, Today’s earnings *=2
Actions that update the exit condition (current day ++)
These examples were taken from the text “Starting out with Java 5, Early Objects” by
Tony Gaddis
import java.util.Scanner;
public class Pennies{
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int totalPenniesEarned=0, currentDaysEarnings=1, numDays;
int currentDay;
System.out.println("Please enter the number of days, > 0.");
numDays = input.nextInt();
if (numDays <= 0) System.out.println("The number of days must be
positive, try again later.");
else {
for (currentDay=1; currentDay <= numDays; currentDay++) {
System.out.println("On day " + currentDay + " you earned " +
currentDaysEarnings + ".");
totalPenniesEarned += currentDaysEarnings;
currentDaysEarnings = currentDaysEarnings * 2;
}// end of loop
System.out.println("You earned " + totalPenniesEarned +
" pennies, which is $"
+ ((double)totalPenniesEarned/100.0));
}
}
}
These examples were taken from the text “Starting out with Java 5, Early Objects” by
Tony Gaddis
2. Greatest and Least of these:
Write a program using a loop that lets the user enter a series of
positive integers. The user should enter -99 to signal the end of
the series. After all the numbers have been entered, the program
should display the largest and smallest numbers entered.
o The variables to be declared.
o Variables for the largest and smallest values
o Variable for the user’s input
o The initialization to be done before the loop executes
o Need to read the user’s first input
o Set greatest and least to the first value input
o
o The loop exit condition
o When the number entered is -99
o Actions to be performed in the loop body
o See if the # entered is > than greatest or < least
o Actions that update the exit condition
o Prompt for and read the next #
These examples were taken from the text “Starting out with Java 5, Early Objects” by
Tony Gaddis
public class Greatest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int currentNum, greatest, least;
System.out.println("Please enter an integer, -99 to exit. ");
currentNum = input.nextInt();
least = greatest = currentNum;
while( currentNum != -99) {
if (currentNum > greatest) greatest = currentNum;
else if (currentNum < least) least = currentNum;
System.out.println("Please enter an integer, -99 to exit. ");
currentNum = input.nextInt();
}// end loop
if (least == -99) System.out.println("You did not enter any valid
numbers other than -99");
else System.out.println("The least value entered was " + least +
" the greatest value entered was " + greatest);
}
}
These examples were taken from the text “Starting out with Java 5, Early Objects” by
Tony Gaddis
3. Program exercise #1 from your text: Write a program that
prompts the user to input an integer, and then outputs both the
individual digits of the number and the sum of the digits. For
example if the number entered is 3456, the output would be
3456
The sum is 18
HINT: Check out the static method “valueOf” in class string,
there is a version that converts an “int” to a string… Then you can use
the index of each character, and charAt to retrieve each digit
individually…. You can then use parseInt to convert it back to an int…
TRICKY The length of the string will control the number of iterations
in the loop
o The variables to be declared.
i. Need an integer variable for the user input
ii. Need a string variable for the converted value
iii. Need a character variable for each digit
iv. Need an integer variable for the sum
o The initialization to be done before the loop executes
i. Prompt for and read the integer
ii. convert the integer to a string
iii. Need a counter variable, that will be the index of each
character in the string, starts at 0 and goes to the length of the
string -1
o The loop exit condition
i. When the character counter variable = the string length
o Actions to be performed in the loop body
i. Get each character, convert to an int and add to sum
o Actions that update the exit condition
i. Counter variable is incremented by 1
These examples were taken from the text “Starting out with Java 5, Early Objects” by
Tony Gaddis
import java.util.*;
public class sumDigits {
public static void main(String[] args) {
int aDigit, aNum, theSum=0;
String aStringNum;
char digitAt;
Scanner console = new Scanner(System.in);
System.out.println("Please enter a positive integer ");
aNum = console.nextInt();
aStringNum = String.valueOf(aNum);
for (int count=0; count < aStringNum.length(); count++) {
digitAt = aStringNum.charAt(count);
aDigit = Character.getNumericValue(digitAt);
theSum += aDigit;
System.out.print(aDigit + " ");
}
System.out.println("The sum is: " + theSum);
}
}
These examples were taken from the text “Starting out with Java 5, Early Objects” by
Tony Gaddis
Download