Saturday, May 5, 2018

C#: What is the difference between “continue” and “break” statements in C#

Using break statement, you can 'jump out of a loop' whereas by using continue statement, you can 'jump over one iteration' and then resume your loop execution.

Eg. Break Statement 
  1. using System;  
  2. using System.Collections;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace break_example   
  7.     {  
  8.         Class brk_stmt {  
  9.             public static void main(String[] args) {  
  10.                 for (int i = 0; i <= 5; i++) {  
  11.                     if (i == 4) {  
  12.                         break;  
  13.                     }  
  14.                     Console.WriteLine("The number is " + i);  
  15.                     Console.ReadLine();
  16.   
  17.                 }  
  18.             }  
  19.         }  
  20.   
  21.     } 
Output 

The number is 0; 
The number is 1; 
The number is 2; 
The number is 3;
Eg.Continue Statement
  1. using System;  
  2. using System.Collections;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace continue_example  
  7. {  
  8.     Class cntnu_stmt   
  9.     {  
  10.         public static void main(String[]   
  11.         {  
  12.             for (int i = 0; i <= 5; i++)   
  13.             {  
  14.                 if (i == 4)   
  15.                 {  
  16.                     continue;  
  17.                 }  
  18.                 Console.WriteLine(“The number is "+ i); 
  19.                 Console.ReadLine();
  20.                   
  21.             }  
  22.         }  
  23.     }  
  24.       
  25. }  
  26.   
  27.           
Output
The number is 1;
The number is 2;
The number is 3;
The number is 5; 

No comments:

Post a Comment