C# while and do while

while loop executes commands until the condition is not true.

int i=9;
int sum=0;
while (i > 0)
{
sum += i;
i--;
} //sum=45

do while executes the commands one time first, then executes the commands until the condition is not true.
int i=9;
int sum=0;
do
{
sum += i;
i--;
}
while (i > 0); //sum=45
//-------------------------------------
int i=9;
int sum=0;
do
{
sum += i;
i--;
}
while (i < 0); //sum=9

break, goto will stop the loop, and continue will skip one specific step of the loop.
int i=9;
int sum=0;
while (i > 0)
{
if (i==5) continue;
sum += i;
i--;
} //sum=40
//-------------------------------------
i=9;
sum=0;
while (i > 0)
{
if (i==5) break;
sum += i;
i--;
} //sum=10



endmemo.com © 2024  | Terms of Use | Privacy | Home