...

/

Practice Challenges for Fun

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?

0/500
Show Answer
1 / 7

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.

0/500
Show Answer
Did you find this helpful?
Press + to interact
Java
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 while
System.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
0/500
Show Answer
Did you find this helpful?
Press + to interact
Java
public class Challenge2
{
public static void main( String args[] )
{
String sentence = "A sample sentence for you to try.";
int numberOfWords = 0; // STUB
System.out.println("The sentence \"" + sentence + '\"');
System.out.println("has " + numberOfWords + " words.");
} // End main
} // End Challenge2

Challenge 3: Read and

...