Monday, 28 April 2014

What are conditional constructs and why do we need it?

What are conditional constructs and why do we need it?
        
        The  ability  to take decisions is fundamental to human beings.  Decision-making can be incorporated into programs as well.  This helps in determining the sequence in which program will execute instructions.
            
             You can control the flow of a program by using conditional constructs.  Conditional constructs allow you to execute selective statements based on the result of the expression being evaluated.  The various conditional constructs that can be included in a c# program are 


  •  The if ....else construct
  •  The switch....case construct
            Now let me explain that in general view.  First we will go to the first conditional construct 
The if....else construct
             Here the if statement in the 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.  The following statements depict the syntax for the if....else construct:
              
             if(expression)
{
              statements:
          else
{
            statements;

}   


Consider an example where you have decide if you want to have dinner or you want to go to sleep.  The condition on which you will make a decision will be your hunger.  If you are hungry, you will have dinner ;  else you will go to sleep.

        The following code snippet shows the decision making of the preceding example by using the if...else construct;

    if (hungry==true )
{
console.writeline("Go and have dinner!");
}
    else
{
console.writeline("Go to sleep");
}
  

The folllowing code shows the use of the if...else construct

using System;
class Game
{   static void Main( string[] args)
     { 

int age;
Console.Writeline("Enter your age::");
Age = Convert.ToInt32(Console.Readline());
if(Age<12)
{
     Console.Writeline("Play the game!");

}
else
{
Console.Writeline(" Sorry!  This game is for children below 12 years");
}


The preceding code checks whether the age of the player is less than 12.  The condition in the if statement checks the age of the player and if the condition is true,  the statement in the if block are executed.  If the condition in the if statement is false, the statement in the else block are executed.

The output of the preceding code will be:
Enter Your age:
14
Sorry!  This game is for children below 12 yearrs
                           The Switch......Case Construct

          Another conditional construct available in C# is the switch.....case construct.  It is used when you have to evaluate a variable for multiple values.

          The following code depicts the syntax for the switch.....case construct:

switch(VariableName)
{
     case ConstantExpression_1;
             statements;
     break;
     case ConstantExpression_2;
             statements;
     break;
     case ConstantExpression_3;
             statements;
     break;
     default:
             statements;
     break;
}

  When the switch statement is executed, the variable given in the switch statement in evaluated and compared with each case constant.  If one of the case constants is equal to the value of the variable given in the switch statement, control is passed to the statement following the matched case statement.  A break statement is used to exit the switch statement.  This prevents the execution of the remaining case structures by ending the execution of the switch...case construct.

Tuesday, 2 July 2013

PROGRAMMING PART OF C# : WHAT ARE OPERATORS IN THIS LANGUAGE AND WHY DO WE NEED IT?

WHAT ARE OPERATORS AND WHY DO WE NEED IT?

Operators are used to compute results and compare the data values of a program.  A program often involves decision-making and iterative tasks (repetitive tasks).  You can use conditional constructs for decision-making and conditional constructs for repetitive for decision making and repetitive tasks in your programs.
This post discusses the various types of operators used in the C# language.  In addition, the chapter discusses the various conditional and looping (repetition) constructs supported by C#.
Using Operators
Consider an example, where you need to develop a C# program for displaying the result and rank of the students in a class.  To compute result and ranks, the application needs to perform some calculations and comparisons.  You can use various operators in your C# program and use them to compute the results and ranks of the students.
Operators like + (addition) and –(subtraction) are used to process variables and return a value.  An operator is a set of one or more characters that is used for computations or comparisons.  Operators can change one or more data values, called operands, into a new data value.
Consider the following example:
X+Y
            Operator
    X   +    Y
    
             
 
The preceding expression uses two operands, x and y, and an operator, +, to add the values of both the variables.  The following figure shows the operator and operands used in the preceding expression.
 








You can use the following types of operators in your C# programs:
·         Arithmetic operators
·         Arithmetic  assignment operators
·         Unary operators
·         Comparison Operators
·         Logical Operators
ARITHMETIC OPERATORS
Arithmetic operators are used to perform arithmetic operations on variables.  The following table describes the commonly used arithmetic operators.
OPERATOR
DESCRIPTION
EXAMPLE
+
USED TO ADD TWO NUMBERS
X=Y+Z
-
USED TO SUBTRACT TWO NUMBERS
X=Y-Z
*
USED TO MULTIPLY TWO NUMBERS
X=Y*Z
/
USED TO DIVIDE ONE NUMBER BY ANOTHER
X=Y/Z
%
USED TO DIVEIDE TWO NUMBERS AND RETURN THE REMAINDER.  THE OPERATOR IS CALLED AS MODULUS OPERATOR
X=Y%Z


ARITHMETIC ASSIGNMENT OPERATORS
Arithmetic assignment operators are used to perform arithmetic operations on two given operands and to assign the resultant value to any one of them
The following table lists the usage and describes the commonly used arithmetic assignment operators.
OPERATOR
USAGE
DESCRIPTION
=
X=5;
Store the value x in 5
+=
X+=5;
Same as X=X+5
-=
X-=5;
Same as X=X-5
*=
X*=5;
Same as X=X*5
/=
X/=5;
Same as X=X/5
%=
X%=Y;
Same as X=X%5
UNARY OPERATORS
Unary operators are used to increment or decrement the value of an operand by 1.  The following table explains the usage of the increment and decrement operators.
OPERATOR
USAGE
DESCRIPTION
EXAMPLE
++
++Operand;
(pre increment operator) or, operand++;
(post increment)
Used to increment the value of an operand by 1
Y=++X;
If the initial value of X is 5, after the preceding statement, values of both X and Y will be 6.  This is because it will first increment the value of x by 1 and then assign it to Y.
Y=X++;
If the initial value of x is 5, after the execution of the preceding   statement, value of x will be 6 and the value of y will be 5.  This is because it will first assign the value of x to y and then increment the value of X by 1.
--
--Operand;
(Pre decrement operator)
Or,
Operand--;
(Post decrement operator)
Used to decrement the value of an operand by 1
Y=--X;
If the initial value of x is 5, after the execution of the preceding statement, values of X and Y will be 4.  This is because it will first decrement the value of X by 1 and then assign the value to Y.
Y=X--;
 If the initial value of X is 5, after the execution of the preceding statement, value of X will be 4, and the value of Y will be 5.  This is because it will first assign the value of X to Y and then decrement the value of X by 1.
LOGICAL OPERATORS
Logical operators are used to evaluate expressions and return a Boolean value.  The following table explains the usage of logical operators.
OPERATOR
USAGE
DESCRIPTION
EXAMPLE
&&
Expression1  && Expression2
Returns true if both expression1 and expression2 are true
Bool result;
String str1, str2;
str1 =”Korea”;
str2=”France”;
Result= (str1=”Korea”) && (str2=”France”);
Console.WriteLine(result.ToString());
The preceding code snippet will print “True” on the screen because str1 has the value “Korea” and str2 has the value “France”

!
! Expression
Returns true if the expression is false.
Bool result;
Int x;
X=20;
Result=(! (x==10)) && (str2=”France”);
Console.WriteLine(result.ToString());
The preceding code snippet will print “True” on the screen because str1 has the value “(x==10)”

||
Expression1
||
Expression2
Returns true if either of  expression1 and expression2 are true or both of them are true
Bool result;
String str1, str2;
str1 =”Korea”;
str2=”France”;
Result= (str1=”Korea”) ||(str2=”France”);
Console.WriteLine(result.ToString());
The preceding code snippet will print “True” on the screen because str1 has the value “Korea” or str2 has the value “France”

^
Expression1
^
Expression2
Returns true if either of  expression1 and expression2 are true
It returns false if both expression1 and expression2 are true or if both expression1 and expression2 are false
Bool result;
String str1, str2;
str1 =”Korea”;
str2=”France”;
Result= (str1=”Korea”) ^(str2=”France”);
Console.WriteLine(result.ToString());
This will print “False” on the screen because both the expression are “True”



COMPARISION OPERATOR
Comparison operators are used to compare two values and perform an action on the basis of the result of that comparison.  Whenever you use comparison operator, the expression result in a Boolean value, ‘true’ or ‘false’.  The following table explains the usage of some commonly used comparison operators.
Operator
Usage
Description
Example
(In the following examples, the value of X is assumed to be 20 and the value of Y is assumed to be 25)
< 
Expression1
< 
Expression2
Used to check whether Expression1 is less than Expression2
Bool Result;
Result = X<Y;
Result will have the value true
> 
Expression1
> 
Expression2
Used to check whether Expression1 is more than Expression2
Bool Result;
Result = X>Y;
Result will have the value false
<=
Expression1
<=
Expression2
Used to check whether Expression1 is less than or equal to Expression2
Bool Result;
Result = X<=Y;
Result will have the value true
=>
Expression1
<=
Expression2
Used to check whether Expression1 is greater than or equal to Expression2
Bool Result;
Result = X=>Y;
Result will have the value false
==
Expression1
==
Expression2
Used to check whether Expression1 is  equal to Expression2
Bool Result;
Result = X==Y;
Result will have the value false
=!
Expression1
!=
Expression2
Used to check whether Expression1 is  not equal to Expression2
Bool Result;
Result = X!=Y;
Result will have the value true



Tuesday, 21 May 2013

PROGRAMMING PART OF C# --- OBJECTS AND VARIABLES CONTINUED

Submit ExpressSEO Services & Tools
PROGRAMMING PART OF C#  --- OBJECTS AND VARIABLES CONTINUED

             A C# program can be written by using the Windows Notepad application.  After creating a C # program in the Notepad application,  you need to compile and execute the program to get the desired output.  The compiler coverts the program's source code to machine code, such that the computer source code to machine code, such that the computer can understands the instructions in the program.

CREATING A SAMPLE C# PROGRAM 
         

using System;
class Car
               {
                 //Member variables
                 string Engine;
                 int NoOfWheels;
                 //Member functions
                 public void InputDetails()
                  {
                      Console.WriteLine("Enter the Engine Model");
                      Engine = Console.ReadLine();
                      Console.WriteLine("Enter the number of Wheels");
                      NoOfWheels = Convert.ToInt32(Console.ReadLine());
                      }

  public void DisplayDetails()
                  {
                      Console.WriteLine("The Engine Model is :{0}", Engine);
                      Console.WriteLine("The number of Wheels are: {0}", NoOfWheels);
                      NoOfWheels = Convert.ToInt32(Console.ReadLine());
                    }
}
//Class used to instantiate the Car class
class MainClass
{
              public static void Main(string[] args)
             {
                 Car MyCar = new Car();
                  MyCar.InputDetails();
                  MyCar.DisplayDetails();
              }
}

Typical building blocks of a C# program are:
  • The using keyword
  • The class keyword
  • The comment entry
  • The member variables
  • The member functions
  • The instantiating class
The using Keyword
    The using keyword is used to include the namespaces in the program.  Keywords are reserved words that have a special meaning.  The statement, using System, declares that you can refer to the classes defined in the namespace without using the fully qualified name.  You can write multiple using statements in your program to include more than one namespace in the program.

The class Keyword
      The class keyword is used to declare a class.  In the preceding code, the class keyword defines the class, Car.  The braces, known as delimiters, are used to indicate the start and end of a class body.

The Comment Entry
       Comments are used to explain the code in a program.  Compilers ignore the comment entries included in a program.  The symbol '//' treats the rest of code within the same line as a comment.  If a comment entry spans more than one line, it has to be enclosed within '/*' and '*/'.

The following examples show the usage of comment entries in C#:

  • // Single Line Comment
  • /* This is the sample program to display addition of two numbers                                                                                                                    
  •    Multiple line comment */
Member Variables
       Variables are used to store data in the memory.  Variables are also called the data members of a class.  In the code, the Car class has two member variables, Engine and NoofWheels.  These variables are used to store the data provided by the user.

Member Functions
        A function is a set of statements that perform a specific task in response to a message.  The  functions of a class are called member functions in C# and are also referred to as methods.  Member functions are declared within a class.  The function declaration declares the name of the function and its attributes in the class and the function definition contains the code of the function.  A program calls a function by using the function name.  However , what will the function do when it is called, is represented by the function definition.
        The Car class code contains two member functions, InputDetails and DisplayDetails.  These are declared and defined within the class.  Notice that the function definition contains code, which is written inside a block by using braces '{}'.  These braces represent the start and end of the function body.
         The InputDetails() mehod in the Car class code snippet will prompt the user to enter the engine model and number of wheels in the vehicle.  It will then store these details in the respective variables.  Further, the DisplayDetails() method will display the values stored in the member variables.

Instantiating Class
    In the Car class code, the MainClass class contains the Main() method.  This class is used to instantiate the Car class.  The first line of code that a C# compiler looks for is the Main() method.
    To implement the functionality of a class, you need to create an object of the class.  Objects interact with each other by passing messages and by responding to the received messages.  In C#, the task of passing messages can be done by using the member functions.
     All the objects of a class share the same copy of the member functions.  However, they maintain a separate copy of each member variable in memory.  The sharing of member functions and non sharing of member variables by the objects is shown in the following .
     Suppose there is Class: Car.  It has two variables: Member Variable1 and Member Variable2 .  And it has two functions : Member function 1 and Member function2.  Now two objects are created from it.  Let me briefly explain it.  In the previously example.  Car class.  To create an object named Mycar of the Car class , the following code snippet is given in the Main() method.
   
      Car Mycar = new Car();
    The member functions of the class are accessed through an object of the class by using the "." operator, as shown in the following code snippet:
    Mycar.InputDetails();
    Mycar.DisplayDetails();
      In the preceding example, the object name and the "." operator are used to access the two member functions, InputDetails() and DisplayDetails().  Inaa other words, the object Mycar of the class Car invoked the InputDetails() and DisplayDetails() methods.  These functions accept the values for the engine type and the number of wheels from the user and display the same, respectively.

Note
     The preceding code invokes the member functions from within the Main() method.  Usually, member functions are declared and defined under the public access specifier.  Access specifiers are used to determine if any other class can access the variables or function of a class.  You will learn more about access specifiers in subsequent posts.

Monday, 20 May 2013

PROGRAMMING PART OF C#: OBJECTS AND VARIABLES


We already have discussed classes.  Now we will go deep in programming, we will start discussing the basic programming part of C sharp.   We start with objects.
OBJECT
An object is an instance of a class.  You create objects to access member variables and member functions of a class.  Now let us discuss what are variables and functions.
VARIABLE
Consider a situation where you have to create a program that accepts two numbers from a user and displays the sum of the numbers on the screen.  Now, while reading the numbers provide by the user, you need to store somewhere in the memory so that you can perform the add operation on the numbers.  You can store the numbers in the memory by using variables.  A variable is a location in the memory that has a name and contains a value.  The value could be integer, such as 27, a decimal, such as 9.85, or a character, such as ‘L’.  A variable is associated with a data type that defines the type tof data that can be stored in the variable.
For example, a variable called TennisPlayerName will ideally store characters, whereas a variable called High Score will store numbers.  A program refers to a variable by its name.
Naming Variables in C#
In C#, the following rules are used for naming variables:
·         A variable name must begin with a letter or an underscore (‘_’), which may be followed by a sequence of letters, digits(0-9), or underscores.  The first character in a variable name cannot be a digit.
·         A variable name should not contain any embedded spaces or symbols, such as                  “ ?!@#$%^&*()[]{}.,’;:\/”.  However, an underscore can be used wherever a space is required, like High_Score.
·         A variable name must be unique.  For example, to store four different numbers, four unique variable names need to be used.
·         A variable name can have any number of characters.
·         Keywords cannot be used as variable names.  For example, you cannot declare a variable named class as it is a keyword in C#.
The examples of valid variable names are:
·         Game_Level
·         High_Score
·         This_variable_is_very_long
The examples of invalid variable names are:
·         #score
·         2strank
Note

C# is a case-sensitive language.  This means that the TennisPlayerName variable is not the same as the tennisplayername variable.  In other words, Uppercase letters are considered distinct from lowercase letters.


DECLARING AND INITIALIZING VARIABLE
You can declare and initialize variables by using the following syntax:
<data_type> <variable_name> = <value>;
In the preceding syntax, the   <data_type> represents the kind of data type that will be stored in a variable and <value> specifies the value that needs to be stored in the variable.
Consider the following statement that declares a variable:
Int age=1;
The preceding statement declares a variable named age of the int data type.  In addition, the statement initializes the variable with the value, 1.  The int data type is used to store numeric data (integers).
Consider the following statement:
Char choice=’y’
The preceding statement declares the variable choice of the char data type and initializes the variable with the value, y.
DATA TYPES IN C#
C# provides various built – in data types.  Built-in data types are predefined data types that can be directly used in a program to declare variables.





The following table lists some of the built in data types in C#



Predefined Type
#Bytes
Range of values

Char
2
0 to 65535
Int
4
-2147483648 to 2147483647
Float
4
-3.402823 * 10^38 to -1.401298*10^-45(for negative values)
1.401298*10^-45 and 3.402823*10^38(for positive values)

Double
8
-1.79769313486232E308 to -4.940656455841247E-324(for negative values) and 4.94065645841247E-324 to       1. 79769313486232E308(for positive values)
Bool
1
True or False
String
Variable length
0-2 billion Unicode characters

The #Bytes column in the preceding table specifies the bytes that are required to store the value in the memory.
TYPES OF DATA TYPES
C# supports the following data types:
·         Value types: The value types directly contain data.  Some examples of the value types are char, int, and float, which can be used for storing alphabets, integers, and floating point values, respectively.  When you declare an int variable, the system allocates memory to store the value.
·         References types: The reference type variables, instead of containing data, contain a reference (address) to the data stored in the memory.  More than one reference type variable can be created to refer to the  same memory location.  This means that if the value in the referenced memory location is modified, all the referring  variables automatically reflect the changed value.  The example of reference type is string data type.

ACCEPTING AND STORING VALUES IN MEMBER VARIABLES
       
           To understand how to store value in a variable, consider the following code snippet:
     
                 int Number;
                 Number = Convert.ToInt32(Console.ReadLine());
          In the preceding code snippet, the  Console.ReadLine() method is used to accept data from the user and store it in the variable named Number.  The Console.ReadLine() method is a method of the Console class, which is a part of the System namespace.

          Further, the Convert.ToInt32() method converts the data provided by the user to the int data type.  You need to do this conversion because the Console.ReadLine() method, by default, accepts the data in the string format.  The Convert() method explicitly informs the compiler to convert one data type to the other.  This is known as explicit conversion.
   
         In addition to explicit conversion, there are instances when the compiler performs implicit conversions, which are done automatically(without any explicit coding).  For example, implicit conversion converts the int data type to float or float data type to int, automatically.