Difference between revisions of "The If-Statement"

From CompSciWiki
Jump to: navigation, search
(Removed references to "I" tried to focus on "we" or "you", changed section after first code block)
(Change spacing)
 
(4 intermediate revisions by one other user not shown)
Line 5: Line 5:
 
|Body=
 
|Body=
 
==Introduction==
 
==Introduction==
An if statement is an expression that contains one or more Boolean expressions whose result will determine whether to execute some segment of code. They are one of the simplest and most widely used control structures. This section will teach you how to write them. It will also teach you when and why to use them.
+
An if statement is an expression that contains one or more '''Boolean''' expressions whose result will determine whether to execute some segment of code. They are one of the simplest and most widely used '''control structures'''. This section will teach you how to write them. It will also teach you when and why to use them.
  
 
==The If-Statement==
 
==The If-Statement==
  
===What is an if statement?===
+
Now that you have a firm grasp of variables, you may have wondered what is the point of having Boolean as a variable? <BR>
Now that you have a firm grasp of variables you may have wondered what is the point of having Boolean as a variable? <BR><BR>
+
 
you probably already know that they can store either true or false, but what is the importance in storing this information if all you know how to do is simply print its contents out to the screen? <BR><BR>
+
You probably already know that they can store either true or false, but what is the importance in storing this information if all you know how to do is simply print its contents out to the screen?  
In this section you will be able to see why Booleans are important. So far the programs you have written have read '''every line''' from the top to the bottom, but sometimes you may not want your program to read every line of code. Now you are probably asking yourself “Why wouldn't I want my program to read every line of code every time?” This example will help explain why this is needed.<BR><BR>
+
 
 +
In this section you will be able to see why Booleans are important. So far the programs you have written have read '''every line''' of code from the top to the bottom, but sometimes you may not want your program to read every line of code. Now you are probably asking yourself “Why wouldn't I want my program to read every line of code every time?” This example will help explain why sometimes this is needed.
  
 
==First Example==
 
==First Example==
Let us say we want the absolute value of a number. There are two ways of doing this. There is a math way, and there is another way. The math way involves some math you learnt back in your high school days. To get the absolute value of a number you take a number and square it. Next you take the square root of that answer. So let's program this.
+
Let us say we want the '''absolute value''' of a number. Remember an absolute number is just the positive value of any number. For example, the absolute value of -4 would be 4. To get the absolute value of a number you take a number and square it. Next you take the square root of that answer.  
 +
 
 +
So let's program this.
 +
 
 
{{CodeBlock
 
{{CodeBlock
 
|Code=
 
|Code=
 
  public static void main(String[] args)
 
  public static void main(String[] args)
 
  {
 
  {
     int number;
+
     double number;
     number = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number"));
+
     double absNumber;
     number = number * number;
+
   
     number = Math.Sqrt(number);
+
    String input = JOptionPane.showInputDialog(null,"Enter a number");
     System.out.println("The number" + number);
+
    Scanner s = new Scanner(input);
 +
     number = s.nextDouble();
 +
   
 +
    //compute the absolute value
 +
    absNumber = number * number;
 +
     absNumber = (double)Math.sqrt(absNumber);
 +
   
 +
     System.out.println("The absolute value of " + number + " is " + absNumber);
 
  }//main
 
  }//main
 
}}
 
}}
  
This code will definitely work, but is it the most elegant way to solve this kind of problem? Is it necessary to square and square root in this case? The answer is no.<BR><BR>
+
This code will definitely work, but is it the most elegant way to solve this kind of problem? Is it necessary to square and square root in this case? The answer is no.
  
When the number is positive, the absolute value is already calculated, so it can just be printed. The only problem is when the number is negative. What if we could check if the number was negative and then do some special code only if it was negative? Turns out we can do exactly that by using something called an if statement.<BR><BR>
+
When the number is positive, the absolute value is already calculated, so it can just be printed. The only problem is when the number is negative. What if we could check if the number was negative and then do some special code only if it was negative? Turns out we can do exactly that by using something called an if statement.
  
==If Statement==
+
==If-Statement==
An if statement has 2 parts:<BR>  
+
An if statement has 2 parts:<BR>
(1) The Condition<BR>  
+
(1) The Condition<BR>
(2) The Body <BR><BR>
+
(2) The Body
  
 
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. Below is a general example of an if statement so you may better understand how it works.
 
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. Below is a general example of an if statement so you may better understand how it works.
 +
 
{{CodeBlock
 
{{CodeBlock
 
|Code=
 
|Code=
Line 47: Line 59:
  
 
  //if the condition is not satisfied, the code in the curly braces will be skipped
 
  //if the condition is not satisfied, the code in the curly braces will be skipped
 
 
 
}}
 
}}
  
 
Now let's get back to our absolute value question. In order to make this program more efficient, we have to do two things:<BR>
 
Now let's get back to our absolute value question. In order to make this program more efficient, we have to do two things:<BR>
 
 
(1) Check to see if the number is negative<BR>
 
(1) Check to see if the number is negative<BR>
 
(2) If the number is negative then we need to multiply it by -1, making it positive <BR><BR>
 
(2) If the number is negative then we need to multiply it by -1, making it positive <BR><BR>
Line 60: Line 69:
 
{{CodeBlock
 
{{CodeBlock
 
|Code=
 
|Code=
 
 
  public static void main(String[] args)
 
  public static void main(String[] args)
 
  {
 
  {
Line 83: Line 91:
 
}}
 
}}
  
This program can also be written a little differently. A Boolean variable isn't necessary here. It was only used to make the code more readable. You may choose to get rid of the variable. If you did the if statement would look like this if(number < 0). The reason why Boolean variables are invaluable is they give the ability to break long complicated expressions into a bunch of shorter ones.
+
This program can also be written a little differently. A Boolean variable isn't necessary here. It was only used to make the code more readable. You may choose to get rid of the variable. If you did the if-statement would look like this if(number < 0). The reason why Boolean variables are invaluable is because they give the ability to break long complicated expressions into a bunch of shorter ones.
 
+
 
+
  
 
===Another Example===
 
===Another Example===
Line 105: Line 111:
  
 
  }//main
 
  }//main
 
 
}}
 
}}
 
 
  
 
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.
 
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.
Line 116: Line 119:
 
Together the keyword ''if'', the condition, and the body form what is called an '''''if block''''' or '''''if statement'''''.
 
Together the keyword ''if'', the condition, and the body form what is called an '''''if block''''' or '''''if statement'''''.
  
 
+
===Review: Anatomy of the If-Statement===
===Anatomy of the If-Statement===
+
 
As described in the previous example an if-statement is made up of several parts:
 
As described in the previous example an if-statement is made up of several parts:
 
*the keyword '''if'''
 
*the keyword '''if'''
Line 124: Line 126:
  
 
The general form for the if-statement is:
 
The general form for the if-statement is:
<pre>
+
 
 +
{{CodeBlock
 +
|Code=
 
if (condition)    //"if" and condition on same line, condition is contained inside parentheses
 
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
 
     body          //all statements that should be executed if and only if the condition returns a value of true
 
}//if
 
}//if
</pre>
+
}}
  
Normally the body is contained inside braces (the '''{...}''' characters).  However, if the body is only one statement these braces may be omitted.  The following to if statements are equivalent:
+
Normally the body is contained inside the curly braces (the '''{...}''' characters).  However, if the body is only one statement these braces may be omitted.  The following two if statements are equivalent:
<pre>
+
 
 +
{{CodeBlock
 +
|Code=
 
if(condition)
 
if(condition)
 
{
 
{
 
     System.out.println("The condition was true");
 
     System.out.println("The condition was true");
 
}
 
}
</pre>
+
}}
<br>
+
 
<pre>
+
{{CodeBlock
 +
|Code=
 
if(condition)
 
if(condition)
 
     System.out.println("The condition was true");
 
     System.out.println("The condition was true");
</pre>
+
}}
  
If the body has more than one statement it is very important to put braces around it. If not then the if-statement will only control the line of code right after the if(condition) line and all others would be executed regardless. That is, in the following example, the output would be <b>"Congratulations on your A+! Your grade is: 59"</b> when the programmer was expecting just <b>"Your grade is: 59"</b>.
+
If the body has more than one statement it is very important to put curly braces around it. If not then the if statement will only control the line of code right after the if(condition) line and all others would be executed regardless. For example, the output would be <b>"Congratulations on your A+! Your grade is: 59"</b> when the programmer was expecting just <b>"Your grade is: 59"</b>.
<br>
+
 
<pre>
+
{{CodeBlock
 +
|Code=
 
int grade = 59;
 
int grade = 59;
  
Line 154: Line 162:
  
 
System.out.println("Your grade is: " + grade);
 
System.out.println("Your grade is: " + grade);
</pre>
+
}}
 +
 
 +
As you can see, bad things can happen if you forget your curly braces. It is good practice to always put curly braces, even if you only have one line in your body, that way you won't forget to put them if you add to the body of the if statement later.
 +
 
 +
===Summary===
 +
If statements are very useful for executing code only at certain times. The '''if-statement''' has two main parts: the '''condition''' and the '''body'''. The ''condition'' is a statement that can result in ''true'' or ''false'' depending on variables. The code inside the ''if-statement'' is called the ''body''. The ''body'' is only evaluated if the ''condition'' is true. If the ''condition'' is false, the ''body'' will not be executed.
  
As you can see, bad things can happen if you forget your curly braces. It is good practice to always put curly braces, even if you only have one line in your body, that way you wont' forget to put them if you add to the body of the if statement later.
+
If there is no curly braces directly following the if(condition) part of the ''if-statement'', the next line will be considered part of the ''if-statement''. Any lines following this will get executed regardless of if the ''condition'' is ''true'' or not.
 
}}
 
}}

Latest revision as of 13:39, 7 December 2011

COMP 1010 Home > Control Stuctures


Introduction

An if statement is an expression that contains one or more Boolean expressions whose result will determine whether to execute some segment of code. They are one of the simplest and most widely used control structures. This section will teach you how to write them. It will also teach you when and why to use them.

The If-Statement

Now that you have a firm grasp of variables, you may have wondered what is the point of having Boolean as a variable?

You probably already know that they can store either true or false, but what is the importance in storing this information if all you know how to do is simply print its contents out to the screen?

In this section you will be able to see why Booleans are important. So far the programs you have written have read every line of code from the top to the bottom, but sometimes you may not want your program to read every line of code. Now you are probably asking yourself “Why wouldn't I want my program to read every line of code every time?” This example will help explain why sometimes this is needed.

First Example

Let us say we want the absolute value of a number. Remember an absolute number is just the positive value of any number. For example, the absolute value of -4 would be 4. To get the absolute value of a number you take a number and square it. Next you take the square root of that answer.

So let's program this.

 public static void main(String[] args)
 {
     double number;
     double absNumber;
     
     String input = JOptionPane.showInputDialog(null,"Enter a number");
     Scanner s = new Scanner(input);
     number = s.nextDouble();
     
     //compute the absolute value
     absNumber = number * number;
     absNumber = (double)Math.sqrt(absNumber);
     
     System.out.println("The absolute value of " + number + " is " + absNumber);
 }//main 

This code will definitely work, but is it the most elegant way to solve this kind of problem? Is it necessary to square and square root in this case? The answer is no.

When the number is positive, the absolute value is already calculated, so it can just be printed. The only problem is when the number is negative. What if we could check if the number was negative and then do some special code only if it was negative? Turns out we can do exactly that by using something called an if statement.

If-Statement

An if statement has 2 parts:
(1) The Condition
(2) The Body

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. Below is a general example of an if statement so you may better understand how it works.

 if(condition) 
 { 
    //Body - This will get executed only if the condition is satisfied. 
 } 

 //if the condition is not satisfied, the code in the curly braces will be skipped 

Now let's get back to our absolute value question. In order to make this program more efficient, we have to do two things:
(1) Check to see if the number is negative
(2) If the number is negative then we need to multiply it by -1, making it positive

So now let's program this:

 public static void main(String[] args)
 {
     int number;
     boolean isNumberNegative;

     number = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number"));

     //Check to see if the number is negative
     isNumberNegative = number < 0;

     //use an if to execute the code in the braces only if the number is negative
     if(isNumberNegative)
     {
        //we remove the negative sign
        number = number * -1;
     }

     System.out.println("The number" + number);

 }//main 

This program can also be written a little differently. A Boolean variable isn't necessary here. It was only used to make the code more readable. You may choose to get rid of the variable. If you did the if-statement would look like this if(number < 0). The reason why Boolean variables are invaluable is because they give the ability to break long complicated expressions into a bunch of shorter ones.

Another Example

In this example the user is asked for a number and the program tells the user if the number is even.

 public static void main(String[] args)
 {
     int number;
     number = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number"));
 
     //if the number is even, print a message saying "The number is even"
     if(number%2 == 0)
     {
         System.out.println("The number is even");
     }

 }//main 

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 curly 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.

Review: 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 

Normally the body is contained inside the curly braces (the {...} characters). However, if the body is only one statement these braces may be omitted. The following two if statements are equivalent:

 if(condition)
{
    System.out.println("The condition was true");
} 
 if(condition)
    System.out.println("The condition was true"); 

If the body has more than one statement it is very important to put curly braces around it. If not then the if statement will only control the line of code right after the if(condition) line and all others would be executed regardless. For example, the output would be "Congratulations on your A+! Your grade is: 59" when the programmer was expecting just "Your grade is: 59".

 int grade = 59;

if(grade >= 90)
     System.out.print("Excellent work!");
     System.out.print("Congratulations on your A+! ");

System.out.println("Your grade is: " + grade); 

As you can see, bad things can happen if you forget your curly braces. It is good practice to always put curly braces, even if you only have one line in your body, that way you won't forget to put them if you add to the body of the if statement later.

Summary

If statements are very useful for executing code only at certain times. The if-statement has two main parts: the condition and the body. The condition is a statement that can result in true or false depending on variables. The code inside the if-statement is called the body. The body is only evaluated if the condition is true. If the condition is false, the body will not be executed.

If there is no curly braces directly following the if(condition) part of the if-statement, the next line will be considered part of the if-statement. Any lines following this will get executed regardless of if the condition is true or not.

Previous Page: Control Stuctures Next Page: The If-Else Statement