You are on page 1of 42

Object Oriented Programming

Lab Manual 1

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!

The four basic principles of object-oriented programming are:

 Abstraction Modeling the relevant attributes and interactions of entities as classes


to define an abstract representation of a system.
 Encapsulation Hiding the internal state and functionality of an object and only
allowing access through a public set of functions.
 Inheritance Ability to create new abstractions based on existing abstractions.
 Polymorphism Ability to implement inherited properties or methods in different
ways across multiple abstractions.
1. Installing Visual Studio 2022 (Community Version)

1. In our tutorial, we will use Visual Studio


Community, which is free to download from
https://visualstudio.microsoft.com/vs/community/.

2. Once the Visual Studio Installer is


downloaded and installed, choose the .NET
workload and click on
the Modify/Install button:

3. After Installing , Open Visual Studio.

4. After the installation is complete, click on


the Launch button to get started with
Visual Studio.

On the start window, choose Create a new


project:

5. Then click vison the "Install more tools


and features" button: 6. Choose "Console App (.NET
Core)" from the list and click on
the Next button:

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.

Note: Every C# statement ends with a semicolon ;.

Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.

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).

The above code uses a single-line comment before a line of code.

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# Variable

C# Variables
Variables are containers for storing data values.

In C#, there are different types of variables (defined with different keywords),
for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -


123
 double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes.
 string - stores text, such as "Hello World". String values are surrounded
by double quotes.
 bool - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:

type variableName = value;

Where type is a C# type (such as int or string), and variableName is the


name of the variable (such as x or name). The equal sign is used to assign
values to the variable.

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":

string name = "Sana";

Console.WriteLine(name);

Add Code on VS IDE:


Code: Output:
C# datatype:
int myNum = 5; //
Integer (whole number)

double myDoubleNum = 5.99D; //


Floating point number
Other data types with variable
declaration char myLetter = 'D'; //
Character

bool myBool = true; //


Boolean

string myText = "Hello"; //


String

Get User Input:


 You have already learned that Console.WriteLine() is used to output (print)
values.

 Now we will use Console.ReadLine() to get user input.

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

string userName = Console.ReadLine();

// Print the value of the variable (userName), which will display the
input value

Console.WriteLine("Username is: " + userName);

Code With Output:

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)

int sum2 = sum1 + 250; // 400 (150 + 250)

int sum3 = sum2 + sum2; // 800 (400 + 400)

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:

Operator Name Description

+ Addition Adds together two values

- Subtraction Subtracts one value from another

* Multiplication Multiplies two values

/ Division Divides one value by another

% Modulus Returns the division remainder

++ Increment Increases the value of a variable by 1


-- Decrement Decreases the value of a variable by 1

Assignment Operator

int x = 10;

x += 5;

A list of all assignment operators:

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

Task (Close Ended): Scenario Based

Question 1: Create a C# program that displays the result of adding two numbers

Solution:
Explanation

Task (Close Ended): Scenario Based

Question 2: Write a C# program that swaps the values of two variables.

Solution:

Explanation

Task (Close Ended): Scenario Based

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:

class CalculatorProgram { // ... }

Defines a class named CalculatorProgram.


3. Main Method:

static void Main() { // ... }

The entry point of the program. Execution starts from the Main method.

4. Display Greeting:

Console.WriteLine("Welcome to the Simple Calculator App!"); Console.WriteLine("This calculator will


help you add two numbers.\n");

Prints a welcome message to the console, explaining the purpose of the calculator.

5. Declare Variables:

double num1, num2;

Declares two variables of type double named num1 and num2.

6. Take User Input:

Console.Write("Enter your name: "); string userName = Console.ReadLine(); Console.Write($"Hello,


{userName}! Enter the first number: "); num1 = double.Parse(Console.ReadLine()); Console.Write("Enter
the second number: "); num2 = double.Parse(Console.ReadLine());

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:

double sum = num1 + num2;

Calculates the sum of num1 and num2 and stores it in the variable sum.

8. Display Result:

Console.WriteLine($"\n{nameof(num1)}: {num1}"); Console.WriteLine($"{nameof(num2)}: {num2}");


Console.WriteLine($"The sum of {num1} and {num2} is: {sum}");

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:

Console.WriteLine("\nThank you for using the calculator!");

Prints a closing message to thank the user for using the calculator.

10. End of Program:

The Main method completes, and the program finishes execution.


OP Question 4 :
Simple Calculator
Create a C# program for a simple calculator. The program should prompt the user to enter two
numbers and an operation (+, -, *, /). Perform the corresponding operation and display the result.

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;

// Take User Input


Console.Write("Enter the distance (in kilometers): ");
distance = double.Parse(Console.ReadLine());

Console.Write("Enter the time (in hours): ");


time = double.Parse(Console.ReadLine());

// Validate Time Input


if (time <= 0)
{
Console.WriteLine("Error: Time must be greater than zero.");
return; // Exit the program
}

// 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:

Question 6: Temperature Converter Design a C# program that converts


temperatures between Fahrenheit
and Celsius. Prompt the user to
input a temperature along with its
unit (F or C), and then convert and
display the equivalent temperature
in the other unit.

class TemperatureConverter “ In the context of the provided C#


{ code, the Parse method is used to
static void Main()
{
// Display Greeting
Console.WriteLine("Welcome to the Temperature
Converter!");

// Prompt User for Input


Console.Write("Enter the temperature value: ");
double temperature =
double.Parse(Console.ReadLine());

Console.Write("Enter the temperature unit (F for


Fahrenheit, C for Celsius): ");
char unit = char.ToUpper(Console.ReadKey().KeyChar);
Console.WriteLine(); // Move to the next line

// Convert and Display


double convertedTemperature = 0;

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)

Console.WriteLine("20 is greater than 18");

Code with Output:


Explanation:

In the example above we use two variables, x and y, to test whether x is


greater than y (using the > operator). As x is 20, and y is 18, and we know that
20 is greater than 18, we print to the screen that "x is greater than y".

The else Statement


Use the else statement to specify a block of code to be executed if the condition
is False.

Syntax
if (condition)

// block of code to be executed if the condition is True

else

{
// block of code to be executed if the condition is False

Code with Output

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".

The else if Statement:


Use the else if statement to specify a new condition if the first condition
is False.

Syntax
if (condition1)

// block of code to be executed if condition1 is True

else if (condition2)

// block of code to be executed if the condition1 is false and


condition2 is True

else

// block of code to be executed if the condition1 is false and


condition2 is False

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).

Problem 2: Ticket Pricing


Develop a C# program for a movie ticket pricing system. Prompt the user to enter
their age, and use conditional statements to determine and display the ticket
price based on the following criteria:
 Children (age 0-12): $5
 Teenagers (age 13-17): $8
 Adults (age 18-64): $12
 Seniors (65 and older): $7
Problem 3: Positive/Negative/Zero Checker
Create a C# program that checks whether a given number is positive, negative, or
zero. Prompt the user to input a number and use conditional statements to
determine and display the result.
Problem 4: Leap Year Checker
Write a C# program that checks if a given year is a leap year. Prompt the user to
input a year, and use conditional statements to determine and display whether it
is a leap year or not.
Problem 5: Triangle Type Identifier
Develop a C# program that identifies the type of a triangle based on its three side
lengths. Prompt the user to input the lengths of the three sides, and use
conditional statements to determine and display whether it's an equilateral,
isosceles, or scalene triangle.
Problem 6: Password Strength Checker
Create a C# program that checks the strength of a password. Prompt the user to
enter a password and use conditional statements to assess and display whether it
is weak, medium, or strong based on certain criteria (e.g., length, use of
uppercase letters, numbers, and special characters).
Problem 7: Time of Day Greeting
Write a C# program that greets the user based on the time of day. Prompt the
user to input the current hour (in 24-hour format), and use conditional
statements to display a personalized greeting for morning, afternoon, evening, or
night.
Problem 8: Credit Card Validator
Develop a C# program that checks the validity of a credit card number. Prompt
the user to enter a credit card number and use conditional statements to
determine and display whether it is a valid or invalid card number based on a
simple algorithm (e.g., Luhn's algorithm).
Problem 9: BMI Calculator
Create a C# program that calculates and categorizes the Body Mass Index (BMI) of
a person. Prompt the user to input their weight (in kilograms) and height (in
meters), and use conditional statements to calculate and display whether they
are underweight, normal weight, overweight, or obese.
Problem 10: Time Converter
Write a C# program that converts a given time in hours to its equivalent in
minutes or seconds based on user choice. Prompt the user to enter a time in
hours and choose whether they want the result in minutes or seconds and use
conditional statements to perform the conversion.

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;

This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed.

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)

// code block to be executed

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

The Do/While Loop

 The do/while loop is a variant of the while loop.


 This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition is
true.

Syntax
do

// code block to be executed

}
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)

// code block to be executed


}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Explanation:

Statement 1 sets a variable before the loop starts (int i = 0).

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":

The foreach Loop


There is also a foreach loop, which is used exclusively to loop through elements
in an array:

Syntax
foreach (type variableName in arrayName)
{

// code block to be executed

For Loop Problem Scenario: (Problem 1: Factorial Calculator)


Write a C# program using a for loop to calculate the factorial of a given positive
integer. Prompt the user to input a number, and then use the for loop to calculate
and display its factorial.
Foreach Loop Problem Scenario: (Problem 2: Array Sum Calculator)
Develop a C# program that calculates the sum of elements in an array using a
foreach loop. Prompt the user to input the size of the array and its elements, and
then use the foreach loop to calculate and display the sum.
While Loop Problem Scenario: (Problem 3: Number Reversal)
Create a C# program that reverses a given positive integer using a while loop.
Prompt the user to input a number, and then use the while loop to reverse the
digits and display the result.
Do-While Loop Problem Scenario: (Problem 4: Guess the Number
Game)
Write a C# program for a simple "Guess the Number" game using a do-while loop.
Generate a random number between 1 and 100, and prompt the user to guess
the number. Provide feedback on whether the guess is too high, too low, or
correct. Continue the game until the user guesses correctly.
Nested Loop Problem Scenario: (Problem 5: Multiplication Table)
Develop a C# program that generates a multiplication table up to a specified
number using nested for loops. Prompt the user to input the number of rows and
columns, and then use nested loops to generate and display the multiplication
table.
Loop with Conditional Statements Problem Scenario: Problem
6: Vowel Counter
Write a C# program that counts the number of vowels in a given string using a for
loop and conditional statements (if). Prompt the user to input a string, and then
use the for loop to iterate through each character, checking if it's a vowel and
incrementing the count.

C# Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets:

string[] universities;

We have now declared a variable that holds an array of strings.

To insert values to it, we can use an array literal - place the values in a comma-
separated list, inside curly braces:

string[] universities = {"UET", "UMT", "UOL", "PU"};


Access the Elements of an Array
You access an array element by referring to the index number.

This statement accesses the value of the first element in universities:

Loop Through an Array


 You can loop through the array elements with the for loop, and use
the Length property to specify how many times the loop should run.

The following example outputs all elements in the universities array:


Sort an Array
There are many array methods available, for example Sort(), which sorts an
array alphabetically or in an ascending order:
System.Linq Namespace
Other useful array methods, such as Min, Max, and Sum, can be found in
the System.Linq namespace:
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known as single
dimension arrays. These are great, and something you will use a lot while
programming in C#. However, if you want to store data as a tabular form, like a
table with rows and columns, you need to get familiar with multidimensional
arrays.

 A multidimensional array is basically an array of arrays.

 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:

Access Elements of a 2D Array


To access an element of a two-dimensional array, you must specify two indexes:
one for the array, and one for the element inside that array. Or better yet, with
the table visualization in mind; one for the row and one for the column (see
example below).

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} };

Console.WriteLine(numbers[0, 2]); // Outputs 2


Loop Through a 2D Array
You can easily loop through the elements of a two-dimensional array with
a foreach loop:

Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

foreach (int i in numbers)

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.

You might also like