By default it will show the recent post/content added.
To read from starting....Click Here
See "ChapterWise Posts" right side for complete list.

Friday, 24 April 2015

Functions

A function is a block of statements that perform a coherent task for you. Each C# class can contain one or more functions. Execution always begins with Main() function present in the class that is marked as startup object.

For any function, we will pass data to it by giving its arguments and the function will pass data back using a return value. We can have any number of arguments/parameters but only one return value to a function.


Defining a function:

 <security level[takes default value if not specified]> <return data type[if not return value then we need to write “void”]> <function_name>(declaration of 1 or more parameters)  
 {  
   We can use the parameters defined above as local variables here,and return a value  
 } 

Example:

//Defining a function:  
 static int Kiran(int a,int b)//static keyword here is required as we are not creating object.We will discuss in OOPS.  
 {  
    int c; //this is local variable to Kiran function and only available here.  
    c=a+b;  
    return c;//to return back the variable c value to function call.  
 }  
 //calling a function  
 int d=Kiran(4,5);  

In C# there are 3 ways to pass parameters to a function. As value, reference and out parameters.

In Call by Value, value of each of the arguments in calling function is copied into corresponding formal arguments of the called function. The changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function.

 //Calling a function by Value  
 using System;  
 namespace CallingByReferenceandValue  
 {  
  class CallingByReferenceandValue  
   {  
     static void Main(string[] args)  
     {  
       int a=10,b=20;  
       Swap(a,b);  
       Console.WriteLine("a={0} b={1}",a,b);  
       Swapp(a,b);  
       Console.WriteLine("a={0} b={1}",a,b);  
     }  
     static void Swap(int x,int y)//Calling a function by value.  
     {  
      int t;  
      t=x;  
      x=y;  
      y=t;  
      Console.WriteLine("x={0} y={1}",x,y);  
     }  
    static void Swapp(ref int x,ref int y)//Calling a function by reference.  
     {  
      int t;  
      t=x;  
      x=y;  
      y=t;  
      Console.WriteLine("x={0} y={1}",x,y);  
     }  
   }  
 }  

The output of above program would be:
x=20 y=10
a=10 b=20
x=20 y=10
a=20 b=10

If you see, a and b values are unchanged even after exchanging the values of x and y in first Swap function/method which is Call by Value.But it changing with second method Swapp which is Call by Reference.

The third way is used when we want to return multiple values from a function. à OutParameters.

//OutParameters  
 using System;  
 namespace OutParameters  
 {  
  class OutParameters  
   {  
     static void Main(string[] args)  
     {  
       int a=10,b=20,c=30;  
       int s,p;  
       SumProd(a,b,c,out s,out p);  
       Console.WriteLine("Sum={0} Prod={1}",s,p);  
     }  
     static void SumProd(int x,int y,int z,out int ss,out int pp)  
     {  
      ss=x+y+z;  
      pp=x*y*z;  
     }  
   }  
 }  

Note: Once we define output parameters it’s mandatory to assign some value.We will get error if don’t.
We can use reference variables instead of output parameters but then it is necessary to initialize those variables in Main() i.e., calling function.

Function Overloading:
We can define multiple functions with same name [ But with different parameter (both in type or number).]

//Function Overloading  
 using System;  
 namespace FunctionOverloading  
 {  
   class FunctionOverload  
   {  
     static void Main(string[] args)  
        {  
           int i=-25,j;  
           long l=-100000,m;  
           double d=-12.34,e;  
           j=Abs(i);  
           m=Abs(l);  
           e=Abs(d);  
           Console.WriteLine("j={0} m={1} e={2}",j,m,e);}  
     }  
     static int Abs(int ii)  
        {  
           return(ii>0?ii:ii*-1);  
        }  
        static long Abs(long ii)  
        {  
        return(ii>0?ii:ii*-1);  
        }  
       static double Abs(double ii)  
       {  
           return(ii>0?ii:ii*-1);  
       }  
      }  
 }  

Recursion:
A function is recursive if a statement within the body of a function calls the same function.
Below is the example for calculating factorial using recursive function.

 using System;  
 namespace RecursiveFunction  
 {  
   class RecursiveFunction  
   {  
     static void Main(string[] args)  
        {  
           int a,fact;  
           Console.WriteLine("Enter any number");  
           a=Convert.ToInt32(Console.ReadLine());  
        fact=Rec(a);  
           Console.WriteLine("Factorial value="+fact);}  
     }  
     static int Rec(int x)  
        {  
           int f;  
           if(x==1)  
            return(1);  
           else  
            f=x*Rec(x-1);  
     return(f);             
        }  
      }  
 }  

Tuesday, 21 April 2015

Control Instructions

Decision Control Instructions

By default, the instructions in a program are executed sequentially. We can change this order or make certain statements to execute based on some condition.

The decision control instruction can be implemented in C# using if, if-else, conditional operators and switch statement.

 if(condition or any expression evaluates to bool value)  
 execute this statement; //this particular statement(or statements if we group them in block) will get executed only when the above condition is true.



We express a condition using relational operators.











There is difference in = and ==.
= is for assignment and == is for comparison.

If we want to keep a separate branch for execution when a condition is false, use if-else.

if(condition or any expression evaluates to bool value)  
 execute this statement; // this will be executed when the above expression evaluates to true.  
 else  
 execute this statement; // this will be executed when the above expression evaluates to false.  

If want to check more conditions after a condition is true or false we can use Nested if-else.

if(condition1 or any expression evaluates to bool value)  
 {  
    If(condition2)  
     {  
         execute this statement; // this will be executed when the above expression evaluates to true.  
     }  
    else  
      {  
          Execute this statement;  
      }  
 }  
 else  
 {  
     If(condition3)  
     {  
         execute this statement; // this will be executed when the above expression evaluates to true.  
     }  
    else  
      {  
          Execute this statement;  
      }  
 }  

Instead of nested we can use below option also.

if(condition1 or any expression evaluates to bool value)  
 {  
         execute this statement; // this will be executed when the above expression evaluates to true.  
 }  
 else if(condition2) //executes condition1 is false 2 is true  
 {  
        Execute this statement;  
 }  
 Else  //executes condition1 is false 2 is false  
 {  
        Execute this statement;  
 }  

We can combine conditions using logical operators.&&(and),||(or),!(not)

As we are including logical operators also, below is the revised hierarchy.














Conditional/ternary operator ( ?:)
Expression1?expression2:expression3   à checks expression1, if it evaluates to true then expression2 gets executed else expression3 will.

Note: The execution for ternary operator is right to left.

Loop Control Instructions

This particular type is for executing set of instructions repeatedly.
There are 3 types.(for,while,do-while)

 while(condition/expression)  
 {  
    //these statements will be executed repeatedly till the above expression evaluates to false.  
 }  
 do  
 {  
   //set of statements   
 }while(condition/expression)  

The difference between while and do-while is in while the checking is done before execution of statements whereas in do-while the checking is done later.

You can do this by keeping some counter variable and increment it inside the loop.

This loop counter logic is implemented directly in for.

 for(initialize counter;test counter;increment counter)  
 {  
    Set of statements  
 }  

Example:

 for(int i=0;i<=89;i++) // we can do multiple initializations for(int i=0,j=8;i<=89;i++)   
 {  
   //set of statements executed repeatedly 90 times—0 to 89.  
 }  

We can use break to stop the loop execution in the middle of repetition. Whereas continue will stop the current execution and continue the loop from next counter.

switch, can be used if we are having multiple options and select one of the branch based on condtion or value of switch variable.This will be useful instead of sometimes to use instead of very big nested if branch.

switch(expression)  
 {  
    case constant 1:  
       do this;  
       break;   //if break is not there then the execution will continue to next branch also.  
    case constant 2:  
       do this;  
       break;  
    case constant 3:  
       do this;  
       break;  
    case constant 4:  
    case constant 5:  // this branch will be executed if the expression evaluates to constant 4 or 5  
       do this;  
       break;  
    case default:  
       do this;  
       break;  
 }  

goto Keyword is been used traditionally since batch scripts.
It is not advisable to use it as it may create many issues if we miss any logic.

We can label a part of code using colon “:”and use goto keyword to send the execution to this part of code.

We can use return keyword to return control from Main() function which will terminate the execution of the program.

Monday, 20 April 2015

C# Instructions

Types of C# Instructions:
  1. Type Declaration
  2. Arithmetic
  3. Control
  4. Exception Handling
  5. Advanced













The following statements would work.

int a,b,c,d;
a=b=c=d=10;
int d=67,g=98;
float k=7.8f,r=k+3.1f;

But not below.

int a=b=c=d=10;//trying to use b,c,d before defining them.
float b=a+3.1f,a=1.5f; //trying to use a before defining it.

In an arithmetic expression, if both real and integer types are there, then the final result will be implicitly converted to real type.

But even though the expected result is real for an expression having all integers, the decimal will be truncated. So we need to convert it explicitly.
Ex: float a=(float)6/4;

Hierarchy of Operations.










Within the parenthesis same hierarchy will be given precedence.

If we want to prevent user from changing the variable, we can define it as constant. They must be defined and initialized simultaneously.
const float pi=3.14f;
const float pi; pi=3.14f; //will give error.

ReadLine() and Read() à used for getting input from console.
Convert.ToChar() to convert data read to character from string.Similary other methods are there in Convert class.

We can insert variables in the middlwe of WriteLine() and Write() using format specifiers.
Ex: Console.Write(“Avg={0:d}\nPercentage={1:f}”,avg,per);













\n is an escape sequence which is mentioned above example.These characters have special meaning in the string when they keep in program.











In control instructions there are 4 types(sequential, selection or decision control, repetition or loop control, case control).

We will discuss about them in next post.

Sunday, 19 April 2015

Data Types and a sample program execution

Data is represented in any programming language by its Data types.

It specifies 3 things:

  1. What value can the data type take.
  2.  How many bytes would the data type occupy in memory.
  3. What operations can be performed on it.

Example:- integer data type value range is -2147483648 to +2147483647,it occupies 4 bytes in memory and operations like addition, subtraction, multiplication, division, etc. can be performed on it. Similarly, a bool data type can take a value true or false, occupies 1 byte in memory and permits comparison operations on it.

Based on where a data type can be created in memory, it is called a value type(in stack) or reference type(in heap).C# forces certain data types to get created only in stack(ex: integer) and certain only in heap(ex: string).This can’t be changed by us. All data types that are small in size are created in stack and the other in heap.

A value type as well as reference type can be further categorized into pre-defined/primitives(ex: integer) and user-defined(ex: structure) categories.
















To use these data types, we need t create constants and variables. A constant is a specific value from the range(Ex: for char it is 0 to 65535)  of values offered by the data type, whereas a variable is  a container(a memory location) which can hold a constant value. A constant/literal value can’t be changed but a variable/identifier can.

There are certain rules for creating constants and variables.

For Constants:
  1.  If no sign precedes a numeric constant, then assumed as +ve.
  2.  No commas or blanks allowed.
  3. Bytes occupied by constant are fixed and can’t change from one compiler to another.
  4. Only float constants(must be followed by suffix f) can take decimal point.
  5. Float constants can be expressed in fractional(ex: 314.58f) or exponential(ex:3.1458e2f)
  6. A character constant(max. length 1 character) is a single alphabet/digit/special symbol enclosed within inverted commas pointing to left. ’A’ is valid but not ‘A’.

For Variables:
  1. Variable name is combination of alphabets,digits,underscores with maximum length 247 charactes by some compilers but recommended 31.First character should be alphabet.
  2.  No commas or blanks allowed and no special symbol other than underscore.
  3. Variable names are case sensitive.

We need to declare a variable type before using it.
Ex: int si,hra;

C# Keywords: whose meaning is already defined.int is a keyword above. If we want to use the keyword name for variable use @ symbol. Ex: @if

List of keywords mentioned in below table.





















In addition to above keywords, which have special meaning in a limited program context are known as Contextual Keywords. As C# evolves new keywords are added to it as contextual to avoid breaking programs written in earlier versions of C# language.

First C# program

Before we begin, let’s see the below common programming rules.
  1. Each instruction is a separate statement.Therefore,a complete C# program consists a series of statements.
  2. The statements should appear in same order which we wish them to be executed; unless of course the logic of problem demands a deliberate ‘jump’ or transfer of control to a statement, which is out of sequence.
  3. Blank spaces may be inserted between 2 words but not allowed within a variable,constant or keyword.
  4. All statements are in small case letters.
  5. Every statement must end with a semicolon (;).Thus ; acts as a statement terminator.

 /*Calculation of simple interest*/  
 using System;  
 namespace SimpleInterestProject  
 {  
    class SimpleInterest  
      {  
           static void Main(string args[])  
             {      
                 float p,r,si;  
                 int n;  
                 p=1000.50f;n=3;r=15.5f;  
                 si=p*n*r/100;  
                 Console.WriteLine(si); // For printing data to console.  
             }  
       }  
 }  

Some details about above program:
  • Comments à Lines skipped by compiler in the program.
    // à Singleline comments.           /*  */ à Multiline comments.
  •  Every instruction used in program should belong to a function.Every function must belong to a class and every class should belong to a namespace.And main function is the start point of execution.
  • print data to a separate line, to print in same line use Write() method.If we want to get input from keyboard using Read() and ReadLine().But it will take all the values as strings.If any numeric value exists, we need to convert them using ToSingle() à float,ToInt32()à32bit integer functions.
  • To supply any command line arguments use solution explorer properties node debug option command line argument box in visual studio.We can parse those values using args[] variable in our Main program,like args[0],args[1] depending on number of arguments.
Steps for Compilation and Execution
  • Start Visual Studio 2008 from Start|All Programs|Microsoft Visual Studio 2008
  • Select File|New Project…from the File menu.Select project type as Visual C#|Win w32 Console App from the dialog pops up.Give your name and click finish.
  •  Visual studio would provide just a skeleton program with empty main program created.
  • You can delete the unnecessary namespaces and we can delete string args[] from Main() if no arguments are there to execute in the program.
  • Save your program after typing your statements by using Ctrl+S.Compile and execute using Ctrl+F5.

C# provides many flavors of integers and reals.
Integer Types:













Default type is int.
Real Types:







Default type is double.If we wish to treat it as float or decimal,we need o suffix f or F and a m or M for decimal.


float x=3.5; //error float x=3.5f; //correct doublet x=3.5f; //correct double x=3.5; //correct decimal x=3.5; //error decimal x=3.5m; //correct

If you want an integer number treated as double,use the suffix d or D.
                                    double x=3d;

If the value of float/double/decimal is too small or large then use exponential form.
                            float a=3.41295e-5f; //0.0000341295f

When a real number is stored in a float/double/decimal it is stored in binary form. During this conversion some precision may be lost.

char data type represents a character in Unicode format.

In addition to the normal form a character constant can also be specified in hexadecimal escape sequence and Unicode representation.

                               char ch=’X’; //character literal
              char dh=’\x0058’; //hexadecimal
              char eh=’u0058’//Unicode

bool Data Typeàvalues true/false.Like c or c++ here bool is not integer but a separate data type.

Introduction...


What is C#

C# is a programming language developed my Microsoft in 2000.

C#, like C++ and Java, makes use of a principle called Object Oriented Programming(OOP) to organize the program.

What is .NET

.NET Framework is the more appropriate term for it. But it is famous with the short form .NET(DotNet).

It is a software development platform created by Microsoft for execution and development of C# and many other languages supported by it. It consists of two parts-FCL and CLR.

FCL(Framework Class Library) is a collection of readymade classes that can be used for common programming tasks. It is very versatile.
CLR(Common Language Runtime) is responsible for execution of C# programs.It handles the memory management and security while executing a C# program.

Programs written in any language cannot be executed directly and need to be converted into machine language instructions. In .NET this conversion is done in 2 steps.








The reason for the 2 steps is for language interoperability (Means different part of the same software can be written in different .NET-compilant languages(like C#,VB.NET,Visual C++) and can be compiled into one common executable program.




NET based programs must have .NET framework installed on the target machine to run them. On machines Windows XP(and server 2003) and earlier, the framework should be installed separately. The later OS versions like Vista,7 has .NET framework installed on it.

Though .NET is primarily used for Windows platforms.There are implementations available for Linux and Mac also.Please check MonoProject for reference.

What is Visual Studio

You need some development tools for building a software in any language.Like you need an editor to type the program and a compiler to compile the program, a debugger to detect,analyze and eliminate bugs in the program,etc.

IDE    à Visual studio comes in different editions based on the licensing terms.Visual Studio Express edition is available for free of cost and can be downloaded from Microsoft Download Site


In this Website, you need to download “Visual Studio Express for Windows”.
Two modes of Download exists in the site.
  1. Stub File (Less than 2 mb size and you need to be connected with internet during installation).
  2. ISO File (It is more than 600 mb and complete offline installation).

You can go with any mode of installation based on your requirement and just go with your default steps.