Sams Teach Yourself C in 21 Days

(singke) #1
Java Language Fundamentals 719

BD4


switch(numberOfSiblings) {
case 0:
System.out.println(“An only child, I see.”);
break;
case 1:
System.out.println(“The typical family!”);
break;
case 2:
System.out.println(“Three kids can be a handful.”);
break;
default:
System.out.println(“It must have been crowded at your house!.”);
}
Suppose the breakstatement were omitted from the case 0:block. Then, when the
expression is equal to 0 , the code under case 0:would be executed followed by the
code under case 1:. In other words, when switchfinds a match, it starts executing code
at the matching casestatement and continues until it finds a breakstatement or reaches
the end of the switchconstruct. Again, this functionality matches C and C++.

for................................................................................................................

Theforconstruct is used to execute a block of statements a specified number of times.
The syntax is
for (variable= initial value; expression1; expression2)
{
statementblock;
}
variableis any numeric variable, and expression1is a Boolean (true/false) expression.
Here’s how a forconstruct works when execution reaches it:
1.variableis set equal to initial value.
2.expression1is evaluated. If true,statementblockis executed. If false, exit the
forconstruct.


  1. Evaluate expression2.

  2. Return to step 2.
    Most frequently, the forconstruct is used to “count” from one value to another. This
    loop counts up from 0 to 100 and displays the values on the screen:
    for (i = 0; i < 101; i++)
    {
    System.out.println(i);
    }


39 448201x-Bonus4 8/13/02 11:19 AM Page 719

Free download pdf