Learn how to use the ternary operator (? :) for compact conditional checks.
To write a C/C++ program that takes a number as input from the user and checks whether it is odd or even using the conditional operator (? :), also known as the ternary operator.
The conditional operator (? :) is a shorthand way of writing an if-else statement. Its syntax is:
In this practical, you will use the conditional operator to check if a number is even or odd:
num % 2 == 0Run the program:
Sample Input & Output:
| Syntax | Description | Example |
|---|---|---|
condition ? expr1 : expr2 |
If condition is true, execute expr1; else execute expr2 | (num % 2 == 0) ? "Even" : "Odd" |
| Feature | if-else |
?: (Ternary) |
|---|---|---|
| Syntax Length | Longer (multiple lines) | Shorter (one line) |
| Readability | More readable for complex logic | Better for simple conditions |
| Multiple Statements | Supports multiple statements | Only single expressions |
| Return Value | No return value | Returns a value |
| Best Used For | Complex decision making | Simple assignments |
? : provides a compact way to write if-else statements.
You have successfully written a C program that checks whether a number is even or odd using the conditional operator (? :). You have learned how to use the ternary operator for compact conditional checks.
condition ? value_if_true : value_if_false. It is a concise alternative to if-else.
if-else for better readability.
ایک C/C++ پروگرام لکھنا جو صارف سے ایک عدد ان پٹ کے طور پر لے اور مشروط آپریٹر (? :) کا استعمال کرتے ہوئے چیک کرے کہ آیا یہ طاق ہے یا جفت۔
مشروط آپریٹر (? :) if-else بیان لکھنے کا ایک مختصر طریقہ ہے۔ اس کا نحو یہ ہے:
اس عملی میں، آپ مشروط آپریٹر کا استعمال کرتے ہوئے چیک کریں گے کہ آیا عدد جفت ہے یا طاق:
num % 2 == 0پروگرام چلائیں:
نمونہ ان پٹ اور آؤٹ پٹ:
| نحو | وضاحت | مثال |
|---|---|---|
condition ? expr1 : expr2 |
اگر شرط درست ہے تو expr1 پر عمل کریں، ورنہ expr2 پر عمل کریں | (num % 2 == 0) ? "Even" : "Odd" |
| خصوصیت | if-else |
?: (Ternary) |
|---|---|---|
| نحو کی لمبائی | لمبا (متعدد لائنیں) | چھوٹا (ایک لائن) |
| پڑھنے میں آسانی | پیچیدہ منطق کے لیے بہتر | سادہ شرائط کے لیے بہتر |
| متعدد بیانات | متعدد بیانات کو سپورٹ کرتا ہے | صرف واحد ایکسپریشنز |
| واپسی کی قیمت | کوئی واپسی کی قیمت نہیں | ایک قیمت واپس کرتا ہے |
| بہترین استعمال | پیچیدہ فیصلہ سازی | سادہ تفویض |
? : if-else بیانات لکھنے کا ایک مختصر طریقہ فراہم کرتا ہے۔
آپ نے کامیابی سے ایک C پروگرام لکھا ہے جو مشروط آپریٹر (? :) کا استعمال کرتے ہوئے چیک کرتا ہے کہ آیا کوئی عدد جفت ہے یا طاق۔ آپ نے سیکھ لیا ہے کہ مختصر مشروط چیک کے لیے ternary آپریٹر کا استعمال کیسے کیا جاتا ہے۔
condition ? value_if_true : value_if_false۔ یہ if-else کا ایک مختصر متبادل ہے۔
if-else استعمال کریں۔