C# - SPLessons

C# Program Control Statements

Home > Lesson > Chapter 5
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C# Program Control Statements

Program Control Statements in C#

shape Description

Program Control Statements or Decision Making Statements help to control the processing of code with additional functionality on provision of certain set of conditions/rules.
  • Control Statement-Selection
  • Control Statement-Loop

shape Syntax Explanation

shape Syntax

Statement Syntax
if If(true) { //execute the code }
if-else If(true) { //execute the code-1 } else { //execute the code-2 }
Nested if If(true) { //execute the code-1 } Else if(true) { //execute the code-2 } Else { //execute the code-3 }
Switch/Break/goto switch (x) { case “A”: break; Case “B”: Goto case”A” }

shape Example

An example of a Selection Statement is shown below.  [csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPLessons { class Program { static void Main(string[] args) { char voting; voting='B'; switch (voting) { case 'A': Console.WriteLine("First:", +voting); break; case 'B': Console.WriteLine("Second" + voting); break; case 'C': Console.WriteLine("third" + voting); break; default: Console.WriteLine("Invalid Option" + voting); break; } Console.ReadLine(); } } } [/csharp] Output:

Loop Statement

shape Description

Executes statements repeatedly in a sequence until a given/set condition is satisfied.

shape Syntax

Operator Description Syntax
for Iterates the statement for ‘n’ number of times. For(datatype variable;variable<number;variable++)
foreach It works similar to for loop but iterates the loop against a value/Object. For(datatype variable;variable<number;variable++) { //Block of code to execute }
do Executes the statement in the loop once before the condition is tested, and, continues only when the condition is satisfied. do { //Execute block of code }while(variable
While Executes the statement in loop only when a condition is satisfied. While(variable<number) { //Execute block of code }
continue It stops the statement execution and allows to check condition again. for(datatype variable;variable<number;variable++) { //Block of code to execute continue; }
break To stop the execution of the statement. for(datatype variable;variable<number;variable++) { //Block of code to execute break; }