DEV Community

Cover image for loop for and while.
Rivojiddin
Rivojiddin

Posted on • Edited on

loop for and while.

loop bu tsikl bo'lib u xar-xil korinishda boladi masalan bu ; -->

int main() 
{
    int sum = 0, num;


    for (;;) 
    {
    cin >> num; 

        if (num == 0)
        {
            break;  
        }
        sum += num;  
    }

    cout << sum << endl; 
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

bu tsikl for loop deyiladi.

int main()
{
        long long son, fact = 1, b = 2;

        cin >> son;

    while(true)
    {
        fact *= b;

        if(fact == son)
        {
            cout << "true";
            return 0;
        }
        else if(fact > son)
        {
            cout << "false";
            return 0;
        }
        b++;
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

bu esa while tsikl deb ataladi

for loop;

Image description

wile loop;

Image description

Kod blokining bajarilishidan oldin (bir marta) bayonot 1 bajariladi.

Bayonot 2 kod blokini bajarish shartini belgilaydi.

Kod bloki bajarilgandan so'ng 3-bayonnoma (har safar) bajariladi.

Quyidagi misol 0 dan 4 gacha raqamlarni chop etadi:

for (int i = 0; i < 5; i++) 
{
  cout << i << endl;
}
Enter fullscreen mode Exit fullscreen mode

Misol tushuntirildi
1-bayon o'zgaruvchini tsikl boshlanishidan oldin o'rnatadi (int i = 0).

2-bayon tsiklni ishga tushirish shartini belgilaydi (i 5 dan kam bo'lishi kerak). Agar shart rost bo'lsa, tsikl qaytadan boshlanadi, agar noto'g'ri bo'lsa, tsikl tugaydi.

3-bayonot tsikldagi kod bloki har gal bajarilganda qiymatni (i++) oshiradi.


Yana bir misol
Bu misol faqat 0 va 10 orasidagi teng qiymatlarni chop etadi:

for (int i = 0; i <= 10; i = i + 2) 
{
  cout << i << endl;
}
Enter fullscreen mode Exit fullscreen mode

agar for loopda forni ichida umuman shart bolmasa shunday " ; " belgidan 2dona qo'yiladi

ustun- |
       |
       |

Enter fullscreen mode Exit fullscreen mode
qator ---------
Enter fullscreen mode Exit fullscreen mode

Top comments (0)