Showing posts with label C# Programming. Show all posts
Showing posts with label C# Programming. Show all posts

Polymorphism

As the same name suggests 'Poly' (many) 'morphos' (forms) an object existing in different forms. In our Programming environment we call it as an "Entity existing in many forms". Resilence to change is the best example of polymorphism. In OOPs we express polymorphism as " One Interface, Multiple Functions".

Talking about kinds of Polymorphism, they are classified into two basic forms

1. Static Polymorphism or compile time polymorphism
2. Dynamic Polymorphism or run time polymorphism.

In our programming environment we can see the importance of polymorphism by creating more than one function in a class with the same name but differing them with the parameter declaration, i.e method overloading is one of the feature where we see the implementation of polymorphism.

example: a woman who can be a wife, a daughter,a sister,a mother etc.... is an example of polymorphism.

Static Polymorphism:

"The Mechanism of linking a function to a class object at compile time is called static polymorphism or early binding. "

C# uses two approaches to implement static polymorphism.....

1. Function overloading.
2. Operator Overloading.

1. Function Overloading:

Process of defining a function multiple times with same name inside a single class by changing the type of parameters, sequence of parameters, no of parameters.

additionFunction(int n1,int n2);
additionFunction(float n1, float n2);

Here the return type of the functions can be same or they can differ.
2. Operator Overloading:

/*

*/

Dynamic Polymorphism:

In Dynamic polymorphism the decision about function execution is made at runtime. Dynamic polymorphism is more useful as compared to static polymorphism because dynamic polymorphism gives much flexibility for manipulating objects.

"The mechanism of linking of a function with an object at runtime is called Dynamic Polymorphism of late binding. "
C# uses two approaches to implement dynamic polymorphism,

1. Abstract classes .
2. Virtual Functions.

1. Abstract classes:

These are special type of base classes that consists of abstract class members. we can have abstract classes as well as abstract methods, and any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword.

We cant create objects for abstract classes i.e ( classname obj=new classname), this kind of declaration is not possible for abstract classes.

We can create object references for abstract classes i.e ( classname ref; ).

We cant declare abstract static methods and abstract constructors.


2. Virtual Functions:

These are the functions which do not really exists, but appear to be present in some parts of the program.

Destructors

  • Destructors are the special methods that r used to release the instance of the class from memory.
  • The main purpose of it is to perform the memory clean up action. the programmer can not have any control to call the destructor.
  • The .Net frame work automatically runs the destructor to destroy objects in the memory.
  • A single class can have only one destructor.

Declaration of Destructor

  • Destructor follows the same rules as that of constructors but the difference comes in the functioning.
  • Destructor has same name as class name as its class but is prefixed with a '~' called as tilde operator.
  • Destructors can not be inherited or overloaded.
example:

using System;

class Addition
{
static int n1,n2;
int total;
}

Addition()
{
n1=5;
n2=3;
total=0;
}
public void operation()
{
total=n1+n2;
Console.WriteLine("The result is {0}", total);
}
~Addition()/*.............. Destructor.............*/
{
Console.WriteLine("Destructor invoked");
}
static void Main(String [] arg)
{
Addition obj=new Addition();
obj.operation();
}
}

note: Even when u dont call the destructor, garbage collector releases the memory.

Garbage Collection

  • It is a process that automatically frees the memory space which is used for the objects at the time of program execution.
  • The memory for the object is freed only after observing the status of the object (i.e when object is no longer in use).
  • The decision to invoke the destructor is made by a special program of C# called as garbage collector.
  • In C#, you can not destroy an object explicitly in code, in fact it has the feature of garbage collection which destroys the objects for the programmers.
  • Garbage collection mainly involves,
  1. objects get destroyed: doesnt specify when the object is destroyed.
  2. Only unused objects are destroyed: object is nt deleted unless it holds any reference.
  • C# uses two special methods to release the instance of a class from memory
  1. Finalize()
  2. Dispose()
  • Finalize destructor is a special method that is called from the class to which it belongs or from the derived class.
  • It is called only after the last reference of the object is released from the memory.
  • .Net frame work automatically runs the Finalize() destructor to destroy objects in the memory. and keep in mind that the Finalize method does nt invoke immediately.
  • Dispose() method is called to release a resource, such as a database connection as soon as the object using such a resource is no longer in use.
  • Unlike the Finalize() destructor , the Dispose() method is not called automatically, and you must explicitly call it from the client application when an object is no longer needed.
  • IDisposable interface contains the Dispose() method. So in order to invoke the Dispose() method a class must implement the IDisposable interface.

Constructors

  • These form the special member functions of the class .
  • These have the same name as class name and constructors do not return any value .
  • A Constructor is complimentary to a destructor. It is a good programming to use both constructors as well as destructors.
  • Constructors can be defined in two ways as
1. static Constructors.
2.Instance Constructors.


Static Constructors:
  • These r used to intialise static variables of a class.
  • These variables r created using static key word and they store values that can be shared by all the instances of a class .
  • Static constructors have an implict private access.
  • These ill be invoked only once during execution.
  • exam:

    public class Example
    {

    static int n1;
    int n2;

    static Example()
    {
    n1=5; /*.................. accepts the value for variable n1............................*/

    n2=10; /.......................... puts an error msg...........*/
    }
    }

note: We use constructors to intialise data members and not for any input or output operations.
and we can have more than one constructor for a class.

Constructors with parameters

At times user wants to pass values to variables at run time where it cant be possible through intializing them at the starting of prog, so during this situation he can make use of passing the values to variables through parameters.
constructors can be used in order to supply values to variables at run time. ......

here is an exam program to illustrate the process of functioning.........

using System;

namespace arithemetic_oper
{
class Addition
{
static int num1,num2;
int total;

Addition(int n1,int n2)
{
num1=n1;
num2=n2;
}

public void addNum()
{
total=num1+num2;
}

public void displayNum()
{
Console.WriteLine(" Result is : {0}",total);
}

public static void Main(String [] arg)
{
int var1,var2;
Console.WriteLine("Enter the var1:\t");
var1= Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the var2:\t");
var2=Convert.ToInt32(Console.ReadLine());

Addition obj=new Addition(var1,var2);

obj.addNum();
obj.displayNum();
Console.ReadLine();
}
}
}

Instance Constructors:

  • Instance constructor is called when ever instance of a class is created.
  • These r used to intialize data members of the class.
  • Constructors do not return any values.
  • If there r no constructors for a class, then compiler creates a default constructor for itself.



/*............... Sample prog's 1.......................*/

using System;

class AgeValidation
{
int age;

void accept()
{
Console.WriteLine("Enter the Age:");
age=Convert.ToInt32(Console.ReadLine());
}
void display()
{
if(age<0)
{
Console.WriteLine("Invalid age");
}
else
{
Console.WriteLine("valid age");
}
}
public static void Main(String [] arg)
{
AgeValidation obj=new AgeValidation();
obj.accept();
obj.display();
}
}
/*................ end of sample prog 1...............*/


/*................sample prog 2..................*/

using System;

class MyTable
{
int t,i;
void accept()
{
Console.WriteLine("Enter the table number:");
t=Convert.ToInt32(Console.ReadLine());
}
void show()
{
for(i=1;i>0;i++)
{
Console.WriteLine("{0} * {1} = {2}",i,t,(i*t));
}
}

public static void Main(string [] arg)
{
MyTable obj=new MyTable();
obj.accept();
obj.show();
}
}

/*............. End of sample prog 2............*/

using System;

public class Swapping
{
void Swap(ref int a, ref int b)
{
int temp;
temp=a;
a=b;
b=temp;

}

static void Main(string [] arg)
{
Swapping obj=new Swapping();
int n1,n2;
Console.WriteLine("Enter the no's:\t");
n1=Convert.ToInt32(Console.ReadLine());
n2=Convert.ToInt32(Console.ReadLine());
obj.Swap(ref n1, ref n2);

Console.WriteLine("The values of the numbers before swapping is :\t"+n1);
Console.WriteLine("The values of the numbers before swapping is :\t"+n2);
Console.ReadLine();
}
}

As we know parameters allow information to be passed in and out of a method.
When you define method, you can include list of parameters in parentheses.

Declaring Methods with parameters

Each parameter has a type and a name. u can declare parameters by placing parameter declaration inside parentheses. A syntax that is used to declare parameters is similar to the syntax that is used to declare local variables.

The syntax for declaring parameters inside methods

void Method(int n, string y)
{
// body.
}


the preceding code declares the method (Method) with out parameters and y. The first parameter is of type int and 2nd of type string.

Calling methods with Parameters

value type:

values r some time passed in parameters, therefore, the data can be transferred into the method but cannot be transferred out.

Reference type:

These r some times called In/Out parameters, therfore, the data can be transferred into the method and out again.

Pass Parameter by value


The simplest definition of a value parameter is the data type name followed by a variable name.
When a method is called, a new storage location is created for each value parameter. The values of the corresponding expressions are copied into them. The expressions supplied for each value parameter must be similar to the declaration of the value parameter or it must be a type that cane be implicitly converted to the value type .

example :
class calculator
{
void Addone(int var)
{
var++;
}
public static void Main(string [] arg)
{
Calculator Cal=new Calculator();
int number=6;
cal.Addone(number);
Console.WriteLine(number); //.................. Display value 6 .
}
}
pass parameter by reference

A reference parameter is a reference to a memory location of a data member.
Unlike a value parameter, a reference parameter does not create a new storage location., instead reference parameters represents the same location in memory as the variable that is supplied in the method call.

you can declare reference parameter by using the ref keyword before the data type, as shown in the following example:

class Calculator
{
void Addone(ref int var)
{
var++;
}
public static void Main(string [] arg)
{
Calculator obj=new Calculator();
int number =6;
obj.Addone(ref number);
Console.WriteLine(number);//....................Displays value 7.
}
}


/*..................Printing student info ......................*/

using System;

class Student
{

//Member data.
string name;
string regno;
string add;
int age;

//Member function
void Accept()
{
Console.WriteLine("Enter the name:\t");
name=Console.ReadLine();

Console.WriteLine("Enter the regno:\t");
regno=Console.ReadLine();

Console.WriteLine("Enter the address:\t");
add=Console.ReadLine();

Console.WriteLine("Enter the age :\t");
age=Convert.ToInt32(Console.ReadLine());
}
void Display()
{
Console.WriteLine("The name of student is :{0}",name);
Console.WriteLine("The regno of student is :{0}",regno);
Console.WriteLine("The age of student is :{0}",age);
Console.WriteLine("The add of student is :{0}",add);
}
public static void Main(string [] arg)
{
Student S=new Student();
S.Accept();
S.Display();
}
}

/*...................Fibonacci series.................*/

using System;

class Fibonacci
{
int f[] =new int[15];

void Accept()
{
f[0]=0;
f[1]=1;
Console.WriteLine("Enter the num:\t");
int num=Convert.ToInt32(Console.ReadLine());
}

void Display()
{
for(int i=2;i<=num;i++)
{
f[i]=f[i-1]+f[i-2];
Console.WriteLine(f[i]);
}
}

}
class Result
{
public static void Main(string [] arg)
{
Fibonacci F=new Fibonacci();
F.Accept();
F.Display();
}
}

Before coming to methods and there types first we shall know what r the features of Methods....

  • Method is a set of one or more statements or instructions.
  • Methods r mainly used for data hiding (i.e) providing the facility of encapsulation and also abstraction.
  • They allow the user to implement the concept of reusability .
  • They play a key role in modular programming ,when a application is divided into methods then it ill be easy to maintain the code and also to debug.
  • Methods r used for performing repetitive tasks such as fetching specific records and text. They allow user to break an application into discrete logical units, which makes the application more readable.
  • We can reuse the code written in a method and can be executed any number of times by calling methods with little change or else no change .
To use methods, you need to perform 2 things mainly
  1. Define method.
  2. Call method.
Defining methods:

defining a method means declaring the elements of its structure. methods r defined with the following syntax......
(para list)
{
//................Method body;
}

  • Access specifier:
    This explains the extent to which a variable and mtd can be accessed.
  • Return type:
    A method can return any type of value, if method does not return any value then use void as the return type.
  • Method name:
    This plays a prominent role in shaping a class. Method names can not be keywords of the programming language and it is a good practice to follow follow pascal case (eg: Methodone). It can not be same as a variable name also .
  • Parameter list:
    This is used to receive and pass the data from one method to other. We can leave the parameter list empty with out any values.
  • Method body:
    Method body mainly contains the code which is required to perform some specific operation.
example:
class Calculator
{
public int AddNumber(int n1, int n2)
{
int res;
res=n1+n2;
return res;
}
}
Types of Methods
  • calling Methods
    After defining a method , you can use it by its name. The method name is followed by parentheses even if the method call has no parameters.
example:
using System;

class Calculator
{
public int AddNumber(int n1, int n2)
{
int res;
res=n1+n2;
return res;
}
static void Main(string [] arg)
{
Calculator C=new Calculator();
int total=C.AddNumber(10,20);
Console.WriteLine("Te result is :{0}",total);
Console.ReadLine();
}
}
Execution process:
  • In the above program the execution starts from main function . so initially memory is allocated dynamically for the Calculator class and a object is created.
  • Nw by using the object we r trying to access the code defined inside the method. When the method (AddNumber) is accessed the actual arguments(10, 20) supplied in the method is passed to the formal parameters(int n1,int n2) and these values r stored in n1 and n2.
  • since the method uses a return type as int, it is the duty of the user to return a value of type int . so after performing the addition operation the data is returned and the returned value is caught by a variable (total) which is in main function.
  • Last but not the least.............. The value is printed.
  • Here We have to remember one thing that return type of the main method is 'void ' so it doesnt return any value.
example:
/*.................. Recursion method...............*/
using System;

class Number
{
public int Factorial(int n)
{
int res;
if(n==1)
return 1;
else
{
res=factorial(n-1)*n;
return res;
}

}
static void Main(string [] arg)
{
Number obj=new Number();
Console.WriteLine("Factorial of 3 is "+obj.factorial(3));
Console.WriteLine("Factorial of 4 is "+obj.factorial(4));
Console.WriteLine("Factorial of 5 is "+obj.factorial(5));
Console.ReadLine();
}
}

In above program, the factorial() method is recursive method. If the value entered by the used is not 1, this method will call itself.

/*.............. Progr@m to calculate area of rectangle and square.........*/

using System;

class Area
{
static int res;//.............declaring static variable.

public static void RecArea()//........... defining a static func.
{
int l, b;

Console.WriteLine("Enter the length :\t");
l=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the breadth :\t");
b=Convert.ToInt32(Console.ReadLine());

res=l*b;
Console.WriteLine("The area of a rectangle is :{0}",res);

// (or) Console.WriteLine("The area of rectangle is :\t"+res);
}
public static void SqrArea()//........... defining a static func.
{
int side;

Console.WriteLine("Enter the side of the square:\t");
side=Convert.ToInt32(Console.ReadLine());

res=side*side;
Console.WriteLine("The area of a square is :{0}",res);
}
}
class Result
{
public static void Main(string [] arg)
{
int option;
Area a=new Area();

Console.WriteLine("Main Menu");
Console.WriteLine("1. Area of Rectangle ");
Console.WriteLine("2. Area of Square ");
Console.WriteLine("Enter the option :\t");
option=Convert.ToInt32(Console.ReadLine());

switch(option)
{
case 1:

a.RecArea();
break;
case 2:
a.SqrArea();
break;
default:
Console.WriteLine("oops..!.............Wrong choice buddy, u can leave ");
break;
}
Console.ReadLine();
}
}

Note:

steps to compile and execute
  1. save teh file with .cs extension (i.e) Area.cs
  2. compilation:
    csc Area.cs
  3. execution:
    Area.cs (or) Area.exe

Access specifier defines the scope of a class member. We generally use these access specifiers to give complete security to the data . We use different type of access specifiers to specify the extent of visibility of a class member. In C# we use totally 5 types of access specifiers

  1. public
  2. private
  3. protected
  4. internal
  5. protected internal
  • public access specifier
    1. This access specifier allows the member data and functions of a class to be exposed to other class functions and objects .
    2. The member which is declared as public can be accessed from outside the class.
example:

using System;

class Car
{
private string Car_color;
}
class Bike
{
public string bike_color;
}
class Result
{
static void Main(string [] arg)
{
Car Camry=new Car();
Bike unicorn=new Bike():

Camry.Car_color="white"; //.................................. Error..! cant access private var outside class.
unicorn.bike_color="black"; //................................assigns black to variable.
Console.ReadLine();
}
}

example 2:
using System;
class Car
{
public string color;
public void Honk()
{
Console.WriteLine(" Member function invoked");
}
}
class Result
{
static void Main(string [] arg)
{
car Camry =new Car();
Camry.Honk();//.............. displays the msg.........................Member function invoked.
Console.ReadLine();
}
}

  • private access specifier
    1. This access specifier allows the private data of a class to be hidden from out side classes.
    2. Only the members of the same class r provided permissions to access the private members.
example:

using System;

class Car
{
private string Model;

void Honk()
{
Console.WriteLine("beep beep....!");
}
public void setModel
{
Console.WriteLine("Enter the model num:\t");
Model=Console.ReadLine();
}
public void Display()
{
Console.WriteLine("The model is :\t");
}
}
class Result
{
static int Main(string [] arg)
{
Car Camry=new Car();

Camry.setModel(); //..................Prompts user to enter the model..
Camry.Display();//...............Displays the model.
Camry.Honk();// ................. can not access private methods out side class.
Console.WriteLine(Camry.Model);//...............can not access private mem outside class.

return 0;
Console.ReadLine();
}
}


Note:
When u do not specify any data members as either public, private, protected then the default access specifier is private.
  • Protected access specifier:
    1. This specifier allows a class to expose its member data and functions only to its child classes .
    2. It hides the data to be accessed from other class objects and functions.
example:

using System;
class Car
{
protected string model;
void Method()
{
Console.WriteLine("Member function invoked");
}
public void setModel()
{
Console.WriteLine("Enter the model name :\t");
model=Console.ReadLine();
}
void Display()
{
Console.WriteLine("The model is :\t");
}
}
class Result
{
static int Main(string [] arg)
{
Car civic =new Car();
civic.Method();//......... Error!...can not access this member as it is a protected member.
civic.setModel();//....... accepts the input.
civic.Display();//.......Error!...private member can not be accessed.
Console.WriteLine(civic.model);//.....protected members can not be accessed.

return 0;
Console.ReadLine();
}
}
  • internal access specifier:
    1. Any member that is declared internal can be accessed from any class or method defined within an application in which the member is defined.
    2. When u do not specify any class class as either public, private, protected then the default access specifier for a class is internal.
example:

using System;
class Bike
{
private string col;

internal void Method()
{
Console.WriteLine("Method invoked");
}
}
class Result
{
static void Main(string[] arg)
{
Bike Fz=new Bike();
Console.WriteLine(Fz.col);//...........Error!...can not access private data.
Fz.Method();//............Displays method invoked.
Console.ReadLine();
}
}

Note:
the main difference between public and internal is
  1. public is visible to objects of other class outside the namespace collection and also to the child classes outside the namespace collection.
  2. But internal access specifier is not visible to objects of other class outside the namespace collection and also to the child classes outside the namespace collection.
  • protected internal access specifier:
    1. This specifier allows a class to hide its mem var, mem funct, to be accessed from other class objects and functions, except the child class ,within the application.
    2. This access specifier ecomes important while implementing inheritance.
example:

using System;

class Car
{
protected internal string col;
void Method()
{
Console.WriteLine(" Method invoked");
}
}
class Result
{
static int Main(string [] arg)
{
Car audi =mew Car();
audi.Method();//........Error!... private function.
Console.WriteLine(audi.col);//...... cannot access protected internal members outside the class .

return 0;
Console.ReadLine();
}
}
  1. this Acc.Spec has the similar properties as that of internal and the only dfference is that it can not be visible to objects of other class within the same namespace.






Object Oriented Programming mainly deals with concepts such as Abstraction, Encapsulation, Polymorphism, Inheritance.


Abstraction:

  • Abstraction mainly involves extraction of only relevant information.
  • The concepts of abstraction and encapsulation mainly deals with the member functions of the class.
  • abstraction can be explained in other words as ' Looking for what u want ' in an object or a class.
  • after reading this summary of abstratcion one gets a doubt " does abstraction mean that information is unavailable" .....! No, It means that all the information exists, but only the relevant information is provided to the user.
  • we shall learn more abt abstraction by considering the below given example...
example:

Anautomobile salesperson is aware that different people have different preferences. Some r intrested in the mileage of the car, some in its price, some in its engine, and some in its style.

So every individual have diffferent views and wants . Although every individual is intrested in diff aspects of the car finally tey all come to the category of buying a car. The sales man knows the details of the car , but he presents only the relevant information to potential to the customer. As a result, the salesman practices abstraction and presents only relevant details to customer.


Encapsulation:

  • Encapsulation means packing of one or more components together.
  • It short encapsulation means ' to enclose it or as if in a capsule' .
  • Encapsulation can be defined as " the process of enclosing one or more items within a physical or logical package ", it involves preventing access to non-essential data.
example:

When you plug in the cord of a vacuum cleaner and turn on the switch, the vacuum cleaner starts. You do not see the complex process needed to actually convert electricity into suction power. In other words , the exact working of the cleaner has been encapsulated. Therefore, encapsulation is also explained as information hiding or data hiding because it involves hiding many of the important details of an object from the user.

Abstraction and encapsulation are realated features. abstraction enables you to make relevant information visible. Encapsulation enables you to package information to impent the desired level of abstaraction. Therefore, encapsulation assists abstraction by providing a means of suppressing the non essential details.
the feature of encapsulation is achieved by access specifiers............

1. static void main(String [] arg)
{
char ch;
Console.WriteLine("Enter the character:\t");
ch=Convert.ToChar(Console.ReadLine());

if(ch=='U')
Console.Writeline("The character is X");
else
Console.WriteLine("The char is not X");
Console.ReadLine();
}

wats the o/p of the above code .............................?

2. To which category does the operator ++, = belong.........?

3. In the statement using System, System is a.........................

4. which of the following data type is not a value type.............?

  • char
  • int
  • float
  • string
5.The .............. compiler is used for C#.
  • cc
  • csc
  • cs
6.In which of the following datatypes does the Console.readLine() function accept a value.........?
  • int
  • float
  • bool
  • string
7. Console is a ..........
  • class
  • function
  • namespace
8.In any program, the execution of the program starts from ........

Note:
Give the answers by there respective question numbers.

Some times we need to exit out of the loop with out performing next iteration. SO in such case we make use of break and continue statements.

Break statement:

  1. break statement is used in order to exit from the loop.
  2. It Terminates a statement sequence in a switch statement.
Continue statement:
  1. Used to skip all the subsequent instructions and shift the cursor position back to the loop.
  2. Here the compiler tries to iterate the loop when ever the condition is satisfied .
Example:
/*....................... sum of +ve numbers..........................*/
using System;

class Break_Continue
{
static void Main(string [] arg)
{
int num,sum,i;
for(sum=num=i=0;i<5;i++)
{
Console.WriteLine("Enter the +ve number:\t");
num=Convert.ToInt32(Console.ReadLine());

if(num<=0) //............checks for +ve numbers.
continue;
sum=sum+num; //..............adds only +ve numbers.
}
Console.WriteLine("The sum of +ve numbers:\t"+sum); //..... Displays result of +ve numbers.
}
}

using System;

class Fibonacci
{
public static void Main(string [] arg)
{
int num;
int f[] =new int[15];
Fibonacci()
{
f[0]=1;
f[1]=1;
}
void accept()
{
Console.WriteLine("Enter the number :\t");
num =Convert.ToInt32(Console.ReadLine());
}
for(int i=2; i<=num;i++) { f[i]=f[i-1]+f[i-2]; Console.WriteLine(f[i]); } } } Note:

When u write a program using C sharp u have to save the file with ' .cs' extension.

example: Fibonacci.cs

compilation mtd: csc Fibonacci.cs

execution mtd: Fibonacci.cs

We have three types of loop constructs
1. while.
2. do...while .
3. for.

  • while loop
    1. This construct is generally used to execute a block of statements for a definite number of times, depending on the condition.
    2. while statements checks the condition before executing the statements within the loop.
    3. When the execution reaches the last line of the block the control is transferred to the condition of while and if the condition is satisfied then the statements are executed again and when the condition sets to false it comes out the loop.
syntax:
while(expression)
{
statements;
}
  • do..while loop
1. Both Iterate until the specified loop condition becomes false.
2. however, in do...while loop , the body of the loop is executed at least once and the condition is checked for next subsequent iterations.
3. The do...while loop construct is similar to the while loop constructs.

syntax:
do
{
statements;
}while(expression);

example:

int var=10;
do
{
Console.WriteLine("value of var is :{0}",var);
var=var+10;
}
while(var<20);
  • for loop
  1. for loop is used to execute a block of statements for a specific number of times.
  2. Here the main difference between for and while is mainly in syntactical format. The syntax used for loop is ......
Syntax:
for(initialization; condition; increment/decrement)
{
statements;
}
example:

for(int i=1;i<=10;i++) { Console.WriteLine("{0}",i); }
Note:
We can follow different syntax's for for loop
for(; ;)
{
statements;
}

        Conditional constructs are used to control the flow of program . conditional constructs allow the flow selective execution of statements , depending on the value of the expressions associated with them. The comparison operators are required for evaluating the conditions . various conditional constructs are :

        1. if....else construct.
        2. switch... case construct.

        • if....else construct
          if...else conditional construct is followed by a logical expression where data is compared and a decision is made on the basis of the result of the comparison. syntax is
        if (expression)
        {
        statements;
        }
        else
        {
        statements;
        }
        example:

        class Number
        {
        static void Main(string [] arg)
        {
        int num;

        Console.WriteLine("Enter the number: \t");
        num=Convert.ToInt32(Console.ReadLine());

        if(num%!=0)
        {
        Console.WriteLine(" Number is odd");
        }
        else
        {
        Console.WriteLine(" Number is even");
        }


        if....else constructs can be nested inside each other. This process of using multiple if....else constructs is known as cascading if ...else. consider the example :
        int n1=5;
        int n2=6;
        int n3=7;
        if(n1>n2)
        if(n1>n3)
        {
        Console.WriteLine("Number 1 is great");
        }
        else
        {
        Console.WriteLine("number 3 is great");
        }
        else if(n2>n3)
        {
        Console.WriteLine("number 2 is great");
        }
        else
        {
        Console.WriteLine("number 3 is great");
        }
        • switch...case construct
        This construct is used when there are multiple values for a single variable. syntax for this construct is
        switch(variable name)
        {
        case option: statement;
        break;
        case option: statement;
        break;
        default: statement;
        }

        "Operators r the ones which r used to perform different operations on atleast one operand".

        Operators r mainly classified into 5 types

        • Arithmetic operators
        • Arithmetic assignment operators
        • unary operators
        • comparison operators
        • Logical operators
        1. Arithmetic operator:
        These operators r used in order to perform operations on atleast two operands i.e variables. We can perform operations such as addition(+) ,subtraction(-), multiplication(*), division(/), modulo(%).

        2. Arithmetic assignment operator:

        These operators r used in order to perform assignment operations to assign values to variables (operands).We can perform Operations such as ( +=, -=, *=, /=, %= ) . We shall understand them with examples
        • += :- x+=y it implies x=x+y;
        • *= :- x*=y it implies x=x*y;
        3. Unary operators:

        These operators use only single operand. These r mainly used for incrementing and decrementing the value present at the variable. these incrementation process includes mainly post and pre process. we shall see examples,
        • ++ which is used as ++x where x is the operand and this is called pre incrementation. where the value is assigned after getting incremented . and if we use the operator like x++ then it is called post increment . and the case is similar with decrement process.
        • -- is used for decrementation process . the pre and post decrementations r done similar to that of incrementation process.
        4. Comparison operators:

        These operators r used to compare two values and perform the required action.when ever u use a comparison operator the expression results a boolean value (true or false) .
        Comparison operators are ( <, >, <=, >=, !=, ==) .These r used in between two expressions .

        5. Logical operators:

        These r used to evaluate a expression and return a boolean value . the logical operators includes (&&, !, ||, ^).

        6. Terenary operator (or) conditional operator: this operator is used to perform an action based on the result that is generated.

        syntax:
        expr1? expr2 : expr3

        here if expr1 is true then expr2 is printed if it is false then expr3 is printed. In general expr1 contains statements regarding comparison of values present at the operands .

        /* Example One */

        using System;
        class Myclass
        {
        public static void Main(String arg[])
        {
        string add='A';
        string Response_code="007";
        int counter=60;
        Console.WriteLine(add);
        Console.WriteLine(Responce_code);
        Console.WriteLine(counter);
        }
        }

        output:

        fnds can u guess it .......................!

        In the sample program we have come across a statement "using System"

        using System;

        Here using is a keyword used to include the namespaces in the program. Keywords r reserved words which have special meaning. Here using System declares that you can refer to the class defined in the namespace without using the fully qualified name. A program can include multiple using statements.

        class Keyword

        The class keyword is used to declare a class . The braces ,known as delimeters ,are used to indicate the start and end of class body.

        Member variables

        variables are used to store data. These r also called as date members of a class or instance members of a class. These variables r declared with the suitable data types.

        Member functions

        A function is a set of statements that perform a specific task in response to a message . Member functions of a class r declared inside the class.

        Instantiating a class

        To create memory for a class we generally use the system of dynamic allocation in C#.(i.e by using the keywords new and delete). so to allocate memory to a class we take help of objects which act as instance for the class . These objects interact with each other by passing messages and by responding to received messages. Objects use methods to pass messages, the task of passing messages is done by using member functions. all the objects of a class will use the same copy of member functions through out but they use different copy of member variables in memory.

        eg: Student std=new Student();

        here 'std' is the object of class Student where memory is allocated dyanamically using the keyword new.
        we can access the member functions using this object 'std' .

        eg:
        std.Accept();
        std.Display();

        Here is a sample C# program

        using System;

        class Student
        {
        //Member data.
        string name;
        int id;

        //Member functions.
        Public void Accept()
        {
        Console.WtiteLine("Enter the name:\t");
        name =Console.ReadLine();
        Console.WriteLine("Enter the id of employee:\t");
        id=Convert.ToInt32(Console.ReadLine());
        }
        public void Display()
        {
        Console.WriteLine("The name is :{0}",name);
        Console.WriteLine("The id is :{0}",id);
        }
        }
        // class used to intiate student class
        class Executestudent
        {
        public static void Main(string[] arg)
        {
        Student st=new Student();
        st.Accept();
        st.Display();
        }
        }

        Older Posts Home