Difference between revisions of "Control Structures"

From CompSciWiki
Jump to: navigation, search
Line 82: Line 82:
  
  
===Anatomy of the if-else statement===
+
===Anatomy of the If-Else Statement===
 
The if-else statement is made up of the following parts:
 
The if-else statement is made up of the following parts:
 
*the keyword '''if'''
 
*the keyword '''if'''
Line 111: Line 111:
 
==Nesting==
 
==Nesting==
  
===if-else ladders===
+
===If-Else Ladders===
 
====A Second Example====
 
====A Second Example====
 
The following program asks the user for two sports scores and tells the user which team won or if the game was a draw.  The key components to pay attention to are lines '''07 to 14'''.
 
The following program asks the user for two sports scores and tells the user which team won or if the game was a draw.  The key components to pay attention to are lines '''07 to 14'''.

Revision as of 16:44, 22 February 2007

Control Structures are blocks of code that force the computer to make a decision. Sometimes you will want your program to perform different tasks depending on certain boolean conditions. For example if you were writing a game you would probably find it very useful to be able to know when the user has won the game so that you could show a high scores page.

Without control structures programs would begin at the first line and excecute every line of code in order, giving the same output every time. Imagine how boring Tetris would be if there was only one piece! Control structures allow you to change the order of execution, jumping from one section of code to another as needed.


The If-Statement

A First Example

In this example the user is asked for a number and the program tells the user if the number is even. Pay careful attention to lines 05 to 08.

00 public static void main(String[] args)
01 {
02     int number;
03     number = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number"));
04
05     if(number%2 == 0)
06     {
07         System.out.println("The number is even");
08     }//if
09
10 }//main

The keyword if is used to tell the computer to make a decision based on a condition. If the condition returns a value of true then the lines of code contained inside the body is executed. If the condition returns false the code inside the body is skipped entirely.

In this example the condition is number%2 == 0. You can always identify the condition of an if-statement by looking at what is contained in the parentheses after the word if. The condition must always return either true or false. Any other values (such as a number, string, or character) will result in an error when you try to compile your program.

The body of the if-statement is everything contained within the curled braces. In this case the body contains one line: System.out.println("The number is even");.

Together the keyword if, the condition, and the body form what is called an if block or if statement.


Anatomy of the If-Statement

As described in the previous example an if-statement is made up of several parts:

  • the keyword if
  • the condition
  • the body

The general form for the if-statement is:

if (condition)    //"if" and condition on same line, condition is contained inside parentheses
{
    body          //all statements that should be executed if and only if the condition returns a value of true
}//if


The If-Else Statement

Sometimes it is not sufficient to simply tell the computer "If such-and-such condition is true do this". Somtimes you will want to say "If such-and-such is true do this, otherwise do that". A simple way of doing this would be to have a separate if-statement that will return the opposite value of the first:

if (number%2 == 0)
{
    System.out.println("The number is even");
}//if

if (number%2 !=0)
{
    System.out.println("The number is odd");
}//if

While this approach works, it is needlessly complicated; there is a better way of doing the same task, but with less work. The keyword else can be used to tell the computer do execute a different body of code if the condition of an if-statement returns false. We can rewrite the code from above to take advantage of this keyword like this:

if (number%2 == 0)
{
    System.out.println("The number is even");
}//if

else
{
    System.out.println("The number is odd");
}//else

If we step through this last example the computer will evaluate the condition number%2 == 0 and check the result. If the result is true the body of the if-statement will be executed, just like in the previous examples. If the result is false then the body of the else-statement is executed.

The keyword else and the corresponding body form what is called an else-block or else-statement. It is very important to note that an else-block is always associated with an if-block, and each if-block can only ever be associated with zero or one else-blocks.

Together the keywords if, else, the condition, and the two bodies form a code-block known as an if-else block or if-else statement.


Anatomy of the If-Else Statement

The if-else statement is made up of the following parts:

  • the keyword if
  • the condition
  • the body of the if-statement
  • the keyword else
  • the body of the else-statement

The general form of an if-else statement is:

if (condition)
{
    code to execute if condition == true
}

else
{
    code to execute if condition == false
}


Conditions

Logical and Relative Operators

Comparing Strings

Nesting

If-Else Ladders

A Second Example

The following program asks the user for two sports scores and tells the user which team won or if the game was a draw. The key components to pay attention to are lines 07 to 14.

00 public static void main(String[] args)
01 {
02    int scoreA, scoreB;
03    
04    scoreA = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Team A's score"));
05    scoreB = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Team B's score"));
06
07    if(scoreA > scoreB)
08    {
09        System.out.println("Team A won");
10    }//if
11
12    else if(scoreA < scoreB)
13    {
14        System.out.println("Team B won");
15    }//else if
16
17    else
18    {
19        System.out.println("The game was a draw");
20    }//else
21 }//main


Review Questions and Exercises

Template loop detected: Template loop detected: