BreakAndContinue.md - brainchildservices/curriculum GitHub Wiki

SLIDE-1

C# Break and Continue

SLIDE-2

Break Statement

A Break statement breaks out of the loop at the current point or we can say that it terminates the loop condition.
image

SLIDE-3

C# Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
image

SLIDE-4

  • Example

.NET Fiddle link

                        using System;

                        public class Program
                        {
                        	public static void Main()
                        	{
                        		for(int i=1;i<=10;i++)
                        		{
                        			if(i==4)
                        				continue;			// The iteration stops at line 10 and goes to i++ where i gets incremented to 5 and checks the condition
                        			if(i==7)
                        				break;				// The loop stops and exits out of the loop when i=7 and goes to line 15
                        			Console.Write(i+"\t");
                        		}
                        	}
                        }

SLIDE-5&6

Exercise:

Q1. Write a program to print numbers from 1 to 100. It should skip if the number is a multiple of 7 and terminate the printing when the number 67 is encountered. Use continue and break statements

Q2. Write a program to calculate the sum of 10 numbers. If the user enters a negative number, the loop terminates Test Data :
Enter 10 numbers : 1
2
4
-17
Expected Output :
You have entered a negative number. Loop terminated
Sum=7

Q3. Write a program to calculate the sum of 5 numbers. If the user enters a negative number, it's not added to the result Test Data :
Enter 5 numbers : 1
2
4
-25
4 Expected Output :
Sum=11