Control Flow Statements in Java

  • Decision Making
       --if-else
       --switch-case
  • Looping
       --for
       --while
       --do-while
  • Others
       --break, continue, label
If...else:

if (condition)
{
  Statements;
}
else
{
  Statements;
}


switch:

switch(expression)
{
    case value1: statement1; break;
    case value2: statement 2; break;
    default :statement 4;
}


for:
for(initial statement;terminal condition;increment instruction)
{
  statements;
}

while statement:
while(condition)
{
  statements;
}

Do-while statement:
do
{
  Statements;
}while(condition);


break, continue, label

break:
  • Can be used to jump out of the loop.
  • break statement can be used with the label also, when a statement is labeled.

  • break label;
    When it is used like this the break is made to labeled statement

    Ex:
    up1: a=a+3;
        ....
    for (i=1;i<100;i++)
    {
        ....
        if (condition) break up1;
        ....
    }
continue:
  • Can be used to continue with the next iteration. continue statement can be used with the label also, when a statement is labeled.

  • continue label;

    up1: for (j=1;j<200;j++)
        ....
        for(i=1;i<100;i++)
        {
          ....
          if (condition) continue up1;
          ....
        }

Program

class factFind
{
  public static void main(String args[])
  {
    int n=5,fact=1,temp;
    temp=n;
    while(n>0)
    {
      fact=fact*n;
      n--;
    }
    System.out.println("Factorial of " +temp+" is "+fact);
  }
}

Click here for another example

Using Do...While

class FactDo
{
 public static void main (String args[])
 {
  int fact=1, i=1, n=5;
  do
  {
    fact = fact *i;
    i++;
  }
  while (i<=n);
  System.out.println("The Factorial of " +n +" is " +fact);
 }
}

Using For Loop

class FactFor
{
 public static void main (String args[])
 {
  int fact=1, i, n;
  n=5;
  for (i=1;i<=n;i++)
  {
    fact=fact*i;
  }
  System.out.println("The Factorial of "+n +" is " +fact);
 }
}


Data types and Operators << Previous

Next>> Arrays, Sorting and Searching

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus










Footer1