Class 11 | Control Statements | Java Programming Notes

UNIT 4
Class 11Java Programming

Control Statements

Original Scanned PDF – View Notes

01

Control Statements

The statements that control or alter the flow of execution of the program are known as control statements. In Java control statements are categorized into following groups:

  1. Sequential Statements
  2. Selection (Branching) Statements – if else, if–else–if ladder, nested if–else, switch
  3. Iteration (Looping) Statements – while, do–while, for, foreach
  4. Unconditional (Jumping) Statements – break, continue, goto, return
02

Sequential Statements

Sequential statements are executed one instruction after another or in order in which they occur in the program.

Syntax

Statement 1;
Statement 2;
Statement N;
03

Selection (Branching) Statements (Conditional / Decision Making)

  • They are control statement that executes statements depending upon condition.
  • The condition may be either true or false.
  • If condition is true, set of steps are executed; otherwise another set of steps are executed.

Following types of statement in Java

  1. Simple if statement
  2. if else statement
  3. Nested if–else statement
  4. if–else–if ladder statement
  5. Switch statement

1. Simple if Statement

  • Simple selection statement that executes statement(s) when condition is true.
  • If condition is false, control enters next part of the program.

Syntax

if (condition)
{
    statements;
}
Flowchart for simple if statement Entry Condition T Statements F Exit
Flowchart for simple if statement

Program to calculate commission if sale amount >= 20000

(Commission will be 15% of total sale.)

import java.util.*;
class IFTest
{
    public static void main(String []args)
    {
        float sale, comm=0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter total sale amount");
        sale = sc.nextFloat();
        if (sale >= 20000)
        {
            comm = (sale * 15) / 100;
        }
        System.out.println("Commission amount:" + comm);
    }
}

2. if–else Statement

  • Selection control statement that decides the execution path based on the condition is true or false.
  • If the condition is true, then the statements in the body of if part are executed; otherwise statements in the body of else part are executed.

Syntax

if (condition)
{
    statement 1;
}
else
{
    statement 2;
}
Flowchart for if else statement Entry Condition true false Statement 1 Statement 2 Exit
fig. – flowchart for if–else statement

Program to enter a number and check whether it is odd or even

import java.util.*;
class Number
{
    public static void main(String []args)
    {
        int a;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        a = sc.nextInt();
        if (a % 2 == 0)
        {
            System.out.println("The number is even:" + a);
        }
        else
        {
            System.out.println("The number is odd:" + a);
        }
    }
}

Program to input two numbers to find greater number

import java.util.*;
class Number
{
    public static void main(String []args)
    {
        int a, b;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter first number");
        a = sc.nextInt();
        System.out.println("Enter second number");
        b = sc.nextInt();

        if (a > b)
        {
            System.out.println("a is greater number:" + a);
        }
        else
        {
            System.out.println("b is greater number:" + b);
        }
    }
}

3. Nested if–else Statement

  • An if statement can be inside another if statement.
  • An entire if–else statement within the body of if part or else part of element of another if–else statement is called nested if–else statement.

Syntax

if (condition)
{
    if (condition)
        statement = 1;
    else
        statement = 2;
}
else
    statement = 3;

Program to input age and weight of a person and check he/she is eligible to donate blood or not

(Hint: age > 18 and weight >= 50)

import java.util.*;
class NestedIF
{
    public static void main(String []args)
    {
        int age, weight;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter age and weight");
        age = sc.nextInt();
        weight = sc.nextInt();

        if (age > 18)
        {
            if (weight >= 50)
            {
                System.out.println("You are eligible for donate blood");
            }
            else
            {
                System.out.println("You are not eligible for donate blood");
            }
        }
        else
        {
            System.out.println("You are not eligible for donate blood");
        }
    }
}

4. if–else–if Statement (if–else–if Ladder)

  • Type of conditional statement that allows to check multiple condition and executes different code blocks based on those conditions.
  • It can have multiple branches.

Syntax

if (condition_1)
    statement_1;
else if (condition_2)
    statement_2;
else if (condition_3)
    statement_3;
...
else if (condition_N)
    statement_N;
else
    default statement;
Flowchart for if else if ladder Entry Condition 1 T Statement 1 F Condition 2 T Statement 2 F Condition 3 T Statement 3 F Condition N T Statement N F Default Statement
Flowchart for if–else–if ladder

Program to find greatest number among three numbers

Source note: The comparison expressions below are retained as written in the scanned notes.
import java.util.*;
class GreatestNum
{
    public static void main(String []args)
    {
        int a, b, c;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter three number");
        a = sc.nextInt();
        b = sc.nextInt();
        c = sc.nextInt();

        if (a > b && b > c)
        {
            System.out.println(a + " is the greatest number");
        }
        else if (b > c && c > a)
        {
            System.out.println(b + " is the greatest number");
        }
        else
        {
            System.out.println(c + " is the greatest number");
        }
    }
}

5. Switch Statement

  • Type of conditional statement that allows to check a variable against multiple possible value i.e. case values.
  • Executes different code blocks based on which case value matches with variable.
  • If one case value matches, then default block statement is executed.

Syntax

switch (variable)
{
    case value 1:
        statement 1;
        break;

    case value 2:
        statement 2;
        break;

    ...
    case value N:
        statement N;
        break;

    default:
        default statement;
        break;
}

Program to display name of day according to user choice (1–7)

import java.util.*;
class SwitchTest
{
    public static void main(String []args)
    {
        int choice;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your choice (1-7)");
        choice = sc.nextInt();

        switch (choice)
        {
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            case 4:
                System.out.println("Wednesday");
                break;
            case 5:
                System.out.println("Thursday");
                break;
            case 6:
                System.out.println("Friday");
                break;
            case 7:
                System.out.println("Saturday");
                break;
            default:
                System.out.println("Sorry, your choice is wrong!!");
                break;
        }
    }
}

Program to perform basic arithmetic operation based on user choice

Source note: In the scan, the multiplication, division and modulus cases print result without a visible assignment immediately before those print statements. That source structure is preserved.
import java.util.*;
class ArithmeticOperators
{
    public static void main(String []args)
    {
        int a, b, choice;
        double result;
        Scanner sc = new Scanner(System.in);

        System.out.println("**** menu ****");
        System.out.println("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division\n5 Modulus");
        System.out.println("Enter your choice (1-5)");
        choice = sc.nextInt();

        System.out.println("Enter two number:");
        a = sc.nextInt();
        b = sc.nextInt();

        switch (choice)
        {
            case 1:
                result = a + b;
                System.out.println("The sum is =" + result);
                break;
            case 2:
                result = a - b;
                System.out.println("The Sub is =" + result);
                break;
            case 3:
                System.out.println("The Mul is =" + result);
                break;
            case 4:
                System.out.println("The quotient is =" + result);
                break;
            case 5:
                System.out.println("The Remainder is =" + result);
                break;
            default:
                System.out.println("Your choice is invalid!");
                break;
        }
    }
}
04

Iteration (Looping) Statements

Looping is the process of executing the same program statement or block of statements repeatedly for specified no. of times or until given condition is satisfied.

Looping statements in Java are:

  1. While loop
  2. do–while loop
  3. for loop
  4. Foreach loop

a) While Loop

  • Looping statement that executes program statements repeatedly until given condition is true.
  • Also known as entry-controlled or pre-test loop because condition is checked initially.
  • Statements are not executed if the condition is false initially.

Syntax

initialization;
while (condition)
{
    statement(s);
    increment/decrement;
}
Flowchart for while loop Entry Initialization Condition F Exit T Statement(s) increment/decrement
fig. – Flowchart for loop of while loop

Program to display numbers from 1 to 20

class WhileLoop
{
    public static void main(String args[])
    {
        int i = 1;
        while (i <= 20)
        {
            System.out.println(i);
            i++;
        }
    }
}

Program to find sum of natural numbers from 0 to 100

class NaturalNumber
{
    public static void main(String args[])
    {
        int i = 0;
        int sum = 0;

        while (i <= 100)
        {
            sum += i;      // sum = sum + i;
            i++;
        }

        System.out.println("The sum is" + sum);
    }
}

b) do–while Loop

  • Looping statement that executes program statement repeatedly until given condition is true.
  • Also called post-test or exit controlled loop.
  • Statement(s) are executed once at first even condition is false.

Syntax

initialization;
do
{
    statement(s);
    increment/decrement;
}
while (condition);
Flowchart for do while loop Entry Initialization Statement(s) Increment/decrement Condition False Exit True
fig. – flowchart for do–while loop

Program to display series 5, 9, 13, upto 10th term

Source note: The scan visibly writes int i = 10, n = 5;. It is retained here rather than silently changing it.
class DoWhileLoop
{
    public static void main(String args[])
    {
        int i = 10, n = 5;
        do
        {
            System.out.println(n);
            n = n + 4;
            i++;
        }
        while (i <= 10);
    }
}

c) For Loop

  • Executes statement(s) repeatedly until given condition is true.
  • Also pre-test looping statement.
  • Consists of 3 parts: initialization, condition and increment or decrement.

Syntax

for (initialization; condition; increment/decrement)
{
    statement(s);
}

Example

for (i = 1; i <= 10; i++)
{
    System.out.println(i);
}
Flowchart for for loop Entry Initialization Condition F Exit T Statement(s) increment/decrement
fig. – flowchart for for loop

To display Fibonacci series 0, 1, 1, 2, 3, 5, 8 … nth terms

import java.util.*;
class FibonacciSeries
{
    public static void main(String args[])
    {
        int i, n;
        int t1 = 0, t2 = 1;
        int nextTerm = t1 + t2;

        Scanner sc = new Scanner(System.in);
        System.out.println("How many terms");
        n = sc.nextInt();

        System.out.println(t1 + " " + t2); // Display first & second term
        for (i = 3; i <= n; i++)
        {
            System.out.println(" " + nextTerm);
            t1 = t2;
            t2 = nextTerm;
            nextTerm = t1 + t2;
        }
    }
}

d) Foreach Loop

  • Foreach is looping statement used to access array elements in a array.
  • It travers the arrays or collection until the last element.
  • For each element, it stores element in the variable and executes the body of the foreach loop.

Syntax

for (type var : array)
{
    statements;
}
Flowchart for foreach loop Entry Any element in an array? False Exit True Assign first element to local variable Loop body Any element in an array? False True Assign next element to local variable
fig. – flowchart for foreach loop

Program to illustrate foreach loop

class Program
{
    public static void main(String []args)
    {
        int [] num = {2, 4, 6, 8, 10}; // array declaration/initialization

        for (int i : num)
        {
            System.out.println(i + " ");
        }
    }
}

a. Difference between while & do–while loop

while loopdo–while loop
1. Condition is at top.1. Condition is at the bottom.
2. There is no semicolon at the end of while.2. There is semicolon is compulsory at the end do while.
3. While loop is entry controlled loop.3. do while loop is exit controlled loop.
4. Syntax:
while (condition)
{
    Statement(s);
}
4. Syntax:
do { Statement(s); }
while (condition);

Infinite Loop

  • A loop never terminates is called infinite loop.
  • Executes statement(s) repeatedly which does not meet any ending point.

Example

public class Test
{
    public static void main(String []args)
    {
        int i;
        for (i = 1; i >= 0; i++)
        {
            System.out.println("Value of i:" + i);
        }
    }
}
05

Unconditional (Jumping) Statements

  • Used to jump execution of programs statements from one place to another.
  • Executes some program statements repeatedly or skip some program statements.
  • 3 types of jumping statements:
  1. break
  2. continue
  3. goto return

a) break Statement

  • Used to break the normal flow of program statement execution in loop and switch case statement.
  • Allows to exit from loop or switch statement as soon as certain condition is satisfied.
  • When break is encountered remaining part of loop or switch statement is skipped and control passed to the next statement after loop.

Syntax

break;

Example

for (int i = 1; i <= 5; i++)
{
    if (i == 4)
        break;
    System.out.println(i);
}
O/P
1 2 3

b) Continue Statement

  • Used to continue the flow of execution in loop skipping the iteration in the loop as soon as.
  • When continue is encountered in the loop then that particular iteration is skipped and loop will be continued with next iteration.

Syntax

continue;

Example

class program
{
    public static void main(String []args)
    {
        for (int i = 1; i <= 5; i++)
        {
            if (i == 4)
                continue;
            System.out.println(i);
        }
    }
}
O/P
1
2
3
5

c) return Statement

It returns the value of expression from called method to calling location.

Syntax

return expression;

Program to display sum of two number

Source note: The final print label on page 25 reads "Area =" even though the program heading says sum of two numbers. It is preserved as written.
import java.util.*;
class sum
{
    int a, b;

    void setData(int x, int y)
    {
        a = x;
        b = y;
    }

    int calculate()
    {
        int result;
        result = a + b;
        return result;
    }
}

class Returnstatement
{
    public static void main(String []args)
    {
        int num1, num2;
        sum obj = new sum();
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter two number");
        num1 = sc.nextInt();
        num2 = sc.nextInt();

        obj.setData(num1, num2);
        System.out.println("Area =" + obj.calculate());
    }
}

Program to read a number and check whether it is palindrome or not

(Palindrome no is equal to reversing its digits eg. 121, 11, 252 etc.)

import java.util.*;
class Palindrome
{
    public static void main(String []args)
    {
        int num, rev = 0, digit, temp;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number:");
        num = sc.nextInt();
        temp = num;

        while (num != 0)
        {
            digit = num % 10;
            rev = rev * 10 + digit;
            num = num / 10;
        }

        if (temp == rev)
            System.out.println(temp + " is palindrome number");
        else
            System.out.println(temp + " is not palindrome number");
    }
}

Write Java Program to display multiplication table of ‘n’ number

import java.util.*;
class Multiplication
{
    public static void main(String []args)
    {
        int n, i;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number:");
        n = sc.nextInt();

        for (i = 1; i <= 10; i++)
        {
            System.out.println(n + " * " + i + " = " + n * i);
        }
    }
}

Program to check the entered number is arm strong number or not

Source note: Page 28 contains crossed-out output statements. The final uncrossed output wording is transcribed below, including the phrase “arm strange number”.
import java.util.*;
class Armstrong
{
    public static void main(String []args)
    {
        int n, arm = 0, rem, a;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter n number");
        n = sc.nextInt();

        a = n;
        while (n > 0)
        {
            rem = n % 10;
            arm = (rem * rem * rem) + arm;
            n = n / 10;
        }

        if (a == arm)
            System.out.println(a + " is a arm strange number");
        else
            System.out.println(a + " is a not arm strange number");
    }
}

Discussion

Share a helpful question, idea, or explanation with other students.

Leave a Comment

Write a clear question, answer, or helpful explanation.
Your email will not be published.

Download Our Offline App

Study class-wise notes even when internet is not available. Get the app from Play Store.

Nepal eNotes offline app preview
Get it on Google Play