Selection/Branching, Boolean Expressions & Loops


Boolean Expressions 

Equality and Relational Operators

==      Equal to
!=      Not equal to
>       Greater than
>=      Greater than or equal to
<       Less than
<=      Less than or equal to

Conditional Operators

&&      Conditional-AND
||      Conditional-OR


Selection/Branching

  IF Statement                   Switch Statement                                           

Decision Making  Switch Statement


Sr.No.Statement & Description
1if statement

An if statement consists of a boolean expression followed by one or more statements.

2if...else statement

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

3nested if statement

You can use one if or else if statement inside another if or else if statement(s).

4switch statement

switch statement allows a variable to be tested for equality against a list of values.

  




1. Write a Java program to get a number from the user and print whether it is positive or negative. 

Test Data
Input number: 35
Expected Output :
Number is positive

HINT:

        if (input > 0)
        {
            System.out.println("Number is positive");
        }
        else if (input < 0)
        {
            System.out.println("Number is negative");
        }
        else
        {
            System.out.println("Number is zero");
        }


2. Take three numbers from the user and print the greatest number. 

Test Data
Input the 1st number: 25 
Input the 2nd number: 78 
Input the 3rd number: 87
Expected Output :
The greatest: 87


Solution:

import java.util.Scanner;
public class Exercise3 {

    
  public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
   
  System.out.print("Input the 1st number: ");
  int num1 = in.nextInt();
   
  System.out.print("Input the 2nd number: ");
  int num2 = in.nextInt();
   
  System.out.print("Input the 3rd number: ");
  int num3 = in.nextInt();
   
   
  if (num1 > num2)
   if (num1 > num3)
    System.out.println("The greatest: " + num1);
   
  if (num2 > num1)
   if (num2 > num3)
    System.out.println("The greatest: " + num2);
   
  if (num3 > num1)
   if (num3 > num2)
    System.out.println("The greatest: " + num3);
 }
}


3. Write a Java program that keeps a number from the user and generates an integer between 1 and 7 and displays the name of the weekday.

Test Data
Input number: 3 
Expected Output :
Wednesday


Solution:

We can also use switch 


import java.util.Scanner;
public class Exercise3 {

    
  public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Input number: ");
        int day = in.nextInt();

        System.out.println(getDayName(day));
    }

    // Get the name for the Week
    public static String getDayName(int day) {
        String dayName = "";
        switch (day) {
            case 1: dayName = "Monday"; break;
            case 2: dayName = "Tuesday"; break;
            case 3: dayName = "Wednesday"; break;
            case 4: dayName = "Thursday"; break;
            case 5: dayName = "Friday"; break;
            case 6: dayName = "Saturday"; break;
            case 7: dayName = "Sunday"; break;
            default:dayName = "Invalid day range";
        }

        return dayName;
    }
}




4. Write a Java program to find the number of days in a month.

Test Data
Input a month number: 2
Input a year: 2016
Expected Output :
February 2016 has 29 days

Write a program that uses only if statements then another program that uses only a switch statement. 


LOOPS

loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −

Loop Architecture

Java programming language provides the following types of loop to handle looping requirements. 

Sr.No.Loop & Description
1

for loop

Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

2
while loop

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body

3do...while loop

Like a while statement, except that it tests the condition at the end of the loop body.

The for loop Syntax

The syntax of a for loop is −

for(initialization; Boolean_expression; update) {
   // Statements
}

Here is the flow of control in a for loop −

  • The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;).

  • Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop.

  • After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end.

  • The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Flow Diagram

Java For Loop

Example

Following is an example code of the for loop in Java.

public class Test {

   public static void main(String args[]) {

      for(int x = 10; x < 20; x = x + 1) {
         System.out.print("value of x : " + x );
         System.out.print("\n");
      }
   }
}

This will produce the following result −

Output

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19


1. Write a program in Java to display the first 10 natural numbers.

Expected Output :

The first 10 natural numbers are:                                                
                                                                                
1                                                                                
2                                                                                
3                                                                                
4                                                                                
5                                                                                
6                                                                                
7                                                                                
8                                                                                
9                                                                                
10


import java.util.Scanner;

public class Exercise1{


    

  public static void main(String[] args)

    {     

    int i;

System.out.println ("The first 10 natural numbers are:\n");

       //ADD your loop here


System.out.println ("\n");

}

}

2. Write a program in Java to display n terms of natural numbers and their sum.

Test Data
Input number: 7
Expected Output :

                                                                            
The first n natural numbers are : 7                                
1                                                                  
2                                                                  
3                                                                  
4                                                                  
5                                                                  
6                                                                  
7                                                                  
The Sum of Natural Number up to n terms : 28   


Nested loops

We have all seen web page counters that resemble the one shown below .  Your car's odometer works in a similar manner.



Let's take a look at a trace of two nested loops.  In order to keep the trace manageable, the number of iterations have been shortened.

for(num2 = 0; num2 <= 3;  num2++)
{
      for(num1 = 0; num1 <= 2; num1++)
      {
            System.out.println(num2 + "   " + num1);
      }
}
       
MemoryScreen
int num2 int num1
00
1
2
3  end loop
10
1
2
3  end loop
20
1
2
3  end loop
30
1
2
3  end loop
4  end loop

    Remember, in the memory, for loops will register a value one beyond (or the step beyond) the requested ending value in order to exit the loop.

0   0
0   1
0   2
1   0
1   1
1   2
2   0
2   1
2   2
3   0
3   1
3   2

Are we getting a little loopy?



3. Write a program in Java to display the pattern like right angle triangle with a number. USE NESTED LOOPS

Test Data
Input number of rows : 10 
Expected Output :

1                                                                                
12                                                                               
123                                                                              
1234                                                                             
12345                                                                            
123456                                                                           
1234567                                                                          
12345678                                                                         
123456789                                                                        
12345678910     



THE while loops

In the last post we discussed about for loop. In this tutorial we are going to discuss about while loop with the help of examples and flow diagrams. We will cover following topics in this article: a) Introduction to while loop b) Syntax of while loop c) Flow diagram of while loop d) While loop example e) infinite while loop.

What is while loop?
Like for loop, It also executes a block of statements repeatedly until the condition(Boolean expression) returns false.

Syntax of while loop

while (Boolean expression) {
    statement(s) //block of statements
}

The logic in while loop is simple it executes the block of statements when the Boolean expression returns true. It gets terminated when the Boolean expression returns false.

Are you confused??
Don’t worry we will see the flow diagrams and example. That would make you comfortable.

While loop example

class WhileLoopExample {
    public static void main(String args[]){
         int i=10
         while(i>1){
              System.out.println(i);
              i--;
         }
    }
}

The output of this program is:
10
9
8
7
6
5
4
3
2

Image result for java while loops write a program

The do while loop

Image result for java while loops write a program


break Statement 

Image result for java loops break and continue

continue Statement 

Image result for java loops break and continue

Exercise   rewrite Q1, Q2 and Q3 from the for loop and convert them into while loops.

ć
Mohammad Rashed,
Mar 4, 2017, 1:08 AM
ċ
Mohammad Rashed,
Mar 19, 2017, 5:36 AM
ċ
Mohammad Rashed,
Mar 16, 2017, 3:57 AM
ċ
Mohammad Rashed,
Mar 23, 2017, 1:44 AM
Comments