Day15: Loop
Loop(Iterative Statement)
In Java loops are two types:
- Entry Controlled Loop(Condition is tested before the body Ex:- while, for)
- Exit Controlled Loop(Condition is tested after loop body Ex:- do while)
Syntax for while loop:
while(test-condition)
{
//loop body
}
class PrintNos
{
public static void main(String[] args)
{
int i = x;
while(i<=10);
{
System.out.println(i);
i++;
}
}
}
Output : 1 2 3 4 5 6 7 8 9 10
Factorial by while loop
import java.util.Scanner;
class Factorial
{
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int n,f = 1;
System.out.println("Enter an int: ");
n = sc.nextInt();
while(n>1)
{
f = f * n;
n--;
}
System.out.println("factorial is "+f );
}
}
Output : Enter a value -- 10
Syntax of for loop
for(intializer ; text-condition; Stmt)
{
//Loop Body
}
class PrintNos
{
public static void main(String [ ] args)
{
int i;
for (i = 1; i<=10; i++)
{
System.out.println(i);
}
System.out.println("Final value of i is "+i);
}
}
Output :
Factorial from for loop
import java.util.Scanner;
class Factorial
{
public static void main(String [ ] args)
{
Scanner sc = new Scanner(System.in);
int n,f;
System.out.println("Enter an Integer ");
n = sc.nextInt();
for(f = 1; n>1;n--)
f = f * n;
System.out.println("Factorial is "+f);
}
}
Output: Enter an Integer -- 10
Syntax of Do-While loop:
do
{
//loop body
}(while test-condition)
By Using do-while Add Number
import java.util.Scanner;
class AddNo
{
public static void main(String [ ] args)
{
Scanner sc = new Scanner(System.in);
String choice;
do{
System.out.println("Enter the two integer ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Sum is "+(a+b));
System.out.println("Do yourself to repeat(Yes/No)");
choice = sc.nextLine();
}while(choice.equalsIgnoreCase("Yes"));
System.out.println("Thank You");
}
}
Output :





Comments