0% found this document useful (0 votes)
5 views

c#module2

Module 2 of the C# and .NET course covers the fundamentals of C#, an object-oriented programming language developed by Microsoft, including its features, data types, and basic programming concepts such as variables, operators, and control flow. It explains how to write C# programs, handle user input, and utilize command line arguments, along with the structure of a C# program including namespaces and the Main method. The module also highlights the importance of data types and provides examples of how to work with them in C#.

Uploaded by

Shashank S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

c#module2

Module 2 of the C# and .NET course covers the fundamentals of C#, an object-oriented programming language developed by Microsoft, including its features, data types, and basic programming concepts such as variables, operators, and control flow. It explains how to write C# programs, handle user input, and utilize command line arguments, along with the structure of a C# program including namespaces and the Main method. The module also highlights the importance of data types and provides examples of how to work with them in C#.

Uploaded by

Shashank S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

22ISE451 / C# and .

NET/Module2

MODULE 2:

C# Program –Execution, Sample Programs, Command Line Arguments, Programming


Examples,

Literals, Variables and Data Types: Keywords, Identifiers, Literals, Variables, Data Types,
Boxing and Unboxing. Operators, branching and looping.

What is C#?

C# is pronounced "C-Sharp".

It is an object-oriented programming language created by Microsoft that runs on the .NET


Framework.

C# has roots from the C family, and the language is close to other popular languages like c++
and java

The first version was released in year 2002. The latest version, C# 12, was released in
November 2023.

C# is used for:

• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And much, much more!
Why Use C#?

• It is one of the most popular programming languages in the world


• It is easy to learn and simple to use
• It has huge community support
• C# is an object-oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
• As C# is close to c,c++,java, it makes it easy for programmers to switch to C# or vice
versa
C# Features

C# is object oriented programming language. It provides a lot of features that are given
below.
1. Simple

PREPARED BY K. THAMARAI SELVI- AP/ISE 1


22ISE451 / C# and .NET/Module2

2. Modern programming language


3. Object oriented
4. Type safe
5. Interoperability
6. Scalable and Updateable
7. Component oriented
8. Structured programming language
9. Rich Library
10. Fast speed

1) Simple
C# is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.
2) Modern Programming Language
C# programming is based upon the current trend and it is very powerful and simple for
building scalable, interoperable and robust applications.
3) Object Oriented
C# is object oriented programming language. OOPs makes development and maintenance
easier where as in Procedure-oriented programming language it is not easy to manage if code
grows as project size grow.
4) Type Safe
C# type safe code can only access the memory location that it has permission to execute.
Therefore it improves a security of the program.
5) Interoperability
Interoperability process enables the C# programs to do almost anything that a native C++
application can do.
6) Scalable and Updateable
C# is automatic scalable and updateable programming language. For updating our application
we delete the old files and update them with new ones.

PREPARED BY K. THAMARAI SELVI- AP/ISE 2


22ISE451 / C# and .NET/Module2

7) Component Oriented
C# is component oriented programming language. It is the predominant software
development methodology used to develop more robust and highly scalable applications.
8) Structured Programming Language
C# is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify.
9) Rich Library
C# provides a lot of inbuilt functions that makes the development fast.
10) Fast Speed
The compilation and execution time of C# language is fast.

Understanding the Code:


Using Visual Studio, if we are creating a console application (excluding .NET 6), then
automatically we are getting four sections which are shown in the below image.

(i) Importing Namespace Section:

This section contains importing statements that are used to import the BCL (Base Class
Libraries) as well as user-defined namespaces if required. This is similar to the included
statements in the C programming language. Suppose you want to use some classes and
interfaces in your code, then you have to include the namespace(s) from where these classes
and interfaces are defined. For example, if you are going to use the Console class in your
code, then you have to include the System namespace as the Console class belongs to the
System namespace.

Syntax: using NamespaceName;


Example: using System;

PREPARED BY K. THAMARAI SELVI- AP/ISE 3


22ISE451 / C# and .NET/Module2

If the required namespace is a member of another namespace, we have to specify the parent
and child namespaces separated by a dot as follows:

using System.Data;
using System.IO;

Note: A namespace is a container that contains a group of related classes and interfaces, as
well as, a namespace can also contain other namespaces.

(ii) Namespace Declaration Section:


Here a user-defined namespace is declared. In .NET applications, all classes and interfaces or
any type related to the project should be declared inside some namespace. Generally, we put
all the related classes under one namespace and in a project, we can create multiple
namespaces.
Syntax: namespace NamespaceName {}
Example: namespace MyFirstProject {}

(iii) Class Declaration Section:

For every Desktop Application in .NET, we need a start-up class file. For example, for every
.NET Desktop Application like Console and Windows, there should be a Start-Up class that
should have the Main method from where the program execution is going to start. When we
create a Console Application using Visual Studio, by default, Visual Studio will Create the
Start-Up class file with the name Program.cs which will have a class with the name Program
that contains the Main method. A start-up class is nothing but a class that contains a Main()
method from which the program execution is going to start.
Syntax:
class ClassName
{
}
Example:
class Program
{
}
(iv) Main() Method Section:

The main() method is the entry point or starting point of the application to start its execution.
When the application starts executing, the main method will be the first block of the
application to be executed. The Main method contains the main logic of the application.

C# Comments
Comments can be used to explain C# code, and to make it more readable. It can also be used
to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by C# (will not be executed).
This example uses a single-line comment before a line of code:

PREPARED BY K. THAMARAI SELVI- AP/ISE 4


22ISE451 / C# and .NET/Module2

Example
// This is a comment
Console.WriteLine("Hello World!");
C# Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by C#.
This example uses a multi-line comment (a comment block) to explain the code:
Example
/* The code below will print the words Hello World
to the screen, and it is amazing */
Console.WriteLine("Hello World!");

C# Output
To output values or print text in C#, you can use the WriteLine() method:

Console.WriteLine("Hello World!");
You can add as many WriteLine() methods as you want. Note that it will add a new line for
each method:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine("I am Learning C#");
Console.WriteLine("It is awesome!");
}
}
}

You can also output numbers, and perform mathematical calculations:

Console.WriteLine(3 + 3);
The Write Method
There is also a Write() method, which is similar to WriteLine().
The only difference is that it does not insert a new line at the end of the output:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{

PREPARED BY K. THAMARAI SELVI- AP/ISE 5


22ISE451 / C# and .NET/Module2

Console.Write("Hello World! ");


Console.Write("I will print on the same line.");
}
}
}
Output:

C# User Input
Get User Input
In C#, the simplest method to get input from the user is by using the ReadLine() method
of the Console class. However, Read() and ReadKey() are also available for getting input
from the user. They are also included in the Console class. The most important thing is all
these three methods are static methods of the Console class, and hence we can call these
methods using the class name.
Example to Get String Input from User in C#:

using System;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
string str;
Console.Write("Enter a string - ");
str = Console.ReadLine();
Console.WriteLine($"You entered {str}");
}
}
}

Output:

Difference between ReadLine(), Read() and ReadKey() methods in C#:


The difference between ReadLine(), Read() and ReadKey() method in C# are as follows:
1. ReadLine(): The ReadLine() method of Console class in C# reads the next line of input
from the standard input stream. It returns the same string.
2. Read(): The Read() method of Console class in C# reads the next character from the
standard input stream. It returns the ASCII value of the character.

PREPARED BY K. THAMARAI SELVI- AP/ISE 6


22ISE451 / C# and .NET/Module2

3. ReadKey(): The ReadKey() method of the Console class in C# obtains the next key
pressed by the user. This method is usually used to hold the screen until the user press
a key.

Reading Integer and floating Numbers (Numeric Values)

The ReadLine() method receives the input as a string, we need to typecast it into an integer
or floating-point type as per our requirement. The simplest approach for converting user input
to integer or floating-point type is by using the methods of the Convert class.

using System;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
string userInput;
int intVal;
double doubleVal;

Console.Write("Enter integer value: ");


userInput = Console.ReadLine();
// Converts to integer type
intVal = Convert.ToInt32(userInput);
Console.WriteLine("You entered {0}", intVal);

Console.Write("Enter double value: ");


userInput = Console.ReadLine();
// Converts to double type
doubleVal = Convert.ToDouble(userInput);
Console.WriteLine("You entered {0}", doubleVal);
}
}
}

Command Line Arguments in C#


We know that we can pass parameters to a function as an argument but what about
the Main(string[] args) method? Can we pass parameters to the Main() method in C#? Yes,
we can pass parameters to the Main() method and this is possible through Command Line
Arguments in C#. The arguments which are passed by the user or programmer to the Main()
method are termed as Command-Line Arguments in C#.
The Main() method is the starting point from where the program execution starts. The most
important point that you need to remember is that the main method doesn’t accept any

PREPARED BY K. THAMARAI SELVI- AP/ISE 7


22ISE451 / C# and .NET/Module2

parameter from any method. It only accepts parameters through the Command-Line. If you
notice the Main method signature, it has a string array type parameter that can accept n
number of parameters at runtime. In Main(string[] args), args is a string type of array that can
hold numerous parameters.
Passing Command Line Arguments in C# using Visual Studio:
Create a new console application and then modify the Program.cs class file as follows:
using System;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"First Command Line Argument {args[0]}");
Console.WriteLine($"Second Command Line Argument {args[1]}");
Console.WriteLine($"Third Command Line Argument {args[2]}");
Console.ReadLine();
}}}
If you notice, the above example excepts at least three parameters to be supplied by the Main
method. Now, if you run the application, then you will get the following
System.IndexOutOfRangeException: ‘Index was outside the bounds of the array’ run time
exception.

And this makes sense. Because we have not supplied any parameters and in the program, the
string array does not have any element, it is empty and we are trying to access the array
elements. Now, the question is how we can pass arguments to the Main Method. The answer
is by using the command Line. Let us see how we can do this using Visual Studio.

PREPARED BY K. THAMARAI SELVI- AP/ISE 8


22ISE451 / C# and .NET/Module2

Passing Command Line Arguments to Main Method using Visual Studio:


Open the Properties window. To open the properties window, right-click on the project in
solution explorer and then click on the Properties menu as shown in the below image.

From the Properties window, select the debug tab and in the Command Line Arguments text
box, provide the values that you want to pass to the Main method separated by a space. As in
our example, we except three values in the string array, so here I am putting three values in
the Command Line Arguments text box as shown in the below image.

Here Value1 will store in args[0], Value2 will store in args[1], and Value3 will store in
args[2]. Now, save the changes and run the application and you will get the following output
in the Console window.

Passing Numeric Command Line Arguments in C#


In C#, Command Line Arguments are always stored as strings and always separated by
spaces. The Main() method of every C# application can only accept string arguments. If an
application needs to support a numeric command-line argument, then what do you need to
do? You need to pass the numeric number as a string and in your application, it is your

PREPARED BY K. THAMARAI SELVI- AP/ISE 9


22ISE451 / C# and .NET/Module2

responsibility to convert that string to numeric. And, hence it is possible to pass numeric
arguments through the command line. However, we can later convert string arguments into
numeric values.
Example to Pass Numeric Command Line Arguments in C#
using System;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
//convert into integer type
int argument1 = Convert.ToInt32(args[0]);
Console.WriteLine("Argument in Integer Form : " + argument1);
//convert into double type
double argument2 = Convert.ToDouble(args[1]);
Console.WriteLine("Argument in Double Form : " + argument2);
Console.ReadLine();
}
}
}
Now, modify the Properties=>Debug window as shown in the below image.

Now, save the changes and run the application and you will get the following output.

PREPARED BY K. THAMARAI SELVI- AP/ISE 10


22ISE451 / C# and .NET/Module2

C# | Keywords
Keywords or Reserved words are the words in a language that are used for some
internal process or represent some predefined actions. These words are therefore not
allowed to use as variable names or objects. Doing this will result in a compile-time
error.

Data Types in C#

PREPARED BY K. THAMARAI SELVI- AP/ISE 11


22ISE451 / C# and .NET/Module2

Why do we need Data Types in C#?


The Datatypes in C# are basically used to store the data temporarily in the computer through
a program. In the real world, we have different types of data like integers, floating-point,
characters, boolean, strings, etc. To store all these different kinds of data in a program to
perform business-related operations, we need the data types.
What is a Data Type in C#?
The Datatypes are something that gives information about
1. Size of the memory location.
2. The Range of data that can be stored inside that memory location
3. Possible Legal Operations that can be performed on that memory location.
4. What Types of Results come out from an expression when these types are used inside
that expression?
The keyword which gives all the above information is called the data type in C#.

• C# contains two general categories of built-in data types:


• value types
• reference types.
• The difference between the two types is what a variable contains. For a value type, a
variable holds an actual value, such 3.1416 or 212. For a reference type, a variable
holds a reference to the value. The most commonly used reference type is the class

• a reference type doesn't store its value directly. Instead, it stores the address where the
value is being stored. In other words, a reference type contains a pointer to another
memory location that holds the data.
• For example, consider the following string variable:
• string s = "Hello World!!";

PREPARED BY K. THAMARAI SELVI- AP/ISE 12


22ISE451 / C# and .NET/Module2

Numbers in C#
• Numbers, in general, can be divided into two types: Integer type and floating-point
types.
• Integer type numbers are whole numbers without decimal points. It can be negative
or positive numbers.
• Floating-point type is numbers with one or more decimal points. It can be negative
or positive numbers.
• C# includes different data types for integer types and floating-point types based on
their size in the memory and capacity to store numbers.

Integers
• Integers C# defines nine integer types: char, byte, sbyte, short, ushort, int, uint, long,
and ulong. However, the char type is primarily used for representing characters

PREPARED BY K. THAMARAI SELVI- AP/ISE 13


22ISE451 / C# and .NET/Module2

Floating Point Types


You should use a floating point type whenever you need a number with a decimal, such as
9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you should end the
value with an "F" for floats and "D" for doubles:
Float: It occupies 4 bytes in the memory.
Double: It occupies 8 bytes in the memory.
Use float or double?
The precision of a floating point value indicates how many digits the value can have after the
decimal point. The precision of float is only six or seven decimal digits,
while double variables have a precision of about 15 digits. Therefore it is safer to
use double for most calculations.

Decimal
• Decimal. This type accurately stores numeric data. In some C# programs (like those
with financial data) rounding errors are harmful—decimal helps.
• Decimal stores large and small numbers with many digits after the decimal place..
• In C#, ‘decimal’ is a data type used for storing floating-point numbers with a high
level of precision.
• Memory. Decimal values require 16 bytes. The decimal type is a value type—it
requires more memory than most other value types used commonly in C#.

Booleans

PREPARED BY K. THAMARAI SELVI- AP/ISE 14


22ISE451 / C# and .NET/Module2

A boolean data type is declared with the bool keyword and can only take the
values true or false: Size: 1 byte

Output

Characters
• char is an unsigned 16-bit type having a range of 0 to 65,535. The standard 8-bit
ASCII character set is a subset of Unicode and ranges from 0 to 127.
• C# uses a 16-bit character type called Unicode. Unicode defines a character set that is
large enough to represent all of the characters found in all human languages
• The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
char myGrade = 'B';
Console.WriteLine(myGrade);
}
}
}

PREPARED BY K. THAMARAI SELVI- AP/ISE 15


22ISE451 / C# and .NET/Module2

Strings
The string data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string greeting = "Hello World";
Console.WriteLine(greeting);
}
}
}
There two ways to declare a string variable in C#. Using System.String class and
using string keyword. Both are the same and make no difference
using System;

public class Program


{
public static void Main()
{
string str1 = "Hello"; // uses string keyword
String str2 = "Hello"; // uses System.String class
Console.WriteLine(str1);
Console.WriteLine(str2);
}
}

Special Characters
In C#, because a string is surrounded with double quotes, it cannot include " in a string. The
following will give a compile-time error

C# includes escaping character \ (backslash) before these special characters to include in a


string.
Use backslash \ before double quotes and some special characters such as \,\n,\r,\t, etc. to
include it in a string.
using System;
public class Program
{
public static void Main()
{
string text = "This is a \"string\" in C#.";
string str = "xyzdef\\rabc";
Console.WriteLine(text);
Console.WriteLine(str);

PREPARED BY K. THAMARAI SELVI- AP/ISE 16


22ISE451 / C# and .NET/Module2

}
}

Literals in C#
The Literals in C# are the fixed values (or hard-coded values) given to your variable and
these values cannot be modified during the execution of the program.
1. The fixed values are called Literals in C#.
2. Literal is a value that is used by the variables.
For example, int x = 100; Here x is a variable, and 100 is literal.

Example to Understand Integer Literals in C# Language


using System;
namespace LiteralsDemo
{
class Program
{
static void Main(string[] args)
{
// Decimal literal
//Allowed Digits: 0 to 9
int a = 101; //No suffix is required
// Hexa-Decimal Literal
//Allowed Digits: 0 to 9 and Character a to f
int c = 0x123f; //Prefix with 0x, and suffix with f
//Binary literal
//Allowed Digits: 0 to 1
int d = 0b1111; // //Prefix with 0b
Console.WriteLine($"Decimal Literal: {a}");
Console.WriteLine($"Hexa-Decimal Literal: {c}");
Console.WriteLine($"Binary Literal: {d}");
Console.ReadKey();

PREPARED BY K. THAMARAI SELVI- AP/ISE 17


22ISE451 / C# and .NET/Module2

}
}
}
Output:

Floating-Point Literals in C#:


The Literals in C# which have an integer part and a decimal point are known as Floating-Point
literals i.e. Numbers with Decimal. The Floating-Point Literals are used to write values of types
float, double, and decimal.
By default, every floating-point literal is of double type and hence we can’t assign values directly
to float and decimal variables. If you want to assign values to a float variable, then you need to
add the suffix f at the end of the floating-point literal. Similarly, if you want to assign values to a
decimal variable, then you need to add the suffix m or M at the end of the floating-point literal. If
you are not suffixing the floating-point literal with anything, then the floating-point literal is
going to be double by default. Even, if you want, then you can also specify explicitly floating-
point literal as the double type by suffixed with d or D, of course, this convention is not required.
Example to Understand Floating-Point Literals in C#:
using System;
namespace LiteralsDemo
{
class Program
{
static void Main(string[] args)
{
//Double Literal
double a = 10.15; //By Default Floating Point Literal is double
//Float Literal
float b = 100.72F; //Suffix with F
//Double Literal
double c = 1.45D; //Suffix with D
//Decimal Literal
decimal d = 1.44M; //Suffix with M
Console.WriteLine($"Double Literal: {a}");
Console.WriteLine($"Float Literal: {b}");
Console.WriteLine($"Double Literal: {c}");
Console.WriteLine($"Decimal Literal: {d}");
Console.ReadKey();
}}
}

PREPARED BY K. THAMARAI SELVI- AP/ISE 18


22ISE451 / C# and .NET/Module2

Output:

Character Literals in C#:


The Character Literals in C# are enclosed in single quotes, for example, ‘a’, and can be stored in
a simple variable of char data type. A character literal can be a plain character for example, ‘a’,
an escape sequence for example, ‘\t’, or a universal character for example, ‘\u02B0’. So, for
character data types we can specify character literals in 3 ways. They are as follows:
1. Character Literals using Single Quote:
We can specify Character literals to a char data type as a single character using a single quote.
Example: char ch = ‘A’;
2. Character Literals using Unicode Representation:
We can specify Character literals using Unicode representation ‘\uXXXX’ where XXXX is the 4
hexadecimal numbers.
Example: char ch = ‘\u0041’; // Here /u0041 represent A. Please check the below link for the
list of Unicode characters.
3. Character Literals using Escape Sequence:
Every escape character in C# can be specified as a character literal.
Example: char ch = ‘\n’;
There are certain characters in C# when preceded by a backslash, which will have a special
meaning that they are used to represent. For example, newline (\n) and tab (\t). The following is
the list of some of the escape sequence characters available in C#.

Example to Understand Character Literals in C#:


using System;
namespace LiteralsDemo

PREPARED BY K. THAMARAI SELVI- AP/ISE 19


22ISE451 / C# and .NET/Module2

{
class Program
{
static void Main(string[] args)
{
//Character literal using single quote
char ch1 = 'A';
Console.WriteLine("Single Quote: " + ch1);
//Character literal using Unicode representation
char ch2 = '\u0041';
Console.WriteLine("Unicode: " + ch2);
//Character literal using Escape character
Console.WriteLine("Escape: Hello\nDotNet\tTutorials");
Console.ReadKey();
}}}
Output:

String Literals in C#:


The Literals in C# which are enclosed with double quotes (” “) or start with @” “ are known as
the String literals. In C#, we can represent the string literals in two ways. They are as follows:
1. Regular String Literals: A regular string literal in C# consists of zero or more characters
enclosed in double quotes, for example, “Dot Net Tutorials”, and may include both
simple escape sequences for example, “Dot\nNet\tTutorials” and Unicode escape
sequences.
2. Verbatim String Literals: A verbatim string literal starts with an @ character followed
by a double-quote which may contain zero or more characters, and ends with a double-
quote character. They can store characters or escape sequences, for
example, @”Dot\nNet\tTutorials”. In this case, the escape sequences or characters will
be printed as it is in the output.
Example to understand String Literals in C#:
using System;
namespace LiteralsDemo
{
class Program
{
static void Main(string[] args)
{
string str1 = "Dot Net Tutorials";
string str2 = @"Dot Net Tutorials";
string str3 = "Dot\nNet\tTutorials";
string str4 = @"Dot\nNet\tTutorials";

PREPARED BY K. THAMARAI SELVI- AP/ISE 20


22ISE451 / C# and .NET/Module2

Console.WriteLine($"str1: {str1}");
Console.WriteLine($"str2: {str2}");
Console.WriteLine($"str3: {str3}");
Console.WriteLine($"str4: {str4}");
Console.ReadKey();
}}}
Output:

Boolean Literals in C#:


Only two values are allowed for Boolean literals i.e. true and false. Boolean literals are simple.
There are only two logical values that a boolean value can have, true and false. The values of true
and false do not convert into any numerical representation. The true literal in C# does not equal 1,
nor does the false literal equal 0.
Example:
bool b1 = true;
bool b2 = false;
bool b3 = 0; //Error
bool b4 = 1; //Error
Note: The assigned true and false values should be the lower case only otherwise you will get
compile time error. The following is not allowed.
bool b1 = True; //Error
bool b2 = False; //Error
bool b1 = TRUE; //Error
bool b2 = FALSE; //Error
Example to understand Boolean Literals in C#:
using System;
namespace LiteralsDemo
{
class Program
{
static void Main(string[] args)
{
bool b1 = true;
bool b2 = false;
// bool b3 = 0; //Error
// bool b4 = 1; //Error
Console.WriteLine(b1);
Console.WriteLine(b2);
Console.ReadKey();
}}}

PREPARED BY K. THAMARAI SELVI- AP/ISE 21


22ISE451 / C# and .NET/Module2

Output:

Binary Literals in C#:


The binary literal is used to store the binary value in a variable. And if you want to create a binary
literal, then the literal value should be prefixed with 0b. And here, you can use only 0 and 1. If
you use any other number then you will get compile time error.
int num1 = 0b10001; //Allowed
int num2 = 0b1000145; //Error
Here when the compiler sees 0b in the variable value, then it automatically treated this literal as a
binary literal.
Example to understand Binary Literals:
using System;
namespace LiteralsDemo
{
class Program
{
static void Main(string[] args)
{
// Creating binary literals by prefixing with 0b
int Num1 = 0b100111101;
int Num2 = 0b01000011;
//int num3 = 0b100134; //Error
Console.WriteLine($"Value of Num1 is: {Num1}");
Console.WriteLine($"Value of Num2 is: {Num2}");
Console.WriteLine($"Char value of Num1 is: {Convert.ToChar(Num1)}");
Console.WriteLine($"Char value of Num2 is: {Convert.ToChar(Num2)}");
Console.ReadKey();
}}}
Output:

Variables in C#

A name that is given for any computer memory location is called a variable. The purpose of
the variable is to provide some name to a memory location where we store some data. The
user will access the data by the variable name and the compiler will access the data by the
memory address. So, the variable is a named location in the computer memory where a
program can store the data.
Rules for variable declaration in C#:
1. A variable name must begin with a letter or underscore.
2. Variables in C# are case sensitive
3. They can be constructed with digits and letters.
4. No special symbols are allowed other than underscores.

PREPARED BY K. THAMARAI SELVI- AP/ISE 22


22ISE451 / C# and .NET/Module2

5. sum, Height, _value, and abc123, etc. are some examples of the variable name

How to declare a variable in C#?


The Syntax for declaring a variable in C# is as follows:
Syntax: data_type variable_name;
Here, data_type is the type of data to be stored in the variable, and variable_name is the name
given to that variable.
Example: int age;
Here, the data type is int and age is the name of the variable where the age variable can only
hold an integer value.

Static and Non-Static Variables in C#

If we declare a variable explicitly by using the static modifier, we call it a static variable, and
the rest of all are non-static variables. Again, if we declare a variable inside a static block, then
also that variable is a static variable. And if we declare a variable inside a non-static block, then
that becomes a non-static variable.
For a better understanding, please have a look at the following example. In the below example,
we have declared three variables. The variable x is a static variable as it is declared using the
static modifier. The variable y is non-static by default and the variable z is static as it is declared
inside a static block. As the Main method is a static method and hence the variables declared
inside the Main method are also going to be static.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x; //Static Variable
int y; //Non-Static or Instance Variable
static void Main(string[] args)
{
int z; //Static Variable
}
}
}

Now, let us try to print the value of x and y inside the Main method. Let us initialize the x
value to 100 and the y value to 200. Here, you can print the value of x directly inside the
Main method. But you cannot print the value of y directly inside the Main method.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
static void Main(string[] args)
{
Console.WriteLine($"x value: {x}");

PREPARED BY K. THAMARAI SELVI- AP/ISE 23


22ISE451 / C# and .NET/Module2

Console.Read();
}
}
}

Now, let us try to print the y value also directly. If we try to print the y value directly, then we
will get a compile-time error saying an object reference is required for the non-static
field, method, or property ‘Program.y’. For a better understanding, please have a look at
the following example. Here, we are trying to print the x and y values directly.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
static void Main(string[] args)
{
Console.WriteLine($"x value: {x}");
Console.WriteLine($"x value: {y}");
Console.Read();
}}}

This is because the memory for the variable y is going to be created only when we create
an instance of the class Program and for each instance.

But x does not require an instance of the class. The reason is a static variable is initialized
immediately once the execution of the class starts.
So, until and unless we created the instance of the Program class, the memory will not be
allocated for the variable y and as long as the memory is not allocated for the variable y, we
cannot access it. So, once we create the instance of the Program class, the memory for
variable y will be allocated, and then only we can access the variable y.
using System;
namespace TypesOfVariables
{
internal class Program
{
static int x = 100; //Static Variable
int y = 200; //Non-Static or Instance Variable
static void Main(string[] args)
{
Console.WriteLine($"x value: {x}");
Program obj = new Program();

PREPARED BY K. THAMARAI SELVI- AP/ISE 24


22ISE451 / C# and .NET/Module2

Console.WriteLine($"y value: {obj.y}");


Console.Read();
}}}

Constant Variables in C#:

In C#, if we declare a variable by using the const keyword, then it is a constant variable and
the value of the constant variable can’t be modified once after its declaration. So, it is
mandatory to initialize the constant variable at the time of its declaration only. Suppose, you
want to declare a constant PI in your program, then you can declare the constant as follows:
const float PI = 3.14f;
If you are not initializing the const variable at the time of its declaration, then you get a compiler
error as shown in the below image.

Boxing and Unboxing in C# with Examples

Basic Need: Stack, Heap, Value Type, and Reference Type in C#


What Happens Internally When We Declare a Variable in a .NET Application?
When we declare a variable in a .NET application, it allocates some memory in the RAM. The
memory that it allocates in RAM has three things are as follows:
1. Name of the Variable,
2. The Data Type of the Variable, and
3. Value of the Variable.
For a better understanding, please have a look at the following image. Here, we declare a
variable of type int and assign a value 101.

PREPARED BY K. THAMARAI SELVI- AP/ISE 25


22ISE451 / C# and .NET/Module2

The above image shows a high-level overview of what is happening in the memory. But
depending on the data type (i.e., depending on the value type and reference type ), the
memory may be allocated either in the stack or in the heap memory

Understanding Stack and Heap Memory in C#:


There are two types of memory allocation for the variables we created in the .NET
Application, i.e., Stack Memory and Heap Memory. Let us understand the Stack and Heap
Memory with an Example. To understand Stack and Heap Memory, please have a look at the
following code, and let’s understand what actually happens in the below code internally.

As you can see in the above image, the SomeMethod has three statements. Let’s understand
statement by statement how things are executed internally.
Statement 1:
When the first statement is executed, the compiler allocates some memory in the stack. The
stack memory is responsible for keeping track of the running memory needed in your
application. For a better understanding, please have a look at the following image.

Statement 2:
When the second statement is executed, it stacks this memory allocation (memory allocation
for variable y) on top of the first memory allocation (memory allocation for variable x). You
can think about the stack as a series of plates or dishes put on top of each other. Please have a
look at the following diagram for a better understanding.

The Stack Memory allocation and de-allocation in .NET uses the Last In, First Out Principle.
In other words, we can say that the memory allocation and de-allocation are done only at one
end of the memory, i.e., the top of the stack.

PREPARED BY K. THAMARAI SELVI- AP/ISE 26


22ISE451 / C# and .NET/Module2

Statement3:
In the 3rd statement, we have created an object of SomeClass. When the 3rd statement is
executed, it internally creates a pointer on the stack memory, and the actual object is stored in
a different memory location called Heap memory. The Heap Memory location does not track
running memory. Heap is used for dynamic memory allocation. For a better understanding,
please have a look at the below image.

What Happens When the Method Completes Its Execution?


When the three statements are executed, the control will exit from the method. When it passes
the end control, i.e., the end curly brace “},” it will clear all the memory variables created on
the stack. It will de-allocate the memory from the stack in a ‘LIFO’ fashion. For a better
understanding, please have a look at the below image.

It will not de-allocate the Heap memory. Later, the heap memory will be de-allocated by the
garbage collector.
Boxing and Unboxing in C#:

Boxing: Boxing is the process of converting a value type (like int, double, struct) to a reference
type (object). When a value type is boxed, a new object is allocated to the heap, and the value
is copied into it.
Unboxing: Unboxing is the reverse process of boxing, where a value is extracted from an
object. It involves explicitly converting a reference type (object) into a value type. This
operation also involves a copy operation, where the value is copied from the heap into the stack.
Let us understand Boxing and Unboxing in C# with an example. Please have a look at the
following code.

PREPARED BY K. THAMARAI SELVI- AP/ISE 27


22ISE451 / C# and .NET/Module2

The above method contains three lines of code. Now, let us understand what happens when
executing each code line.
Line1: int x = 10;
When this statement is executed, an integer variable x will be created in the Stack memory with
a value of 10. For a better understanding, please have a look at the following diagram.

Line2: object y = x;
When executing this statement, we move the x value, i.e., 10, to an object data type. If you
remember, the object is the parent class for all classes in the .NET Framework. When we move
a value type to a reference type, it is called Boxing. So, here we are moving value type integer
x to reference type object y, so we are performing boxing here.

So, when we move a value type to a reference type or set a value type to a reference type, it is
called Boxing in C#.
Line3: int z = (int)y;
When executing this statement, we move the object value to an integer data type by doing type
casting. When we move a reference type to a value type, it is called Unboxing. So, we are
moving the reference type value, i.e., y, to an integer type, i.e., z, so we are performing
Unboxing here.

PREPARED BY K. THAMARAI SELVI- AP/ISE 28


22ISE451 / C# and .NET/Module2

So, when we move a reference type to a value type or set it to a value type, it is called Unboxing
in C#.
Note: Boxing means you set a value type to a reference type, and unboxing means you set a
reference type to a value type.
Example to Understand Boxing and Unboxing in C#:
Now, we will create a simple example implementing the Boxing and Unboxing using C#
Language, and then we will see how the IL code looks like. So, create a console application
and then modify the Program class as follows:
namespace BoxingUnboxingDemo
{
class Program
{
static void Main(string[] args)
{
int x = 10;
object y = x; //Boxing
int z = (int)y; //Unboxing
}}}
Operators in C#
Operators in C# are symbols that are used to perform operations on operands. For
example, consider the expression 2 + 3 = 5, here 2 and 3 are operands, and + and = are
called operators. So, the Operators in C# are used to manipulate the variables and
values in a program.
int x = 10, y = 20;
int result1 = x + y; //Operator Manipulating Variables, where x and y are variables and
+ is operator
int result2 = 10 + 20; //Operator Manipulating Values, where 10 and 20 are value and +
is operator
Note: In the above example, x, y, 10, and 20 are called Operands. So, the operand may
be variables or values.
Types of Operators in C#:
The Operators are classified based on the type of operations they perform on operands
in C# language. They are as follows:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Unary Operators or
7. Ternary Operator or Conditional Operator

PREPARED BY K. THAMARAI SELVI- AP/ISE 29


22ISE451 / C# and .NET/Module2

In C#, the Operators can also be categorized based on the Number of Operands:
1. Unary Operator: The Operator that requires one operand (variable or value) to
perform the operation is called Unary Operator.
2. Binary Operator: Then Operator that requires two operands (variables or values)
to perform the operation is called Binary Operator.
3. Ternary Operator: The Operator that requires three operands (variables or values)
to perform the operation is called Ternary Operator. The Ternary Operator is also
called Conditional Operator.

For a better understanding of the different types of operators supported in C#


Programming Language, please have a look at the below image.

Arithmetic Operators in C#

In the below example, I am showing how to use Arithmetic Operators with Operand which
are variables. Here, Num1 and Num2 are variables and all the Arithmetic Operators are
working on these two variables.

using System;
namespace OperatorsDemo
{
class Program
{
static void Main(string[] args)
{
int Result;
int Num1 = 20, Num2 = 10;

// Addition Operation
Result = (Num1 + Num2);
Console.WriteLine($"Addition Operator: {Result}" );

// Subtraction Operation
Result = (Num1 - Num2);
Console.WriteLine($"Subtraction Operator: {Result}");

PREPARED BY K. THAMARAI SELVI- AP/ISE 30


22ISE451 / C# and .NET/Module2

// Multiplication Operation
Result = (Num1 * Num2);
Console.WriteLine($"Multiplication Operator:
{Result}");

// Division Operation
Result = (Num1 / Num2);
Console.WriteLine($"Division Operator: {Result}");

// Modulo Operation
Result = (Num1 % Num2);
Console.WriteLine($"Modulo Operator: {Result}");

Console.ReadKey();
}
}
}
Output:

Relational Operators in C#:


The Relational Operators in C# are also known as Comparison Operators. It determines
the relationship between two operands and returns the Boolean results, i.e. true or false
after the comparison. The Different Types of Relational Operators supported by C# are
as follow
using System;
namespace OperatorsDemo
{
class Program
{
static void Main(string[] args)
{
bool Result;
int Num1 = 5, Num2 = 10;

// Equal to Operator
Result = (Num1 == Num2);
Console.WriteLine("Equal (=) to Operator: " +
Result);

// Greater than Operator


Result = (Num1 > Num2);
Console.WriteLine("Greater (<) than Operator: " +
Result);

// Less than Operator

PREPARED BY K. THAMARAI SELVI- AP/ISE 31


22ISE451 / C# and .NET/Module2

Result = (Num1 < Num2);


Console.WriteLine("Less than (>) Operator: " +
Result);

// Greater than Equal to Operator


Result = (Num1 >= Num2);
Console.WriteLine("Greater than or Equal to (>=)
Operator: " + Result);

// Less than Equal to Operator


Result = (Num1 <= Num2);
Console.WriteLine("Lesser than or Equal to (<=)
Operator: " + Result);

// Not Equal To Operator


Result = (Num1 != Num2);
Console.WriteLine("Not Equal to (!=) Operator: " +
Result);

}
}
}
Output:

Logical Operators in C#:


The Logical Operators are mainly used in conditional statements and loops for
evaluating a condition. These operators are going to work with boolean expressions.
The different types of Logical Operators supported in C# are as follows
using System;
namespace OperatorsDemo
{
class Program
{
static void Main(string[] args)
{
bool x = true, y = false, z;

//Logical AND operator


z = x && y;
Console.WriteLine("Logical AND Operator (&&) : " +
z);

//Logical OR operator
z = x || y;
Console.WriteLine("Logical OR Operator (||) : " + z);

PREPARED BY K. THAMARAI SELVI- AP/ISE 32


22ISE451 / C# and .NET/Module2

//Logical NOT operator


z = !x;
Console.WriteLine("Logical NOT Operator (!) : " + z);

Console.ReadKey();
}
}
}
Bitwise Operators in C#:
The Bitwise Operators in C# perform bit-by-bit processing. They can be used with any of
the integer (short, int, long, ushort, uint, ulong, byte) types. The different types of Bitwise
Operators supported in C# are as follows.
Bitwise OR (|)
Bitwise OR operator is represented by |. This operator performs the bitwise OR operation on
the corresponding bits of the two operands involved in the operation. If either of the bits is 1,
it gives 1. If not, it gives 0.
For example,
int a=12, b=25;
int result = a|b; //29
How?
12 Binary Number: 00001100
25 Binary Number: 00011001
Bitwise OR operation between 12 and 25:
00001100
00011001
========
00011101 (it is 29 in decimal)
Note: If the operands are of type bool, the bitwise OR operation is equivalent to the logical
OR operation between them.
using System;
namespace OperatorsDemo
{
class Program
{
static void Main(string[] args)
{
int a = 12, b = 25, Result;
// Bitwise AND Operator
Result = a & b;
Console.WriteLine($"Bitwise AND: {Result}");
// Bitwise OR Operator
Result = a | b;
Console.WriteLine($"Bitwise OR: {Result}");
// Bitwise XOR Operator
Result = a ^ b;
Console.WriteLine($"Bitwise XOR: {Result}");
Console.ReadKey();
}

PREPARED BY K. THAMARAI SELVI- AP/ISE 33


22ISE451 / C# and .NET/Module2

}
}
Output:

Unary Operators in C#:


The Unary Operators in C# need only one operand. They are used to increment or
decrement a value. There are two types of Unary Operators. They are as follows:
1. Increment operators (++): Example: (++x, x++)
2. Decrement operators (–): Example: (–x, x–)

using System;
namespace OperatorsDemo
{
class Program
{
static void Main(string[] args)
{
// Post-Increment
int x = 10;
// Result1 is assigned 10 only,
// x is not updated yet
int Result1 = x++;
//x becomes 11 now
Console.WriteLine("x is {0} and Result1 is {1}", x,
Result1);

// Pre-Increment
int y = 10;
int Result2 = ++y;
//y and Result2 have same values = 11
Console.WriteLine("y is {0} and Result2 is {1}", y,
Result2);
}
}
}

Output:

using System;
namespace OperatorsDemo
{
class Program
{
static void Main(string[] args)

PREPARED BY K. THAMARAI SELVI- AP/ISE 34


22ISE451 / C# and .NET/Module2

{
// Post-Decrement
int x = 10;
// Result1 is assigned 10 only,
// x is not yet updated
int Result1 = x--;
//x becomes 9 now
Console.WriteLine("x is {0} and Result1 is {1}", x,
Result1);

// Pre-Decrement
int y = 10;
int Result2 = --y;
//y and Result2 have same values i.e. 9
Console.WriteLine("y is {0} and Result2 is {1}", y,
Result2);

Console.ReadKey();
}
}
}
Output:

Five Steps to Understand How the Unary Operators Works in C#?

Sample program:

using System;
namespace OperatorsDemo
{
class Program

PREPARED BY K. THAMARAI SELVI- AP/ISE 35


22ISE451 / C# and .NET/Module2

{
static void Main(string[] args)
{
int x = 10, y = 20, z;
z = x++ * --y;
Console.WriteLine($"x={x}, y={y}, z={z}");
Console.ReadKey();
}}}

Let us evaluate the expression z = x++ * –y; by following the above 5 steps:
1. The First step is Pre-Increment or Pre-Decrement. Is there any pre-increment or
pre-decrement in the expression? There is no pre-increment but there is a pre-
decrement in the expression i.e. –y. So, execute that pre-decrement operator
which will decrease the value of y by 1 i.e. now y becomes 19.
2. The second step is Substitution. So, substitute the values of x and y. That means
x will be substituted by 10 and y will be substituted by 19.
3. The third step is Evaluation. So, evaluate the expression i.e. 10 * 19 = 190.
4. The fourth step is the Assignment. So, assign the evaluated value to the given
variable i.e. 190 will be assigned to z. So, now the z value becomes 190.
5. The last step is Post-Increment and Post-Decrement. Is there any post-
increment or post-decrement in the expression? There is no post-decrement but
there is a post-increment in the expression i.e. x++. So, execute that post-
increment which will increase the value of x by 1 i.e. x becomes 11.
So, when you will execute the above program it will print the x, y, and z values as 11, 19,
and 190 respectively.
Ternary Operator in C#:

The Ternary Operator in C# is also known as the Conditional Operator (?:).

It is called ternary because it has three operands or arguments. The first argument is a
comparison argument, the second is the result of a true comparison, and the third is the result
of a false comparison.
Syntax: Condition? first_expression : second_expression;
Example to understand Ternary Operator in C#:
using System;
namespace OperatorsDemo
{
class Program
{
static void Main(string[] args)
{
int a = 20, b = 10, res;
res = ((a > b) ?a : b);
Console.WriteLine("Result = " + res);
Console.ReadKey();
}}}
Output: Result = 20

PREPARED BY K. THAMARAI SELVI- AP/ISE 36


22ISE451 / C# and .NET/Module2

Branching and Looping.

Types of Control Flow Statements in C#:

In C#, the control flow statements are divided into the following three categories:

Selection Statements or Branching Statements: (Examples: if-else, switch


case, nested if-else, if-else ladder)
Iteration Statements or Looping Statements: (Examples: while loop, do-while
loop, for-loop, and foreach loop)
Jumping Statements: (Examples: break, continue, return, goto)

Selection or Branching Control Flow Statements in C#

The Selection or Branching or Decision-Making Statements in C# allows us to control


the flow of program execution based on some condition. It executes different sections of
code depending on a specific condition.

If Statement in C# Language:

It executes a block of statements (one or more instructions) when the condition in the if
block is true and when the condition is false, it will skip the execution of the if block. Using
else block is optional in C#. Following is the syntax to use the if block in the C# language.

using System;
namespace ControlFlowDemo
{
class Program
{

PREPARED BY K. THAMARAI SELVI- AP/ISE 37


22ISE451 / C# and .NET/Module2

static void Main(string[] args)


{
int number;
Console.WriteLine("Enter a Number: ");
number = Convert.ToInt32(Console.ReadLine());
if (number > 10)
{
Console.WriteLine($"{number} is greater than 10 ");
Console.WriteLine("End of if block");
}
Console.WriteLine("End of Main Method");
Console.ReadKey();
}}}

IF-ELSE Statement in C#

Let us write a Program to Check Whether a Number is Even or Odd using If Else Statements
in C# Language. Here we will take the input number from the user and then we will check
whether that number is even or odd using the if-else statement in C# Language. The
following program exactly does the same.

using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a Number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (number % 2 == 0)
{

PREPARED BY K. THAMARAI SELVI- AP/ISE 38


22ISE451 / C# and .NET/Module2

Console.WriteLine($"{number} is an Even Number");


}
else
{
Console.WriteLine($"{number} is an Odd Number");
}
Console.ReadKey();
}}}

using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a Number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (number % 2 == 0)
{
Console.WriteLine($"{number} is an Even Number");
}
else
{
Console.WriteLine($"{number} is an Odd Number");
}
Console.ReadKey();
}
}
}

Ladder if-else statements in C# Language:

In Ladder if-else statements one of the statements will be executed depending upon the truth or
false of the conditions. If the condition1 is true then Statement 1 will be executed, and if condition2

PREPARED BY K. THAMARAI SELVI- AP/ISE 39


22ISE451 / C# and .NET/Module2

is true then statement 2 will be executed, and so on. But if all conditions are false, then the last
statement i.e. else block statement will be executed.

namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int i = 20;
if (i == 10)
{
Console.WriteLine("i is 10");
}
else if (i == 15)
{
Console.WriteLine("i is 15");
}
else if (i == 20)
{
Console.WriteLine("i is 20");
}
else
{
Console.WriteLine("i is not present");
}
Console.ReadKey();

PREPARED BY K. THAMARAI SELVI- AP/ISE 40


22ISE451 / C# and .NET/Module2

}}}

Switch Statements in C#

The switch is a keyword in the C# language, and by using this switch keyword
we can create selection statements with multiple blocks. And the Multiple blocks
can be constructed by using the case keyword.

using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
string str = "C#";
switch (str)
{
case "C#":
case "Java":
case "C":
Console.WriteLine("It’s a Programming Langauge");
break;
case "MSSQL":
case "MySQL":
case "Oracle":
Console.WriteLine("It’s a Database");
break;

PREPARED BY K. THAMARAI SELVI- AP/ISE 41


22ISE451 / C# and .NET/Module2

case "MVC":
case "WEB API":
Console.WriteLine("It’s a Framework");
break;
default:
Console.WriteLine("Invalid Input");
break;
}
Console.ReadKey();
}}}
Output: It’s a Programming Language

Loops in C#

The process of repeatedly executing a statement or group of statements until the condition is
satisfied is called looping. In this case, when the condition becomes false the execution of the
loops terminates. The way it repeats the execution of the statements or instructions will form a
circle that’s why iteration statements are called loops.
Types of Loops in C#
Iteration statements create loops in the program. It repeats the same code several times until a
specified condition is satisfied. Iteration statements execute the same set of instructions until a
termination condition is met. There are four types of looping statements in C#. They are as
follows:
1. For loop
2. For Each Loop
3. While loop
4. Do while loop

(i) While Loop in C#

A while loop is used for executing a statement repeatedly until a given condition
returns false. Here, statements may be a single statement or a block of statements.

using System;

PREPARED BY K. THAMARAI SELVI- AP/ISE 42


22ISE451 / C# and .NET/Module2

namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int x = 1;
while (x <= 5)
{
Console.WriteLine("Value of x:" + x);
x++;
}
Console.ReadKey();
}}}
Output:

(ii) Do While Loop

The do-while loop is a post-tested loop or exit-controlled loop i.e. first it will execute the
loop body and then it will be going to test the condition.

In the below example we are printing the numbers from 1 to 5 using the do while loop.
using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)

PREPARED BY K. THAMARAI SELVI- AP/ISE 43


22ISE451 / C# and .NET/Module2

{
int number = 1;
do
{
Console.Write($"{number} ");
number++;
} while (number <= 5);
Console.ReadKey();
}}}
Output: 1 2 3 4 5

(iii) For Loop in C#

For loop is one of the most commonly used loops in the C# language. If we know the
number of times, we want to execute some set of statements or instructions, then we
should use for loop. For loop is known as a Counter loop. Whenever counting is involved
for repetition, then we need to use for loop.

using System;

namespace ControlFlowDemo

class Program

static void Main(string[] args)

Console.Write("Enter one Integer Number:");

int number = Convert.ToInt32(Console.ReadLine());

for (int counter = 1; counter <= number; counter++)

PREPARED BY K. THAMARAI SELVI- AP/ISE 44


22ISE451 / C# and .NET/Module2

Console.WriteLine(counter);

Console.ReadKey();

}}}
Output:

Infinite Loop in C#:


using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int number = 10;
int i = 1;
for (; i <= number; )
{
Console.WriteLine("Hello C#");
}
Console.ReadKey();
}}}

Output

PREPARED BY K. THAMARAI SELVI- AP/ISE 45


22ISE451 / C# and .NET/Module2

Nested for Loop in C#:


When we created one for loop inside the body of another for loop, then it is said to be
nested for loop in C# language. The syntax to use nested for loop is given below.

.
Foreach Loop in C#

Looping is a way to execute a statement(s) multiple times depending on the result of a


condition. As long the given condition satisfies the loop executes. Once the condition failed,
the loop terminates.
The Foreach Loop in C# is a different kind of loop that doesn’t include initialization,
termination, and increment/decrement characteristics. It uses the collection to take values one
by one and then processes them.
The foreach loop in C# is used to iterate over the elements of a collection. Here, the
collection may be an array or a list or a dictionary, etc. As per the name i.e. foreach, it executes
the loop body for each element present in the array or collection.

PREPARED BY K. THAMARAI SELVI- AP/ISE 46


22ISE451 / C# and .NET/Module2

using System;
namespace ForeachLoopDemo
{
class Program
{
static void Main(string[] args)
{
// creating an array of integer type
int[] IntArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
Console.WriteLine("Print Array Elememnts using Foreach Loop:");
// The foreach loop will run till the last element of the array
foreach (int item in IntArray)
{
Console.WriteLine(item);
}
Console.ReadKey();
}}}

Break Statement in C#

In C#, the break is a keyword. By using the break statement, we can terminate either the loop
body or the switch body

PREPARED BY K. THAMARAI SELVI- AP/ISE 47


22ISE451 / C# and .NET/Module2

using System;
namespace JumpStatementDemo
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine($"I : {i}");
if (i == 5)
{
break;
}
}
Console.WriteLine("Out of for-loop");
Console.ReadKey();
}}}
Output:

Continue Statement in C#
In C#, continue is a keyword. By using the continue keyword, we can skip the statement
execution from the loop body. Like the break statement, the use of the continue statement is
also optional but if you want to use then you can use it only within the loop body.

In the below example, we have provided the condition for the loop to be executed 5 times i.e.
starting from I value 1 to 5. But our requirement is when the I value becomes 3, we need to
skip the loop body execution and continue with the next iteration.

using System;
namespace JumpStatementDemo
{
class Program

PREPARED BY K. THAMARAI SELVI- AP/ISE 48


22ISE451 / C# and .NET/Module2

{
static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue;
}
Console.WriteLine($"I : {i}");
}
Console.ReadKey();
}}}
Output:

Goto Statement in C#
The Goto Statement in C# is used to transfer the control to the labeled statement in the program.
The label is a valid identifier and placed just before the statement from where the control is
transferred. That means the goto Statement provides an unconditional jump from the goto to a
labeled statement in the same function.

Syntax to use goto statement in C# Language:

using System;
namespace JumpStatementDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("1st Statement: ");

PREPARED BY K. THAMARAI SELVI- AP/ISE 49


22ISE451 / C# and .NET/Module2

goto label1; //goto label label1:


Console.WriteLine("2nd Statement: ");
label1: //label:
Console.WriteLine("3rd Statement: ");
Console.WriteLine("End of Main Method Statement: ");
Console.ReadKey();
}
}
}
Output:

SAMPLE PROGRAMS

1.Print the numbers in the following format up to a given number and


that number is entered from the keyboard.
2 4 6 8 …………………….. up to that given number

Program:
using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int i, n;
Console.Write("Enter a Number : ");
n = Convert.ToInt32(Console.ReadLine());
i = 2;

PREPARED BY K. THAMARAI SELVI- AP/ISE 50


22ISE451 / C# and .NET/Module2

while (i <= n)
{
Console.Write($"{i} ");
i = i + 2;
}
Console.ReadKey();
}}}
Output:

2. Example: Enter a number and print the Fibonacci series up to that


number using a while loop in C# Language.
using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int i, n, j, k;
Console.Write("Enter a Number : ");
n = Convert.ToInt32(Console.ReadLine());
i = 0;
j = 1;
Console.Write($"{i} {j}");
k = i + j;
while (k <= n)
{
Console.Write($" {k}");
i = j;
j = k;
k = i + j;
}
Console.ReadKey();
}

PREPARED BY K. THAMARAI SELVI- AP/ISE 51


22ISE451 / C# and .NET/Module2

}
}
Output:

3.Example to Print the Following Format using Nested While Loop in


C# Language

using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
Console.Write("ENTER A NUMBER ");
int n = Convert.ToInt32(Console.ReadLine());
int i = 1;
while (i <= n)
{
Console.WriteLine();
int j = 1;
while (j <= i)
{
Console.Write(j + " ");
j++;
}
i++;
}
Console.ReadKey();

PREPARED BY K. THAMARAI SELVI- AP/ISE 52


22ISE451 / C# and .NET/Module2

}}}

4.Program using Do while- Switch case

using System;

namespace ControlFlowDemo

class Program

static void Main(string[] args)

char Choice;

int MenuOption;

int Number1, Number2;

do

Console.WriteLine("Press 1 for Addition, 2 for Subtraction, 3 for Multiplication, 4 for


Division");

MenuOption = Convert.ToInt32(Console.ReadLine());

switch (MenuOption)

case 1:

Console.WriteLine("Enter the value of two numbers");

Number1 = Convert.ToInt32(Console.ReadLine());

Number2 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine($"Sum Is {Number1 + Number2}");

break;

PREPARED BY K. THAMARAI SELVI- AP/ISE 53


22ISE451 / C# and .NET/Module2

case 2:

Console.WriteLine("Enter the value of two numbers");

Number1 = Convert.ToInt32(Console.ReadLine());

Number2 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine($"Difference Is {Number1 - Number2}");

break;

case 3:

Console.WriteLine("Enter the value of two numbers");

Number1 = Convert.ToInt32(Console.ReadLine());

Number2 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine($"Multiplication Is {Number1 * Number2}");

break;

case 4:

Console.WriteLine("Enter the value of two numbers");

Number1 = Convert.ToInt32(Console.ReadLine());

Number2 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine($"Division Is {Number1 / Number2}");

break;

default:

Console.WriteLine("Invalid choice");

break;

Console.WriteLine("Please Enter Y to continue, any keys to terminate");

Choice = Convert.ToChar(Console.ReadLine());

PREPARED BY K. THAMARAI SELVI- AP/ISE 54


22ISE451 / C# and .NET/Module2

while (Char.ToUpper(Choice) == 'Y');

}}}

Output:

5. Program to enter a number and check whether that no is the perfect


number or not using for loop in C#

A perfect number is a positive integer that is equal to the sum of its positive divisors,
excluding the number itself. For instance, 6 has divisors 1, 2 and 3, and 1 + 2 + 3 = 6, so
6 is a perfect number

using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int number, i, sum = 0;
Console.Write("Enter a Number :");
number = Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= number / 2; i++)
{
if (number % i == 0)

PREPARED BY K. THAMARAI SELVI- AP/ISE 55


22ISE451 / C# and .NET/Module2

sum += i;
}
if (sum == number && number != 0)
Console.WriteLine($"{number} is a Perfect Number");
else
Console.WriteLine($"{number} is not a Perfect Number");
Console.ReadKey();
}
}
}
Output:

6. Program to check whether a number is Armstrong number or not


using for loop C# Language
An Armstrong Number is a number that is equal to the sum of, the power of each digit by
the total number of digits. For example, the numbers such as 0, 1, 153, 370, 371, 407,
1634, 8208, 9474 are Armstrong numbers. Let us have a look at the following diagram
which shows how the Armstrong number is calculated.

using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int digitCount = 0;
int[] digitArray = new int[10];
double sum = 0;
//Step1: Take the input
Console.Write("Enter a Number : ");

PREPARED BY K. THAMARAI SELVI- AP/ISE 56


22ISE451 / C# and .NET/Module2

int number = int.Parse(Console.ReadLine());


//Step3: Store the number in a temporary variable
int temporaryNumber = number;
//Step3: Find the total number of digits in number as well as
//Store each each digit in the digit array
while (number > 0)
{
digitArray[i++] = number % 10;
number = number / 10;
digitCount++;
}
//Step4: Calculate the result
for (i = 0; i < digitCount; i++)
{
sum += Math.Pow(digitArray[i], digitCount);
}
//Step5: Check whether it is prime number or not
if (sum == temporaryNumber)
{
Console.WriteLine($"{temporaryNumber} is an Armstrong number");
}
else
{
Console.WriteLine($"{temporaryNumber} is not an Armstrong number");
}
Console.ReadLine();
}
}
}

Output:

7. Program to enter a number and check whether it is a prime number


or not using for loop in C# Language

A Prime Number is a number that should be greater than 1 and it is only divided by 1 and
itself. In other words, we can say that the prime numbers can’t be divided by other numbers
than itself and 1. For example, 2, 3, 5, 7, 11, 13, 17, 19, and 23…., are the prime numbers.

PREPARED BY K. THAMARAI SELVI- AP/ISE 57


22ISE451 / C# and .NET/Module2

using System;
namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int number, i;
Console.Write("Enter a Number :");
number = Convert.ToInt32(Console.ReadLine());
for (i = 2; i < number; i++)
{
if (number % i == 0)
{
break;
}
}
if (i == number && number >= 2)
{
Console.WriteLine($"{number} is a Prime Number");
}
else
{
Console.WriteLine($"{number} is not a Prime Number");
}
Console.ReadKey();
}
}
}
Output:

Program to print the Fibonacci series up to a given number using for loop in
C# Language
using System;

PREPARED BY K. THAMARAI SELVI- AP/ISE 58


22ISE451 / C# and .NET/Module2

namespace ControlFlowDemo
{
class Program
{
static void Main(string[] args)
{
int number, number1 = 0, number2 = 1, temp;
Console.Write("Enter a Number :");
number = Convert.ToInt32(Console.ReadLine());
if (number >= 1)
{
Console.Write($"{number1} {number2}");
temp = number1 + number2;
for (; temp <= number;)
{
Console.Write($" {temp}");
number1 = number2;
number2 = temp;
temp = number1 + number2;
}
}
else
Console.WriteLine("please enter a number greater than zero");
Console.ReadKey();
}
}
}
Output:

PREPARED BY K. THAMARAI SELVI- AP/ISE 59

You might also like