Difference between revisions of "The If-Statement"

From CompSciWiki
Jump to: navigation, search
(Changed Code blocks to CodeBlock template, tidied up code, rewrote a bunch of stuff)
(Removed references to "I" tried to focus on "we" or "you", changed section after first code block)
Line 11: Line 11:
 
===What is an 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><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? <BR><BR>
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''' 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>
  
 
==First Example==
 
==First Example==
Line 28: Line 28:
 
}}
 
}}
  
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>
+
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>
(1) we check to see if the sign is negative<BR>
+
 
(2) if it is then we need to do something <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.<BR><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". Here we only want to execute the 3rd part if and only if the sign is negative, conversely we don't want to execute the 3rd part if the sign is positive. So how is this done?
+
==If Statement==
This is done by the use of something called an if statement.<BR>
+
 
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>
+
(2) The Body <BR><BR>
  
This 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 52: Line 51:
 
}}
 
}}
  
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.
+
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. 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) 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>
(1) Check to see if the sign is negative <BR>
+
(2) If it is, multiply the number by -1 to make it positive <BR>
+
<BR>
+
  
 
So now let's program this:
 
So now let's program this:
Line 87: Line 83:
 
}}
 
}}
  
 
+
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 they give the ability to break long complicated expressions into a bunch of shorter ones.
+
  
  

Revision as of 00:53, 5 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

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?

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.

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.

 public static void main(String[] args)
 {
     int number;
     number = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number"));
     number = number * number;
     number = Math.Sqrt(number);
     System.out.println("The number" + number);
 }//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 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.


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 braces (the {...} characters). However, if the body is only one statement these braces may be omitted. The following to 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 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 "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 wont' forget to put them if you add to the body of the if statement later.

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