OOP in C# Tasks
OOP in C# Tasks
Lab Manual 1
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!
7. Enter a name for your project, and click on the Create button:
8. Visual Studio will automatically generate some code for your project:
Output: Run the program by pressing the F5 button on your keyboard (or click
on "Debug" -> "Start Debugging"). This will compile and execute your code.
The result will look something to this:
Congratulations! You have now written and executed your first C# program.
C# Syntax:
In the previous chapter, we created a C# file called Program.cs, and we used
the following code to print "Hello World" to the screen.
Code Explanation:
Line 1: using System means that we can use classes from the System namespace.
Line 2: A blank line. C# ignores white space. However, multiple lines makes the code
more readable.
Line 3: namespace is used to organize your code, and it is a container for classes and
other namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to your
program. Every line of code that runs in C# must be inside a class. In our example, we
named the class Program.
Line 7: Another thing that always appear in a C# program, is the Main method. Any code
inside its curly brackets {} will be executed. You don't have to understand the keywords
before and after Main. You will get to know them bit by bit while reading this tutorial.
Line 9: Console is a class of the System namespace, which has a WriteLine() method
that is used to output/print text. In our example it will output "Hello World!".
If you omit the using System line, you would have to write System.Console.WriteLine() to print/output
text.
C# Output
To output values or print text in C#, you can use the WriteLine() method:
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).
C# Multi-line Comments
Multi-line comments start with /* and ends with */.
Example
/* The code below will print the words Hello World
Console.WriteLine("Hello World!");
C# Variable
C# Variables
Variables are containers for storing data values.
In C#, there are different types of variables (defined with different keywords),
for example:
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type string and assign it the value "Sana":
Console.WriteLine(name);
Code:
// Type your username and press enter
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and
store it in the variable
// Print the value of the variable (userName), which will display the
input value
C# Operator:
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example:
int x = 100 + 50;
The + operator is often used to add together two values, like in the example
above, it can also be used to add together a variable and a value, or a variable
and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:
Assignment Operator
int x = 10;
x += 5;
Operato Example
r
= x=5
+= x += 3
-= x -= 3
*= x *= 3
/= x /= 3
%= x %= 3
&= x &= 3
|= x |= 3
^= x ^= 3
>>= x >>= 3
<<= x <<= 3
Question 1: Create a C# program that displays the result of adding two numbers
Solution:
Explanation
Solution:
Explanation
Question 3: Imagine you are developing a simple calculator application in C#. Your program
should greet the user, perform a calculation based on user input, and display the result. Here are
the specific tasks you need to accomplish:
Display Greeting:
Display a welcome message to the user when the program starts. The message should include a
friendly greeting and an explanation of the calculator's purpose.
Declare Variables:
Declare two variables of type double named num1 and num2.
Take User Input:
Prompt the user to enter the first number and store it in the variable num1.
Prompt the user to enter the second number and store it in the variable num2.
Perform Calculation:
Calculate the sum of num1 and num2.
Display Result:
Display a message that includes the user's name (obtained through input), the entered numbers,
and the calculated sum
Write a complete C# program that fulfills the requirements of this scenario. Ensure that your
program is well-structured and user-friendly.
Solution:
Explanation:
1. Using Statement:
using System;
This line includes the System namespace, which contains fundamental classes and provides access to the
Console class for input and output operations.
2. Class Declaration:
The entry point of the program. Execution starts from the Main method.
4. Display Greeting:
Prints a welcome message to the console, explaining the purpose of the calculator.
5. Declare Variables:
Prompts the user to enter their name and the two numbers. User input is obtained using
Console.ReadLine(), and the entered numbers are converted to double using double.Parse().
7. Perform Calculation:
Calculates the sum of num1 and num2 and stores it in the variable sum.
8. Display Result:
Prints the entered numbers and the calculated sum to the console. The nameof operator is used to
dynamically get the variable names.
9. Closing Message:
Prints a closing message to thank the user for using the calculator.
Question 5: Develop a user-friendly Speed Calculator program in C#. Begin with a welcoming
message explaining the program's purpose. Prompt users to input the distance traveled (in
kilometers) and time taken for a journey (in hours). Ensure that the entered time is greater than
zero; display an error message and terminate the program if not. Calculate and display the speed
in kilometers per hour using the formula: speed = distance / time. Conclude with a closing
message thanking users for using the Speed Calculator. Emphasize clear user prompts,
meaningful variable names, and error handling in your program.
Answer:
class SpeedCalculator
{
static void Main()
{
// Display Greeting
Console.WriteLine("Welcome to the Speed Calculator!");
// Declare Variables
double distance, time, speed;
// Perform Calculation
speed = distance / time;
// Display Result
Console.WriteLine($"\nDistance: {distance} kilometers");
Console.WriteLine($"Time: {time} hours");
Console.WriteLine($"Speed: {speed} km/h");
// Closing Message
Console.WriteLine("\nThank you for using the Speed Calculator!");
}
}
}
Solution:
if (unit == 'F')
{ convert a string representation of a
// Convert Fahrenheit to Celsius
number to its equivalent numeric
convertedTemperature = (temperature - 32) * 5 / 9;
Console.WriteLine($"Equivalent Celsius temperature: value. In particular, this line of code
{convertedTemperature:F2}°C"); uses double.Parse:”
}
else if (unit == 'C')
{
// Convert Celsius to Fahrenheit
convertedTemperature = (temperature * 9 / 5) + 32;
Console.WriteLine($"Equivalent Fahrenheit
temperature: {convertedTemperature:F2}°F");
}
else
{
Console.WriteLine("Invalid temperature unit. Please
enter 'F' or 'C'.");
}
// Closing Message
Console.WriteLine("\nThank you for using the
Temperature Converter!");
}
}
C# If …. Else:
C# supports the usual logical C# has the following conditional statements:
conditions from mathematics: Use if to specify a block of code to be
executed, if a specified condition is
Less than: a < b
true
Less than or equal to: a <= b
Use else to specify a block of code to
Greater than: a > b
be executed, if the same condition is
Greater than or equal to: a >=
false
b
Use else if to specify a new condition
Equal to a == b
to test, if the first condition is false
Not Equal to: a != b
Use switch to specify many
alternative blocks of code to be
executed
The if Statement:
Use the if statement to specify a block of C# code to be executed if a condition
is True.
In the example below, we test two values to find out if 20 is greater than 18. If
the condition is True, print some text:
Example
if (20 > 18)
Syntax
if (condition)
else
{
// block of code to be executed if the condition is False
Explanation:
In the example above, time (20) is greater than 18, so the condition is False.
Because of this, we move on to the else condition and print to the screen
"Good evening". If the time was less than 18, the program would print "Good
day".
Syntax
if (condition1)
else if (condition2)
else
class Condition
{
static void Main()
{
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
// Outputs "Good evening."
}
}
}
Explanation:
In the example above, time (22) is greater than 10, so the first
condition is False. The next condition, in the else if statement, is also False, so
we move on to the else condition since condition1 and condition2 is
both False - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
Nested if Statements:
In C#, you can nest if statements within each other to create a hierarchy of conditions. This
means that you can have an if statement inside another if statement. The inner if statement
will only be executed if the outer if condition is true
Problem Scenario: Open Ended Question
Problem 1: Grade Classifier
Write a C# program that classifies a student's grade based on the percentage they
scored in an exam. Prompt the user to input their percentage and use conditional
statements to determine and display their grade (A, B, C, D, or F).
C# Switch:
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression)
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
The example below uses the weekday number to calculate the weekday name:
class NestedIfExample
{
static void Main()
{
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}
// Outputs "Thursday" (day 4)
}
}
Loops:
Loops can execute a block of code if a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make
code more readable.
C# While Loop
The while loop loops through a block of code as long as a specified condition
is True:
Syntax
while (condition)
Example:
int i = 0;
while (i < 5)
Console.WriteLine(i);
i++;
}
In the example below, the code in the loop will run, over and over
again, as long as a variable (i) is less than 5
Syntax
do
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
C# For Loop
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3)
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Explanation:
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true,
the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Nested Loops
It is also possible to place a loop inside another loop. This is called
a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer
loop":
Syntax
foreach (type variableName in arrayName)
{
C# Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
string[] universities;
To insert values to it, we can use an array literal - place the values in a comma-
separated list, inside curly braces:
Arrays can have any number of dimensions. The most common are two-
dimensional arrays (2D).
Two-Dimensional Arrays
To create a 2D array, add each array within its own set of curly braces, and
insert a comma (,) inside the square brackets:
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
numbers is now an array with two arrays as its elements. The first array
element contains three elements: 1, 4 and 2, while the second array
element contains 3, 6 and 8. To visualize it, think of the array as a table with
rows and columns:
This statement accesses the value of the element in the first row
(0) and third column (2) of the numbers array:
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Console.WriteLine(i);
}
Array Problem Scenario: (Array Sum and Average)
Write a C# program that calculates the sum and average of elements in
an array. Prompt the user to input the size of the array and its elements,
and then use a for loop to calculate the sum and average. Display both
results.
Loop Problem Scenario:
Develop a C# program that doubles each element in an array using a for loop.
Prompt the user to input the size of the array and its elements, and then use a for
loop to double each element and display the modified array.
Array For Each Loop Problem Scenario:
Create a C# program that squares each element in an array using a foreach loop.
Prompt the user to input the size of the array and its elements, and then use a
foreach loop to square each element and display the modified array.
Multi-Dimensional Array Problem Scenario:
Write a C# program that performs addition on two matrices. Prompt the user to
input the size of the matrices and their elements, and then use nested for loops to
add the corresponding elements and display the resulting matrix.
Loop with Array Problem Scenario:
Create a C# program that finds the largest element in an array using a for loop.
Prompt the user to input the size of the array and its elements, and then use a for
loop to determine and display the largest element.