Thank you for visiting our site! You landed on this page because you entered a search term similar to this: java examples to find the number & sum of integers divisible by 7, here's the result:
Notes and Exercises for Week 3
We are finally starting to realize why programming can be a powerful tool in solving problems, but we have one more control structure to learn.
Suppose we want to rewrite our guess the number game, but this time we want to let the player have as many guesses as she wants. We discussed in class that this would be impossible if we tried to do it with if statements. It is possible, however, with the use of a while loop.
We can think of a while loop as a generalized form of the if statement. It works just like the if statement, in that it executes the body of code following only if the condition in parenthesis is true, but after it is finished, it continues to repeat the body as long as the condition in the parenthesis remains true. Here is an example:
(1) /** (2) * Summation.java (3) * This program determines the sum of the first n integers, (4) * where n is an integer input by the user (5) */ (6) public class Summation { (7) public static void main(String [] args) { (8) int number; //the number that will be input by the user (9) int sum; //the sum of the numbers (10) int num; // a number that will be used to traverse the string (11) //read the input from the user (12) System.out.print("Please enter a number: "); (13) number = Keyboard.readInt(); (14) (15) //initialize sum to zero (16) sum = 0; (17) num = number; (18) //calculate sum (19) while(num > 0) (20) sum += num--; (21) (22) //output the answer (23) System.out.println("The sum of the first " + number (24) +" integers is " + sum + "."); (25) }//end main (26) }//end class
The while loop is in lines (19) and (20). Notice that in the body of the while loop, we add sum to whatever num currently is and store the result in sum. After that, we decrement num (since we use a post evaluation decrement). Running the program would yield:
C:\semmy\csci1301\>javac Summation.java
C:\semmy\csci1301\>java Summation
Please enter a number: 100
The sum of the first 100 integers is 5050.
C:\semmy\csci1301\>
Is it possible to do this without a loop? Actually, it is - there is an explicit formula to calculate the sum of the first n numbers, but this example was just for illustration.
A palindrome is a word or a sentence that is the same forward as it is backwards (this only includes letters - not punctuation, or other symbols). For example, the following are examples of palindromes:
- kayak
- racecar
- Go hang a salami, I'm a lasagna hog.
- A man, a plan, a canal - Panama!
- Sit on a potato pan, Otis.
We'd like to write a program that tests whether a given string is a palindrome or not. It must ignore punctuation and symbols, and differences in upper and lower case letters. I propose a solution to this problem as follows:
- Remove all punctuation, spaces and special symbols from the string, creating a new string
- Reverse the order of the letters of the new string.
- Compare the two strings to see if they are equal
This sounds fairly easy, but there are a few details that need to be taken into account. First of all, how are we going to remove punctuation from the string? The easiest way is to check each character in the original string - if it falls outside of the letter range, ignore it. Otherwise, add it to the new string. The characters in Java are encoded using the unicode character set (see Appendix C of your textbook). This is simply a way of storing characters as integers in memory. Hence, they have a numerical type ordering, and we can use our primitive comparison operators to compare them, as we learned two weeks ago. Next, we reverse the string by simply traversing modifiedInput backwards, and adding each character to the end of reverseInput. Here is the source code for a program which determines whether an input string is a palindrome or not:
(1) /** (2) * PalindromeTester.java (3) * This program reads a String from the user and (4) * checks to see if it is a palindrome. It disregards (5) * punctuation and spaces. (6) */ (7) public class PalindromeTester { (8) public static void main(String [] args) { (9) int count; //this is a counter to tell us where we are in the string (10) String input; //our original input (11) String modifiedInput = new String(""); //this will be our string that has no punctuation, etc. (12) String reverseInput = new String(""); //the reverse of modifiedInput (13) (14) System.out.println("Welcome to Palindrome Tester version 3.0"); (15) System.out.print("Please enter a string to be tested: "); (16) input = Keyboard.readString(); (17) (18) //Here, we remove all punctuation, spaces and other non-letter characters (19) count = 0; (20) while(count = 'A' && input.charAt(count) = 'a' && input.charAt(count) = 0) { (33) reverseInput += modifiedInput.charAt(count); (34) count--; (35) } (36) (37) System.out.println("Reversed Input: " + reverseInput); (38) (39) if(reverseInput.equalsIgnoreCase(modifiedInput)) (40) System.out.println("\"" + input + "\" is a palindrome."); (41) else (42) System.out.println("\"" + input + "\" is not a palindrome."); (43) }//end main (44) }//end class
In addition to the while loop, we have a similar looping structure called a do...while loop. The difference is subtle but important. In a while loop, the condition is checked before entering the loop body each time the loop is executed. It is, therefore, possible that the body of a while loop will never be executed (if the condition is false the first time the program arrives at the while loop. A do...while loop, on the other hand, checks the condition at the END of the loop, after exiting the body of the loop. Therefore the body of a do...while loop is always executed at least once. There is a great example using a do...while loop in the text - it is a program that reverses the digits of number mathematically. For copyright reasons, I probably shouldn't include the source code in my notes, but you can see it in the text. It is Lewis and Loftus listing 3.13.
See Lewis and Loftus listing 3.13
Using a do...while loop with a while loop nested inside, we can easily create a guess the number game that allows the user to have an arbitrary number of guesses and play as many times as she wants! This program uses a sentinel value of -1 to terminate the inner while loop. A sentinel value is a numeric value that is outside the range of allowable inputs that we assign some semantic meaning (in this case -1 is not a valid guess, since the number generated is between 1 and 100, so we assign to it the "I am ready to quit" interpretation).
(1) /** (2) * RevisedGuessTheNumber.java (3) * This program plays a number guessing game with the user. (4) * It allows her to have as many guesses as she wants, and (5) * to play again. (6) */ (7) import java.util.Random; (8) public class RevisedGuessTheNumber { (9) public static void main(String [] args) { (10) final int RANGE = 100; (11) int number; //the number the user is trying to guess (12) int guess; //the number the user guesses (13) boolean exit; //a flag to tell us when it is time to exit the inner while loop (14) Random generator = new Random(); //random number generator (15) String play; //String to determine whether the user wants to play again or not (16) System.out.println("Welcome to GuessTheNumber version 2.0"); (17) do { //main game do loop, repeats when user wants to play again (18) number = generator.nextInt(RANGE) + 1; (19) System.out.println("I am thinking of a number between 1 and " + RANGE + "."); (20) exit = false; (21) while(!exit) { (22) System.out.print("Guess a number (enter -1 to quit): "); (23) guess = Keyboard.readInt(); (24) if(guess == -1) (25) exit = true; (26) else if(guess number) (29) System.out.println("Too high!"); (30) else { (31) System.out.println("You got it!"); (32) exit = true; (33) } (34) }//end while (35) //check to see if they quit (36) if(guess == -1) (37) System.out.println("Sorry! The number was " + number); (38) System.out.print("Would you like to play again(Y/N): "); (39) play = Keyboard.readString(); (40) }while(play.equalsIgnoreCase("Y"); (41) }//end main (42) }//end class
Finally, we have the for loop. The for loop is equivalent to a while loop since we can implement a for loop with a while loop and vice-versa (see exercises), but it is a bit more compact representation for a commonly used structure. In addition to just having a condition, for loops have an initialization and an update statement in their decleration. Here is an example of a for loop's structure:
(1) for(int i = 0; iWhen entering the for loop, the initialization (int i = 0) is executed and the conditional (i ) is tested. If the condition evaluates to true, the body of the for loop is executed. When the body is finished executing, the update (i++) is executed and the conditional is evaluated again. If it evaluates to true, the process repeats.
For loops tend to be useful when we know exactly how many times we are going to be doing something (for example, in exercise 6, we know that we will be going through each character in the string - hence the loop will repeat exactly once for each character in the string).
An integer is prime if it is not divisible by any integer other than itself and 1. The first prime integer is 2 (1 is not considered a prime number), because every negative integer is also divisible by -1. Using a for loop, we can determine if a number is prime by checking every number between 2 and the number itself to determine if it is prime. Here is a program that does exactly that:
(1) /** (2) * Prime.java (3) * This is a program that determines whether (4) * a number input by the user is prime or not (5) */ (6) public class Prime { (7) public static void main(String [] args) { (8) int num; (9) boolean isPrime; (10) (11) //read number from the user (12) System.out.print("Please enter a number: "); (13) num = Keyboard.readInt(); (14) (15) //we assume num is prime until we find evidence (16) //to the contrary (17) isPrime = true; (18) (19) if(numExercises
- What would happen if we used a pre-evaluation decrement in line (20) of Summation.java? Would the program work properly? What would be the output when the user inputs 15?
- How does my solution to the Palindrome problem differ from the book's solution? Explain both solutions in words (no code or pseudocode).
- Explain how and why ReverseNumber (Lewis and Loftus listing 3.13) works.
- Add code to RevisedGuessTheNumber.java so that it counts the number of guesses that it takes the user to guess the number. When the user guesses correctly, output this number (e.g. "It took you 5 guesses!"). When the user doesn't answer correctly output something like "It took you 100 guesses and you still couldn't get it!".
- Lewis and Loftus Programming Project 3.3 (use a while loop).
- Lewis and Loftus Programming Project 3.5 (use a for loop).
- Lewis and Loftus Exercises 3.5, 3.6, 3.9, 3.10.
- Show that a for loop is functionally equivalent to a while loop by implementing each one in terms of the other.
- A number is composite if it is not prime. Write a program called Composite that determines whether an input number is composite (do not just use the code from Prime.java and change the if statement at the end).