Class 21
Class 21
Class 21
If number of iterations are not known by the user then we need to use while loop.
If number of iterations are not known by the user but code must execute alteast for
one time then we need to use do while loop.
ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.print(i+" "); //1 2 3 4 5 6 7 8 9 10
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
for(;;)
{
System.out.print("Hello "); // infinite Hello
}
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.print("Hello ");
i--;
}
}
}
input:
5
output:
It is a prime number
ex:
----
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
boolean flag=true;
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
System.out.println("It is a prime number ");
else
System.out.println("It is not a prime number");
}
}
class Test
{
public static void main(String[] args)
{
for(int n=2;n<=100;n++)
{
boolean flag=true;
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
System.out.print(n+" ");
}
}
}
input:
6
output:
It is a perfect number
ex:
---
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt(); //6
int sum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
sum+=i;
}
}
if(n==sum)
System.out.println("It is perfect number ");
else
System.out.println("It is not perfect number");
}
}
Q) Write java program to display GCD (Greatest Common Divisor) of two numbers?
input:
12 18
output:
6
ex:
class Test
{
public static void main(String[] args)
{
int a=12,b=18,gcd=0;
fibonacci series : 0 1 1 2 3 5 8
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt(); // 6
int a=0,b=1,c;
for(int i=2;i<=n;i++)
{
c = a+b;
System.out.print(c+" ");
a=b;
b=c;
}
}
}
Assignment program
-------------------
Q) Write a java program to check given number is even or odd without using modules
operator?
ex:
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number :");
int n=sc.nextInt(); // 6
if((n&1) == 0)
System.out.println("It is even number");
else
System.out.println("It is odd number");
}
}