Practice Challenges for Fun
In this lesson, we will practice what we learned in this chapter.
Quiz
Attempt the following quiz questions:
1.
What are the four steps of a typical while
loop? Which steps are repeated?
Show Answer
Q1 / Q7
Challenge 1: Change the direction of a counted loop
1.
Revise the following while
loop so that count
decrements, but sum
has the same value at the end of the loop as it does in the original loop.
Show Answer
Q1 / Q1
Did you find this helpful?
Press + to interact
public class Challenge1{public static void main( String args[] ){int sum = 0;int count = 0;while (count < 5){sum = sum + count;count = count + 1;} // End whileSystem.out.println(sum);} // End main} // End Challenge1
Challenge 2: Count words in a sentence
1.
Using the String
method charAt
, write a loop that counts the number of words in the string sentence
. You can make the following assumptions:
- Words are separated by exactly one blank character
- The string begins and ends with a non-blank character
Show Answer
Q1 / Q1
Did you find this helpful?
Press + to interact
public class Challenge2{public static void main( String args[] ){String sentence = "A sample sentence for you to try.";int numberOfWords = 0; // STUBSystem.out.println("The sentence \"" + sentence + '\"');System.out.println("has " + numberOfWords + " words.");} // End main} // End Challenge2
Challenge 3: Read and
...Access this course and 1400+ top-rated courses and projects.