C Programming सीखते समय if–else statement का use समझना बहुत जरूरी होता है।
इस article में हम एक simple C program सीखेंगे जो Profit और Loss calculate करता है।
यह program beginners के लिए best exercise है क्योंकि इसमें:
- User input
- Condition checking
- Real-life logic
सब कुछ शामिल है।
Problem Statement
C language में एक program लिखिये जो profit और loss calculate करें।
Program को ये काम करने होंगे:
- User से Cost Price (cp) और Sell Price (sp) input लेना
- अगर cost price या sell price 0 या 0 से कम हो, तो
“Invalid Input! Price cannot be 0 or negative” - अगर sell price > cost price → Profit
- अगर sell price < cost price → Loss
- अगर दोनों बराबर हों → No Profit, No Loss
Program Code (C Language)
#include<stdio.h>
int main()
{
float sp, cp;
printf("Enter Cost price : ");
scanf("%f", &cp);
printf("Enter Sell price : ");
scanf("%f", &sp);
if(sp <= 0 || cp <= 0)
{
printf("Invalid Input! Price cannot be 0 or negative.");
}
else if(sp > cp)
{
printf("Profit : %.2f Rupees", sp - cp);
}
else if(sp < cp)
{
printf("Loss : %.2f Rupees", cp - sp);
}
else
{
printf("No Profit, No Loss");
}
return 0;
}
Sample Output
Input:
Enter Cost price : 500
Enter Sell price : 650
Output:
Profit : 150.00 Rupees
Program Explanation (Step-by-Step)
1️. Header File
#include<stdio.h>
यह header file printf() और scanf() जैसे input-output functions के लिए जरूरी है।
2️. Variable Declaration
float sp, cp;
- cp → Cost Price store करता है
- sp → Sell Price store करता है
float इसलिए use किया गया है ताकि decimal values भी handle हो सकें।
3️. Taking Input from User
scanf(“%f”, &cp);
scanf(“%f”, &sp);
User से cost price और sell price input लेकर variables में store किया जाता है।
4️. Invalid Input Check
if(sp <= 0 || cp <= 0)
अगर कोई भी price:
- 0 है
- या negative है
तो input invalid माना जाएगा और program आगे नहीं बढ़ेगा।
5️. Profit Calculation
else if(sp > cp)
अगर sell price ज़्यादा है cost price से, तो profit होगा।
Formula:
Profit = Sell Price − Cost Price
6️. Loss Calculation
else if(sp < cp)
अगर sell price कम है cost price से, तो loss होगा।
Formula:
Loss = Cost Price − Sell Price
7️. No Profit No Loss Case
else
अगर cost price और sell price बराबर हैं, तो ना profit होगा और ना loss।
