Write a program to calculate profit or loss


The program first creates a Scanner object to read input from the user. It then prompts the user to enter the cost price and selling price of the product using System.out.println() and input.nextInt().

Next, the program uses an if-else statement to determine whether a profit or loss was made. If the selling price is greater than the cost price, the program calculates the profit by subtracting the cost price from the selling price, stores the result in the variable p, and prints the profit. If the selling price is less than the cost price, the program calculates the loss by subtracting the selling price from the cost price, stores the result in the variable l, and prints the loss. If the selling price is equal to the cost price, the program prints "No Profit No Loss".

It is important to note that this program assumes integer values for the cost price and selling price. If the values are decimal numbers, the data type of the variables cp and sp would need to be changed to double instead of int.

Source Code

import java.util.Scanner;
class Profit_Loss
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter The Cost Price :");
		int cp = input.nextInt();
		System.out.println("Enter The Selling Price :");
		int sp = input.nextInt();
		int p,l;		
		if(sp>cp)
		{
			p = sp-cp;
			System.out.println("Profit : "+p);
		}
		else if(sp<cp)
		{
			l = cp-sp;
			System.out.println("Loss : "+l);	
		}
		else
		{
			System.out.println("No Profit No Loss");
		}
	}
}

Output

Enter The Cost Price :
15300
Enter The Selling Price :
18690
Profit : 3390

Example Programs