DEV Community

NilufarBukhorova
NilufarBukhorova

Posted on

Comand: if - else vs else if

Odatda if else komandasi ternary komandasini o'rnida bemalol kela oladi. Farqi ternaryda branchlar 2ta bo'lsagina, masalani ishlasa bo'ladi, if komandasi 2 va undan ortiq execution partlar mavjud bo'lgan masalalarni bemalol ishlay oladi.

if komandasida beriladigan ifoda tog'ri bo'lsagina uni chop etadi.

   if( expression )
{
statement1
}
Enter fullscreen mode Exit fullscreen mode

if statementda yo'l qo'yiladigan kichik xatolar

  • if (expression) shu ifodadan so'ng ; mana bu belgini qo'yish xato hisoblanib, ifoda shu qatorda tugadi degan komadani berib yuboradi.
  • if ning (expression) qismida = bu belgini bitta qo'yish xato, chunki teng bir o'zi kelganda o'zgaruvchi uchun yangi qiymat o'zlashishida ishlatiladi, ya'ni == shu belgini qo'yish to'g'ri bo'ladi.
    • yana bir kichik qoida bor, agarda if, elseda statement, ya'ni buyruq bitta bo'lsa, {} bularni qo'yish shart emas.

if-else

If else bn ko'p hollarda qo'llanadigan qo'shimcha komanda bu else hisoblanib, if dagi ifoda xato bo'lganda ikkinchi statement chiqar degan buyruq berishda ishlatiladi.

if(expression) 
{
statement1
}
else 
{
statement2
}
Enter fullscreen mode Exit fullscreen mode

if else vs else if

Bu ikki komanda aslida bir xil bo'lib, else komandasini ichida bemalol xohlagancha, if else komandasini o'zida foydalansa bo'ladi. Shuni hisobiga aslida if else komandasi else if deb ko'rinadi, ya'ni:

#include <iostream>

 using namespace std;

 int main()
{

int baho;

cin >> baho;

if(baho >= 90)

{

cout << "A" << endl;

}


else


{

if (baho >= 80)

{

cout <<< "B" <<<< endl;

}


else


{

if (baho > 70)

{

cout << "C" << endl;

}

else

{

if (baho > 60)

{

cout << "D" <<<<endl;

}

else


{


cout << "F" << endl;

}

}

}

}

return 0;

42}
Enter fullscreen mode Exit fullscreen mode
1 #include <iostream>

3 using namespace std;


5 int main()
{


int baho;


cin >> baho;

10

if (baho >= 90)

cout << "A" << endl;

else if(baho >= 80)

cout << "B" << endl; 

else if(baho >= 70)

cout << "C" << endl;

else if(baho >= 60)

cout << "D" << endl;

else

cout << "F" << endl;


return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)