Java (Chapter 2.1) : Starting IF


For any type of consultation, query or doubt. You may contact to the following:
(+91) 9804 436 193
debabrataguha20@gmail.com 
and join the group 
https://www.facebook.com/groups/331231161093613/


Hope you are now little familiar with the initial code. But the programming we solved in the first chapter was predictable. I want to mean that in case of Centigrade to Fahrenheit temperature conversion program, you always knew that the program will ask for the temperature in centigrade. Then it will give the output in Fahrenheit. The output temperature value will be changed as per the input value. But input lines and output lines are predictable, better to say that the output lines are fixed.

It will never happen that a program sometimes is giving the output as square of input value and sometimes the cube of input value. So if we want two types of output from a single program , we can use “IF”. In real life, we always face multiple options. As an example if we enter month number means 1 for January, 2 for February so on. And we need to write a program which will throw the number of days as output. So the answer is not fixed. For some month-numbers , the answer will be 31, for some it will be 30, sometimes 28 , sometimes 29, even for some absurd values it may show “Invalid month” as well.

So we need to put some condition to get different outputs. We use “IF” to implement this kind of conditions. The simple structure of “IF” is like below:



If ( Condition ) 
{
 //condition is true
            //Some statements 
}

else
{
 //condition is false
            //Some statements 
}


This means, on the success of the condition, java will execute the upper code block whatever is written inside. But on the failure of the condition, it will come to lower code block. I forgot to tell one thing that one “Condition” always will have exact 2 answers. Either “Yes” or “No”. So if the condition returns “yes” , then one part of code , it the condition returns “no”, then another part of code will be executed.

As an example, if we require to write 1 program which will take percentage of attendance as input and return if the student is eligible to sit in the exam or not. To sit in the exam one student requires atleast 60% attendance. So we need to write the program as per below:


import java.util.*;

class chapter2_program1
{
            public static void main (String args[])
{
            Scanner sc=new Scanner(System.in);
                        int a;

                        System.out.println(“Enter percentage of attendance”);
                        a=sc.nextInt();

                        if(a>60)
                        {
System.out.println(” You will be allowed to sit in the exan”);
                        }

                        else
{
System.out.println(” You will not be allowed to sit in the exan”);
}           
}
}


Look at the condition. It should always be written in a way that the answer of this condition comes as “yes” or “no”. To get the answer “yes” or “no” , we can use the operator like greater than (“>”) that we have already used in the above program. We can also use below operators as per requirement to derive into answer either with “yes” or “no”.

Greater than and equals to?       “>=”
Lesser than?                                    “<”
Lesser than and equals to?         “<=”
Equals?                                              “==”
Not equals?                                      “!=”



So if the answer comes “yes” for the above program, it will print “allowed” . Otherwise, means if the answer comes as “no” , it will print “not allowed”. “Else” is similar with the term “otherwise”.


So now my question to you.. Can we write a condition that can give both the answer “yes” and “no” together? If you have any such condition , you can send the same to my email. But it is not possible at all. This is mandatory in the world that  answer to a condition can never be “yes” and “no” together. So either it may be “yes” or it may be “no” . So as a result only one code block can execute in if-else code statement.


We can build more complex logic using this basic If-else structure multiple times in one single program. But for the time being we will use only 1 if-else block in our program.






Remember one thing, to compare the equality of two values , we use double equals , that is “ = =”. Single equals means to assign a value to a variable. Single equals sign never can return “yes” or “no”.

Let’s take another example to take 2 numbers and print the division result of them. Here division would not be that easy. Because if anyone enters the second value as zero. That should be an error or infinite as a result. You can try to divide 10 with zero in your mobile calculator or in desktop. It will never show any result. Rather it will throw some message. In programming , if we try the same, java will throw an error at the runtime. You can try the same. So to avoid that error, we need to handle that situation by writing a condition on second input value.


import java.util.*;
class chapter2_program2
{
            public static void main (String args[])
{

            Scanner sc=new Scanner(System.in);
                        int num1,num2;

                        System.out.println(“Enter 2 numbers”);
                        num1=sc.nextInt();
                        num2=sc.nextInt();

                       
                        if(num2==0)
                        {
System.out.println(” can not divide.. ”);
                        }
                        else
{
System.out.println(” the answer is ” + (num1 / num2) );
}           
}

}



Similarly we can write conditions to check if the input number is even or odd , or a year is leap year or not etc. We can also build tough logics using nested If-Else structure. We will discuss the same on the next chapter.



Lastly , It is not mandatory to use an “Else” part with “IF” part. We can also write programs using if statement only, without using “else” option. In some situation , it may happen that we do not require to write any code for Else part. Then we can skip the same. As an example , with the continuation of above program, if anyone input second number greater than first number. Then to get correct division answer , we need to swap them. But if the first number is greater, we do not require to do anything.

import java.util.*;

class chapter2_program3

{

            public static void main (String args[])

{

            Scanner sc=new Scanner(System.in);

                        int num1,num2;

                        System.out.println(“Enter 2 numbers”);
                        num1=sc.nextInt();
                        num2=sc.nextInt();

                       

                        // swapping the numbers 
// if second number is larger than the first number
// if the first number is greater , no action required

if ( num2 > num1 )
                        {
                                    int t    = num1;
                                    num1 = num2;
                                    num2 = t;
                        }

                        // separate if block, separate condition
                        if(num2==0)
                        {
System.out.println(” can not divide.. ”);
                        }
                        else
{
System.out.println(” the answer is ” + (num1 / num2) );
}           
}
}


In the above program,  it should also be noticed that 2nd if block is not dependent on the 1st IF block. They are separated flow and independent to each other.



Now lets do some exercise from the FACEBOOK Group à “Basic Exercise” album and from the page “Starting If” only. You can send me your query or doubt to the email id mentioned above with all the program related details.


Comments

Popular posts from this blog

Java concepts Theory