Skip to main content

Control Structure in Java Programming

Control Structure

Control structure or control statements are the statements which control the flow of program execution. Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be more clear and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions. These are of four types.

1. Conditional or Decision making statement. Example : if, if-else, nested if-else
2. Selection statement and branching. Example : else if ladder, switch, nested switch
3. Iteration or looping. Example for, while, do-while, for each loop
4. Jump statement. Example: break, continue

Decision Making and Branching

Decision Making or Conditional Statements
In programming we face some situations where we want certain block of code to be executed when some condition is fulfilled.

Decision making works on same concept these statement perform a conditional test. If condition evaluates to true one part of program will execute otherwise another part of program will execute.

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time. For example IF, IF-ELSE, NESTED IF-ELSE.

IF Statement
It is very simple decision making statement. It is used to check whether a block of statements will executed or not. It perform a conditional test if condition evaluates to true than block of code executes otherwise not. If statement works only when condition returns true if condition returns false it do nothing.

Syntax for single statement
if (Condition)
    Statement;

Syntax for multiple statement or block
if(Condition)
{
   Statement;
   Statement;
   ------------
   -----------
}

Example: Enter two number and check first number is greater than second number.
Program
import java.util.*;
class Greater_Number
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

//Reading number by user
System.out.println("Enter two numbers ");
int number1 = sc.nextInt();
int number2 = sc.nextInt();

//testing number by if statement;
if(number1>number2)
{
System.out.println("First Number is greater");
System.out.println("Number is "+number1);
}
}
}
Output

IF-ELSE Statement
We know that if statement works only when condition returns true but in case of false return it do nothing. So if we want to work for false part also we can use else block. Else statement can works only with if statement. Direct use of else statement is not possible. So we can say that else is dependent on if statement for it's execution.

Syntax for single statement
           if (Condition)
                 Statement;
           else
                 Statement;

Syntax for multiple statement or block
if (Condition)
{
    Statement;
    Statement;
    ------------
    ------------
}
else 
{
    Statement;
    Statement;
    ------------
    ------------
 }

Example: 
Input selling price and cost price of an item and print whether seller has made profit or loss and how much.
Program
import java.io.*;
class Profit_Loss
{
      public static void main(String args[]) throws IOException
      {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
           
            //Reading values by user
            System.out.println("Enter Selling price of item ");
            int sellingPrice=Integer.parseInt(br.readLine());
            System.out.println("Enter Cost Price of item ");
            int costPrice=Integer.parseInt(br.readLine());
           
            //Calculating difference
            int difference=sellingPrice-costPrice;
           
            //printing message
            if(difference>0)
            {
                        System.out.println("Seller get profit : "+ difference);
            }
            else
            {
                        System.out.println("Seller get loss: "+ difference);
            }
      }
}
Output

Exercise for if else

1. Write a program to find whether a number is even or odd?
2. Write a program to enter temperature in Celsius and convert it into Fahrenheit and if the
    temperature is 98.6 F or more than display fever otherwise normal. F=9*c/5+32.
3. Write a program to find whether a number is positive or negative.
4. Write a program to find whether a year is leap or not.
5. Enter age of a person and check whether he is eligible for voting or not.

Nested If Else Statement
When an If-Else statement contain further If-Else statement inside it than it is known as Nested If-Else.
Syntax:         
If (condition)
{
if(condition)
{
Statement;
                        }
                        else
                        {
                                    Statement;
                        }
            else
            {
                        if(condition)
{
                                    Statement;
                        }
                        else
                        {
                                    Statement;
                        }
            }
Example
Enter a number and check weather number is even or odd and positive or negative.
Program
import java.util.*;
class NestedIfElse
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        System.out.println("Enter a number ");
                        int number = sc.nextInt();
                       
                        if(number>=0)
                        {
                                    if(number%2==0)
                                    {
                                                System.out.println("Number is even positive");
                                    }
                                    else
                                    {
                                                System.out.println("Number is odd positive");
                                    }
                        }
                        else
                        {
                                    if(number%2==0)
                                    {
                                                System.out.println("Number is even negative");
                                    }
                                    else
                                    {
                                                System.out.println("Number is odd negative");
                                    }
                        }
            }
}
Output

Exercise for nested if else

  1. Enter a number and check number is divisible by 2 and 5 or not?
  2. Enter a year and check whether it is Leap year or not or Century year or not. A year which divisible by 100 is century year and year which is divisible by 400 is leap century year and year which is divisible by 4 is leap year.
  3. Enter a character and find whether it is vowel or consonant and upper case or lower case.
  4. Enter three different numbers and arrange them in ascending order?
The Else-If-Ladder
It is a selection statement which select one out of multiple statement. It is also known as If-Else-If staircase because of its appearance. 

It is used to handle multiple conditions. Conditions in else if ladder executes from top to bottom. As soon as a condition returns true statement associated with that get executed and rest of the condition skipped. 

If none of the condition returns true than last else statement executes. But last else statement is optional.

else if ladder is created by adding if statement after else statement because we cannot put a condition inside else directly.

Syntax:
if(condition)
{
    Statement;
}
else if(condition)
{
    Statement
}
else if(condition)
{
    Statement
}
else
{
    Statement
}
Example
Enter marks of three subjects and check the ranking of student according to given slab.
  • If marks are greater than 60% than first division.
  • If marks are greater than 50% than second division.
  • If marks are greater than 40% than third division.
  • If marks lesser than 40% than print fail.
Program
import java.util.*;
class Student_Result
{
public static void main(String args[])
{
 Scanner sc = new Scanner(System.in);

//Reading marks
System.out.println("Enter marks of three subject ");
int physics = sc.nextInt();
int chemistry = sc.nextInt();
int math = sc.nextInt();

//calculating percentage
int total = physics+chemistry+math;
double percent = total*100/300;

//printing message
if(percent>=60)
   System.out.println("First Division");
else if(percent>=50 && percent<60)
   System.out.println("Second Division");
else if(percent>=40 && percent<50)
   System.out.println("Third Division");
else
   System.out.println("Fail");
}
}
Output


Exercise
1.  Enter three sides of a triangle and find whether it is a equilateral(three sides are equal)  or isosceles (two sides are equal) or a scalene (no side is equal) triangle.
1. if(a==b && b==c && c==a) Equilateral
2. if(a==b || b==c || c==a) Isosceles

3. if(a!=b  && b!=c && c!=a) Scalene

2.      Enter a number and check Number entered by you is single digit or  2 digit or 3 digit.
If(n>0 && n<10) Single Digit
If(n>=10 && n<100) Double Digit
If(n>=100 && n<1000) Triple Digit

3.      Find out the total cost that will be paid by the customer
Total Cost
Discount (in Percentage)
Less than Rs. 2000
5%
Rs. 2001 to Rs. 5000
25%
Rs. 5001 to Rs. 10000
35%
Above Rs. 10000
50%

4.      Display grade accordingly.
Marks
Grades
80% and above
Distinction
60% or more but less than 80%
First Division
45% or more but less than 60%
Second Division
40% or more but less than 45%
Pass
Less than 40%
Promotion not granted

5.      Tax rate for water consumed by a consumer:
Water Consumed (in Gallons)
Tax Rate in Rs.
More than 45 but 75 or less
475.00
More than 75 but 125 or less
750.00
More than 125 but 200 or less
1225.00
More than 200 but 350 or less
1650.00
More than 350
2000.00

Example
Write a program to calculate total charges on unit consume according to given slab.

            Units Consumed
Charges
Up to 100 units
80 paise /unit
>100 and up to 200 unit
Rs. 1/unit
>200 units
Rs. 1.25/unit

Program
import java.util.*;
class Bill
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

//reading units by user
System.out.println("Enter total unit consume ");
int unit = sc.nextInt();

double charges=0;

//Calculating charges
if(unit>=1 && unit<=100)
charges = unit*0.80;
else if(unit>=101 && unit<=200)
charges = (100*0.80)+(unit-100)*1;
else if(unit>200)
charges = (100*0.80)+(100*1)+(unit-200)*1.25;

System.out.println("Charges are "+charges);
}
}
Output

Exercise
1.    Program to input the number of days the book in returned late to the library and print the fine to be paid.
Days                                                         Fine / day (Rs)
First 5 days                                               0.80/day
Next 5 days                                               1.20/day
Next 10 days                                             1.70/day
Remaining day’s                                       2.40/day

2.     Calculate charges for parasol:
            Weight
Charge
Up to 10 kg.
Rs. 20 per kg.
For the next 20 kg.
Rs. 10 per kg.
For the next 20 kg.
Rs. 8 per kg.
More than 50 kg.
Rs  5 per kg.

 3.   Calculate Income tax:
Annual Salary
Rate of income tax
Up to Rs. 1,00,000
0%
Rs. 1,00,001 to Rs. 1,50,000
10% of the amount exceeding Rs. 1,00,000
Rs. 1,50,001 to Rs. 2,50,000
Rs. 5000+20% of the amount exceeding Rs. 1,50,000
Above Rs. 2,50,000
Rs. 25,000+30% of the amount exceeding Rs. 2,50,000

The Switch Statement

Switch is a multiple branch selection statement. This statement tests the value of an expression or condition against a list of constants (integers or character or strings constant but never floating point number).

If a match is found, the statements associated with that constant are executes until the break statement or end of switch is reached.

The default statement is executes when no match is found. The default statement is optional.

Switch statement is like if else ladder but like if else it cannot work with real (fractional) values.

Some points about switch
1. A switch can only work for equality comparison because it tests equality of a variable against multiple values.
2. No two case labels in the same switch can have identical value.
3. Switch can work only constant values like int, byte, short, char, long but never with real values like double, float we cannot use variable in place of constant values.
4. A switch statement execute only once when a match is found and never again in the program.
5. Switch case value must be unique, a duplicate value will raise a compile time error.
6. Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case.

Syntax
switch(constant expression)
{         
case 1:
Statement;      
break;
case 2:
Statement;      
            break;
default :
      Statement;                  
}

Switch with Integer
Calculate area according to following criteria.
1.      Area of Circle
2.      Area of Rectangle
3.      Area of Square

Program
import java.util.*;
class Switch_With_Integer
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        System.out.println("1: Area of Circle ");
                        System.out.println("2: Area of Rectangle");
                        System.out.println("3: Area of Square");
                        System.out.println("Enter your choice ");
                        int choice = sc.nextInt();
                       
                        switch(choice)
                        {
                                    case 1:
                                                            System.out.println("Enter Radius ");
                                                            double radius=sc.nextDouble();
                                                            double circleArea = 3.14*radius*radius;
                                              System.out.println("Area of circle is "+circleArea);
                                                            break;
                                    case 2:
                                                            System.out.println("Enter Length");
                                                            int length = sc.nextInt();
                                                            System.out.println("Enter Width");
                                                            int width = sc.nextInt();
                                                            int rectangleArea = length*width;
                                             System.out.println("Area of Rectangle is "+rectangleArea);
                                                            break;
                                    case 3:
                                                            System.out.println("Enter side of square ");
                                                            int side = sc.nextInt();
                                                            int squareArea = side*side;
                                              System.out.println("Square area is "+squareArea);
                                                            break;
                                    default:
                                                System.out.println("Wrong choice");
                        }
            }
}
Output

Switch with Character
Enter two numbers and perform following operations (+, -, *, /, %)
Program
import java.util.*;
class Switch_With_Character
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        //reading data from user
                        System.out.println("Enter two numbers ");
                        int number1 = sc.nextInt();
                        int number2 = sc.nextInt();
                       
                        System.out.println("Enter a symbol (+, -, /, *, %) ");
                        char symbol = sc.next().charAt(0);
                       
                        //switch statement
                        switch(symbol)
                        {
                                    case '+':
                                                System.out.println("Sum "+(number1+number2));
                                                break;
                                    case '-':
                                                System.out.println("Subtract "+(number1-number2));
                                                break;
                                    case '/':
                                                System.out.println("Division "+(number1/number2));
                                                break;
                                    case '*':
                                                System.out.println("Product "+(number1*number2));
                                                break;
                                    case '%':
                                             System.out.println("Modulus "+(number1%number2));
                                             break;
                                    default:
                                                System.out.println("Wrong choice");
                        }
            }
}
Output

Switch with String
Java 7 allow us to use string object in switch statement but for this their are some key points to keep in mind while using string object in switch:

  • It must be only a string object.
  • String object is case sensitive i.e. upper and lower case will treated separately.
  • String object can not be null it must contain some values.

Program
import java.util.*;
class Switch_With_String
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        //reading
                        System.out.println("sports");
                        System.out.println("fruits");
                        System.out.println("vegetable");
                        System.out.println("\nEnter Your choice ");
                        String choice = sc.nextLine();
                        choice=choice.toLowerCase();
                       
                        //switch
                        switch(choice)
                        {
                                    case "sports":
                                                      System.out.println("Cricket, Vally Ball, Hockey");
                                                      break;
                                    case "fruits":
                                                         System.out.println("Apple, Mango, Pine Apple");
                                                         break;
                                    case "vegetable":
                                                         System.out.println("Bringel, Tomato, Potato");
                                                         break;
                                    default:
                                                         System.out.println("Wrong Choice");
                        }
            }
}
Output

Exercise   

1. Enter a weak day number and print following message:
    From 1 To 5 : Monday to Friday
    6 : Weak End
    7 : Holiday
    Any other : Wrong Day Number

2. Write a program to find area, perimeter or diagonal of a rectangle according to the choice taking length and breadth as input. (perimeter =2*(L+B), diagonal=(a2+b2), area=a*b )

3. Enter a character a for addition, s for subtraction, p for product d for division and perform appropriate operation on two numbers.

Fall through

When in absence of break statement after a case its following cases executes automatically until a break statement is found or end of switch is reached, this process is called fall through.

Syntax
switch(constant expression)
{
case 1:
case 2:
case 3:
                statement;       
                break;
case 4:
case 5:
case 6:
              statement;       
              break;
default :
        statement;                   
}

Fall through with integer

Print an appropriate message with the help of slab given below:
1, 2, 11, 12  Winter season
3, 4, 5, 6      Summer season
7, 8              Rainy Season
9, 10            Autumn Season

Program
import java.util.*;
class Fallthrough_By_Integer
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        System.out.println("Enter a month number from 1 to 12 ");
                        int monthNumber = sc.nextInt();
                       
                        switch(monthNumber)
                        {
                                    case  1:
                                    case  2:
                                    case 11:
                                    case 12:
                                                            System.out.println("Winter Season");
                                                            break;
                                    case 3:
                                    case 4:
                                    case 5:
                                    case 6:
                                                            System.out.println("Summer Season");
                                                            break;
                                    case 7:
                                    case 8:
                                                            System.out.println("Rainy Season");
                                                            break;
                                    case  9:
                                    case 10:
                                                            System.out.println("Autumn Season");
                                                            break;
                                    default:
                                                            System.out.println("Wrong Month Number");
                        }
            }
}
Output

Fall through with character

Enter an alphabet and check weather it is an alphabet or not. If it is an alphabet than weather it is vowel or consonant.

Program
import java.util.*;
class Fallthrough_By_Character
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        //Reading alphabet from user
                        System.out.println("Enter an Alphabet ");
                        char alphabet = sc.next().charAt(0);
                       
                        //converting alphabet in lower case
                        alphabet = Character.toLowerCase(alphabet);
                       
                        if(alphabet>='a' && alphabet<='z')
                        {
                                    //Switch
                                    switch(alphabet)
                                    {
                                                case 'a':
                                                case 'e':
                                                case 'i':
                                                case 'o':
                                                case 'u':
                                                                        System.out.println("Vowel");
                                                                        break;
                                                default:
                                                                        System.out.println("Consonant");
                                    }
                        }
                        else
                        {
                                    System.out.println("Not an alphabet");
                        }
            }
}
Output

Fall through exercise

1. Design a Traffic light program with characters (r or R for stop, g or G to go, y or Y for wait)
2. Enter a color from R G B or r g b (Red, Green, Blue) and print it’s name.

Switch with expression

Switch can work with expression also. For this we can put expression in cases instead of a constant value. But it must be clear that no expression should return duplicate value otherwise it will raise a problem for switch and switch will not work because switch is unable to work with duplicate cases.

Example
import java.util.*;
class Switch_With_Expression
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        System.out.println("Enter a number from 1 to 5");
                        int number = sc.nextInt();
                       
                        switch(number)
                        {
                                    case (4/2)-1:
                                                            System.out.println("One");
                                                            break;
                                    case (2*3)/3:
                                                            System.out.println("Two");
                                                            break;
                                    case 9-(2*3):
                                                            System.out.println("Three");
                                                            break;
                                    case (2*2)+0:
                                                            System.out.println("Four");
                                                            break;
                                    case 12%7:
                                                            System.out.println("Five");
                                                            break;
                                    default:
                                                            System.out.println("Wrong Choice");
                        }
            }
}
Output:

Switch with shuffling

Switch shuffling means case will be under i.e. no case will in sequence. If case are un-order still than switch works correctly because switch construct compare constant with case. If a case matched with constant than that case execute.

Program
import java.util.*;
class Switch_With_Shuffling
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        //Reading number from user
                        System.out.println("Enter a number from 1 to 5");
                        int number = sc.nextInt();
                       
                        //switch
                        switch(number)
                        {
                                    case 5:
                                                            System.out.println("Five");
                                                            break;
                                    case 3:
                                                            System.out.println("Three");
                                                            break;
                                    case 1:
                                                            System.out.println("One");
                                                            break;
                                    case 4:
                                                            System.out.println("Four");
                                                            break;
                                    case 2:
                                                            System.out.println("Two");
                                                            break;
                                    default:
                                                            System.out.println("Wrong Choice");
                        }
            }
}
Output

Nested Switch

When a switch contain further switch inside it than it is known as nested switch. A switch cases can have switch in them.

Syntax
switch(expression)
{
case 1:
            switch(expression)
            {
               case 1:
                              Statement:
                           break;
               case 2:
                              Statement;                                          
                              break;
            }
            break;
case 2:
             switch(expression)
            {
               case 1:
                              Statement:
                           break;
               case 2:
                              Statement;                                          
                              break;
            }
            break;
}

Program
import java.util.*;
class Nested_Switch
{
            public static void main(String args[])
            {
                        Scanner sc = new Scanner(System.in);
                       
                        //Creating swith menu
                        System.out.println("1: Cloths");
                        System.out.println("2: Sweets");
                        System.out.println("3: Snacks");
                       
                        //reading user choice
                        System.out.println("Enter your choice ");
                        int choice = sc.nextInt();
                       
                        int ch;
                       
                        //applying switch
                        switch(choice)
                        {
                                    case 1:
                                                 System.out.println("CLOTHS SECTION");
                                                 System.out.println("1: Jeans");
                                                 System.out.println("2: Shirt");
                                                 System.out.println("3: T-Shirt");
                                                 System.out.println("Enter your choice ");
                                                 ch = sc.nextInt();
                                                 
                                                 //Nested switch
                                                 switch(ch)
                                                 {
                                                            case 1:
                                                                   System.out.println("You purchase Jeans");
                                                                   break;
                                                            case 2:
                                                                   System.out.println("You purchase Shirt");
                                                                   break;
                                                            case 3:
                                                            System.out.println("You purchase T-Shirt");
                                                                 break;
                                                            default:
                                                                   System.out.println("Wrong Choice");
                                                 }
                                                 break;
                                    case 2:
                                                System.out.println("SWEETS SHOP");
                                                System.out.println("1: Cake");
                                                System.out.println("2: Chocklet");
                                                System.out.println("Enter your choice");
                                                ch=sc.nextInt();
                                                switch(ch)
                                                {
                                                            case 1:
                                                                   System.out.println("You purchase Cake");
                                                                   break;
                                                            case 2:
                                                           System.out.println("You  purchase Chocklet");
                                                                   break;
                                                            default:
                                                                   System.out.println("Wrong Choice");
                                                }
                                                break;
                                    case 3:
                                                System.out.println("SNACKS STORE");
                                                System.out.println("1: Chips");
                                                System.out.println("2: Cookies");
                                                System.out.println("3: Namkins");
                                                System.out.println("Enter your choice");
                                                ch = sc.nextInt();
                                                switch(ch)
                                                {
                                                            case 1:
                                                                   System.out.println("You purchase Chips");
                                                                   break;
                                                            case 2:
                                                                   System.out.println("You  purchase Cookies");
                                                                   break;
                                                            case 3:
                                                                   System.out.println("You  purchase Namkins");
                                                                   break;
                                                            default:
                                                                   System.out.println("Wrong Choice");
                                                }
                                    default:
                                                System.out.println("Wrong Choice");
                        }
            }
}
Output

Difference between Switch

Switch
If Else
It support integer, character and string constant but does not support any other type.
It support integer, character, decimal , boolean and all other types of value.
The  case does not support variable
It supports variable
It does not support relational operator
It supports relational operator.

Iteration or Looping

The statement that allow a set of instruction to be performed repeatedly until a certain condition is fulfilled is known as iteration or looping.

Java provides three types of loops for, while and do-while loop. All the loops repeat a set of statement as long as a specified condition remains true. This specified condition is generally referred to as loop control.

All loops are similar in functionality, they differ only in their syntax and condition checking time.
Elements and parts of loop

Elements and parts of loop

Generally a loop has four parts:

1. Initialization Expression: Before entering in a loop , its control variable must be initialized. The initialization of control variable takes palace under initialization expression. The initialization expression gives the loop control a starting point and this expression is executed only once in the beginning of the loop.

2. Test Expression: This is the expression whose value decides whether the loop body will be executed or not. If the test expression evaluates to true the loop body gets executed otherwise the loop is terminated.

3. Update Expression: The update expression change the value of loop variable. The update expression is executes at the end of the loop after the loop body is executed.

4. Loop Body: The statement that are executed repeatedly (as long as the test expression is true) makes loop body.

Types of loop

Generally loops are to two types.

1. Entry control or pretested or top-tested loop: Loops in which testing occurs first than if testing returns true the loop body will executed otherwise loop will be terminated is known as entry control loop. for example for, while loop. 

2. Exit control or post-tested or bottom tested loop: When loop body is executed first and then the test expression executes, if it returns true then the loop is repeated otherwise loop will terminated. Such type of loop is known as exit control loop. 

Because testing occurs at the last of loop so in exit control loop, body of the loop will execute at least once whether the test condition returns true of false. 

for loop

for loop provides a concise way of writing the loop structure. A for loop statement contain the initialization, condition and updation in one line which provide a easy structure of looping.

Syntax
for(initialization; testing; updation)
{
    Statement 1;
    Statement 2;
    .................
    ................. 
}

Example: Print this series
1     2     3     4     5     6     7     8     9     10
Program
class ForLoop
{
public static void main(String args[])
{
for(int i=1; i<=10; i++)
{
System.out.println(i);
}
}
}
Output

Exercise

1        2        3        4        5        6        7        8        9        10
2        4        6        8        10      12      14      16      18      20
1        4        9        16      25      36      49      64      81      100
2        5        10      17      26      37      50      65      82      101
0        3        8        15      24      35      48      63      80      99     
2        4        8        16      32      64      128    256    512    1024
10      9        8        7        6        5        4        3        2        1

Series element sum
1+1/1*1     2+2/2*2     3+3/3*3     4+4/4*4     5+5/5*5
Program
class ForLoop
{
public static void main(String args[])
{
double sum=0.0;
for(double i=1; i<=5; i++)
{
sum=sum+((i+i)/(i*i));
}
System.out.println("\nSeries element sum is "+sum);
}
}
Output

Exercise

1+ 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +10
1/1  +  1/ 2  +  1/3  +  1/ 4  +  1/5  +  1/7  +  1/8  +  1/9  +  1/10
1/1  +  2/2  +  3/3  +  4/4  +  5/5  +  6/6  +  7/7  +  8/8  +  9/9  +  10/10
1/2  +  2/3  +  3/4  +  4/5  +  5/6  +  6/7  +  7/8  +  8/9  +  9/10  +  10/11
1  +  11  +  111  +  1111  +  11111  + …………..n terms. (Formula: T=T*10+1)

Sum of Series with variable
a+1/3 + a+2/5 + a+3/7 + a+4/9 + a+5/11 + a+6/13 + a+7/15 + a+8/17 + a+9/19 + a+10/21
Program
class Series_Sum
{
public static void main(String args[])
{
//variable declaration
double a = 5, sum = 0, j = 3;
//series element sum
for(int i=1; i<=10; i++)
{
sum=sum+(a+(i/j));
j=j+2;
}
//printing result
System.out.println("\nSeries Sum is : "+sum);
}
}
Output

Exercise

x/1  +  x/2  +  x/3  +  x/4  +  x/5  +  x/6  +  x/7  +  x/9  +  x/10
a/1  +  a/2  +  a/3  +  a/4  +  a/5  + a/6  +  a/7  +  a/8  +  a/9  +   a/10
(a+1)  +  (a+2)  +  (a+3)  +  (a+4)  +  (a+5)  +  (a+6)  +  (a+7)  +  (a+8)  +  (a+9)  +  (a+10)
(1*2) + (2*3) + (3*4) + (4*5) + (5*6) + (6*7) + (7*10) + (8*9) + (9*10)  +  (10*11)

Sum of Series having powered elements
a1/1  + a3/5  + a5/9   +  a7/13 + a/17 ……..…………………….. up to n-terms.
Program
import java.util.*;
class Power_Series_Sum
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//Reading values by user
System.out.println("Enter Number of terms of series ");
int N = sc.nextInt();
System.out.println("Enter value of variable a ");
double a = sc.nextDouble();
double sum=0, j=1;

//Doing sum of series
for(double i=1; i<=N; i=i+2)
{
sum=sum+Math.pow(a,i)/j;
j=j+4;
}
//printing result
System.out.println("Sum is "+sum);
}
}
Output

Exercise

a1/1 + a2/2  +  a3/3  +  a4/4  +  a5/5  +  a6/6  +  a7/7  +  a8/8  +  a9/9  +  a10/10
1/ a1 + 2/a2   + 3/a3    +  4/a4   + 5/a5    + 6/a6   + 7/a7   +  8/a8   +   9/a9  +  10/a10

Do sum of following series having +ve and -ve sign
a/1 - a/2 + a/3 - a/4 + a/5 - a/6 + a/7 – a/8 + a/9 - a/10
Program
class Sign_Series_Sum
{
public static void main(String args[])
{
  //variable declaration
  double a = 5, sum=0;
  int j=2;

  //series sum
  for(double i=1; i<=10; i++)
 {
    sum=sum+(a/i)*Math.pow(-1,j);
    j++;
 }

  //printing of series
  System.out.println("\nSign Series Sum is "+sum);
}
}
Output

Exercise

-1/1  +  1/2  -  1/3  +  1/4  -  1/5  +  1/6  -  1/7  +  1/8  -  1/9  +  1/10
2 – 4 + 6 – 8 + 10 – 12 + 14 – 16 + 18 – 20 


Do sum of following series having elements with factorial
a1/1! + a2/2! + a3/3! + a4/4! + a5/5! +  a6/6!  +  a7/7!  +  a8/8!  +  a9/9!  +  a10/10!
Program
class Factorial_Series_Sum
{
public static void main(String args[])
{
//variable declaration
double a = 5, sum = 0;

//factorial series sum
for(double i=1; i<=10; i++)
{
double factorial=1;
for(double j=1; j<=i; j++)
{
factorial=factorial*j;
}
sum=sum+Math.pow(a,i)/factorial;
}

//printing result
System.out.println("\nFactorial Series Sum is "+sum);
}
}
Output

Exercise

                       1/3!  +  1/4!  +  1/5!  +  1/6!  +  1/7!  +  1/8!  +  1/9!  +  1/10!
                       a/2!   +  a/3!  +  a/4!  +  a/5!  +  a/6!   +  a/7!  +  a/8!  +   a/9!  +  a/10!
             x!/10 + (x+2)!/15 + (x+4)!/20 + (x+6)!/25 +………………….. up to n terms

Nested loop

When a loop contain another loop inside it than it is known as nested loop i.e. Loop inside Loop is nested loop.
Syntax
for(initialization; testing; updatation)
{
    for(initialization; testing; updation)
    {
        statement;
        statement;
        ...............;
        ...............;
    }
}
Example
(1) + 1 + (1*2) + 2 + (1*2*3) + 3 + (1*2*3*4) + 4 + (1*2*3*4*5) + 5
Program
class Nested_Loop
{
public static void main(String args[])
{
//variable declaration
int sum=0, product;
//nested loop
for(int i=1; i<=5; i++)
{
product=1;
for(int j=1; j<=i; j++)
{
product=product*j;
}
sum=sum+product+i;
}
//printing result
System.out.println("\nSum of series is "+sum);
}
}
Output

Exercise

(1) + (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5)

Variations of for Loop

Java offers several variation of for loop that increase the flexibility and applicability of it.

Multiple initialization and updation
A for loop can contain multiple initialization and update expression and these expression are separated by comma.
Example
class Multiple_Initialization
{
public static void main(String args[])
{
//Multiple Initialization in for loop
for(int i=1, j=10; i<=10 && j>=1; i++, j--)
{
System.out.println(i+"\t"+j);
}
}
}
Output

breaking expression, skipping statement, closing for statement 
All expression of  for loop are optional, we can skip any of the expression. If we skip testing condition it makes loop infinite. We can break expression in different lines also like while loop. We can end a loop by adding semicolon (;) after loop.

Example
class For_Loop_Variations
{
public static void main(String args[])
{
//breaking 3 expression in different lines
int i=1;
for(; i<=10; )
{
System.out.println(i);
i++;
}
//updating while printing
for(int j=1; j<=10; )
System.out.println(j++);
//time updating while testing
for(int k=0; ++k<=10;)
System.out.println(k);
//infinite loop because of missing condition
for(int k=1; ;k++)
System.out.println(k);
//infinite empty loop, neither testing nor doing any thing
for(;;);
//Time delay loop i.e. will execute after some time due to very long testing value and hello will print after some delay
for(double k=1; k<=989456563; k++);
System.out.println("Hello");
}
}

Factorial

Factorial of a number is the product of all positive descending integers. Factorial of a number is denoted by exclamation (!) symbol. 

For example if variable is N then it will be represented like N! and if value is 4 than it will be represented like 4!

Factorial of N=5  will be  120. We can calculate it like this:
Factorial = 5 * 4 * 3 * 2 * 1
Factorial = 120

Program
import java.util.*;
class Factorial_Calculation
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number by user
System.out.print("\nEnter a positive number = ");
int Number = sc.nextInt();
//calculating factorial
double factorial=1;
for(double i=1; i<=Number; i++)
{
factorial*=i;
}
//printing result
System.out.println("\nFactorial of "+Number+" is "+factorial);
}
}
Output

Prime Number

A number which is divisible by 1 or itself is known as prime number. For example 2, 3, 5, 7, 11, 17, 19 etc.

0 and 1 are not prime number and 2 is only even prime number rest of the prime numbers are odd.

All numbers after 2 are divisible by 2, so they can never be prime number.

Program
import java.util.*;
class PrimeNumber
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

//reading number from user
System.out.print("Enter a positive number = ");
int Number = sc.nextInt();

//checking for prime
int counter=0;
for(int i=1; i<=Number; i++)
{
if(Number%i==0)
{
counter++;
}
}

//Printing message
if(counter==2)
System.out.println("Number is prime ");
else
System.out.println("Number is not prime");
}
}
Output

Fibonacci Series

Fibonacci series starts from 0 and 1, rest of the steps are created by addition of previous two digits.  For example 0+1 will create 1 and 1+1 will create 2 and 2+1 will create 3 and so on.
Example
              0    1    1    2    3     5     8    13    21    34 ....................................
Program
class Fibonacci_Series
{
public static void main(String args[])
{
//variable declaration
int a=0, b=1,c=0;

//printing first two steps
System.out.print(a+" ");
System.out.print(b+" ");

//printing Fibonacci series
for(int i=1; i<=10; i++)
{
c=a+b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}
Output

Pattern or Shape printing

Simple Number pattern - 1
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Program
class NumberPattern
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(j);
}
System.out.println();
}
}
}
Output

Exercise

5                              5                          1                     
5 4                           4 5                       2 1
5 4 3                        3 4 5                    3 2 1
5 4 3 2                     2 3 4 5                 4 3 2 1
5 4 3 2 1                  1 2 3 4 5              5 4 3 2 1
Simple Number pattern - 2
1 2 3 4 5                  1 2 3 4 5             5 4 3 2 1
1 2 3 4                     2 3 4 5                4 3 2 1
1 2 3                        3 4 5                   3 2 1
1 2                           4 5                      2 1
1                              5                         1
Number pattern with spaces (180 degree rotation)
            1
         2 1
      3 2 1
   4 3 2 1
5 4 3 2 1
Program
class SpaceNumberPattern
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
for(int j=5; j>i; j--)
{
System.out.print(" ");
}
for(int k=i; k>=1; k--)
{
System.out.print(k);
}
System.out.println();
}
}
}
Output

Exercise


            1                   5                   5             1 2 3 4 5           1 2 3 4 5              5 4 3 2 1
         1 2                4 5                5 4                1 2 3 4              2 3 4 5                 5 4 3 2 
      1 2 3             3 4 5             5 4 3                   1 2 3                 3 4 5                    5 4 3
   1 2 3 4          2 3 4 5          5 4 3 2                      1 2                    4 5                       5 4
1 2 3 4 5       1 2 3 4 5       5 4 3 2 1                         1                       5                          5

Triangle Pattern


Program
class TrianglePattern
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)//Raw Print
{
for(int j=5; j>i; j--)//Space print
{
System.out.print(" ");
}
for(int k=1; k<=i; k++)//left Columns print
{
System.out.print(k);
}
for(int k=i-1; k>=1;k--)//right Columns print
{
System.out.print(k);
}
System.out.println();
}
}
}
Output

Exercise

        



    

Diamond Pattern


Program
class DiamondPattern
{
public static void main(String args[])
{
//upper half matrix print
for(int i=5; i>=1; i--)//Raw loop
{
for(int j=1;j<i; j++)//space loop
{
System.out.print(" ");
}
for(int k=i; k<=5; k++)//left column loop
{
System.out.print(k);
}
for(int k=4; k>=i; k--)//right column loop
{
System.out.print(k);
}
System.out.println();
}

//lower half matrix print
for(int i=2; i<=5; i++)//Raw loop
{
for(int j=1; j<i; j++)//space loop
{
System.out.print(" ");
}
for(int k=i; k<=5; k++)//left column loop
{
System.out.print(k);
}
for(int k=4; k>=i; k--)//right column loop
{
System.out.print(k);
}
System.out.println();
}
}
}
Output

Exercise

 

Square Shape Pattern

1 2 3 4 5 4 3 2 1
1 2 3 4 4 3 2 1
1 2 3 3 2 1
1 2 2 1
1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 4 3 2 1
Program
class SquareShape
{
public static void main(String args[])
{
  //top half matrix print
  int space=-1;
for(int i=5; i>=1; i--)//raw loop
{
for(int j=1; j<=i; j++)//left top column print
{
System.out.print(j);
}
for(int k=1; k<=space; k++)//middle top space print
{
System.out.print(" ");
}
space=space+2;
for(int j=i; j>=1; j--)//right column print
{
if(j==5)
continue;
else
System.out.print(j);
}
System.out.println();
}
             
  //bottom half matrix print
space=5;
for(int i=2; i<=5; i++)//raw loop
{
for(int j=1; j<=i;j++)//left bottom column print
{
System.out.print(j);
}
for(int k=1; k<=space; k++)//middle bottom space print
{
System.out.print(" ");
}
space=space-2;
for(int j=i; j>=1; j--)//right bottom column print
{
if(j==5)
continue;
else
System.out.print(j);
}
System.out.println();
}
}
}
Output

Exercise

5 4 3 2 1 2 3 4 5
5 4 3 2 2 3 4 5
5 4 3 3 4 5
5 4 4 5
5 5
5 4 4 5
5 4 3 3 4 5
5 4 3 2 2 3 4 5
5 4 3 2 1 2 3 4 5

Star Pattern 

*
* *
* * *
* * * *
* * * * *
Program
class StarPattern
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Output

Exercise

* * * * *                    *               * * * * *                      *                             *
* * * *                    * *                  * * * *                    *  *                          * *
* * *                    * * *                     * * *                 *  *   *                       * * *
* *                    * * * *                        * *               *   *  *  *                    * * * *
*                    * * * * *                           *           *  *   *  *  * *                * * * * *

Numbers without re assigning or Floyd's Triangle

1
2    3
4    5    6
7    8    9    10
11  12  13  14  15
Program
import java.util.*;
class Re_Assign_Pattern
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

//reading rows for Floyd's triangle
System.out.print("Enter number of rows for Floyd's  triangle = ");
int rows=sc.nextInt();

//Printing Floyd's triangle
int k=0;
for(int i=1; i<=rows; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(++k+"\t");
}
System.out.println();
}
}
}
Output

Special Pattern 

1
1 0
1 0 1
1 0 1 0
1 0 1 0 1
Program
class SpecialPattern
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(j%2+" ");
}
System.out.println();
}
}
}
Output

Exercise

Pattern 1
*
*
*
* *
*
* * *
*
* * * *
*
* * * * *
*
* * * * * *
Pattern 2
      #          #          #          #          #
      #          *          *          *          #
      #          *          *          *          #
      #          *          *          *          #
      #          #          #          #          #

Enhanced For loop or for each loop

It is a loop by which we can iterate through the elements of an array. It can be used only to iterate through the elements of array in sequential manner without knowing the index of array elements.

It is a read only loop because values in the array can not be modified by using for each loop. It is only used to display values of array.
Syntax
for(int element: Array)
{
    System.out.println(element);
}
Program
class For_Each_Loop
{
public static void main(String Array[])
{
for(String element:Array)
{
System.out.println(element);
}
}
}
Output

Second program of for each loop 
class For_Each_Loop
{
public static void main(String args[])
{
int Array[]={10,20,30,40,50};
System.out.println("Array elements are ");
for(int element:Array)
{
System.out.println(element);
}
}
}
Output

While Loop

It is an entry controlled loop because it performs a conditionl test first, if this test returns true than loop executes otherwise not.

This loop is used when the number of times to repeate a process is not known beforehanded or fixed.

It is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

The while loop can be consider as a repeating if statement.
Syntax
initialization;
while(Boolean condition) // for single statement
         statement;
Or
initialization;
while(Boolean condition) // for multiple statement
{
   Statement 1;
   Statement 2;
   …………...
   ……….......
   updation;
}
Example
Print a reverse series from 10 to 1 like this
10   9   8   7   6   5   4   3   2   1
Program
class Reverse_Series
{
public static void main(String args[])
{
int i=10;
while(i>=1)
{
System.out.println(i);
i--;
}
}
}
Output

Variations of while loop

While loop have many variations like for loop. It can be empty or infinit loop. It's three statements (initialization, testing, updation) are in three different lines unlike for loop where all statements are in one line. We can arrange these three statements in different ways.
Program
class While_Loop_Variations
{
public static void main(String args[])
{
//time delay loop
long wait=0;
while(++wait<999999999)
{
;
}
System.out.println("It was time delay loop");
//infinite loop
int i=1;
while(i<=10)
System.out.println(i);
//infinite loop
while(true)
System.out.println("Welcome To Infinite Loop");
//testing and updation in one line
int i=0;
while(i++<=10)
{
System.out.println(i);
}
}
}

Reverse digits of a multi digit number

Program
import java.util.*;
class Reverse_Digit
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

//reading number by user
System.out.print("\nEnter a multi digit number = ");
int number=sc.nextInt();

//doing reverse digit of number
int remainder,sum=0;
while(number>0)
{
remainder=number%10;
sum=sum*10+remainder;
number/=10;
}
System.out.println("\nReverse digit of number = "+sum);
}
}
Output

Exercise

  1. Do sum of all digits of a number like, sum of digits of 1234 is 10.
  2. Do sum of first and last digit of a number, like sum of first and last digit of 1234 is 5.
  3. Do sum of even and odd digits separatly, like sum of even digits is 6 and odd digits is 9 in number 12345.
  4. Count the digits of a number except 0, like number 12035064 have 6 digit without 0.
  5. Count the odd and even digits of a number seporatly, like 1254362 contain 4 even digits and 3 odd digits.

Armstrong Number

A number is said to armstrong number
if sum of cube of every digit of a  number in case of triple digit number
if sum of biquadrates (4 power) of every digit of a number in case of four digit number
if sum of number raise to power n of every digit of a number in case of n digit number
is equal to orignal number

for example following are armstrong number

triple digit number 153 
153 = (1)3 + (5)3 + (3)3
153 = 1 + 125 + 27
153 = 153

four digit number 1634
1634 = (1)4  + (6)4 + (3)4 + (4)4
1634 = 1 + 1296 + 81 + 256
1634 = 1634

multiple digit number abcde
abcde…. =  pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + pow(e,n) + ……..
where n is total number of digits of number abcde.....
Program
import java.util.*;
class Armstrong_Number
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number by user
System.out.print("\nEnter a multi digit number = ");
int number=sc.nextInt();
//keeping a temporary copy of number
int tempNumber=number;
//counting total digit of number
int totalDigit = Integer.toString(number).length();
//doing sum of digit
double remainder,sum=0;
while(number>0)
{
remainder=number%10;
sum=sum+Math.pow(remainder,totalDigit);
number/=10;
}
//printing message
if(sum==tempNumber)
System.out.println("\nArmstrong number");
else
System.out.print("\nNot Armstrong number");
}
}
Output

Palindrome Number

A number whose reverse and anti reverse is same is known as palindrome number. For example 121 is a plindrome number because it's reverse is also 121.
Program
import java.util.*;
class Palindrome_Number
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

//reading number by user
System.out.print("\nEnter a multi digit number = ");
int number=sc.nextInt();

//storing temporary copy of number
int temporaryNumber = number;

//doing reverse digit of number
int remainder,sum=0;
while(number>0)
{
remainder=number%10;
sum=sum*10+remainder;
number/=10;
}

//printing message
if(sum==temporaryNumber)
{
System.out.println("\nPalindrome Number");
}
else
{
System.out.print("\nNot Palindrome Number");
}
}
}
Output

Perfect Number

Any number can be a Java Perfect Number if the sum of its positive divisors excluding the number itself is equal to that number. 
For example 6 is a perfect number because it divisor 1, 2 and 3 sum is also equal to 6.
6 = 1 + 2 +3
6 = 6
Program
import java.util.*;
class Perfect_Number
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number by user
System.out.print("\nEnter a number = ");
int number=sc.nextInt();
//doing sum of divisor
int i=1,sum=0;
while(i<number)
{
if(number%i==0)
{
sum=sum+i;
}
i++;
}
//printing message
if(sum==number)
System.out.println("Number is perfect");
else
System.out.println("number is not perfect");
}
}
Output

Buzz Number

A number is said to be Buzz Number if it ends with 7 or is divisible by 7. 
Example 
1007 is a Buzz Number as it end with 7  
343 is also a Buzz Number as it is divisible by 7 
77777 is also a Buzz Number as it ends with 7 and also it is divisible by 7 
Program
import java.util.*;
public class BuzzNumber_Check
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
//reading number
        System.out.println("Enter a number ");
        int number=sc.nextInt();
//printing message
        if(number%10==7 || number%7==0)
        {
            System.out.println(number+" is a Buzz Number");
        }
        else
        {
            System.out.println(number+" is not a Buzz Number");
        }
    }
}
Output

Automorphic number

A number whose square "ends" in the same digits as the number itself is known as Automorphic number.
Example
52 = 25
62 = 36
762 = 5776
3762 = 141376
Program
import java.util.*;
class AutomorphicNumber_Check
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number by  user
System.out.println("Enter a number ");
int number=sc.nextInt();

//storing square of number
int square=number*number;

//checking number
while(number>0)
{
if(number%10 != square%10)
{
break;
}
number/=10;
square/=10;
}

//printing message
if(number==0)
System.out.println("Number is Automorphic ");
else
System.out.println("Not Automorphic Number ");
}
}
Output

Special Number

A number is said to be Special if the sum of the factorial of its digits is equal to the original number. 

For example 145 is a special number because it's digit factorial sum is also 145. 

To check for special number, we need first calculate the factorial of its digits and then sum it up.

Orignal Number = 145
Sum = 1! + 4! + 5!
Sum = 1  + 24 + 120
Sum = 145
Orignal Number == Sum
Program
import java.util.*;
class SpecialNumber_Check
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number
System.out.print("\nEnter a multi digit number = ");
int number = sc.nextInt();
//keeping a temporary copy of original number
int temporaryNumber = number;
//calculating sum of digit's factorial
int sum=0;
while(number!=0)
{
int remainder = number%10;
int factorial=1;
for(int i=1; i<=remainder; i++)
{
factorial=factorial*i;
}
sum=sum+factorial;
number=number/10;
}
if(sum==temporaryNumber)
System.out.println("\nNumber is special");
else
System.out.println("\nNumber is not special");
}
}
Output

Magic Number

A magic number is one whose digit sum is calculated till a single digit is obtained by recurisively adding the sum of its digits. 

If single digit obtained is 1, then the number is magic number, otherwise not.

for example 874 is a magic number because if we add its digit recursive upto obtained single digit, then we will get 1 as single digit from it.
874 = 8 + 7 +4
       = 19
19   = 1+9 
       = 10
10   = 1+0
       = 1
Program
import java.util.*;
class MagicNumber_Check
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number
System.out.print("\nEnter a multi digit number = ");
int number = sc.nextInt();
//calculating sum of digits recursively to get single digit
int sum=0;
while(true)
{
//doing sum of digits
sum=0;
while(number!=0)
{
int remainder = number%10;
sum=sum+remainder;
number=number/10;
}
//checking for single digit to stop process of adding
if(sum>=1 && sum<=9)
break;
else
number=sum;
}
//Printing message
if(sum==1)
System.out.println("\nNumber is Magic");
else
System.out.println("\nNumber is not Magic");
}
}
Output

Duck Number

A number is said to be DUCK Number if zeros (0) are present in it, but no 0 should be present in the beginning of number.

For example 1205, 1230 are duck numbers while 0142 is not a duck number because starting with 0
Program
import java.util.*;
class DuckNumber_Test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

//reading a number by user in string variable
System.out.println("Enter a number ");
String num=sc.next();

//fetching 0th position number
char startDigit = num.charAt(0);

//checking 0th position number is 0 or not
if(startDigit!='0')
{
//converting string number to integer number
int number=Integer.parseInt(num);

//checking for 0s in between of number
while(number>0)
{
int remainder=number%10;
if(remainder==0)
{
break;
}
number=number/10;
}

//printing message
if(number!=0)
System.out.println("Number is duck, contain 0s in between");
else
System.out.println("Number is not duck, does not contain 0s in between");
}
else
{
System.out.println("Not duck number because starting with 0");
}
}
}
Output

Unique Number

A number is said to be unique if digits of it are not repeated. It must be a positive integer with no duplicate digits and no leading zeros (zeros at last).

For example 5, 123, 5469 are all unique numbers whereas 11, 5151, 400 are not unique numbers.
Program
import java.util.*;
class UniqueNumber_Check
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading an integer by user
System.out.print("\nEnter a number = ");
int number = sc.nextInt();
//keeping temporary copy of number
int NumberCopy=number;
//checking for repetition of digits
int counter=0;
while(number!=0)
{
int remainder = number%10;
//keeping original number copy into temp variable
int temp = NumberCopy;
//counting repetition of digit
counter=0;
while(temp!=0)
{
if(remainder==temp%10)
{
counter++;
}
temp=temp/10;
}
if(counter>1)
break;
else
number=number/10;
}
//printing message
if(counter==1)
System.out.println("\nNumber is unique number");
else
System.out.println("\nNumber is not unique number");
}
}
Output

Twisted Prime Number

If a number and its reverse is a prime number then it is a twisted prime number.
For example 167 is a prime number and its reverse is 761 that is also a prime number, so it is a twisted prime number.
Program
import java.util.*;
class TwistedPrime_Check
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number by user
System.out.print("\nEnter a number = ");
int number = sc.nextInt();
//checking for prime
boolean result1 = isPrime(number);
if(result1==true)
{
//keeping temporary copy of number
int temporayNumber = number;
//reversing digit of number
int sum=0;
while(temporayNumber!=0)
{
int remainder = temporayNumber%10;
sum=sum*10+remainder;
temporayNumber = temporayNumber/10;
}

//checking reverse number is prime or not
boolean result2=isPrime(sum);
//printing message
if(result1==result2)
System.out.println("\nTwisted Prime Number ");
else
System.out.println("\nNot Twisted Prime Number");
}
else
{
System.out.println("\nEnter a prime number ");
}
}
//function to checking prime number
static boolean isPrime(int number)
{
int  counter=0;
for(int i=2; i<number; i++)
{
if(number%i==0)
{
counter++;
}
}
if(counter==0)
return true;
else
return false;
}
}
Output

Twin Prime 

A twin prime are the prime numbers whose difference is two. For example 5 and 7 are prime number and their difference is 2 so these are twin prime.
Program
import java.util.*;
class TwinPrime_Check
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

//reading number by user
System.out.print("\nEnter first number = ");
int number1 = sc.nextInt();

System.out.print("\nEnter second number = ");
int number2 = sc.nextInt();

//checking for prime
boolean result1 = isPrime(number1);
boolean result2 = isPrime(number2);

//testing for twin prime
if((result1==true && result2==true) && Math.abs(number1-number2)==2)
{
System.out.println("\nThese are twin prime number");
}
else
{
System.out.println("\nThese are not twin prime number");
}
}

//function to checking prime number
static boolean isPrime(int number)
{
int  counter=0;
for(int i=2; i<number; i++)
{
if(number%i==0)
{
counter++;
}
}
if(counter==0)
return true;
else
return false;
}
}
Output

Removing zero

Removing zeros from a multidigit number. Like if number is 5400207 then it pring like 5427
Program
import java.util.*;
class Removing_Zeros
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number by user
System.out.print("Enter a number = ");
int number = sc.nextInt();
//removing zeros from number
String sum="";
while(number>0)
{
int remainder=number%10;
if(remainder!=0)
{
sum=remainder+sum;
}
number=number/10;
}
//printing converted number
System.out.println("\nNumber after removal of zeros "+sum);
}
}
Output

Greatest common divisor or HCF (Highest Common Factor)

The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder).
Program
import java.util.*;
class GCD_HCF
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading two numbers
System.out.print("\nEnter first number = ");
int number1=sc.nextInt();
System.out.print("\nEnter second number = ");
int number2 =sc.nextInt();

//testing for GCD or HCF
while(number1%number2!=0)
{
int temporaryVarible=number1%number2;
number1=number2;
number2=temporaryVarible;
}
//printing 
System.out.println("\nGCD or HCF of two numbers = "+number2);
}
}
Output

LCM (Least Common Multiple)

LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers.
For example LCM of 15 and 20 is 60 and LCM of 5 and 7 is 35.
Program
import java.util.*;
class LCM_Check
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading two numbers
System.out.print("\nEnter first number = ");
int number1=sc.nextInt();
System.out.print("\nEnter second number = ");
int number2 =sc.nextInt();
//getting product of two numbers
int product = number1*number2;
//testing for LCM
while(number1%number2!=0)
{
int temporaryVarible=number1%number2;
number1=number2;
number2=temporaryVarible;
}
//calculation for lcm
int LCM = product/number2;
//printing result
System.out.println("\nLCM of two numbers = "+LCM);
}
}
Output

Happy Number

A happy number is one whose digit sum is calculated till a single digit is obtained by recurisively adding the sum of squares of its digits. 
If single digit obtained is 1, then the number is happy number, otherwise not.
for example 19 is a happy number because if we add its digits square recursively upto obtained single digit, then we will get 1 as single digit from it.
19à(12+92)à82
82à(82+22)à68
68à(62+82)à100
100à(12+02+02)à1

Program
import java.util.*;
class HappyNumber
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number by user
System.out.print("\nEnter a number = ");
int number=sc.nextInt();
//calculating happy number
int sum;
while(true)
{
//adding sum of digit square
sum=0;
while(number!=0)
{
int remainder=number%10;
sum=sum+(remainder*remainder);
number=number/10;
}
if(sum>=1 && sum<=9)
{
break;
}
else
{
number=sum;
}
}

//printing message
if(sum==1)
System.out.println("\nNumber is Happy");
else
System.out.println("\nNumber is not Happy");
}
}
Output

Do While loop

It is an exit control loop because unlike for and while loop, the do-while loop evaluates its test expression at the end of loop. This means that a do-while loop always executes at least once whether condition is true or false. So where we need to execute loop body atlease once there we can use do while loop.
Syntax
do
{
    statement1;
    statement2;
    ..................
    ..................
    updation;
} while(test expression or conditional expression);

Example
class Character_Series_Print
{
public static void main(String args[])
{
//initialization of loop counter
char ch='a';
do
{
//printing statement in loop body
System.out.print(ch+" ");
//updation of loop counter
ch++;
//testing loop condition
}while(ch<='z');
}
}
Output

Problem

Write a programe to enter some number by user in do while loop and do the sum of all positive number and counting of all negative number entered. After every iteration loop will ask user to continue or break the loop.
Solution
import java.util.*;
class Even_Odd_Test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//variable declaration
int positiveSum=0, negativeCounter=0;
//initialization of loop counter
char choice='y';
do
{
//reading numbers by user
System.out.println("Enter a number ");
int number = sc.nextInt();
//testing number for operation
if(number>0)
positiveSum=positiveSum+number;
else
negativeCounter++;
//reading user choice for next iteration
System.out.println("\nDo you want to enter more numbers \nPress y for yes ");
choice = sc.next().charAt(0);
//testing condition for loop next iteration
}while(choice=='y' || choice=='Y');
//printing results obtained after loop
System.out.println("Positive Number Sum is "+positiveSum);
System.out.println("Negative Number Count is "+negativeCounter);
}
}
Output

Problem

Write a programe to enter some numbers and find maximum and minimum number entered by do while loop.
Solution
import java.util.*;
class Maximum_Minimum_Check
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading initial number by user
System.out.println("Enter initial number ");
int number = sc.nextInt();
//variable declaration and initialization
int maximum=number, minimum=number;
//initialization of loop counter
char choice='y';
do
{
//reading numbers by user
System.out.println("Enter a number ");
number = sc.nextInt();
//testing number for operation
if(number>0)
{
//searching for maximum number
if(maximum<number)
maximum=number;
//searching for minimum number
if(minimum>number)
minimum=number;
}
else
{
System.out.println("You should enter positive number only");
}
//reading user choice for next iteration
System.out.println("\nDo you want to enter more numbers \nPress y for yes ");
choice = sc.next().charAt(0);
//testing condition for loop next iteration
}while(choice=='y' || choice=='Y');
//printing results obtained after loop
System.out.println("Maximum Number Entered is "+maximum);
System.out.println("Minimum Number Entered is "+minimum);
}
}
Output

Problem

Write a programe to enter some numbers and find second maximum number  by do while loop.
Solution
import java.util.*;
class SecondMaximum_Test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading initial number
System.out.println("Enter a number ");
int number=sc.nextInt();
//variable declaration and initialization
int maximum=number, secondMaximum=0;
char choice='y';
do
{
//reading number by user
System.out.println("Enter a number ");
number=sc.nextInt();
//checking for second Maximum number
if(maximum<number)
{
if(secondMaximum<maximum)
{
secondMaximum=maximum;
}
maximum=number;
}
else if(secondMaximum<number)
{
secondMaximum=number;
}
//reading user choice for next iteration
System.out.println("Do you want to enter more numbers\nPress y for yes");
choice=sc.next().charAt(0);
//testing for loop control for loop progress
}while(choice=='y' || choice=='Y');
//printing message
System.out.println("First Maximum number is "+maximum);
System.out.println("Second Maximum number is "+secondMaximum);
}
}
Output

Exercise

  1. Print a table of 2 from 2  to 20.
  2. Print a reverse series from 19 to 1 with step of 2 like this : 19  17  15  ............. 1
  3. Print all prime numbers between 1 to 500
  4. Write a program to enter few numbers by do while loop, and to the sum of even, odd number seporatly.
  5. Write a program to enter characters and print vowals only out of them by do while loop.

Difference in for and while loop

FOR LOOP
WHILE LOOP
Initialization may be either in loop or outside the loop.
Initialization is always outside the loop.
Once the statement(s) is executed then after increment is done.
Increment can be done before or after the execution of the statement(s).
It is used when the number of iterations is known.
It is used when the number of iterations is unknown.
Condition is a relational expression.
Condition may be expression or boolean value.
It is used when initialization and increment is simple.
It is used for complex initialization.
For is entry controlled loop.
While is also entry controlled loop.
for ( initialization ; condition ; updation )
{
   statement(s);
 }
while ( condition )
{
    statement(s);
    updation;

Difference in while and do-while loop

WHILE
DO-WHILE
While is entry controlled loop.
Do-while is exit controlled loop.
Condition is checked first then statement(s) is executed.
Statement(s) is executed atleast once, thereafter condition is checked.
No semicolon at the end of while
while(condition)

Semicolon at the end of while.
while(condition);

Brackets are not required for single statement
Brackets are compulsory.
Variable used in loop condition should be initialized before the execution of loop.
Variable may be initialized before or within the loop.
while(condition)
{
statement(s);
updation;
}
Do
 {
 statement(s);
updation;
 }while(condition);

Jump Statement

Jump Statements unconditionally transfer program control from one point to any where within a program. Java has three Jump Statements break, continue and return.
break and continue are used inside loop and switch to intrupt their working while return statement we can use to jump out from functions.
Beside these statements java also provide a standard library function System.exit(1) that helps you break out of a program.

break statements

break statements enables a program to skip over part of the code. 
break statement terminates the smallest enclosing while, do-while, for or switch statement. Execution resumes to the statement immediately after the body of the terminated statement.
If a break statement appears in a nested loop, then it causes an exit from only inner loop.
break is also known as loop control statement because it is used to terminate the loop.
break statement force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop.
break statements are used in the situations where we do not know the actual number of iterations for the loop.
Program
class breakStatement_Check
{
public static void main(String args[])
{
for(int i=1; i<=10; i++)
{
if(i==6)
break;
else
System.out.println(i);
}
}
}
Output

Exercise

  1. Enter 10 numbers and do the sum of only positive numbers, if a negative number occurs then terminate the loop.
  2. Enter few numbers by do while loop and count only even number and as soon as odd number is entered break the loop.
  3. Enter few radius of circle in while loop and check if radius is positive calculate area of circle otherwise terminate the loop.

continue statement

continue statement forces next iteration of loop to execute by skipping code in between.
continue is a loop control structure only because we can use it only in any of three loop (while, do-while, for)
continue immediate jump the loop control to next iteration as soon as it encountered in a loop.
Program
class continueStatement_Check
{
public static void main(String args[])
{
for(int i=1; i<=10; i++)
{
if(i==6)
{
System.out.println();
continue;
}
else
System.out.println(i);
}
}
}
Output

Exercise

  1. Enter few numbers by while loop and do the sum of even positve numbers only,  continue the loop for rest of the numbers.
  2. Enter few numbers by do while loop and count only even number and as soon as odd number is entered continue the loop.
  3. Enter few numbers in a loop and do the sum of positive numbers only if a negative number is entered continue the loop.

Labels statements or Labeled Loop

Label statement in java is just similar to the goto-label statement of c and c++. Here we can use break and continue statement with labels, and by the combination of jump statement and label we can create labeled jump statements. these statements are generally applied in block and nested loops. Label in these statement can be any valid java identifier, generally label is placed before the statement or loop or block ended with colon symbol (:)
Syntax
           Lable :
Program
class LabeledLoop
{
public static void main(String args[])
{
//making labeled loop
outerLoop:
while(true)
{
for(int i=1; i<=10; i++)
{
//using label 
if(i==6)
break outerLoop;
else
System.out.println(i);
}
}
}
}
Output

Exercise

  1. Print this shape by labeled loop
     

Difference between break and continue

break
continue
break takes the control out of the loop
continue brings control on to next the iteration of loop.
break terminate the entire loop.
it skips the remaining statements after it in the loop
break work with loop and switch
continue works with loop only.
It cause early termination of loop
It cause early execution of next iteration.
It stops the loop
It does not stop loop but stop current iteration of loop

Comments

Popular posts from this blog

Structure In C++ Programming

Definition Structure is collection of heterogeneous (different) data types. It is declared by struct keyword. All members of structure by default are public and can be access outside structure by reference variable (structure variable).   Structure elements stored at contiguous memory location. Structure is similar to class except it does not have access specifier (Public, Private, Protected). For example if we want to collect information of a student (Name, Roll Number, Class etc) than we can group these different type of information into a single unit by structure. Syntax struct <structure name> {     element 1;     element 2;     ------------     ------------ }; Declaration of Structure Structure is declared by struct keyword followed by an identifier i.e. the structure name.for example: struct Student Structure body starts with an opening curly braces and ends with closing curly bra...

Array and Two-D Array In Java Programming

Introduction An Array is a collection of constants of similar data type which are reference by a common name i.e. the array name. Array elements store at contiguous (together in sequence) memory location. The lowest address corresponds to the first element and the highest address to the last element. Array can be of any data type but it always stores elements of its own type, i.e. array of integer type will store integers only not any other type values. Need of Array We need array to store multiple values of similar type for which multiple declaration of variable is not possible. Like if we want to store marks of 50 students then it is not possible to declare 50 variables for them but we will simply use an array of integer to store these marks. Indexing in Array Array index always starts from 0. Array first element stores at 0th index and last element’s position will be one less than the total size of array. Subscript Subscript is the index of array....