Conditional Operator in C Programming in Hindi

इस tutorial में हम Conditional Operator के बारे में पढ़ेंगे लेकिन अगर आपने if else control in C Programming वाला tutorial नहीं पढ़ा है तो पहले उसे जरूर पढ़ें.

जैसा की हमने if else control statement के tutorial में पढ़ा था की उनका use अपने programs में decision making के लिए किया जाता है.

Conditional operator भी लगभग if else statement की तरह work करता है यानी की conditional operator का use भी हम if-else statement की तरह ही decision making में करते हैं.

Conditional operator का program में use करने का format (syntax) if-else control statement से छोटा (short) होता है इसलिए हमें कुछ जगह पर इसे जरूर use करना चाहिए. 

Conditional operator पूरी तरह से if-else का replacement नहीं है यानी सिर्फ कुछ tasks के लिए ही आप conditional operator को if else के alternate की तरह use कर सकते हैं.

Conditional operator (ternary operator) में two symbols ( ? ) और ( : ) का use होता है. आइए अब हम conditional operator का syntax और कुछ examples के साथ इसे समझते हैं.

C Programming Conditional Operator Syntax:

(condition) ? true-expression : false-expression;
variable = (condition) ? true-expression : false-expression;

Condition वाली जगह पर आप कोई भी boolean expression लिख सकते हैं यानी ऐसी condition जिसका result या तो true (1) आये या false (0).

अगर condition का result true आया तो first expression executed (return) होगा और अगर condition का result false आया तो second expression executed (return) होगा.

नीचे हमने 2 example programs  बनाए हैं जिन्हें हमने पहले if else की help से बनाया और फिर same programs हमने conditional operator की help से बनाया है.

Conditional Operator Example Program 1:

पहले हमने program को if else conditional statement से बनाया है और फिर उसी program को conditional operator की help से बनाया है.

Example program using if-else:

#include<stdio.h>
void main()
{
	int a,b;
	
	printf("Enter Value of A : ");
	scanf("%d",&a);
	printf("Enter Value of B : ");
	scanf("%d",&b);
	
	if(a>b)
    {
        printf("A is greatest number");
    }
    else
    {
        printf("B is greatest number");
    }
}

Example program using conditional operator:

#include<stdio.h>
void main()
{
	int a,b;

	printf("Enter Value of A : ");
	scanf("%d",&a);
	printf("Enter Value of B : ");
	scanf("%d",&b);

	(a>b) ? printf("A is greatest number") : printf("B is greatest number");
}

Conditional Operator Example Program 2:

Example program using if-else:

#include<stdio.h>
void main()
{
	int a,b,c;

	printf("Enter Value of A : ");
	scanf("%d",&a);
	printf("Enter Value of B : ");
	scanf("%d",&b);

	if(a>b)
    {
        c=a;
    }
    else
    {
        c=b;
    }

	printf("Maximum Value : %d",c);
}

Example program using conditional operator:

#include<stdio.h>
void main()
{
	int a,b,c;

	printf("Enter Value of A : ");
	scanf("%d",&a);
	printf("Enter Value of B : ");
	scanf("%d",&b);

	c = (a>b) ? a : b;

	printf("Maximum Value : %d",c);
}