0% found this document useful (0 votes)
15 views14 pages

Workshop3 212802

Uploaded by

khadkaankush10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views14 pages

Workshop3 212802

Uploaded by

khadkaankush10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Workshop

3
Workshop Exercise 1:
Create a method named "GetFullName" that takes two string
parameters, "firstName" and "lastName." The method should return
the full name by concatenating the first and last names with a space in
between. Handle the cases where either the first name or the last name
is empty and return the non-empty name. Test the method by calling it
with different arguments and printing the result.
using System;

class Program
{
static void Main()
{
// Test cases
Console.WriteLine(GetFullName("John", "Doe")); // Output: "John Doe"
Console.WriteLine(GetFullName("Jane", "")); // Output: "Jane"
Console.WriteLine(GetFullName("", "Smith")); // Output: "Smith"
Console.WriteLine(GetFullName("", "")); // Output: ""

// Additional tests
Console.WriteLine(GetFullName("Alice", "Johnson")); // Output: "Alice Johnson"
Console.WriteLine(GetFullName("", "Brown")); // Output: "Brown"
}

static string GetFullName(string firstName, string lastName)


{
if (string.IsNullOrEmpty(firstName)) return lastName;
if (string.IsNullOrEmpty(lastName)) return firstName;

return $"{firstName} {lastName}";


}
}
Workshop Exercise 2:
1. Define a local function named "Add" inside the Main method
that takes two integer parameters, "x" and "y," and returns their
sum. Call the "Add" function with appropriate arguments and
print the result.
using System;

class Program
{
static void Main()
{
// Define the local function
int Add(int x, int y)
{
return x + y;
}

// Call the local function with appropriate arguments


int result1 = Add(5, 3);
int result2 = Add(10, 20);

// Print the results


Console.WriteLine($"Result of Add(5, 3): {result1}"); // Output: Result of Add(5, 3): 8
Console.WriteLine($"Result of Add(10, 20): {result2}"); // Output: Result of Add(10, 20): 30
}
}
2. Implement a recursive method named "RecursiveFactorial" that
calculates the factorial of a given integer "n." Test the method
by calling it with different values of "n" and printing the result.
using System;

class Program
{
static void Main()
{
// Test cases for RecursiveFactorial
Console.WriteLine($"Factorial of 5: {RecursiveFactorial(5)}"); // Output: 120
Console.WriteLine($"Factorial of 7: {RecursiveFactorial(7)}"); // Output: 5040
Console.WriteLine($"Factorial of 0: {RecursiveFactorial(0)}"); // Output: 1
Console.WriteLine($"Factorial of 1: {RecursiveFactorial(1)}"); // Output: 1
}

static int RecursiveFactorial(int n)


{
if (n < 0)
{
throw new ArgumentException("Factorial is not defined for negative numbers.");
}
if (n == 0 || n == 1)
{
return 1;
}
return n * RecursiveFactorial(n - 1);
}
}
Workshop Exercise 3:
1. Create a method named "CalculateSum" that takes two integer
parameters, "a" and "b," and returns their sum. Test the
method by calling it with different arguments and printing the
result.
using System;

class Program
{
static void Main()
{
// Test cases for CalculateSum
Console.WriteLine($"Sum of 5 and 3: {CalculateSum(5, 3)}"); // Output: 8
Console.WriteLine($"Sum of 10 and 20: {CalculateSum(10, 20)}"); // Output: 30
Console.WriteLine($"Sum of -5 and 15: {CalculateSum(-5, 15)}"); // Output: 10
Console.WriteLine($"Sum of 0 and 0: {CalculateSum(0, 0)}"); // Output: 0
}

static int CalculateSum(int a, int b)


{
return a + b;
}
}
2. Implement a method named "PrintMultiples" that takes an
integer parameter "n" and prints the first five multiples of "n" to
the console. Test the method by calling it with different values of
"n".
using System;

class Program
{
static void Main()
{
// Test cases for PrintMultiples
PrintMultiples(3); // Output: 3, 6, 9, 12, 15
PrintMultiples(5); // Output: 5, 10, 15, 20, 25
PrintMultiples(7); // Output: 7, 14, 21, 28, 35
PrintMultiples(1); // Output: 1, 2, 3, 4, 5
}

static void PrintMultiples(int n)


{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(n * i);
}
}
}
Workshop Exercise:
True or False: Optional parameters must appear after all required
parameters. Explain your answer.
using System;

class Program
{
static void Main()
{
// Calling the method with only the required parameter
DisplayMessage("Hello");

// Calling the method with both the required and optional parameters
DisplayMessage("Hello", "World");
}

static void DisplayMessage(string message, string prefix = "Info")


{
Console.WriteLine($"{prefix}: {message}");
}
}
Workshop Exercise:
True or False: Named arguments can be used after positional
arguments. Provide a brief explanation.
using System;

class Program
{
static void Main()
{
// Correct usage: All positional arguments come before named arguments
PrintDetails("John", 30, city: "New York");

// Incorrect usage: Named argument used before positional arguments


// PrintDetails(name: "John", 30, city: "New York"); // This will cause a compile-time error
}

static void PrintDetails(string name, int age, string city)


{
Console.WriteLine($"Name: {name}, Age: {age}, City: {city}");
}
}
Workshop Exercise:
Explain the meaning and appropriate usage of the following common
exception types in C#: NotImplementedException,
InvalidOperationException, ArgumentNullException.
1)
public void SomeMethod()
{
throw new NotImplementedException("This method is not implemented yet.");
}

2)public class BankAccount


{
public bool IsClosed { get; set; }

public void Withdraw(decimal amount)


{
if (IsClosed)
{
throw new InvalidOperationException("Cannot perform operations on a closed account.");
}

// Perform withdrawal
}
}

Test with this line


BankAccount account = new BankAccount();
account.IsClosed = true; // Simulating a closed account
account.Withdraw(100);

output:
Unhandled exception. System.InvalidOperationException: Cannot perform operations on a closed account.
Workshop Exercise:
Explain the concept of recursion in methods. Provide an example of a
recursive method in C#.

using System;

class Program
{
static void Main()
{
// Test cases for RecursiveFactorial
Console.WriteLine($"Factorial of 5: {RecursiveFactorial(5)}"); // Output: 120
Console.WriteLine($"Factorial of 7: {RecursiveFactorial(7)}"); // Output: 5040
Console.WriteLine($"Factorial of 0: {RecursiveFactorial(0)}"); // Output: 1
}

static int RecursiveFactorial(int n)


{
// Base Case
if (n == 0 || n == 1)
{
return 1;
}
// Recursive Case
return n * RecursiveFactorial(n - 1);
}
}
Explain the concept of exception handling in C#. What is the purpose
of try-catch blocks? Provide an example of using try-catch to handle a
potential exception in a method.
using System;

class Program
{
static void Main()
{
// Test the Divide method with different inputs
DivideNumbers(10, 2); // Valid division
DivideNumbers(10, 0); // Division by zero
}

static void DivideNumbers(int numerator, int denominator)


{
try
{
// Attempt to perform division
int result = numerator / denominator;
Console.WriteLine($"Result of {numerator} / {denominator} = {result}");
}
catch (DivideByZeroException ex)
{
// Handle division by zero error
Console.WriteLine($"Error: Cannot divide by zero. {ex.Message}");
}
catch (Exception ex)
{
// Handle any other type of exception
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
finally
{
// This block will always execute
Console.WriteLine("Division operation complete.");
}
}
}
Recursive:

using System;

class Program

static void Main(string[] args)

var p = new Program();

int result = p.RecursiveFactorial(4);

Console.WriteLine($"Factorial of 4 is: {result}");

int RecursiveFactorial(int n)

if (n < 2)

return 1;

return n * RecursiveFactorial(n - 1);

}
Conrolling Parametrs:

using System;

class Program

void PassingParameters(int x, ref int y, out int z)

x++;

y++;

z = 30; // must be initialized inside the method

z++;

static void Main(string[] args)

var p = new Program();

int a = 10;

int b = 20;

Console.WriteLine($"Before: a = {a}, b = {b}"); // Before: a = 10, b = 20

p.PassingParameters(a, ref b, out int c);

Console.WriteLine($"After: a = {a}, b = {b}, c = {c}"); // After: a = 10, b = 21, c = 31

You might also like