C# continue statement

In C# instead of breaking the complete loop, if we want to skip a iteration based on a condition then we can use continue statement. Continue statement, will skip all the code statements if a condition is true for a particular loop iteration.

So, continue statement causes all remaining code statements in a loop to be skipped, and execution returns to the top of the loop. 

Syntax

continue;

Example:

using System;
					
public class ContinueForProgram
{
	public static void Main()
	{
		for(int i=1; i <= 5; i++)
		{
			if(i==4)
			{
				//value of i =4 is not printed, and next loop is executed
				continue;
			}
			Console.WriteLine("End of loop number "+i+" for i");
		}
	}
}

Output:

End of loop number 1 for i
End of loop number 2 for i
End of loop number 3 for i
End of loop number 5 for i

As you can see in the above code, when value of i was 4, nothing was printed and code executed next iteration of loop.

For the while and do-while loops, continue statement causes the program control passes to the conditional tests.

Example, for printing even numbers less than 20

using System;

public class ContinueWhile
{
        public static void Main()
        {
			int i = 1;

			while (i < 20)
			{
							i++;
				//check if value is not equal to 1,3,5 etc then continue for next loop
				if ((i % 2) != 0)
				{
					continue;
				}
				Console.WriteLine ("i = " + i);	
			}
        }
}

Output:

i = 2
i = 4
i = 6
i = 8
i = 10
i = 12
i = 14
i = 16
i = 18
i = 20

Share Tweet