Skip to content

← Back to Overview

Profit or Loss Calculator

Concept Explanation

What is it?

This program calculates whether a transaction results in a profit, a loss, or a break-even scenario. It takes two primary inputs: the cost price (the price at which an item was bought) and the selling price (the price at which an item was sold).

  • Profit: Occurs when the selling price is greater than the cost price.
  • Loss: Occurs when the selling price is less than the cost price.
  • No Profit, No Loss (Break-even): Occurs when the selling price is equal to the cost price.

Why is it important?

Understanding profit and loss is a fundamental concept in business and economics. In programming, it serves as an excellent practical example for applying conditional logic (if-else statements) to make decisions based on numerical comparisons.

Where is it used?

  • Business Applications: Inventory management, sales tracking, financial reporting.
  • E-commerce Platforms: Calculating margins, discounts, and promotional offers.
  • Personal Finance Tools: Budgeting, tracking investments.
  • Algorithmic Trading: Determining entry/exit points for trades.

Real-world example

Imagine a small shop owner buying a toy for $10 (cost price). If they sell it for $15, they make a profit of $5. If they sell it for $8, they incur a loss of $2. If they sell it for $10, it's a break-even. This program automates this simple calculation.


Algorithm

  1. Start.
  2. Get the cost_price from the user.
  3. Get the selling_price from the user.
  4. Calculate the difference = selling_price - cost_price.
  5. If difference is greater than 0: a. Display "Profit" and the value of difference.
  6. Else if difference is less than 0: a. Display "Loss" and the absolute value of difference.
  7. Else (difference is 0): a. Display "No profit, no loss."
  8. End.

Edge Cases: - Non-numeric input for prices (handled by language-specific error mechanisms or explicit validation). - Zero prices (e.g., free items) should be handled logically by the comparisons.


Implementations

import java.util.Scanner;

public class ProfitOrLoss {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the cost price: ");
        double costPrice = scanner.nextDouble();

        System.out.print("Enter the selling price: ");
        double sellingPrice = scanner.nextDouble();

        System.out.println("Cost Price: $" + costPrice);
        System.out.println("Selling Price: $" + sellingPrice);

        if (sellingPrice > costPrice) {
            double profit = sellingPrice - costPrice;
            System.out.println("The seller is in PROFIT of $" + String.format("%.2f", profit));
        } else if (sellingPrice < costPrice) {
            double loss = costPrice - sellingPrice;
            System.out.println("The seller is in LOSS of $" + String.format("%.2f", loss));
        } else {
            System.out.println("No profit, no loss.");
        }

        scanner.close();
    }
}
# Get cost price from user
cost_price_str = input("Enter the cost price: ")
cost_price = float(cost_price_str)

# Get selling price from user
selling_price_str = input("Enter the selling price: ")
selling_price = float(selling_price_str)

print(f"Cost Price: ${cost_price:.2f}")
print(f"Selling Price: ${selling_price:.2f}")

if selling_price > cost_price:
    profit = selling_price - cost_price
    print(f"The seller is in PROFIT of ${profit:.2f}")
elif selling_price < cost_price:
    loss = cost_price - selling_price
    print(f"The seller is in LOSS of ${loss:.2f}")
else:
    print("No profit, no loss.")
#include <stdio.h>

int main() {
    double cost_price, selling_price;
    double difference;

    printf("Enter the cost price: ");
    scanf("%lf", &cost_price);

    printf("Enter the selling price: ");
    scanf("%lf", &selling_price);

    printf("Cost Price: $%.2lf", cost_price);
    printf("Selling Price: $%.2lf", selling_price);

    difference = selling_price - cost_price;

    if (difference > 0) {
        printf("The seller is in PROFIT of $%.2lf", difference);
    } else if (difference < 0) {
        printf("The seller is in LOSS of $%.2lf", -difference); // Display positive loss value
    } else {
        printf("No profit, no loss.");
    }

    return 0;
}
SET SERVEROUTPUT ON;
DECLARE
  cost_price    NUMBER := &Enter_Cost_Price;
  selling_price NUMBER := &Enter_Selling_Price;
  difference    NUMBER;
BEGIN
  DBMS_OUTPUT.PUT_LINE('Cost Price: $' || cost_price);
  DBMS_OUTPUT.PUT_LINE('Selling Price: $' || selling_price);

  difference := selling_price - cost_price;

  IF difference > 0 THEN
    DBMS_OUTPUT.PUT_LINE('The seller is in PROFIT of $' || difference);
  ELSIF difference < 0 THEN
    DBMS_OUTPUT.PUT_LINE('The seller is in LOSS of $' || ABS(difference));
  ELSE
    DBMS_OUTPUT.PUT_LINE('No profit, no loss.');
  END IF;
END;
/

Explanation

  • Java: Uses if-else if-else structure for comparison. Scanner handles double input. String.format("%.2f", ...) ensures output is formatted to two decimal places for currency.
  • Python: Similar if-elif-else logic. float() converts string inputs. f-strings are used for formatted currency output.
  • C: Employs if-else if-else statements. scanf("%lf", ...) reads double inputs, and printf("$%.2lf", ...) formats output. Uses -difference to display a positive loss amount.
  • Oracle: Implemented in PL/SQL. Uses IF-ELSIF-ELSE blocks. ABS() function is used to display the absolute value of loss. Substitution variables for interactive input.

Complexity Analysis

  • Time Complexity: O(1) - A fixed number of arithmetic operations and comparisons.
  • Space Complexity: O(1) - A fixed number of variables are used.

Flowchart

graph TD
    A[Start] --> B[Get Cost Price]
    B --> C[Get Selling Price]
    C --> D[Calculate Difference = Selling Price - Cost Price]
    D --> E{Difference > 0?}
    E -- Yes --> F[Display PROFIT and Difference]
    E -- No --> G{Difference < 0?}
    G -- Yes --> H[Display LOSS and Absolute Difference]
    G -- No --> I[Display No profit no loss]
    F --> J[End]
    H --> J
    I --> J

Sample Dry Run

Step Cost Price Selling Price Difference Description
Input 100 120 - User enters 100, 120
Process 100 120 20 Difference = 120 - 100 = 20
Decision - - 20 20 > 0? (True)
Output - - - Display "PROFIT of $20.00"
End - - - Program terminates
Input 100 80 - User enters 100, 80
Process 100 80 -20 Difference = 80 - 100 = -20
Decision - - -20 -20 > 0? (False)
Decision - - -20 -20 < 0? (True)
Output - - - Display "LOSS of $20.00"
End - - - Program terminates
Input 50 50 - User enters 50, 50
Process 50 50 0 Difference = 50 - 50 = 0
Decision - - 0 0 > 0? (False)
Decision - - 0 0 < 0? (False)
Output - - - Display "No profit, no loss."
End - - - Program terminates

Practice Problems

Easy

  • Modify the program to also calculate the profit/loss percentage.
  • Extend the program to handle multiple items.

Medium

  • Write a program that calculates the total profit/loss for a series of transactions.
  • Implement a simple inventory system where profit/loss is automatically calculated upon sales.

Hard

  • Develop a financial analysis tool that visualizes profit/loss trends over time.

"The most important property of a program is whether it accomplishes the intention of its user." - C.A.R. Hoare