stu nicholls dot com | menu - Professional dropdown #3



Control Flow Statements in Java

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: continue:

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);
 }
}

Our aim is to provide information to the knowledge seekers. 

comments powered by Disqus
click here
click here
click here
Footer1