Skip to main content

Session 3 :- Control Structures in c#


Date
Friday, November 29, 2013
Time
Description
10.00 am to 12.00 pm
Control structure in c#
Learning:
 For Loops
Why is this important to learn about?

Control structures are one of the most fundamental concepts in any programming language you will come across. If you want to know C#, and if you want to learn to program with any language, you must have a firm grip on the control structures of the language.

Definitions of terms used.

Iteration – This is the act of repeating something (that ‘something’ being code statements in the programming context).

Conditional – A conditional action is said to be one that is only performed if a certain condition is true.

For Loops

For loops allow us to specify the number of times to repeat a block of code. It is best demonstrated with an example:
for (int i = 1; i <= 5; i++)
{
   Console.WriteLine(i);
}



While Loop

The while loop is used to repeat a block of code, while a certain condition remains true.

            
Console.WriteLine("Enter 'Q' to quit the while loop. Enter anything else to loop again");
 
while (Console.ReadLine().ToUpper().Equals("Q") == false)
{              
   Console.WriteLine("Still in while loop");
}
 
Console.WriteLine("While loop ended");


Do While

Now, imagine that we have written our while loop as above, and it is working fine. However, you then realise that if the user starts up the program, and then enters “Q” straight away, the loop won’t execute at all! Therefore, your message; “Still in while loop” won’t get displayed at all. You want the message to be displayed at least once.

do{
 
     Console.WriteLine("Still in while loop");
 
} while (Console.ReadLine().ToUpper().Equals("Q") == false); //remember the semi-colon here :)/>/>
 
Console.WriteLine("While loop ended");

Switch Statement:-
   A switch statement allows us to execute code based on a predefined set choices.
 
   switch (i)
   {
    case 10:
    Console.WriteLine("Number is 10!");
    break;
    case 20:
    Console.WriteLine("Number is 20!");
    break;
    case 30:
    Console.WriteLine("Number is 30!");
    break;
    default:
    Console.WriteLine("Number is NOT 10,20 or 30");
    break;
   }

Foreach Loops

Foreach loops (sometimes called “foreach, in” loops) are used to loop through items in an array or a collection. The collection/array must implement an interface called IEnumerable (or IEnumerable<T> if the collection is generic).  It is a way to ensure that an enumerator can be obtained for the collection, of which is needed to allow iteration through the collection.

Here is an example of its use:
//declare an array to hold some numbers
int[] array = new int[] { 1, 5, 3, 8, 3, 5, 8, 6, 10 };
 
//foreach loop
foreach (int i in array)
{
   //this gets executed once ‘for each’ number in the array
   Console.WriteLine(i);
 
}
 
Arrays:-

In simple words array is used to store multiple elements . an array can be of type int, string,char,long,byte,etc.

Syntax of declaring an array in c#:

1)      int[] arr= new int[size];//arr is name of the variable,size is size of array.
2)      int [] arr;
arr=new int[size];
3)      int [] arr ={10,20,30,40};//used only for fixed elements.
4)      Two dimensional array:
int [,] sample=new int[3,3];
  
Program :-
Addition of elements of an array:-

Class program
{
   Static void main(string[] args)
   {
     int[] a= new int[3];
     int i,b;
     console.wr\iteline(“enter 3 array elements”);
     for(i=0;i<a.length;i++)
      {
          a[i]=convert.toInt32(Console.readline());
       }
      for(i=0;i<a.length;i++)
      {
          b=a[i]+a[i+1];
       }
    Console.Writeline(“Sum={0}”,b);

   }
}

Program:-
Accessing array elements using pointer:-
//to access array of elements using pointers we have to use unsafe code,in  short unsafe code is The unsafe code or the unmanaged code is a code block that uses a pointer variable.

Class program
{
   Int [] list={10,100,1000};
   fixed(int *ptr=list);// You can increment the pointer variable p because it is //not fixed in memory but an array address is fixed in memory, and you can't //increment that.
  for(int i=0;i<3;i++)
  {
     Console.Writeline(“Address of list[{0}]={1}”,(int)(ptr+1));
     Console.Writeline(“value of list[{0}]={1}”,i,*(ptr+i));
  }
   Console.Readkey();
}

Output of above code:-
Address of list[0] = 31627168
Value of list[0] = 10
Address of list[1] = 31627172
Value of list[1] = 100
Address of list[2] = 31627176
Value of list[2] = 200


Enumerators:-
 Enumerators are declared using enum keywords. They are the symbols that have fixed values.c# enumeration are value type,in other words inheritance contains its own values and cannot inherit or cannot pass inheritance.

Program:-

using System;
namespace EnumApplication
{
   class EnumProgram
   {
      enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
 
      static void Main(string[] args)
      {
         int WeekdayStart = (int)Days.Mon;
         int WeekdayEnd = (int)Days.Fri;
         Console.WriteLine("Monday: {0}", WeekdayStart);
         Console.WriteLine("Friday: {0}", WeekdayEnd);
         Console.ReadKey();
      }
   }
}

Output:-
Monday: 1
Friday: 5

Comments