Control Statemenats - Part 1


Control Statements:

This lesson shows how to use c# control statements, and the difference between these controls in c++/ JAVA and c#.

The first selection statement is programmer's favorite "if" statement. It has three forms:

1. Single selection
2. if-then-else selection
3. multi-case selection

List: 1  IfTest.cs

//understanding if statement
using System;
class IfTest
{
public static void Main()
{
string s;
int i;
Console.WriteLine("Enter a Number: ");
s = Console.ReadLine();
i = Int32.Parse(s);
//single selection
if(i > 0)
Console.WriteLine("The number {0} is positive",i);
//if-then-else selection
if(i > 0)
Console.WriteLine("The number {0} is positive",i);
else
Console.WriteLine("The number {0} is not positive",i);
//multi-case selection
if(i == 0)
Console.WriteLine("The number is zero");
else if(i > 0)
Console.WriteLine("The number {0} is positive",i);
else
Console.WriteLine("The number {0} is negative",i);
}
}

This program reads a number from console. Input coming from console is in string format. Int32.parse(string) is used to convert string literal to integer. The variable i is the object of evaluation here. c++ programmers can see that the use of if statement is same in c#. Halt it. There is one difference. The expression in an if statement must resolve to bool  value. Take a look at following code.

List: 2

using System;
class IfTest2
{
public static void Main()
{
if(1)
Console.WriteLine("The if statement executed");
}
}

when this code is complied by c# compiler, it will give the error "constant value 1 an not be converted to bool".

conditional or (||) and conditional and (&&) operators are used in the same manner. Consider the following code.

List: 3 LeapTest.cs

//Leap year
using System;
class LeapTest
{
public static void Main()
{
int year;
Console.WriteLine("enter the year value (yyyy) :");
year = Int32.Parse(Console.ReadLine());
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 )
Console.WriteLine("The year {0} is leap year ",year);
else
Console.WriteLine("The year {0} is not leap year ",year);
}
}

Similar to  if-else if-else if-else form of the if statement is the "switch" statement.

List: 4 SwitchTest1.cs

using System;
class SwitchTest1
{
public static void Main()
{
int i = 1;
switch(i)
{
case 1 :
Console.WriteLine("one");
break;
default :
Console.WriteLine("default");
}
}
}

the difference here is if you try to compile above code without putting break statement in case 1, compiler will raise an error "control can not fall through from one case label". I'm sure c++/Java programmers are going to love this. Here is another good news.

The switch expression can evaluate to following types: sbyte, byte,short, ushort, int, uint, long, ulong, char, string or enum. So the following code is perfectly OK with c# compiler.

List: 5  SwitchTest2.cs

using System;
class SwitchTest2
{
public static void Main()
{
string day;
Console.WriteLine("enter the day :");
day = Console.ReadLine();
switch(day)
{
case "Mon" :
case "Monday" :
Console.WriteLine("day is Monday: go to work");
break;
default :
Console.WriteLine("default");
}
}
}
 

Control Statements-Loops 

This lesson shows you how to use c# looping statements. In c#, there are four iteration constructs rather than three. There are familiar for, do, while loops and a new one from Visual basic, foreach.

Let us start with while loop.

The Do and While Statements

List: 1 WhileTest.cs

//find out the number of digits in a given number.
using System;
class WhileTest
{
public static void Main()
{
int i = 123;
int count = 0;
int n = i;
//while loop may execute zero times.
while(i > 0)
{
++count;
i = i/10;
}
Console.WriteLine("Number {0} contains {1} digits.",n,count);
}
}

The above code shows simple while loop, which finds out the number of digits in a number. for a given number i = 123, the loop will execute tree times and hence the value of count will be three at the end of the while loop.

The above code has one logical flaw. If the number i is set to 0, the output of the code will be "Number 0 contains 0 digits." Actually number 0 is of one digit. Since the condition for the while loop i>0 is false from beginning for the value i=0, the while loop won't execute any time and count will be zero. here is a solution: 

List: 2 DoTest.cs 

//find out the number of digits in a given number.
using System;
class DoTest
{
public static void Main()
{
int i = 0;
int count = 0;
int n = i;
do
{
++count;
i = i/10;
}
while(i > 0);
Console.WriteLine("Number {0} contains {1} digits.",n,count);
}
}

The Do-While construct checks condition in the end of the loop. Thus Do-while loop will execute atleast once even though the condition to be checked is false from beginning. 

The For Statement 

List: 3 Fortest.cs

//For loop with break and continue statements
using System;
class ForTest
{
public static void Main()
{
for(int i = 0 ; i < 20 ; ++i)
{
if(i == 10)
break;
if(i == 5)
continue;
Console.WriteLine(i);
}
}
}

The For loop is good when we know how many times the loop needs to be executed. the output of the above code will be:

0
1
2
3
4
6
7
8
9

isn't it self explanatory? when i becomes 5, the loop will skip over the remaining statements in the loop and go back to the post loop action. thus 5 is not part of the output. when i becomes 10, control will break out of the loop. 

The foreach statement 

This statement allows to iterate over the elements in arrays and collections. here is a simple example.

List: 4 ForEach.cs 

//foreach loop
using System;
class ForEach
{
public static void Main()
{
string[] a = {"Chirag","Bhargav","Tejas"};
foreach(string b in a)
Console.WriteLine(b);
}
}

Within the foreach loop parenthesis , the expression is made up of two parts separated by keyword in. The right hand side of in is the collection and left hand side is the variable with type identifier matching to whatever type the collection returns. 

Every time the collection is queried for a new value. As long as the collection returns value, the value is put into the variable and expression will return true. when the collection is fully traversed, the expression will return false and control will be transferred to the next statement after a loop.

Enjoy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all