Difference between revisions of "The If-Statement"

From CompSciWiki
Jump to: navigation, search
(Edit 1: removed some html code visible in the text (again))
(Anatomy of the If-Statement: Brent's Edit - Changed a sentence that was broken up by code to be easier to read. Added an example for forgetting curly braces.)
Line 134: Line 134:
 
</pre>
 
</pre>
  
Normally the body is contained inside braces (the '''{...}''' characters).  However, if the body is only one statement these braces may be omitted.  Thus:
+
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:
 
+
 
<pre>
 
<pre>
 
if(condition)
 
if(condition)
Line 142: Line 141:
 
}
 
}
 
</pre>
 
</pre>
 
+
<br>
and
+
 
+
 
<pre>
 
<pre>
 
if(condition)
 
if(condition)
Line 150: Line 147:
 
</pre>
 
</pre>
  
are the same.  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. It's often a good practice to always put braces around the body, even if it is only one line so as to avoid issues if you wish to add to the statement.
+
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>.
 +
<br>
 +
<pre>
 +
int grade = 59;
 +
 
 +
if(grade >= 90)
 +
    giveScholarship();
 +
    System.out.print("Congratulations on your A+! ");
 +
 
 +
System.out.println("Your grade is: " + grade);
 +
 
 +
It's often a good practice to always put braces around the body, even if it is only one line so as to avoid issues if you wish to add to the statement.

Revision as of 00:27, 4 December 2007

COMP 1010 Home > 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.

   

{{{Body}}}

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?

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?

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.

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 lets program this.

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

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 lets 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 calucations? 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 lets break this sentence up into three parts
(1) we check to see if the sign is negative.
(2) if it is then we need to do somthing
(3) that somthing is we need to remove the negative sign

Remember what I said earlyer: 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? This is done by the use of somthing called an if statement. Hence the name of this section

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 
will execute the code in the body

00 //if the condition is true 
01 if(true) 
02 { 
03    //this part will run
04 } 
05 //this part will always run 

and conversely if the condition is false then the program 
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

Now lets 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 all ready broken this up into 3 steps

(1) we check to see if the sign is negative.
(2) if it is then we need to do somthing
(3) that somthing is we need to remove the negative sign

so now lets program this:

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



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

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)
     giveScholarship();
     System.out.print("Congratulations on your A+! ");

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

It's often a good practice to always put braces around the body, even if it is only one line so as to avoid issues if you wish to add to the statement.