c#module2
c#module2
NET/Module2
MODULE 2:
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".
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#?
C# is object oriented programming language. It provides a lot of features that are given
below.
1. Simple
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.
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.
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.
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.
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:
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!");
}
}
}
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)
{
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:
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.
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;
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.
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.
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.
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#
• 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!!";
•
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
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
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);
}
}
}
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;
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
}
}
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.
}
}
}
Output:
Output:
{
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:
Console.WriteLine($"str1: {str1}");
Console.WriteLine($"str2: {str2}");
Console.WriteLine($"str3: {str3}");
Console.WriteLine($"str4: {str4}");
Console.ReadKey();
}}}
Output:
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.
5. sum, Height, _value, and abc123, etc. are some examples of the variable name
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}");
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();
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.
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
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.
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.
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.
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.
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
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.
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}");
// 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:
// Equal to Operator
Result = (Num1 == Num2);
Console.WriteLine("Equal (=) to Operator: " +
Result);
}
}
}
Output:
//Logical OR operator
z = x || y;
Console.WriteLine("Logical OR 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();
}
}
}
Output:
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)
{
// 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:
Sample program:
using System;
namespace OperatorsDemo
{
class Program
{
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#:
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
In C#, the control flow statements are divided into the following three categories:
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
{
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)
{
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();
}
}
}
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
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();
}}}
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;
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
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;
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:
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)
{
int number = 1;
do
{
Console.Write($"{number} ");
number++;
} while (number <= 5);
Console.ReadKey();
}}}
Output: 1 2 3 4 5
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
Console.WriteLine(counter);
Console.ReadKey();
}}}
Output:
Output
.
Foreach Loop in C#
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
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
{
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.
using System;
namespace JumpStatementDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("1st Statement: ");
SAMPLE PROGRAMS
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;
while (i <= n)
{
Console.Write($"{i} ");
i = i + 2;
}
Console.ReadKey();
}}}
Output:
}
}
Output:
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();
}}}
using System;
namespace ControlFlowDemo
class Program
char Choice;
int MenuOption;
do
MenuOption = Convert.ToInt32(Console.ReadLine());
switch (MenuOption)
case 1:
Number1 = Convert.ToInt32(Console.ReadLine());
Number2 = Convert.ToInt32(Console.ReadLine());
break;
case 2:
Number1 = Convert.ToInt32(Console.ReadLine());
Number2 = Convert.ToInt32(Console.ReadLine());
break;
case 3:
Number1 = Convert.ToInt32(Console.ReadLine());
Number2 = Convert.ToInt32(Console.ReadLine());
break;
case 4:
Number1 = Convert.ToInt32(Console.ReadLine());
Number2 = Convert.ToInt32(Console.ReadLine());
break;
default:
Console.WriteLine("Invalid choice");
break;
Choice = Convert.ToChar(Console.ReadLine());
}}}
Output:
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)
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:
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 : ");
Output:
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.
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;
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: