write a java program to find the factorial using while loop and for loop and write a program to swap number in java.

Find the factorial using for loop.........

import java.util.Scanner;
class Ashraf1
{
public static void main(String[] args)
{
int i,n;
long fact =1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number:");
n= sc.nextInt();
for(i=1; i<=n; i++)
fact = fact*i;
System.out.println("The factorial of " + n + " is "+fact);
}
}



Output:
Enter the number:
6
The factorial of 6 is 720

Find the factorial using while loop............

import java.util.Scanner;
class Ashraf2
{
public static void main(String [] args)
{
int i=1, n;
long  fact = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number:");
n = sc.nextInt();
while (i<=n)
{
 fact = fact*i;
i++;
}
System.out.println("The factorial of "+ n + " is " + fact);
}
}

Output:
Enter the number:
6
The factorial of 6 is 720


Swapping  the number using java...............

import java.util.Scanner;
class JavaExample1
{
public static void main(String[] args)
{
int num1, num2;
Scanner st = new Scanner(System.in);
System.out.println("Enter the first number:");
num1=st.nextInt();
Scanner mt= new Scanner (System.in);
System.out.println("Enter the second number:");
num2= mt.nextInt();
System.out.println("Before swapping");
System.out.println(num1);
System.out.println(num2);
swap(num1,num2);
}
public static void swap(int num1,int num2)
{
int temp= num1;
num1 =num2;
num2 = temp;
System.out.println("After swapping ");
System.out.println(num1);
System.out.println(num2);
}
}

Output:
Enter the first number:
60
Enter the second number :
80
Before swapping 
60
80
After swapping 
80
60



Note: This all program firstly I run in my java compiler then I write on this page. 

Md Ashraf

'KNOWLEDGE WITH ASHRAF' is the platform where you find all the type of knowledge especially on programming based. Our goal is to give you a deeper grasp of technology in specifics that will help you increase your knowledge.

Previous Post Next Post

Contact Form