Difference between revisions of "Control Structures"

From CompSciWiki
Jump to: navigation, search
(Exercises)
m (Change italic to bold in intro)
 
(13 intermediate revisions by 4 users not shown)
Line 1: Line 1:
'''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.
+
{{1010Chapter
 +
|ChapterNum=4
 +
|Picture=Wiki_sign01.jpg
 +
|Introduction='''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 [[Common Primitive Variables#Primitive Type boolean|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.
  
 
If control structures were not used then 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.
 
If control structures were not used then 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.
  
 +
|Body=
 +
==[[The If-Statement]]==
  
==The If-Statement==
+
==[[The If-Else 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'''.
+
  
<pre>
+
==[[Conditions]]==
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
+
</pre>
+
  
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.
+
==[[Nesting]]==
  
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.
+
==[[Control Structures Review Questions and Exercises|Review Questions and Exercises]]==
  
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");'''.
+
|PChapterNum=3
 +
|PChapterLink=[[Calling Methods]]
 +
|NChapterNum=5
 +
|NChapterLink=[[Loops]]
 +
}}
  
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:
 
<pre>
 
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
 
</pre>
 
 
Normally the body is contained inside braces (the '''{...}''' characters).  However, if the body is only one statement these braces may be omitted.  Thus:
 
 
<pre>
 
if(condition)
 
{
 
    System.out.println("The condition was true");
 
}
 
</pre>
 
 
and
 
 
<pre>
 
if(condition)
 
    System.out.println("The condition was true");
 
</pre>
 
 
are the same.  If the body has more than one statement it is very important to put braces around it.  It's often a good practice to always put braces around the body, even if it is only one line.
 
 
==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:
 
 
<pre>
 
if (number%2 == 0)
 
{
 
    System.out.println("The number is even");
 
}//if
 
 
if (number%2 !=0)
 
{
 
    System.out.println("The number is odd");
 
}//if
 
</pre>
 
 
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:
 
 
<pre>
 
if (number%2 == 0)
 
{
 
    System.out.println("The number is even");
 
}//if
 
 
else
 
{
 
    System.out.println("The number is odd");
 
}//else
 
</pre>
 
 
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:
 
<pre>
 
if (condition)
 
{
 
    code to execute if condition == true
 
}
 
 
else
 
{
 
    code to execute if condition == false
 
}
 
</pre>
 
 
 
==Conditions==
 
===Logical and Relative Operators===
 
What happens if you have a statement the requires several conditions to be true before it will be executed? You could nest if statements, but this is messy are certainly not good practice. This is where logical operators come in. The snippet of code below is 100% valid, but is overly complicated.
 
 
<PRE>
 
if (x == 1)
 
{
 
  if (y == 1)
 
  {
 
    System.out.println("X is 1 and Y is 1");
 
  }
 
}
 
</PRE>
 
 
The next version will yield the same result. It shows how logical operators can clean up code.
 
 
<PRE>
 
if (x == 1 && y == 1)
 
{
 
  System.out.println("X is 1 and Y is 1");
 
}
 
</PRE>
 
 
The usefullness of logical operators may not be immediately apparent. However, imagine trying to write an if-statement that is five levels deep when it can be combined into one just as easily. One slip is all it takes to lose track of what is going on. Logical operators can help counter this from occurring.
 
 
There are three logical operators used for conditional statements. They are ''AND'', ''OR'', and ''NOT''. The ''AND'' is represented in code as '''&&'''. The ''OR'' is represented as '''||'''. Lastly, the ''NOT'' is represented as '''!'''. The purpose of these operators is to compare the boolean values of two conditions and come up with a single boolean value. This concept ties in with truth tables. Furthermore, truth tables can help explain how the logical operators work. In the truth table below, if the X condition is true ''AND'' the Y condition is true, then the result of the statement is true. However, if X is false, Y is false, or they are both false, then the result of the statement is false.
 
 
<PRE>
 
AND Truth Table
 
 
X    Y      Result
 
true  true  true
 
true  false  false
 
false true  false
 
false false  false
 
 
 
 
OR Truth Table
 
 
X    Y      Result
 
true  true  true
 
true  false  true
 
false true  true
 
false false  false
 
 
 
 
NOT Truth Table
 
 
X    Result
 
true  false
 
false true
 
</PRE>
 
 
If you have not noticed already, the ''NOT'' operators work slightly different than ''AND'' and ''OR'' operators. The ''NOT'' operator works with a single condition statement, rather than two statements. If the boolean result of statement X is true, then a ''NOT'' will change the statement to false. Likewise, ''NOT''ing a false statement will make it true. Also note that the ''NOT'' operator is put in front of a condition statement. Some examples below show how this is done.
 
 
<PRE>
 
int i = 1;
 
 
if (!(i > 0)) // i > 0 is true, but the ! reverses so the result is false
 
...
 
 
if (!i > 0) // Illegal statement - ! can ONLY be used for boolean value. i is an integer.
 
...
 
 
if (!true == !true) // !true is false, and false == false, so the result is true
 
...
 
</PRE>
 
 
Relational operators are nothing new. You have seen and been using them but probably did not realize it. Relational operators are part of what makes up a conditional statement. They will determine whether a condition will be true or false. Below is a list of the different relational operators.
 
 
<PRE>
 
Operator  True if...
 
  >      Left operand is greater than right operand
 
  >=      Left operand is greater than or equal to right operand
 
 
  <      Left operand is less than right operand
 
  <=      Left operand is less than or equal to right operand
 
 
  ==      Left operand is equal to right operand
 
  !=      Left operand is not equal to right operand
 
</PRE>
 
 
The operands are the numbers that are being compared. Integers are the only operands you '''should''' be comparing. You can compare different types of operands but it is not recommended. Here are some simple examples how relational operators can be used.
 
 
<PRE>
 
int x = 0;
 
int y = 1;
 
 
if (x >= 0 && y == 1)
 
  System.out.println("This statement is true");
 
 
if (x == 10 || !(y == 10))
 
  System.out.println("This statement is also true");
 
 
if ((x == 0 && y != 0) || (y <= -1))
 
  System.out.println("Once again, this statement is true");
 
</PRE>
 
 
If you can understand why all the statements above will print out a message, then you have a firm grasp on logical and relational operators. Make sure you know them well since you will use them on a regular basis.
 
 
===Comparing Strings===
 
Strings are a very large subject so we will only touch the basics about comparing strings in this section. The first way to compare strings is by using the relational operators. The most common approach is to use the '''==''' to see if two strings are equal. Here is an example on how strings can be compared.
 
 
<PRE>
 
String str1 = "hello";
 
String str2 = "hello";
 
 
if (str1 == str2)
 
  System.out.println("The strings are equal");
 
else
 
  System.out.println("The strings are not equal");
 
</PRE>
 
 
The example above will print out "The strings are equal". It seems simple enough. However, when using the '''==''' to compare strings, it will compare by reference instead of by value. Another example will help demonstrate what this means.
 
 
<PRE>
 
String str1 = "hello";
 
String str2 = "he";
 
String str3 = "llo";
 
str2 = str2 + str3; // The value is now "hello".
 
 
if (str1 == str2)
 
  System.out.println("The strings are equal");
 
else
 
  System.out.println("The strings are not equal");
 
</PRE>
 
 
What will be the output of the code above? If you said "The strings are equal" because "hello" is equal to "hello" even though they are concatenated together, you are wrong. We will avoid explaining the details for now. All you need to know is that the values of the strings are '''NOT''' being compared. This will vary between every programming language. In C# you may compare by values or by references, while in Java you can compare references only.
 
 
There is a safer way to compare strings. The [http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html Java String API] contains dozens of useful methods, but we will only look at one. The "equals" method is a great way to compare the values between two strings. Here is the same code as above using the "equals" method for comparison.
 
 
<PRE>
 
String str1 = "hello";
 
String str2 = "he";
 
String str3 = "llo";
 
str2 = str2 + str3; // The value is now "hello".
 
 
if (str1.equals(str2))
 
  System.out.println("The strings are equal");
 
else
 
  System.out.println("The strings are not equal");
 
</PRE>
 
 
This time the program will print out "The strings are equal". The "equals" method takes the value of "str1" and compares it to the value of "str2". Since the value of both are "hello", they are considered equal, and ''true'' will be the result of the condition.
 
 
Note that the "equals" method is case sensitive. Therefore, "HELLO" and "hello" are not considered to be equal. However, the [http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html Java String API] has an "equalsIgnoreCase" method which would consider the above strings to be equal.
 
 
That concludes our introduction for comparing strings. Just be aware that there are other ways to compare strings, but most of them are beyond the scope of this class.
 
 
==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'''.
 
 
<pre>
 
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
 
</pre>
 
 
 
==Review Questions and Exercises==
 
The solutions to these exercises can be found [[Control Structures Solutions|here]].
 
 
===Review Questions===
 
#Name the 3 different logical operators. What are the benefits of using logical operators?
 
#What is the proper way in Java to compare strings? Why?
 
#What are the results of the following logical operations?
 
## 'a' != 'b'
 
## (127-3*9) >= (97+8/4)
 
## "Hello" == "Hello"
 
#Write the truth table for the expression (X || Y) && Z
 
 
 
===Exercises===
 
1. Look at the code below. Clean it up so it uses the proper logical operators and proper use of if-else's.
 
 
<PRE>
 
if (x == 1)
 
{
 
  if (y == 1)
 
  {
 
    if (!!!!true)
 
    {
 
      System.out.println("X and Y are 1!");
 
    }
 
  }
 
}
 
if (x == 2)
 
{
 
  System.out.println("X is 2!");
 
}
 
if (x < 1)
 
{
 
  System.out.println("X is under 1 or over 2!");
 
}
 
if (x > 2)
 
{
 
  System.out.println("X is under 1 or over 2!");
 
}
 
</PRE>
 
 
 
 
2. Is the result of the following statement true or false?
 
 
<PRE>
 
String s1 = "test";
 
String s2 = "TEST";
 
String s3 = "test";
 
 
if (!(!(s1.equals(s2) && s1.equals(s3)) || s2.equals(s3)))
 
  System.out.println("The result is true");
 
else
 
  System.out.println("The result is false");
 
</PRE>
 
 
3. Write a program that will prompt a user to enter an integer. The program will determine whether the number is even or odd and print out the result. It will print out a different result if the number is negative. The program will continue until the user enters a 0. Also note that if the user enters a 0, the program will not print out anything other than that the program has finished.
 
 
4. Write a program that will prompt the user to enter a string.  The program will print out whether or not the first character is a vowel or not.
 
  
 
{{Category:COMP 1010}}
 
{{Category:COMP 1010}}
{{Category:Java}}
 

Latest revision as of 13:57, 7 December 2011


Wiki 1010 Table of Contents

Wiki sign01.jpg

Chapter 4

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.

If control structures were not used then 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.

  Write a Program a Day Case Studies

The If-Statement

The If-Else Statement

Conditions

Nesting

Review Questions and Exercises




Chapter 3: Calling Methods Table of Contents Chapter 5: Loops



Template loop detected: