निर्णय लेने के कथन
- सिंपल if स्टेटमेंट
- if-else स्टेटमेंट
- नेस्टेड if-else स्टेटमेंट
- else-if लैडर
- switch स्टेटमेंट
1. सिंपल if स्टेटमेंट
शर्त सत्य होने पर स्टेटमेंट्स निष्पादित करता है।
if (condition) {
statement(s);
}
उदाहरण: संख्या 50 से बड़ी है?
#include <stdio.h>
int main() {
int a;
printf("Enter any number: ");
scanf("%d", &a);
if (a > 50)
printf("%d is greater than 50", a);
return 0;
}
आउटपुट
Enter any number: 60 60 is greater than 50 Enter any number: 20 (कोई आउटपुट नहीं)
2. if-else स्टेटमेंट
सत्य और असत्य दोनों स्थितियों को हैंडल करता है।
if (condition) {
// ट्रू ब्लॉक
} else {
// फाल्स ब्लॉक
}
उदाहरण: सम/विषम जांच
#include <stdio.h>
int main() {
int n;
printf("Enter any number: ");
scanf("%d", &n);
if (n % 2 == 0)
printf("%d is even", n);
else
printf("%d is odd", n);
return 0;
}
आउटपुट
Enter any number: 10 10 is even
3. नेस्टेड if-else
if को दूसरे if या else के अंदर रखना।
if (condition1) {
if (condition2) stmt1;
else stmt2;
} else {
if (condition3) stmt3;
else stmt4;
}
उदाहरण: तीन संख्याओं में सबसे बड़ी
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter 3 numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
if (a > c)
printf("%d is largest", a);
else
printf("%d is largest", c);
} else {
if (b > c)
printf("%d is largest", b);
else
printf("%d is largest", c);
}
return 0;
}
आउटपुट
Enter 3 numbers: 10 20 30 30 is largest
4. else-if लैडर
बहु-मार्ग निर्णय।
if (cond1) stmt1;
else if (cond2) stmt2;
...
else if (condN) stmtN;
else stmtX;
उदाहरण: द्विघात समीकरण के मूल
#include <stdio.h>
#include <math.h>
int main() {
int a, b, c, d;
float r1, r2;
printf("Enter a, b, c: ");
scanf("%d %d %d", &a, &b, &c);
d = b*b - 4*a*c;
if (d > 0) {
r1 = (-b + sqrt(d)) / (2*a);
r2 = (-b - sqrt(d)) / (2*a);
printf("Roots: %f, %f", r1, r2);
} else if (d == 0) {
r1 = r2 = -b / (2*a);
printf("Equal roots: %f, %f", r1, r2);
} else {
printf("Imaginary roots");
}
return 0;
}
आउटपुट
Enter a, b, c: 1 4 3 Root 1 = -1.000000, Root 2 = -3.000000
5. switch स्टेटमेंट
एक एक्सप्रेशन के आधार पर कई विकल्पों में से चयन।
switch (expression) {
case value1: stmt1; break;
case value2: stmt2; break;
...
default: stmtX;
}
उदाहरण
#include <stdio.h>
int main() {
int n;
printf("Enter a number (0-1): ");
scanf("%d", &n);
switch (n) {
case 0: printf("Zero"); break;
case 1: printf("One"); break;
default: printf("Wrong choice");
}
return 0;
}
आउटपुट
Enter a number: 1 One
मुख्य बिंदु
breakभूलने पर फॉल-थ्रू होता है।defaultवैकल्पिक लेकिन अनुशंसित।- switch केवल इंटीग्रल टाइप्स पर काम करता है।