Friday, 27 April 2018

Android for loop example

Android for loop example


  • Android for loop is used for repeat the block of code many times.
  • you can also break and continue the for loop based on the conditions.

When to use for loop in android


  • For loop is used when you know how many times the loop should run.

Syntax of for loop


for(int i=0; i<n; i++)
{
        //for loop Statements
}

i=0 loop starts from 0(zero)
i<n where n represents number of times loop the statements.

Example of for loop

for(int i=0; i<5 ; i++)
{
    Toast.makeText(getApplicationContext(), ""+i, Toast.LENGTH_SHORT).show();
}

Output

0 1 2 3 4

How to break for loop statements 

for(int i=0; i<5 ; i++)
{
    if(i==2)
    {
        break;
    }
    else {
        Toast.makeText(getApplicationContext(), ""+i, Toast.LENGTH_SHORT).show();
    }
}


Output

0 1


Share This

0 comments: