UNIT II C# LM
UNIT II C# LM
NET UNIT- 2
DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
HANDOUT
on
C#.NET
UNIT-2
Objective:
To impart the concepts of control structures, classes, objects in .NET
Syllabus:
UNIT - II: Control Statements
Introduction to data types: Value Type - Primitive types, Arrays, Reference
Type, Keywords, variables, Operators and Literals in C#
Type Casting- Primitive type casting, Boxing and Unboxing, Special Operators
in C#
Conditional Statements- if, if-else, if-else-if ladder, nested if, switch
statements with examples
Iterative Statements- while, do-while, for, foreach, break, continue
statements with examples
Outcomes:
Students will be able to
Understand various data types in C#
Understand various conditional and iterative control structures
Compose simple programs in C# using control structures
Learning Material
Introduction to data types:Value Type - Primitive types, Arrays, Reference
Type:
Data type:
A data type is defined as a categorizing one of various types of data, such
as floating point and integer, and the operations that can done on that
type.
Data types are especially important in C# because it is a strongly typed
language. Thismeans that, all operations are type-checked by the
compiler for typecompatibility. Illegal operations will not be compiled.
C# contains two general categories of built-in data types: value types and
reference types. Thedifference between the two types is what a variable
contains. For a value type, a variableholds an actual value, such 3.1416 or
212. For a reference type, a variable holds a referenceto the value.
Value type:
Value type variables can be assigned a value directly. Valueof value type to
a variable or field or array element of value type makes a copy of the value.They
are derived from the class System.ValueType.To get the exact size of a type or
a variable use the sizeof() method. The expression sizeof(type) yields the
storage size of the object or type in bytes.
Primitive types:
A value type is a simple type, a struct type or an enum type.Assigning a
Some of the primitive (fundamental) data types:
Reference type:
The reference data types do not contain the actual data stored in a
variable, but they contain a reference to the variables.
If the data is changed by one of the variables, the other variable
automatically reflects this change in value.
A reference type is a class, an interface, an array type, or a delegate
type.
Arrays: Array in C# is a group of similar types of elements that have
contiguous memory location. In C#, array is an object of base type
System.Array. In C#, array index starts from 0. We can store only fixed set of
elements in C# array.
There are 2 methods commonly used for declaring arrays. While both have
their place and usage, most programmers prefer the dynamic array that is
declared at run-time to provide the most flexibility.
The staticarray is great if you have a set structure that will never change.
An array that holds the days of the week, months in the year, or even the
colors in a rainboware the static arrays. These won't change and they won't be
data driven so in this case, a static array will be best.
C# Array Properties:
Property Description
IsFixedSize It is used to get a value indicating whether the Array has a fixed
size or not.
IsReadOnly It is used to check that the Array is read-only or not.
Length It is used to get the total number of elements in all the
dimensions of the Array.
LongLength It is used to get a 64-bit integer that represents the total number
of elements in all the dimensions of the Array.
Rank It is used to get the rank (number of dimensions) of the Array.
C# Array Methods:
Method Description
Clear(Array,Int32,Int32) It is used to set a range of elements in an array to
the default value.
Clone() It is used to create a shallow copy of the Array.
Copy(Array,Array,Int32) It is used to copy elements of an array into
another array by specifying starting index.
Empty<T>() It is used to return an empty array.
Finalize() It is used to free resources and perform cleanup operations.
IndexOf(Array,Object) It is used to search for the specified object and returns
the index of its first occurrence in a one-dimensional array.
Initialize() It is used to initialize every element of the value-type Array by
calling the default constructor of the value type.
PrintArray(arr);
}
// User defined method for iterating array elements
static void PrintArray(int[] arr)
{
foreach (Object elem in arr)
{
Console.Write(elem+" ");
}
}
}
}
Single Dimensional Array
To create single dimensional array, you need to use square brackets []
after the type.
int[] arr = new int[3]{10,20,30};//creating Static array
int[] arr = { 10, 20, 30, 40, 50 }; creating Dynamic array
int[] arr = new int[]{10,20,30}; //creating Dynamic array
Let's see a simple example of C# array, where we are going to declare,
initialize and traverse array.
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = new int[5];//creating dynamic array
arr[0] = 10;//initializing array
arr[2] = 20;
arr[4] = 30;
//traversing array
arr[2,0]=30;
//traversal
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();//new line at each row
}
}
}
Jagged Arrays
In C#, jagged arrayis also known as "array of arrays" because its
elements are arrays. The element size of jagged array can be different.
Declaration of Jagged array
Let's see an example to declare jagged array that has two elements.
int[][] arr = new int[2][];
Initialization of Jagged array
Let's see an example to initialize jagged array. The size of elements can be
different.
arr[0] = new int[4];
arr[1] = new int[6];
Initialization and filling elements in Jagged array
Let's see an example to initialize and fill elements in jagged array (Static).
arr[0] = new int[4] { 11, 21, 56, 78 };
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };
Here, size of elements in jagged array is optional. So, you can write above
code as given below:
arr[0] = new int[] { 11, 21, 56, 78 };
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
Let's see an example to initialize the jagged array while declaration.
int[][] arr = new int[3][]
{
new int[] { 11, 21, 56, 78 },
new int[] { 2, 5, 6, 7, 98, 5 },
new int[] { 2, 5 }
};
Let's see a simple example of jagged array in C# which declares, initializes, and
traverse jagged arrays.
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[2][];// Declare the Jagged array
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
// Traverse array elements
for (int i = 0; i <arr.Length; i++)
{
for (int j = 0; j <arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
} }
Keywords, variables, Operators and Literals in C#:
Keywords:
A computer language is defined by its keywords because they determine
the features built into the language.
C# defines two general types of keywords: reserved and contextual.
Keywords are predefined, reserved identifiers that have special meanings
to the compiler.
Variables:
A variable is a name given to a storage area that our programs can
manipulate.
Each variable in C# has a specific type.
A variable is declared inside a method body, constructor body, or another
block statement.
The variable can be used only in that block statement, and only after it
has been declared.
C# Naming conventions of a variable:
May contain letters (a-z/A-Z), decimal digits (0-9), _ (underscore).
Can start with a capital letter before the keyword
Can use @ at beginning of any keyword
It should not be a keyword
White spaces ar not allowed
Variable names can be of any length
Variable names are case sensitive; Sum and sum are different names
Defining Variables:
Syntax for variable definition in C# is
<data_type><variable_list>;
Example: int i, j, k;int @int;
Initializing Variables:
Variables are initialized (assigned a value) with an equal sign followed by a
constant expression. The general form of initialization is
variable_name = value; or <data_type><variable_name> = value;
Example: i=10, j=20; orint d = 3, f = 5;
Operators:
C# provides an extensive set of operators that give the programmer
detailed controlover the construction and evaluation of expressions. Most of
C#’s operators fall intothe following categories: arithmetic, bitwise, relational,
and logical.
Arithmetic operators:
// C# program to demonstrate the
working of Arithmetic Operators
using System;
namespace Arithmetic {
classsample {
ushortnum;
num = 10;
if((num& 1) == 1)
Console.WriteLine("This won't display.");
num = 11;
if((num& 1) == 1)
Console.WriteLine("{0} is odd.",num);
}
}
Relational and Logical Operators:
Relational operators are used to check
the relationship between two operands. If
the relationship is true the result will be
true, otherwise it will result in false.
using System;
namespace Operator{
classRelationalOperator{
public static void Main(string[] args){
bool result;
int f = 10, s = 20;
result = (f==s);
Console.WriteLine("{0} == {1} returns {2}",f, s, result);
result = (f>s);
Console.WriteLine("{0} > {1} returns {2}",f, s, result);
result = (f< s);
Console.WriteLine("{0} < {1} returns {2}",f, s, result);
result = (f>= s);
Console.WriteLine("{0} >= {1} returns {2}",f, s, result);
result = a || b;
Console.WriteLine("OR Operator: {0}",result);
result = !a;
Console.WriteLine("NOT Operator: {0}",result);
}
}}
Literals:
Literals are value constants that are
assigned to variables in a program. C#
supports several types of literals.
Integer literals: An integer literal refers to the sequence of digits. An
integer literal can be a decimal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal.
Ex: 85 /* decimal */
0x4b /* hexadecimal */
Real/Floating literals:A floating-point literal has an integer part, a
decimal point, a fractional part, and an exponent part. We can represent
floating point literals either in decimal form or exponential form.
Mantissa e/E exponent
Ex: 7500 can be7.5E3//7.5x103
Character literals are enclosed in single quotes. For example, 'x' and can
be stored in a simple variable of char type. A character literal can be a
plain character (such as 'x'), an escape sequence (such as '\t').
Ex: char ch = 'a';
String literals are enclosed in double quotes "" or with @"". A string
contains characters that are similar to character literals: plain characters,
escape sequences, and universal characters.
Ex: string s1=”welcome”; string s2= @”welcome”;
Console.WriteLine(d);
Console.ReadKey();
}
}
}
classIfStatement{
public static void Main(string[] args){
int number = 2;
if (number < 5)
{
Console.WriteLine("{0} is less than 5", number);
}
Console.WriteLine("This statement is always executed.");
}
}
}
IF-ELSE:The block of code inside the else statement will be executed if the
expression is evaluated to false.
The syntax of if...else statement in C# is:
if (boolean-expression)
{
// statements executed if boolean-expression is true
}
else
{
// statements executed if boolean-expression is false
}
Example:
using System;
namespace Conditional{
classIfElseStatement{
public static void Main(string[] args){
int number ;
Console.WriteLine(“enter any integer number:”);
number=Convert.ToInt32(Console.ReadeLine());
if (number >=0)
{
Console.WriteLine("{0} is positive", number);
}
else
{
Console.WriteLine("{0} is negative", number);
}
Console.ReadKey();
}
}}
IF-ELSE-IF LADDER:There are multiple conditions to test and execute one of
the many blocks of code.The syntax for if...else if statement is:
if (boolean-expression-1)
{
// statements executed if boolean-expression-1 is true
}
else if (boolean-expression-2)
{
// statements executed if boolean-expression-2 is true
}
.
.
else
{
// statements executed if all above expressions are false
}
Ex: using System;
namespace Conditional{
classIfElseIfStatement {
{
// code to be executed
}
}
else
{
if (nested-expression-2)
{
// code to be executed
}
else
{
// code to be executed
}
}
Nested-if statements are generally used when we have to test one
condition followed by another. In a nested if statement, if the outer if statement
returns true, it enters the body to check the inner if statement.
Example:to find largest of three numbers
using System;
namespace Conditional{
class Nested{
public static void Main(string[] args){
int first, second, third;
Console.WriteLine(“enter any three integer numbers:”);
first=Convert.ToInt32(Console.ReadLine());
second=Convert.ToInt32(Console.ReadLine());
third=Convert.ToInt32(Console.ReadLine());
if (first > second)
{
case expression_value1:
Statement
break;
case expression_value2:
Statement
break;
case expression_value3:
Statement
break;
default:
Statement
break;
}
The switch statement is often used as an alternative to an if-else
construct if a single expression is tested against three or more conditions. For
example, the following switch statement determines whether a variable of type
Color has one of three values:
Example: using System;
publicenum Color { Red, Green, Blue }
public class Example{
public static void Main() {
Color c = (Color) (new Random()).Next(0, 3);
switch (c)
{
caseColor.Red:
Console.WriteLine("The color is red");
break;
caseColor.Green:
Console.WriteLine("The color is green");
break;
caseColor.Blue:
Console.WriteLine("The color is blue");
break;
default:
Console.WriteLine("The color is unknown.");
break;
}
}}
Iterative Statements- while, do-while, for, foreach, break, continue
statements with examples
WHILE: The simplest of all looping structures in C# is the whilestatement. The
basic syntax of the while statement is
Initialization;
while(test condition)
{
Body of the loop
}
Whileis an entry controlled loop statement. The test condition is evaluated
and if the condition is true, then the body of the loop is executed. After
execution of the body, the test condition is once again evaluated and if it is
true, the body is executed once again. This process of repeated execution of the
body continues until the test condition finally becomes false and the control is
transferred out of the loop.
Ex:
using System;
namespacewhileLoop{
classwhileLoopProgram{
static void Main(string[] args){
int a=1;
while(a<=15)
{
Console.WriteLine(“{0}”,a);
a++;
}
Console.ReadKey();
}
}
}
DO-WHILE: On some occasions it might be necessary to execute the body of
the loop before the test condition is performed. Such situations can be handled
with the help of the do-while statement.
initialization;
do{
Body of the loop
}while(test condition);
On reaching the do statement, the program proceeds to evaluate the
body of the loop first.
At the end of the body of the loop, the test condition in the while
statement is evaluated.
If the condition is true, the program continues to evaluate the body of the
loop once again. If the condition is false, the loop will be terminated and
control goes to the next statement.
Ex: using System;
namespacewhileLoop{
classwhileLoopProgram{
static void Main(string[] args){
int a=1;
do{
Console.WriteLine(“{0}”,a);
a++;
}while(a<=15);
Console.ReadKey();
}
}}
FOR LOOP: for is another entry controlled loop that provides a more concise
loop control structure. The general form of the for loop is
for(initialization; test_condition;inc/dec)
{
Body of the loop
}
Initialization of the control variable is done first.
The value of the control variable is tested using the test condition.
If the condition is true, then the loop will be executed. Otherwise, the loop
will be terminated and control goes to the next statement.
Loop will be incremented or decremented based on the iterator.
Ex:using System;
namespacewhileLoop{
classwhileLoopProgram {
static void Main(string[] args){
for(int i=1;i<=10;i++)
{
Console.WriteLine(“{0}”,i);
}
Console.ReadKey();
}
}}
BREAK ANDCONTINUE:
When abreak statement is encountered inside a loop, the loop is
terminated, and program controlresumes at the next statement following
the loop.
Sometimes it is necessary to force an immediate exit from a loop,
bypassing any code remaining in thebody of the loop and the loop’s
conditional test, by using the break statement.
The continue statement takes the control to the beginning of the loop
and executes the next iteration. The statements following continue are
skipped.
The difference is that the breakstatement takes the control to end of the
loop whereas the continuestatement takes it to the beginning.
Ex: using System;
namespace whileLoop
{
class whileLoopProgram
{
static void Main(string[] args)
{
for (int i = 0; i <= 20; i++ )
{
if (i == 10)
continue;
if (i == 15)
break;
Console.WriteLine(“{0}”,i);
}
Console.ReadKey();
}
}
}
Assignment-Cum-Tutorial Questions
Section-A
Objective Questions
1. Base type of all the data types is _______ [ ]
a) Object type b) string type c) Value type d) Reference type
2. State the default values for the following types
i)char type _________ ii) float type ________
iii) double type _______ iv) All integers ________
v)decimal type ________ vi) bool type ________
vii) all reference type ______ viii) enum type ________
3. Floating point numbers are ________ type by default [ ]
a) string b) int c) float d) double
4. which of the following are reference type [ ]
a) class b) interface c) a & b d) none of the above
5. what is the output of the following code ______
int i;for (i=0;i<10;i++);Console.WriteLine(i);
6. M at the end represent the value is of _____ type [ ]
a) float b) double c) decimal d) int
7. Correct Declaration of Values to variables ‘a’ and ‘b’? [ ]
a) int a = 32, b = 40.6; b) int a = 42; b = 40; c) int a = 32; int b = 40;
d) int a = b = 42;
8. What is the Size of ‘char’ datatype? [ ]
a) 8 bit b) 32 bit c) 16 bit d) 64 bit
9. Select output for the following set of code [ ]
int a = 5; int b = 10;int c;
Console.WriteLine(c = ++ a + b ++);Console.WriteLine(b);
a) 11 10 b) 16 10 c) 16 11 d) 15 11
10. What is the output of following set of code ? ________
char a = 'A';int b=10; b = a + b; Console.WriteLine(“{0} {1}”, a,b);
11. Which of the following is the correct size of a Decimal datatype? [ ]
Section-B
Subjective Questions
1. Explain various data types available in C#?
2. Identifythe types of arrays and give examples?
3. Explain different types of literals in C# and give examples?
4. List out different types of Operators and explain with examples?
5. Explain the declaration and initialization of jagged array?
6. State the need for keywords and variables?
7. Construct a C# program on the usage of jagged array?
8. Explain conditional statements if, if-else, if-else-if ladder and nested if?
9. Describe the usage of boxing and unboxing?
10. List out different loop control structures in C# give examples?
11. Demonstrate the switch case with the example program?