DEV Community

islomAli99
islomAli99

Posted on

C++ Ternary Operator

Assalamu aleykum bugun sizlar bilan C++ dasturlash tilida ishlatiladigon Ternary Operator buni tarjimasi - uchlik operatori xaqida gaplashib o'tamiz.

Uchlik operator sinov shartini baholaydi va shart natijasi asosida kod blokini bajaradi.

Image description

#include <iostream>
using namespace std;

int main() {
  double marks;

  // take input from users
  cout << "Enter your marks: ";
  cin >> marks;

  // ternary operator checks if
  // marks is greater than 40
  string result = (marks >= 40) ? "passed" : "failed";

  cout << "You " << result << " the exam.";

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Natija:

Enter your marks: 80
You passed the exam.
Enter fullscreen mode Exit fullscreen mode

Uchlik operatoridan qachon foydalanish kerak?

C++ da uchlik operatori if...else ifodalarining ayrim turlarini almashtirish uchun ishlatilishi mumkin.

Masalan, biz ushbu kodni almashtirishimiz mumkin

#include <iostream>
using namespace std;

int main() {
  // Create a variable
  int number = -4;

  if (number > 0)
    cout << "Positive Number";
  else
    cout << "Negative Number!";

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Misol uchun shuni ternaryda qilingan variant:

#include <iostream>
#include <string>
using namespace std;

int main() {
  int number = -4;
  string result;

  // Using ternary operator
  result = (number > 0) ? "Positive Number!" : "Negative Number!";

  cout << result << endl;

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Bu erda ikkala dastur ham bir xil natijani beradi. Biroq, uchlik operatoridan foydalanish bizning kodimizni yanada o'qilishi va toza qiladi.

Eslatma: Agar natija qisqa bo'lsa, biz uchlik operatoridan foydalanishimiz kerak.

Top comments (0)