Friday, July 15, 2022

Link to New Site

I am no longer updating this blog. I now have the site https://scitechgen.com where I put up more information and it is also updated regularly. Please visit the site https://scitechgen.com for more. 

I also have my YouTube channel youtube.com/scitechgen where I put up explanatory videos on Computer Science, mathematics, Physics and Statistics. 

 It will be nice if you can join me in these two places (its FREE!) and share your views, experiences and articles. 

 Thank you.

Wednesday, March 4, 2009

Ch 5 C #: Classes and Methods, Part 1

5. Classes and Methods – Part 1

Defining a class :
The keyword class is used to define a class. The basic structure of a class is as follows:

class identifier
{
Class-body
}
Where identifier is the name given to the class and class-body is the code that makes up the class.


Class declarations:
After a class is defined, we use it to create objects. A class is just a definition used to create objects. A class by itself cannot hold information. A class cannot perform any operations. A class is used to declare objects. The object can then be used to hold data and perform operations.

The declaration of an object is called instantiation. We say that an object is an instance of a class.

The format of declaring an object from a class is as follows:

class_name object_identifier = new class_name();

Here,
class_name is the name of the class,
object_identifier is the name of the object being declared.

Example 1:
We create an object called c1 of class Circle as follows:

Circle c1 = new Circle();
On the right side, the class name with parenthesis i.e., Circle(), is a signal to construct – create – an object of class type Circle.

Here:
• Name of the class is Circle.
• Name of the object declared is c1.
• The keyword new is used to create new items. This keyword indicates that a new instance is to be created. In this case, the new instance is the object called c1.

Members of a Class:
A class can hold two types of items:
• data members, and
• function members (methods).

Data Members or fields:
Data members include variables and constants. Data members can themselves be classes. Data members are also called as fields. Data members within a class are simply variables that are members of a class.

Example 1: Consider a class called Circle defined as follows:
class Circle
{
public int x, y; // co-ordinates of the centre of the circle
public int radius;
}

The keyword public is called the access modifier.

Example 2: Create a class called FullName that contains three strings that store the first, middle and last name of a person.
class FullName
{
string firstname;
string middlename;
string lastname;
}

Example 3: Create a class called Customer that contains account holder’s bank account no (long), balance amount (float), and a Boolean value called status (active/inactive account);
class Customer
{
long acno;
flaot balance;
boolean status;
}

How to access Data Members?
Consider a class called Circle. We declare two objects c1 and c2 of this class. Now both the objects can be represented as follows:







If we want to refer to the fields x and y then we must specify which object we are referring to. So we use the name of the object and the data member (field name) separated by the dot operator. The dot operator is also called the member of operator.

To refer to data x and y of object c1, we write: c1.x and c1.y
Similarly, to refer to data x and y of object c2, we write: c2.x and c2.y


Methods:
1. A method is a code designed to work with data. Think of a method like a function.
2. Methods are declared inside a class.
3. Methods are declared after declaring all the data members (fields).

Declaring Methods:
Methods are declared inside the body of a class. The general declaration of a method is :

modifier type methodname (formal parameter list)
{
method body
}

There are 5 parts in every method declaration:
1. Name of the method (methodname)
2. Type of value the method returns
3. List of parameters (formal parameters) (think of these as inputs for the method)
4. Method modifier, and
5. Body of the method.

Examples:
void display(); // no parameters
int cube (int x); // one int type parameter
float area (float len, int bre); // one float, one int parameter, return type float

How is a method invoked (or called)?
A method can be invoked or called only after it has been defined. The process of activating a method is known as invoking or calling.

A method can be invoked like this:
Objectname.methodname(actual parameter list);

Nesting of Methods:
A method of a class can be invoked only by an object of that class if it is invoked outside the class. But a method can be called using only its name by another method belonging to the same class.This is known as nesting of methods.

In the following program, the class Nesting defines two methods, Largest() and Max(). The method Largest() calls the method Max().

Program 1: To compute the largest of two integers.

using System;

namespace Method2
{
class Nesting
{
public void Largest(int m, int n)
{
int large = Max(m, n); // nesting
Console.WriteLine(large);
}

int Max(int a, int b)
{
int x = (a > b) ? a : b;
return (x);
}
}

class NestTesting
{
public static void Main()
{
Nesting next = new Nesting();
next.Largest(190, 1077);
Console.ReadLine();
}
}
}

Method Parameters:
When a method is called, it creates a copy of the formal parameters and local variables of that method. The argument list is used to assign values to the formal parameters. These formal parameters can then be used just like ordinary variables inside the body of the method.
When a method is called, we are interested in not only passing values to the method but also in getting back results from that method. It is just like a function which takes input via formal parameters and returns some calculated result.

To manage the process of passing values and getting back results from a method, C# supports four types of parameters:

1. Value parameters - to pass parameters into methods by value.
2. Reference parameters - to pass parameters into methods by reference.
3. Output parameters - to pass results back from a method.
4. Parameter arrays - used to receive variable number of arguments when called.

PASS BY VALUE:
i) The default way of passing method parameters is “pass by value”.
ii) A parameter declared with no modifier is passed by value and is called a value parameter.
iii) When a method is called (or invoked), the values of the actual parameters are assigned to the corresponding formal parameters.
iv) The method can then change the values of the value parameters.
v) But the value of the actual parameter that is passed to the method is not changed.
vi) Thus formal parameter values can change, but actual parameter values are not changed.
vii) This is because the method refers only to the copy of the parameter passed to it.
viii) Thus, pass by value means pass a copy of the parameter to the method.

The following example illustrates the concept of pass-by-value:

using System;

namespace PassbyValue
{
class Program
{
static void multiply(int x)
{
x = x * 3;
Console.WriteLine("Inside the method, x = {0}", x);
}

public static void Main()
{
int x = 100;

multiply(x);
Console.WriteLine("Outside the method, x = {0}", x);

Console.ReadLine();
}
}
}
In the above program, we have declared a variable x in method Main. This is assigned a value of 100. When the method multiply is invoked from Main(), the formal parameter is x in the method, while x in the calling part is called the actual parameter.

PASS BY REFERENCE:
i) The default way of passing values to a method is by “pass by value”.
ii) We can force the value parameters to be passed by reference. This is done by using the ref keyword.
iii) A parameter declared with the ref keyword is a reference parameter.
E.g., void Change (ref int x). In this case, x is declared as a reference parameter.
iv) A reference parameter does not create a new storage location. It represents or refers to the same storage location as the actual parameter.
v) Reference parameters are used when we want to change the values of the variables in the calling method.
vi) If the called method changes the value of the reference parameter, this change will be visible in the calling method also.
vii) A variable must be assigned a value before it can be passed as a reference variable.

The following example illustrates the use of reference parameters to exchange values of two variables.

using System;

namespace PassByRef
{
class Program
{
static void Swap(ref int x, ref int y)
{
int temp;

temp = x;
x = y;
y = temp;
}

static void Main(string[] args)
{
int m = 100;
int n = 200;

Console.WriteLine("Before swapping:");
Console.WriteLine("m = {0}, n = {1}", m, n);

Swap(ref m, ref n);

Console.WriteLine("After swapping:");
Console.WriteLine("m = {0}, n = {1}", m, n);

Console.ReadLine();

}
}
}
OUTPUT PARAMETERS:
i) Output parameters are used to pass values back to the calling method.
ii) Such parameters are declared with the out keyword.
iii) An output parameter does not create a new storage location.
iv) When a formal parameter is declared with the out keyword, the corresponding actual parameter must also be declared with the out keyword.
v) The actual output parameter is not assigned any value in the function call.
vi) But every formal parameter declared as an output parameter must be assigned a value before it is returned to the calling method.

The following program illustrates the use of out parameter:

using System;

namespace OutParameters
{
class Program
{
static void square (int x, out int n)
{
n = x * x;
}

public static void Main()
{
int n; // no need to initialize this variable
int m = 5;

square(m, out n);

Console.WriteLine("n = {0}", n);
Console.ReadLine();
}
}
}


SOLVED EXAMPLES:

1. Write a PrintLine method that will display a line of 20 character length using the * character.

using System;

namespace StarPrg
{
class CStar
{
public void PrintLine(int n)
{
for(int i = 1; i <= n; i++)
{
Console.Write("*");
}
Console.WriteLine();
}
}

class MStar
{
static void Main()
{
CStar p = new CStar();

p.PrintLine(20);

Console.ReadLine();
}
}
}

2. Modify the PrintLine method such that it can take the “character” to be used and the “length” of the line as the input parameters. Write a program using the PrintLine method.

using System;

namespace StarPrg
{
class CStar
{
public void Star(int n, char ch)
{
for (int i = 1; i <= n; i++)
{
Console.Write(ch);
}
Console.WriteLine();
}
}

class MStar
{
static void Main()
{
CStar p = new CStar();

Console.WriteLine("How many characters ?");
int num = int.Parse(Console.ReadLine());

Console.WriteLine("Which character ? ");
char ch = char.Parse(Console.ReadLine());

p.Star(num, ch);

Console.ReadLine();
}
}
}

C# Control Statements – Part 2

4. Control Statements – Part 2

Iterative statements are used to repeat a statement a number of times. E.g., if we want to print numbers from 1 to 10, or find all prime numbers between 1 to 100, we will use the technique of iteration.

C# has the following types of iteration statements:

Iterative statements
1. while for loop
2. do loop
3. for loop
4. foreach statement

while loop :
The format of the while loop is:

Initialization

while (condition)
{
body of the loop
}

1. The condition is checked first.
2. This loop is called an entry-controlled loop; the condition is checked first, and if it is true, control passes into the body of the loop and statements inside the loop are executed.
3. If the condition is initially false, the body of the loop is not executed at all.
4. After each iteration, control goes back to check if the condition is true.
5. There must be some statement in the body of the loop that makes the condition eventually false, otherwise the loop will continue forever.
6. When the condition becomes false, control passes to the statement after the while loop.

Example: The following program prints the value of n using the while loop

class WhileTest
{
static void Main()
{
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
}
}
Program 1: To reverse a number entered by the user.

// Reverse a number entered by the user
using System;

namespace reverse
{
class reverse
{
static void Main()
{
int num, revnum = 0, d;

Console.WriteLine("Enter a number");
num = int.Parse(Console.ReadLine());

while (num > 0)
{
d = num % 10; // get the least significant digit
revnum = revnum * 10 + d; // reverse partially
num = num / 10; // drop the least significant digit
}

Console.WriteLine("Reversed number is {0}", revnum);
Console.ReadLine();
}
}
}


Program 2: Program to count the number of digits in an integer.

//To count the number of digits in an integer
using System;

namespace CountDigits
{
class count
{
static void Main()
{
int num, ctr = 0;

Console.WriteLine("Enter an integer");
num = int.Parse(Console.ReadLine());

while (num > 0)
{
num = num / 10;
ctr = ctr + 1;
}

Console.WriteLine("No. of digits is {0}", ctr);
Console.ReadLine();
} // end of Main
} // end of class
} // end of namespace
Program 3: Program to print the average of 10 numbers entered by the user.

//Average of 10 numbers entered by the user

using System;

namespace AverageMany
{
class average
{
static void Main()
{
int num, sum = 0, ctr = 0;
float avg;

while (ctr < 10)
{
Console.WriteLine("Pls enter a number");
num = int.Parse(Console.ReadLine());

sum = sum + num;

ctr++;
}

avg = (float)sum / ctr;

Console.WriteLine("Average is {0}", avg);
Console.ReadLine();
}
}
}


do - while loop :

The do-while loop is used when it is necessary to execute the body of the loop at least once. The general format of the do-while lop is :

initialization

do
{

body of the loop

} while (condition);

1. After the initialization, control passes to the body of the loop and the statements in the loop are executed.
2. The condition specified in the while part is then checked. If the condition is true, the body of the loop is executed once again.
3. If the condition becomes false, the body of the loop is not executed and control passes to the statement after the do-while loop..
4. There must be some statement in the body of the loop that makes the condition eventually false, otherwise the loop will continue forever.
5. Since the condition is checked at the bottom of the loop, the do-while loop is also called an exit-controlled loop.
6. The body of the loop is executed at least once.




IMPORTANT QUESTIONS
1. What is iteration? Which iteration statements are supported by C#?
2. Explain the while loop. Draw the relevant flowchart. Give suitable examples. Under what condition will the while loop become an infinite loop?
3. What precautions must be taken in using the while loop?
4. Explain the do-while loop. Draw the relevant flow chart. Under what condition will the while loop become an infinite loop?
5. Explain the for loop. Draw the relevant flowchart. Give an example to illustrate the use of this loop.
6. Compare the looping structures while and for.
7. Compare the looping structures do and for.



PROGRAMMING EXERCISES
1. Write a program to find the product of digits of an integer. E.g., if the integer is 2156, the output should give 2*1*5*6 i.e., 60.
2. Write a program to check whether a given digit d is present in an integer entered by the user.
3. Write a program to count the number of times a given digit d appears in an integer.
4. Write a program to count the number of odd and even digits in a number.
5. Write a program to print only the odd / even digits of an integer.
6. Write a program to print the following series: 2, 8, 18, 32, upto first 7 terms.
7. Write a program to compute the sum of squares of first 10 natural numbers.
8. Write a program to compute the sum of the first 10 odd / even natural numbers.
9. Write a program to print the average of n numbers entered by the user. User will also input the value of n.

C#-Ch 4: Control Statements - Part I

4. Control Statements – Part 1

Control statements are used to change the normal top-down sequence or linear sequence of program execution. If a block of statements has to be skipped we use the control statements to bypass this block. Similarly, if a block of statements has to be repeated many times, we use control statements that will cause this repetition to take place.

C# has the following types of control statements:

1. Selection statements:
a. If statement
b. If … else statement
c. Switch … case statement
d. ? : operator
2. Iterative statements
a. for loop
b. while loop
c. do loop
d. foreach statement

In this section we discuss the selection statements.

if statement:
The if statement executes a given set of statements based on the condition given by the programmer.

Syntax:
if (boolean expression)
statement-1

If boolean expression is true, then statement-1 is executed, otherwise statement-1 is skipped.

if – else statement:
The if – else statement is an extension of the simple if statement.

Syntax:
if (boolean expression)
statement-1
else
statement-2

If boolean expression is true, then statement-1 is executed, otherwise statement-2 is executed. Statement-1 and statement-2 may be a single statement or a set of statements. In case it is a set of statements, then these are enclosed in between the pair of braces { and }.

Nesting of if statements:
Nesting is the inclusion of one statement within another. If one if statement is placed inside another if statement we say that the if statements are nested.
Nesting can be done in the if section or in the else section.

Example:
if (condition1)
{
//action statements-1
}
else
{
if (condition2)
{
//action statements - 2
}
else
{
//action statements - 3
}
}

A complete if …else statement is nested within the else section of the outermost if statement. This nested if statement is shown in bold in the above code.

If condition-1 is true, the first if statement is true and action statements-1 are executed after which control exits the outermost else statement.

If condition-2 is false, control passes to the first if condition inside the else (i.e. condition-2 is checked). If condition-2 is true, then action statements -2 are executed and control exits the if …else structure. This corresponds to the case: condition-1 false and condition-2 true.

If condition-2 is false, control passes to the action statements-3. After executing action statements-3, control exits from the if…else structure. This is equivalent to the case: condition-1 false and condition-2 false.

Stacking if statements
Stacking if statements combines the else part with another if statement. The following example illustrates this:


Example:
if (cond-1)
{
action-1
}
else if (cond-2)
{
action-2
}
else
{
action-3
}
action-4
}


Switch-case statement:
The switch case statement is a selection statement. It is used when there are a number of possible values to be tested and multiple if-else statements become difficult to use.

Syntax :

switch (value)
{
case result1:
// do statements for result 1
break;
case result2:
// do statements for result 2
break;
case result3:
// do statements for result 3
break;
. . . . .
default:
// do statements for default case
break
}

We observe the following in switch – case statement:
1. There is no condition to check.
2. A value is used to branch to the appropriate code.
3. Two case statements cannot have the same value.
4. The value mentioned in the switch statement may be a variable or an expression.
5. The value is compared to each value in the case statement. If the value matches, the code corresponding to that case is executed.
6. If the value does not match any of the values given in case statement, then control flows to the default case.
7. If default case is not mentioned, then control goes to the statement immediately after the switch statement.
8. Each case is terminated by the break statement. This statement signifies the end of the code of that case. If break statement is not given, compiler generates an error.

Fallthrough in switch statement:
In C, C++, and Java, break statement may be omitted in a case block. The control moves to the next block without any errors. This is called as “fallthrough”. But in C#, this fallthrough is not permitted if the case block contains executable code. However, if the code block is empty, then falltrough is permitted in C#. If we want two consecutive case blocks to be executed one after the other, we must force control to go to the next case by using the goto statement

IMPORTANT QUESTIONS
1. What is the use of control statements in programming languages?
2. Explain the following selection statement: if … else in C#
3. When is a switch – case statement used in C# programs? Explain the concept of “fallthrough”.
4. Is the following if statement valid? If so, what is the value of x after this code executes?

int x = 2;
int y = 3;

if (x == 2) if (y < 3) x = 5; else x = 9;
5. In what way does the switch statement differ from the if statement? When is it preferable to use the switch statement?
6. Explain nested if statements with the help of an example.
7. Explain the concept of stacking of if statements with the help of an example.

PROGRAMMING EXERCISES
1. Write a program to add all the even numbers from 0 to 20. Use simple if and goto statements to form a loop of operations.
2. Write a program that accepts an integer between 1 and 7, and based on the input, it prints the day of the week. Assume Monday = 1, etc. If input is not in the range 1 to 7, print an appropriate error message and terminate the program.

C#- Ch 3: Operators and Expressions

3. Operators and Expressions

An operator indicates the type of operation to be performed on operands in a given expression. There are 8 categories of operators in C#. These are:

1. Arithmetic operators (+, -, *, /, % )
2. Relational operators ( >, >=, <, <=, ==, != )
3. Logical operators (&&, ||, !, ~, &, | , ^ )
4. Assignment operators ( =, +=, -=, *=, /=, %= )
5. Increment and decrement operators ( ++, -- )
6. Conditional operator ( ? : )
7. Bitwise operators ( &, |, ~, ^ )
8. Shift operator ( <<, >> )
9. is operator
10. sizeof operator

Arithmetic Operators:

Modulo operator (%):

The “modulo” operator (%) is a binary operator. That is, it requires two operands. This operator gives remainder after the first operator is divided by the second. In C#, the modulo operator can be used with integer as well as real operands.

Case 1: Both operands are integers
If a and b are declared as integer variables, then
a % b = a – (a/b) * b
1) The sign of the first operand decides the sign of the result. If the first operand is positive, the result is positive. If the first operand is negative, the result is negative.
2) This operator can be used to check if a number is even or odd.
 If n % 2 is 0, then n is even, else n is odd.
3) This operator can be used to check whether a number a is divisible by another number b.
 If a % b is 0, then a is divisible by b, else a is not divisible by b.

Case 2: Both operands are real
If a and b are declared as real variables, then
a % b = a – n * b
where, n is the largest possible integer that is less than or equal to a/b.

The following example illustrates the use of modulo operator.

//Program: Ex-Modulo.cs
//Author: Mukesh N Tekwani

// This program illustrates the use of the modulo operator. In C#, modulo
// operator can be used with integer as well as real numbers.

using System;

namespace Ex_Modulo
{
class Modulo
{
static void Main()
{
int a, b, r;
float x, y, z;

// modulo division for both integers positive
a = 14;
b = 3;
r = a % b;
Console.WriteLine("a = {0}, b = {1}, r = {2}", a, b, r);

// modulo division for 1st operand -ve & 2nd operand +ve int
a = -14;
b = 3;
r = a % b;
Console.WriteLine("a = {0}, b = {1}, r = {2}", a, b, r);

// modulo division for 1st operand +ve and 2nd operand -ve int
a = 14;
b = -3;
r = a % b;
Console.WriteLine("a = {0}, b = {1}, r = {2}", a, b, r);

// modulo division for both operands positive floats
x = 100.5F;
y = 22.4F;
z = x % y;
Console.WriteLine("x = {0}, y = {1}, z = {2}", x, y, z);

Console.ReadLine();
}
}
}

Relational Operators:

C# supports six relational operators. These operators are used to compare two quantities. The result of comparison is either true or false.

Relational Operators
Relational Operator Meaning
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Is equal to
!= Is not equal to


Logical Operators:

C# supports 6 logical operators. These are:

Logical Operators
Logical Operator Meaning
&& Logical AND (all conditions must be true)
|| Logical OR (at least one condition must be true)
! Logical NOT
& Bitwise logical AND
| Bitwise logical OR
^ Bitwise logical exclusion

The logical operators && and || are used when we want to combine two or more conditions.
E.g., if we want to carry out an action only if both conditions are true, we will use the && (AND) operator as follows:
C1 && C2
If we want to carry out an action if at least one condition is true, we will use the || (OR) operator as follows:
C1 || C2

e.g., (1) if ( a > b && b > c)
max = a;

(2) if (a < 40 || B < 40)
result = ‘F’;



Truth table for AND ( && ) operator:

Condition C1 Condition C2 Result of C1 && C2
False False False
True False False
False True False
True True True

Truth table for OR ( || ) operator:

Condition C1 Condition C2 Result of C1 || C2
False False False
True False True
False True True
True True True


Increment and Decrement Operators:

The increment operator is ++ and decrement operator is --.
• Both these are unary operators.
• The increment operator adds 1 to the operand while the – operator subtracts 1 from the operand.
• These operators are very useful, especially in writing loops such as the for loop.
• If ++ is applied on a variable x, then ++x is equivalent to x = x + 1
• If -- is applied on a variable x, then --x is equivalent to x = x – 1
• If ++ or -- is used before an operand, it is called pre-increment or pre-decrement operator.
• If ++ or -- is used after an operand, it is called post-increment or post-decrement operator.

Example 1:

If x = 7, then y = ++x implies that y becomes 8. (First increase m and then use its value).

Example 2:

If x = 5, then z = x++ implies that z is first given the original value of x i.e. 5, and then x is increased by 1. (First use the existing value and then increase).



Conditional Operator / Ternary Operator:

The conditional operator in C# is ? :. It is used to construct a condition. E.g., consider the following if statement:
if ( a > b)
max = a;
else
max = b;
This can be written in a more concise way using the conditional operator as follows:

max = ( a > b) ? a : b;


Bitwise Operators:
There are 6 operators in C# that can be used for bit manipulation. These operators are :

Bitwise Operators
Bitwise Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ (tilde character) One’s complement
<< Left shift
>> Right shift

Bitwise AND operator (&) :

Use of & operator:
(1) This operator is used to check whether a particular bit in an integer is high or low. Consider the number 187. We want to check if the bit no. 5 is high or low. Bit 5 has a weight of 32 (since 25 = 32). Hence we use the & operator with these two numbers : 187 (the give no.) and 32.

Bit position -> 7 6 5 4 3 2 1 0
(187)10 = 1 0 1 1 1 0 1 1
(32)10 = 0 0 1 0 0 0 0 0
& 0 0 1 0 0 0 0 0
The resultant binary number in the last row is 0010 0000. This is the equivalent of 32. Thus, the only bit that remains in the result is bit at position 5.
The following program shows how we can test whether a particular bit is set in a number. The number to be tested is stored in x. We set y as 32 since we want to test the 5th bit of x. We know that 25 = 32.
//Program: BitAndOp.cs
//Author: Mukesh N Tekwani

// This program illustrates the use of the bitwise AND (&) operator.

using System;

namespace BitAndOp
{
class bitandop
{
static void Main()
{
int x, y, res;

//Check whether bit 5 is set in number 187
x = 187;
y = 32; // we have taken y as 32 since 2 raised to 5 is 32

res = x & y;

if (res > 0)
Console.WriteLine("Bit 5 is set in {0}", x);
else
Console.WriteLine("Bit 5 is not set in {0}", x);

//Now we check for bit 5 in another number, say 86
x = 86;

res = x & y;

if (res > 0)
Console.WriteLine("Bit 5 is set in {0}", x);
else
Console.WriteLine("Bit 5 is not set in {0}", x);

Console.ReadLine();
}
}
}

(2) Bitwise and (&) operator can also be used to clear bits in an integer value, i.e. set some bits to zero. E.g., suppose we want to clear the 5th bit of a number , i.e., we want to set the 5th bit to 0. We can do it as follows:
Bit position -> 7 6 5 4 3 2 1 0
(187)10 = 1 0 1 1 1 0 1 1
(223)10 = 1 1 0 1 1 1 1 1
& 1 0 0 1 1 0 1 1
Thus, the 5th bit is set to 0 in the result.
So the AND operator (&) is used to set a bit to 0 and leave all other bits unchanged.


Bitwise OR operator ( | ) :
The bitwise OR operator is used to set some bits in a number to 1.
E.g., suppose x = 187 and we want to set bit in position 2 to 1. The process is shown in this diagram:

Bit position -> 7 6 5 4 3 2 1 0
(187)10 = 1 0 1 1 1 0 1 1
(4)10 = 0 0 0 0 0 1 0 0
OR (| ) 1 0 1 1 1 1 1 1

The following program illustrates how we can mask (hide) a bit in a number:

//Program: BitOrOp.cs
//Author: Mukesh N Tekwani

// This program illustrates the use of the bitwise OR ( | ) operator for
// masking a bit

using System;

namespace BitOrOp
{
class bitorop
{
static void Main()
{
int x, mask, res;

//Check whether bit 5 is set in number 187
x = 187;
mask = 4; // we have taken mask as 4 since 2nd bit is to be masked and
// 2 raised to 2 is 4

res = x | mask;

Console.WriteLine("res = {0}", res);

Console.ReadLine();
}
}
}

So the OR operator ( | ) is used to set a bit to 1 and leave all other bits unchanged.

Bitwise XOR operator ( ^ ) :
The bitwise XOR operator (^) is used to toggle a bit. Toggling means that if the bit is 1, it is set to 0, and if the bit is 0, it is set to 1.

x = x ^ mask;
Bits that are set to 1 in the mask will be toggled in x. Bits that are set to 0 in the mask will be unchanged in x.

NOT operator ( ~ ) :
The ~ operator performs a bitwise complement operation on its operand. Each bit is reversed. That is, a high bit (1) becomes low (0) and vice-versa.
This is a unary operator.
When this operator is applied on a positive number, the result may be a negative number.

Left shift operator ( << ):

The left shift operator shifts the bits of a number to the left by a specified number of positions.
E.g., consider the number 8 whose binary equivalent is 0000 1000. This is to be shifted by 1 bit to the left.

Bit position -> 7 6 5 4 3 2 1 0
(8)10 =
0
0 0 0 1 0 0 0
8 << 1 0 0 0 1 0 0 0 0




The new number obtained after left shift by one bit is 16. This is the double of the original number. Thus the left shift operator can be used to multiply by 2 if bits are shifted by one.

This operator may be used on the int, uint, long, and ulong data types.

Right shift operator ( >> ):

The right shift operator shifts the bits of a number to the right by a specified number of positions.
E.g., consider the number 16 whose binary equivalent is 0001 0000. This is to be shifted by 1 bit to the right.

Bit position -> 7 6 5 4 3 2 1 0
(8)10 = 0
0 0 0 1 0 0 0

8 >> 1 0 0 0 0 0 1 0 0


Thus, the new number obtained is 4, which is half of the original number. Thus, the right shift operator can be used to half a given number. This operator may be used on the int, uint, long, and ulong data types.
The is operator :

The is operator checks a variable to see if it's a given type. If so, it returns true. Otherwise, it returns false. Here's an example.

using System;

namespace IsOp
{
class isop
{
static void Main()
{
int x = 0;

bool isTest = x is int;

if (isTest == true)
Console.WriteLine("x is an integer");
else
Console.WriteLine("x is a not an integer");

Console.ReadLine();
}
}
}


The sizeof operator:
The sizeof() operator is used to obtain the size in bytes for a value type.
Syntax: sizeof (type)
where, type is the value type for which the size is obtained.
• The sizeof operator can be applied only to value types, not reference types.
• The sizeof operator can only be used in the unsafe mode.
• The sizeof operator cannot be overloaded.

// Example to illustrate use of sizeof operator
using System;

namespace SizeOfOp
{
class sizeofop
{
static void Main()
{
Console.WriteLine("The size of byte is {0}", sizeof(byte));
Console.WriteLine("The size of short is {0}", sizeof(short));
Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of long is {0}", sizeof(long));

Console.ReadLine();
}
}
}
IMPORTANT QUESTIONS

1. What are the different categories of operators in C# ?
2. With the help of a suitable example, explain the “modulo” operator. Can this operator be used with real operands? Explain.
3. What are relational operators in C#? If relational operators are used in an expression, what values can the expression have?
4. Explain the use of the increment and decrement operators.
5. With reference to Boolean operators, explain the term “short-circuiting”.
6. Explain the bitwise operators in C#.
7. Explain the left shift and right shift operators. What is the use of these two operators?
8. What is meant by masking of bits? How is it achieved through bitwise operators in C#?
9. Explain the use of the left shift and the right shift operators with appropriate examples.
10. Illustrate the use of the is operator.
11. What is the use of the sizeof operator? Give suitable example.

PROGRAMMING EXERCISES

1. What is the output of the following program?

using System;

namespace test1
{
class test1
{
static void Main()
{
byte x = 10;
byte y = 20;

long result = x & y;

Console.WriteLine("{0} AND {1} Result :{2}", x, y, result);

x = 10;

y = 10;

result = x & y;

Console.WriteLine("{0} AND {1} Result : {2}", x, y, result);
Console.ReadLine();
}
}
}

2. In the above example, replace the AND operator (&) with the OR operator (|). What is the output?
3. What is the output of the following program?

using System;

namespace test2
{
class test2
{
static void Main()
{
int a = 1;
int b = 0;
int result;

result = (a == b) ? 1 : 0;

Console.WriteLine("Result is {0}", result);
Console.ReadLine();
}
}
}


4. State the output of the following program:

using System;
class Test
{
static void Main()
{
//33 = 1 0 0 0 0 1
Console.WriteLine(33 >> 3);

//15 = 1 1 1 1
Console.WriteLine(15 << 2);
Console.Read();
}
}


5. State the output of the following program:
using System;

namespace PrePostIncOps
{
class incops
{
static void Main()
{
int x = 0;
int y = 0;

Console.WriteLine(" x = {0}, y = {1}", x, y);
Console.WriteLine(" x = {0}, y = {1}", ++x, y++);
Console.WriteLine(" x = {0}, y = {1}", ++x, y++);
Console.WriteLine(" x = {0}, y = {1}", ++x, y++);

Console.ReadLine();
}
}
}

C# - Chapt 2: Literals, Variables and Data Types

2. Literals, Variables and Data Types

C# is a strongly typed language. That is:
1. Every variable has a data type.
2. Every expression also has a data type.
3. All assignments are checked for type compatibility.
4. There is no automatic correction or conversion of conflicting data types.
5. The C# compiler checks all the expressions and parameters to ensure that the types are compatible.



Important Definitions:
1. Class: A C# program is a collection of classes. A class is a set of declaration statements and methods. A method has executable statements.
2. Token: The smallest textual element that cannot be reduced further is called a token. There are 5 types of tokens in C#. These are:
i) Keywords
ii) Identifiers
iii) Literals
iv) Operators
v) Punctuation symbols
White spaces (space, tab and newline are spaces) and comments are not treated as tokens.
3. Keywords: Keywords are reserved words that have a specific meaning in a programming language. These keywords cannot be used as identifiers or variables. C# permits keywords to be used as identifiers provided the keyword is preceded by the @ symbol. However, this must be avoided.
4. Identifiers: Identifiers are created by the programmer and are used to give names to classes, methods, variables, namespaces, etc.
5. Literals: Literals are constant assigned to variables. Examples of literals are: 250, ‘A’, “Mumbai”.
6. Operators: Operators are symbols used in expressions. An operator acts on operands. Some operators like ‘+’ and ‘*’ require two operands (e.g. 23 + 67), but some operators are unary operators because they require only one operand (e.g., the unary minus operator, -23).
7. Punctuation Symbols: Symbols such as brackets, semicolon, colon, comma, period, etc are called punctuation symbols or punctuators or separators. They are used for grouping statements together, or for terminating a statement, etc.
8. Statements: A statement is an executable combination of tokens. A statement in C# ends with the semicolon symbol (;). Various types of statements in C# are:
i) Declaration statements ii) Expression statements iii) Selection statements
iv) Jump statements v) Interaction statements vi) labeled statements

vii) Empty statements

Keywords :

C# has 76 keywords. A few commonly used keywords are listed below:

bool
byte
char
decimal
double
float
int
long
sbyte
short
string
ulong
ushort
break const
case false
catch in
class new
continue null
do object
else private
for public
foreach return
goto struct
if true
switch void
try while


Literals:

Literals are value constants assigned to variables. The various types of literals in C# are as follows:
1. Numeric Literals
a. Integer Literals -- e.g., 250, 200, -187, 0, 0xcab (hexadecimal literal)
b. Real Literals -- e.g., 3.142, -96.4, 0.0074, 6.023E+3
2. Boolean Literals -- e.g., true, false
3. Character Literals
a. Single character literals -- e.g., ‘A’, ‘4’ , ‘?’, ‘ ‘
b. String literals -- e.g., “Welcome 2009”, “Hello”, “9869012345”
c. Backslash Character Literals -- These are the escape sequences. They are used for formatting the printed output. The most commonly used escape sequences are:
i. ‘\n’ -- new line character
ii. ‘\b’ -- back space
iii. ‘\f’ -- form feed
iv. ’\t’ -- horizontal tab
v. ’\v’ -- vertical tab


Variables:

1. A variable is a named data storage location.
2. A variable is an identifier created by the programmer.
3. A variable refers to some storage location in the computer’s memory.
4. The value of a variable can change during the execution of a program.
5. Every variable has a data type. E.g., an int variable can only store integer type data, etc.
6. The place at which a variable is declared determines the scope of that variable in the program.
7. All variable must be declared before they are used in a program.
8. The data type of a variable determines the following:
a. The space occupied in the memory by the variable. E.g., in C#, int occupies 4 bytes.
b. The operations that can be carried out on that variable. E.g., we can carry out the operation of % (modulus) on integer operands but not on char operands.
c. The range of values that can be stored in the variable.

Rules for forming variable names:
1. The variable name should be meaningful.
2. The first character must be a letter.
3. Remaining characters can be letters, digits or underscore (_).
4. C# is case-sensitive. That is, the variable MARKS and marks are different.
5. C# keywords cannot be used as variable names.

Here are some examples of valid and invalid variable names. For each keyword, write “Valid” or “Invalid”. If it is invalid, justify.

Variable Name Valid/Invalid Reason if invalid
marks
mks in java
for
balance
$balance
2papers
tax_paid


Data Types:

C# supports two types of data types. These are:
1. Value types, and
2. Reference Types.

1. Value types :-
i) These are of fixed length.
ii) They are stored on a stack.
iii) When a variable is assigned to another variable, the values are actually copied.
There are two categories of value types: predefined types (int, float, char, etc) and user-defined types (e.g., structure)

Predefined or Simple Types:
a) Boolean type
b) Character type
c) Numeric type
a. Integer type
i. Signed types
ii. Unsigned types
b. Floating point
c. Decimal types

2. Reference types :-
i) These are of variable length.
ii) They are stored on a heap.
iii) When an assignment occurs between reference variables, only the reference is copied. The actual value remains the same in memory. There are now two references to the same memory location.

Reference type variables are of two types:
a) User-defined / complex, e.g., classes, arrays, interfaces, delegates
b) Predefined / simple e.g., string type, object type.

The object type is the base type for all other inbuilt and user-defined types in C#. The string type is used for creating and performing many operations on string type data.

Default Values of Variables:
A variable may be explicitly assigned a value or it may be assigned a default value by the compiler. Following types of variables are automatically initialized to their default values in C#:
Array elements, Static variables, and Instance variables.

Data Type Default value
Integer 0
Char ‘\x000’
Float 0.0f
Double 0.0d
Decimal 0.0m
Boolean false


Constant Variables

Variables whose values do not change during the execution of the program are called constants.
E.g., suppose the programmer declares a variable called PI which should not change during the program execution. We declare this variable as follows:

const PI = 3.142;

Advantages of using constants are:
i) Programs are easier to read. It is easier to read an expression area = PI * r * r rather than the expression area = 3.142 * r * r.
ii) Programs are easier to modify. E.g., if we want to change the value of PI to 3.14.156, we have to do so in only one place, instead of throughout the program.
iii) Values of such constants cannot be changed even accidentally by the programmer as the compiler will give an error.

Note:
i) const must be declared at class level. They cannot be declared at method level.
ii) Once a constant has been assigned a value, it should not be assigned another value.
iii) In C#, constants are assigned for data types.


Scope of Variables:

C# is a block-structured language. The lifetime of a variable and its accessibility is known as the scope of the variable. A variable has a scope or visibility within a particular block. That is, the variable can be accessed within that block. The scope of the variable depends upon the place of declaration and type of variable.

Types of variables in C#:
• Static variables – declared at class level; also known as filed variables. Scope of this variable ends when the Main function ends.
• Instance variables - declared at class level; also known as filed variables. Scope of this variable ends when the Main function ends.
• Array variables – these come into existence when the array is created and exist only so long as the array exists.
• Local variables – variables declared inside a method. These variables are not available for use outside the method in which they are declared.
• Value parameters – exist till the end of the method
• Reference parameters – do not create new location but only refer to an existing location



Example 1: Consider the following code:

using System;

namespace localscope
{
class Scope
{
public static void Main()
{
for (int x = 1; x <= 10; x++)
{
Console.WriteLine("x is {0}", x);
}
Console.WriteLine("Outside the loop, x is {0}", x);
}

}
}

When this program is compiled, we get the following error:
“The name 'x' does not exist in the current context”

The variable x is declared as part of the “for” statement. As soon as the “for” statement is completed, the variable x goes out of scope. Since it is out of the scope, the second WriteLine statement generates an error.

IMPORTANT QUESTIONS

1. “C# is a strongly typed language”. Explain this statement.
2. Define the term “token” What are the types of tokens in C# ?
3. Distinguish between identifiers and keywords. Can a keyword be used as an identifier?
4. Define the term “separators”. Give examples of at least 5 separators in C#.
5. State the various types of literals used in C#. Give two examples of each type.
6. What are escape sequences? Give examples.
7. What is a variable? What is the effect of declaring a variable?
8. Is it necessary to declare a variable in C#? Give example of one programming language you have learnt in which variables need not be declared.
9. State the rules for forming valid variable names.
10. Explain the difference between value types and reference types in C#.
11. What is the benefit of declaring variables as constants in a C# program? State the rules that must be followed when declaring const variables.
12. Explain the term scope of a variable and for different types of variables, explain their scope.

1. INTRODUCTION TO C#

C#, pronounced as C sharp, is a computer language used to give instructions that tell the computer what to do, how to do it, and when to do it. C# is one of the languages used in the Microsoft .NET Framework.

You can program in C# by using Visual C# 2005 Express Edition, which is available as a free download from the Microsoft Web site at http://msdn.microsoft.com/express/default.aspx

Features of C# :

1. Object-oriented language.

a. C# supports the three most important features of OOP i.e., Polymorphism, Inheritance, and Encapsulation. (PIE). In C#, everything is an object.

b. There are no global functions, variables and constants.

2. Simple : C# is a simple language.

a. It does not support the complicated features of C++ such as pointers, scope resolution operator (::)

b. Macros and templates are not supported in C# as these features cause errors in programs.

c. C++ has three different symbols for working with members: the (.) operator, the (:: ) operator and the -> operator. In C#, all these are replaced by the dot operator (.).

3. Modern: C# is a modern language. It supports the features of

a. garbage collection,

b. code security,

c. error handling features,

d. new approach to debugging,.

4. C# is type-safe: It means the following:

a. C# arrays are bound unlike arrays in C and C++.

b. If uninitialized arrays are used, the compiler produces an error.

c. C# supports automatic garbage collection. Garbage collection is a form of automatic memory management. The garbage collector tries to free the memory used by objects, that will never be accessed again by the application.

d. C# enforces overflow checking in arithmetic operations.

e. All dynamically objects and arrays are initialized to zero. (In C, uninitialized variables have junk value).

5. It has the best features of C++, Visual Basic and Java.

6. It is a component-oriented language.

7. It is derived from C & C++ languages. So it is easy to learn. Syntax is similar to that of C and C++

8. Web-enabled : It is Web-enabled i.e. suitable for Web applications.

9. .NET Framework : It has been designed to support the .NET Framework.

10. C# is powerful and flexible: It can be used for diverse projects such as word-processors, graphics applications, spreadsheets, windows applications, and compilers for other languages.

11. Versionable: Versioning means the creation and management of multiple versions of a software. All versions have the same general function but they are improved, upgraded or customized. New versions of software modules can work with existing applications. C# supports versioning with the keywords called new and override.

12. Compatible: C# enforces the .NET common language specifications and allows inter operation with other .NET languages such as VB .NET.

Shortcomings / Drawbacks of C++:

1. C++ is a complex language.

2. C++ is not truly object-oriented.

3. It is not suitable for Web technologies.

4. It does not support versioning.

5. It is not type-safe.

6. C++ supports pointers which can result in major errors in programs.

Differences between C# and C++ :

Although C# is derived from C++, there are many differences between these two languages. These are:

1. C# does not support the #include statement.

2. C# does not support pointer types.

3. C# supports a native Boolean data type.

4. The entry point of both C# and C++ programs is a main method. In C#, the main method is written as Main (beginning with capital M), while in C++, the main method is written as main (starting with small m).

5. C# supports four iteration statements rather than three in C++. The fourth statement is called foreach.

6. C# can check overflow of arithmetic operations and conversions.

7. C# compiles from source code to object code. Object files are not produced.

8. All basic value types will have the same size on any system. This is not the case with C or C++. Therefore C# is more suitable for writing distributed applications.

9. C# checks for uninitialized variables and gives error messages at compile time. In C++, an uninitialized variable is not detected and causes errors in the output.

10. Arrays are classes in C# and operations such as sorting, reversing, and searching can be carried out.

11. Type casting in C# is safer than in C++.

12. C# does not allow silent fall through in switch statements. We must give an explicit jump statement at the end of each case statement.

13. Accidental use of the assignment operator (=), instead of the equality operator (==) will be caught by the compiler.

14. In C#, the switch statement can also be used on string values.

15. There is less need for destructors as garbage collection is automatic.

16. In C#, Boolean values cannot be treated as integers.

17. C# supports a native string type.

Differences between C# and Java :

Java was also based on C++ and hence C# and Java have many common features. C# was developed as an alternative to Java. The differences between C# and Java are as follows:

1. In C#, all data types are objects.

2. C# has more primitive data types.

3. The entry point of both C# and Java programs is a main method. In C#, the main method is written as Main (beginning with capital M), while in Java, the main method is written as main (starting with small m).

4. C# supports the struct type but Java does not support it.

5. Java does not support operator overloading.

6. In C#, the switch statement supports either integer or string expressions, but Java supports only integer expressions.

7. Java does not directly support enumeration.

8. C# has native support for properties but Java does not have it.

9. Constants are declared in C# by using the const keyword. But in Java, constants are used by using the final keyword.

10. C# has a new primitive data type called decimal which stores decimal numbers without rounding errors. This is useful for financial applications.

11. C# provides better versioning support than Java.

12. C# provides static constructors for initialization.

13. C# allows parameters to be passed by reference but Java permits parameters to be passed by value.

14. C# does not allow free fall-through from case to case.

IMPORTANT QUESTIONS

1. State the important characteristics of C#.

2. What is meant by the phrase “C# is a type-safe language”?

3. Define the term “versioning”.

4. State the differences between Java and C#.

5. State the difference s between C++ and C#.