Blogger templates

Conditional flow of a program

Often we want to change the flow of our program depending on the situation. To handle these, java deploys three main control flow statements.

if    else if    else
These are the main control flow statements in Java.
These statements control how your program can make decisions depending on the situation.
For example, take this into account,
You’ve a program, which prints “You am a good boy” in the console.
Not the awesome program arround, but it’ll do for now.

public class ControlFlow{
    public static void main (String[] args){
        System.out.println("You am a good boy");
    }
}

Simple enough!
Now, let’s say we want a program which will ask how many bad things we’ve done in our life.
If we did no bad things then we’ll give answer with 0.
Now, we want to make a program, which will check if we’ve done no bad things, then it’ll print “You’re a good boy” if we’ve done no bad things.
So, if we enter 0 in the program it’ll print “You’re a good boy”.
Simple, right?
So we’ve got decide if we entered 0 in the program.
So, how’ll we do it?

You remember this from flowchart?


This is a decision box which will print “You’re a good boy” if num is qual to 0.
The equivalent to this decision making box in programming is a if statement.

It’s general form is like below,

if (...condition 1....)
{
    // ...some code to be executed if condition 1 if true....
}

If the condition 1 is true, then the code within the curly braces will execute.
If the condition 1 is false, well, nothing will happen. The code inside the curly braces will be ignored or bypassed.

So the complete if statement for that decision box above is like below,

if(num == 0)
{
    System.out.println("You're a good boy");
}

So the whole program will be like below,

import java.util.Scanner;

public class ControlFlow{
    public static void main (String[] args){
        Scanner keyboard = new Scanner(System.in);
     System.out.println("How many bad things you did in your     life??");       
        int userChoice = keyboard.nextInt();       
        if(userChoice == 0)
        {
            System.out.println("You're a good boy");
        }
    }
}

In flowchart, if we had nothing to do when the condition is false, then we simple merged the two branches using a connector.
But in Java, you need no connector like flowchart.
If if has nothing to do, then you’ll have to write anything for it.

More simply put, Java will only execute the thing you told it to do. You’ve told only to print if the user enters 0. You didn’t say what to do if the user enters anything other than 0. So, java will just ingore the block of codes after the if statement if the user has entered anything other than 0.

So, as you can see, there’s no need for connector!
It’ll become more clear after we’ve seen some more examples!
Now, back to business!

The program prints “You’re a good boy” if we enter 0.
But what if we did some bad things in our life?

Then we’d want the program to print “Not a good boy!”, won’t we?
Lets see how can we do that!

How the flowchart will be then?
It’ll be like below.

Now what we want to do?
We want to check if user gave us 0 or anything other.
If user gave us 0, then we’ll print “You’re a good boy”, otherwise we’ll print “Not a good boy!”..
Now where the else statement comes into play.

Let’s look at the general form of the else statement first,

if (...condition 1....)
{
    // ...some code to be executed if condition 1 if true....  *** Code block 1 ***
}
else
{
    //  ... if condition 1 isn’t true then execute this code..... *** Code block 2 ***
}

If the condition 1 is true then the codes inside *** Code block 1 *** will be executed.
Otherwise, the codes inside the *** Code block 2 *** will be executed!
So the complete if-else statement for the flowchart above will be like,

if(userChoice == 0)
{
    System.out.println("You're a good boy");
}
else
{
    System.out.println("Not a good boy");
}

If, for example,
User gives 0 as input, it’ll print You’re a  good boy
User gives 2 as input, it’ll print Not a good boy
User gives 320 as input, it’ll print Not a good boy
User gives -34 as input, it’ll print Not a good boy

Simply, if user gives anythings other than 0 as input it’ll print Not a good boy
So, you get the point.
So, the complete code for this program will be,

import java.util.Scanner;

public class ControlFlow{
    public static void main (String[] args){
        Scanner keyboard = new Scanner(System.in);       
        System.out.println("How many bad things you did in your life??");        
        int userChoice = keyboard.nextInt();     
        if(userChoice == 0)
        {
            System.out.println("You're a good boy");
        }
        else
        {
            System.out.println("Not a good boy");
        }
    }
}


If you still can’t figure out the similarities between the flowchart and the code, see this,



(I used variable num when making these flowcharts. num and userChoice are just variable names. They’re essentially doing the same thing!)

Now, think about this.
A boy who did 3 bad things isn’t as bad as a boy who did 30 bad things, isn’t he?
But the program prints all the same!

Let’s justify this now!

We want such a program which will,
Print You’re a good boy if the user gives as input.
Print Not a good boy if the user gives anything less than or equal to as input.
Print You’re a bad boy if the user gives anything greater than as input.

We can do this program by these two ways,

import java.util.Scanner;

public class ControlFlow{
    public static void main (String[] args){
        Scanner keyboard = new Scanner(System.in);       
        System.out.println("How many bad things you did in your life??");
       
        int userChoice = keyboard.nextInt();       
        if(userChoice == 0)
        {
            System.out.println("You're a good boy");
        }
       
        if(userChoice <= 3)
        {
            System.out.println("Not a good boy");
        }
       
        if(userChoice > 3)
        {
            System.out.println("Not a good boy");
        }
    }
}

Here, we’re checking the userChoice three times!
If user gives 0 as input, it’ll print,

You’re a good boy
Not a good boy

Now that’s interesting!

The reason behind this is, firstly the if(userChoice == 0) statement gets checked and it’s true since 0 is equal to 0, and thus the code in it gets executed! So the program printsYou’re a good boy

Then the if(userChoice <= 3)statement gets evaluated and since 0 is less than 3so it’s true as well!

So the codes in it also get executed. Thus, the program prints Not a good boy
But we don’t want that. We only want to check   if(userChoice <= 3only if    if(userChoice == 0)  is false.

This is where the else if statement comes into play!
If we write the above program using else if statements this time,

import java.util.Scanner;

public class ControlFlow{
    public static void main (String[] args){
        Scanner keyboard = new Scanner(System.in);
        
        System.out.println("How many bad things you did in your life??");
       
        int userChoice = keyboard.nextInt();
       
        if(userChoice == 0)
        {
            System.out.println("You're a good boy");
        }
        else if(userChoice <= 3)
        {
            System.out.println("Not a good boy");
        }
        else if(userChoice > 3)
        {
            System.out.println("Not a good boy");
        }
    }
}


Now the    if(userChoice <= 3)   will only get checked  if     if(userChoice == 0)   is false.
And  the    if(userChoice > 3)    will only get checked  if     if(userChoice <= 3)   is false.

So now if the user gives 0 as input, it’ll print,

You’re a good boy

The else if statement is used when there’s a need to check another condition provided the previous if condition is false.

One point to remember, you can’t have else if or else statement without an if statement at first.

The other thing to remember is, you DO NOT need to include else with every if statement.
Include the else or else if statement only when you need to execute some code provided the condition of if statement is false.


No comments

Powered by Blogger.