Difference between revisions of "The If-Statement"

From CompSciWiki
Jump to: navigation, search
(Change spacing)
 
(22 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{Template:1010Topic|Chapter_TOC=[[Control Structures]]|Introduction=If-Statements are one of the simplest and most widely used control structures. This section will teach you how they are used and when and why to use them.|Overview=This section will cover the If-Statement from how they are structured to the basics of how they are used.}}
+
{{Template:1010Topic
 +
|Chapter_TOC=[[Control_Structures|Control Stuctures]]
 +
|Previous=[[Control_Structures|Control Stuctures]]
 +
|Next=[[The If-Else Statement]]
 +
|Body=
 +
==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==
 
==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>
+
 
Yes I'm aware that you 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 Boolean is 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?” If I didn't want my program to run some lines of code I wouldn't have written them in the first place. Now let me explain this with an example.<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.  
<pre>
+
00 public static void main(String[] args)
+
01 {
+
02    int number;
+
03    number = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number"));
+
04    number = number * number;
+
05    number = Math.Sqrt(number);
+
06    System.out.println("The number" + number);
+
07 }//main
+
</pre>
+
This is quite simple, and yet is there any other way of computing the absolute value, and if so why isn't there an easier math formula? Well let's think about it; is this not the way we as humans compute the absolute value of a number? When you want to make a number a positive number do you ever do any calculations? I would hope not. This technique is way too mathy, and if we did compute the number it would take forever! What we do instead is we check to see if the number is negative and if it is then we remove the negative sign. So let's break this sentence up into three parts <BR>
+
(1) we check to see if the sign is negative<BR>
+
(2) if it is then we need to do something <BR>
+
(3) that something is we need to remove the negative sign <BR><BR>
+
Remember what I said earlier: that "sometimes you may not want your program to read every line of code".<BR>
+
Here we only want to execute the 3rd part if and only if the sign is negative, conversely<BR>
+
we don't want to execute the 3rd part if the sign is positive<BR>
+
so how is this done?
+
This is done by the use of something called an if statement. Hence the name of this section <BR>
+
<pre>
+
An if statement has 2 parts
+
    -The Condition
+
    -The Body
+
+
00 if(condition)
+
01 {
+
02    //Body
+
03 }
+
  
how they work is if the condition is true then the program  
+
So let's program this.
will execute the code in the body
+
  
00 //if the condition is true
+
{{CodeBlock
01 if(true)  
+
|Code=
02 {  
+
public static void main(String[] args)
03    //this part will run
+
{
04 }
+
    double number;
05 //this part will always run
+
    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
 +
}}
  
and conversely if the condition is false then the program
+
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.
will skip the code in the body
+
+
00 //if the condition is false
+
01 if(false)
+
02 {
+
03    //this part will not run
+
04 }
+
05 //this part will always run
+
  
</pre>
+
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.
Now let's get back to our absolute value question. What we need to do is check to see if the number is negative and if it is then we remove the negative sign. We have already broken this up into 3 steps
+
  
(1) we check to see if the sign is negative. <BR>
+
==If-Statement==
(2) if it is then we need to do something <BR>
+
An if statement has 2 parts:<BR>
(3) that something is we need to remove the negative sign <BR><BR>
+
(1) The Condition<BR>
 +
(2) The Body
  
so now let's program this:
+
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.
<pre>
+
00 public static void main(String[] args)
+
01 {
+
02    int number;
+
03    boolean isNumberNegative;
+
04
+
05    number = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number"));
+
06
+
07      //Check to see if the number is negative
+
08    isNumberNegative = number < 0;
+
09
+
10    //and if the number is negative
+
11    if(isNumberNegative)
+
12    {
+
13        //we remove the negative sign
+
14        number = number * -1;
+
15    }
+
16
+
17    System.out.println("The number" + number);
+
18
+
19 }//main
+
</pre>
+
  
 +
{{CodeBlock
 +
|Code=
  
 +
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:<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>
  
===A First Example===
+
So now let's program this:
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>
+
{{CodeBlock
00 public static void main(String[] args)
+
|Code=
01 {
+
public static void main(String[] args)
02    int number;
+
{
03    number = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number"));
+
    int number;
04
+
    boolean isNumberNegative;
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 executedIf the condition returns ''false'' the code inside the body is skipped entirely.
+
    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.
 +
 
 +
{{CodeBlock
 +
|Code=
 +
 
 +
  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.
 
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");'''.
+
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'''''.
 
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 127: 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 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>.
  
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>.
+
{{CodeBlock
<br>
+
|Code=
<pre>
+
 
int grade = 59;
 
int grade = 59;
  
 
if(grade >= 90)
 
if(grade >= 90)
     giveScholarship();
+
     System.out.print("Excellent work!");
 
     System.out.print("Congratulations on your A+! ");
 
     System.out.print("Congratulations on your A+! ");
  
 
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