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

Experiments: in C#: 1. Implement Jagged Array

Uploaded by

rohitkumar74348
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)
31 views

Experiments: in C#: 1. Implement Jagged Array

Uploaded by

rohitkumar74348
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/ 40

Sub: - .

NET Programming Lab(CS-755) List of


experiments: in C#
1. Implement Jagged Array
Description:
A jagged array is an array of arrays where each "inner" array can be of a
different size.
Code Implementation:
csharp
Copy code
using System;

class JaggedArrayExample
{
static void Main()
{
// Declare the jagged array
int[][] jaggedArray = new int[3][];

// Initialize each inner array with different sizes


jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
// Iterate and display elements
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write("Row {0}: ", i);
foreach (var item in jaggedArray[i])
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}
}
Explanation:
 A jagged array allows arrays of different sizes.
 The outer loop traverses each array, while the inner foreach loop
iterates over its elements.

2. Prime Number Check and Displaying Largest Factor


Description:
Check if a number is prime. If not, find and display the largest factor of
the number.
Code Implementation:
csharp
using System;
class PrimeOrLargestFactor
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
if (IsPrime(number))
{
Console.WriteLine("{0} is a prime number.", number);
}
else
{
Console.WriteLine("The largest factor of {0} is {1}.", number,
LargestFactor(number));
}
}
static bool IsPrime(int num)
{
if (num <= 1) return false;
for (int i = 2; i <= Math.Sqrt(num); i++)
{
if (num % i == 0) return false;
}
return true;
}

static int LargestFactor(int num)


{
for (int i = num / 2; i >= 2; i--)
{
if (num % i == 0) return i;
}
return 1; // For prime numbers
}
}

3. Program to Demonstrate Boxing and Unboxing


Description:
Boxing is the process of converting a value type (e.g., int) to an object
type. Unboxing is the reverse process.
Code Implementation:
csharp
Copy code
using System;
class BoxingUnboxingExample
{
static void Main()
{
// Boxing
int num = 123;
object boxedNum = num;
Console.WriteLine("Boxed value: {0}", boxedNum);

// Unboxing
int unboxedNum = (int)boxedNum;
Console.WriteLine("Unboxed value: {0}", unboxedNum);
}
}
Explanation:
 The integer num is converted into an object type (boxing).
 boxedNum is cast back to an integer (unboxing).

4. List All Substrings of a Given String


Description:
Generate and print all possible substrings of a given string.
Code Implementation:
csharp
Copy code
using System;
class SubstringExample
{
static void Main()
{
Console.Write("Enter a string: ");
string input = Console.ReadLine();
for (int i = 0; i < input.Length; i++)
{
for (int j = 1; j <= input.Length - i; j++)
{
Console.WriteLine(input.Substring(i, j));
}
}
}
}
Explanation:
 Two nested loops are used to generate all possible substrings of
the input string.
5. Program to Implement Multicast Delegates
Description:
A multicast delegate can reference multiple methods and invoke them
in sequence.
Code Implementation:
csharp
Copy code
using System;
delegate void PrintDelegate(string message);
class MulticastDelegateExample
{
static void PrintUppercase(string msg)
{
Console.WriteLine(msg.ToUpper());
}

static void PrintLowercase(string msg)


{
Console.WriteLine(msg.ToLower());
}

static void Main()


{
PrintDelegate del = PrintUppercase;
del += PrintLowercase;

// Invoking multicast delegate


del("Hello Multicast!");
}
}
Explanation:
 A delegate PrintDelegate is used to call two methods.
 The += operator adds methods to the invocation list.

6. Add Given Days to Local System Date


Description:
Add a specified number of days to the current system date and display
the result.
Code Implementation:
csharp

using System;
class DateManipulation
{
static void Main()
{
Console.Write("Enter number of days to add: ");
int daysToAdd = int.Parse(Console.ReadLine());

DateTime currentDate = DateTime.Now;


DateTime newDate = currentDate.AddDays(daysToAdd);

Console.WriteLine("Current Date: {0}", currentDate);


Console.WriteLine("New Date: {0}", newDate);
}
}
Explanation:
 DateTime.Now retrieves the current date.
 AddDays method is used to add a specified number of days.

7. Multiple Inheritance Using Interfaces


Description:
Demonstrate multiple inheritance using interfaces in C#.
Code Implementation:
csharp
using System;
interface IAnimal
{
void Speak();
}
interface IWalk
{
void Walk();
}

class Dog : IAnimal, IWalk


{
public void Speak()
{
Console.WriteLine("Dog says: Woof!");
}

public void Walk()


{
Console.WriteLine("Dog is walking.");
}
}

class MultipleInheritanceExample
{
static void Main()
{
Dog dog = new Dog();
dog.Speak();
dog.Walk();
}
}
Explanation:
 C# does not support multiple inheritance through classes, but it
does through interfaces.
 The Dog class implements both IAnimal and IWalk.

8. Demonstrate Constructors and Inheritance


Description:
Create a base class and derived class to show constructor chaining in
inheritance.
Code Implementation:
csharp
Copy code
using System;

class BaseClass
{
public BaseClass()
{
Console.WriteLine("Base class constructor called.");
}
}

class DerivedClass : BaseClass


{
public DerivedClass()
{
Console.WriteLine("Derived class constructor called.");
}
}

class InheritanceExample
{
static void Main()
{
DerivedClass obj = new DerivedClass();
}
}
Explanation:
 When an object of the DerivedClass is created, the BaseClass
constructor is called first due to inheritance.

9. Demonstrate the Concepts of Polymorphism


Description:
Polymorphism allows methods in derived classes to have different
behaviors, even though they share the same name as methods in the
base class.
Code Implementation:
csharp
Copy code
using System;
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal speaks.");
}
}

class Dog : Animal


{
public override void Speak()
{
Console.WriteLine("Dog barks.");
}
}

class Cat : Animal


{
public override void Speak()
{
Console.WriteLine("Cat meows.");
}
}

class PolymorphismExample
{
static void Main()
{
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.Speak(); // Output: Dog barks.
myCat.Speak(); // Output: Cat meows.
}
}
Explanation:
 This example demonstrates runtime polymorphism using method
overriding.
 The Speak method behaves differently depending on the object
instance.

10. Demonstrate Partial Classes and Extension Methods


Description:
Partial classes allow the definition of a class to be split into multiple
files. Extension methods add new methods to existing classes.
Code Implementation:
File1: PartialClass.cs
csharp
public partial class SampleClass
{
public void Method1()
{
Console.WriteLine("Method 1 in Partial Class.");
}
}
File2: PartialClassExtensions.cs
csharp
Copy code
public partial class SampleClass
{
public void Method2()
{
Console.WriteLine("Method 2 in Partial Class.");
}
}
File3: MainProgram.cs
csharp
Copy code
using System;
static class Extensions
{
public static void Method3(this SampleClass sample)
{
Console.WriteLine("Extension Method 3.");
}
}
class PartialClassExample
{
static void Main()
{
SampleClass sample = new SampleClass();
sample.Method1();
sample.Method2();
sample.Method3(); // Using the extension method
}
}
Explanation:
 The SampleClass is divided into two partial definitions.
 An extension method Method3 is added to SampleClass.

11. Demonstrate the Concepts of Delegates


Description:
A delegate is a type that defines a method signature, enabling methods
to be passed as parameters.
Code Implementation:
csharp
using System;
public delegate void PrintDelegate(string message);
class DelegateExample
{
public static void PrintMessage(string message)
{
Console.WriteLine("Message: " + message);
}

static void Main()


{
PrintDelegate del = new PrintDelegate(PrintMessage);
del("Hello from a delegate!");
}
}
Explanation:
 The PrintDelegate delegate is defined to match methods with a
string parameter.
 The method PrintMessage is invoked via the delegate del.

12. Create a Windows Application for Registration Form


Description:
Develop a form where users can input details. Upon clicking a "Submit"
button, the details are displayed in a message box.
Code Implementation:
csharp
Copy code
using System;
using System.Windows.Forms;
public class RegistrationForm : Form
{
private TextBox nameBox;
private TextBox emailBox;
private Button submitButton;

public RegistrationForm()
{
this.Text = "Registration Form";

Label nameLabel = new Label { Text = "Name:", Top = 20, Left = 10 };


nameBox = new TextBox { Top = 20, Left = 80 };

Label emailLabel = new Label { Text = "Email:", Top = 50, Left = 10 };


emailBox = new TextBox { Top = 50, Left = 80 };

submitButton = new Button { Text = "Submit", Top = 80, Left = 80 };


submitButton.Click += new EventHandler(OnSubmit);
Controls.Add(nameLabel);
Controls.Add(nameBox);
Controls.Add(emailLabel);
Controls.Add(emailBox);
Controls.Add(submitButton);
}
private void OnSubmit(object sender, EventArgs e)
{
string message = $"Name: {nameBox.Text}\nEmail:
{emailBox.Text}";
MessageBox.Show(message, "Registration Details");
}

[STAThread]
static void Main()
{
Application.Run(new RegistrationForm());
}
}
Explanation:
 A simple form is created with textboxes for name and email.
 Clicking the "Submit" button triggers the display of user input.

13. Create a Windows Application for Factorial, Prime,


and Factorial Series Calculation
Description:
Develop a form where users input a number and click buttons to
compute factorial, check for primality, or generate a factorial series.
Code Implementation:
csharp
Copy code
using System;
using System.Windows.Forms;

public class CalculationForm : Form


{
private TextBox inputBox;
private TextBox outputBox;
private Button factorialButton;
private Button primeButton;
private Button factorialSeriesButton;
public CalculationForm()
{
this.Text = "Calculations";
Label inputLabel = new Label { Text = "Input:", Top = 20, Left = 10 };
inputBox = new TextBox { Top = 20, Left = 80 };
outputBox = new TextBox { Top = 80, Left = 80, Width = 200 };

factorialButton = new Button { Text = "Factorial", Top = 50, Left = 10


};
factorialButton.Click += new EventHandler(OnFactorial);

primeButton = new Button { Text = "Prime", Top = 50, Left = 100 };


primeButton.Click += new EventHandler(OnPrime);

factorialSeriesButton = new Button { Text = "Factorial Series", Top =


50, Left = 180 };
factorialSeriesButton.Click += new
EventHandler(OnFactorialSeries);
Controls.Add(inputLabel);
Controls.Add(inputBox);
Controls.Add(outputBox);
Controls.Add(factorialButton);
Controls.Add(primeButton);
Controls.Add(factorialSeriesButton);
}
private void OnFactorial(object sender, EventArgs e)
{
int n = int.Parse(inputBox.Text);
outputBox.Text = Factorial(n).ToString();
}
private void OnPrime(object sender, EventArgs e)
{
int n = int.Parse(inputBox.Text);
outputBox.Text = IsPrime(n) ? "Prime" : "Not Prime";
}

private void OnFactorialSeries(object sender, EventArgs e)


{
int n = int.Parse(inputBox.Text);
string series = string.Join(", ", FactorialSeries(n));
outputBox.Text = series;
}

private int Factorial(int n)


{
return n <= 1 ? 1 : n * Factorial(n - 1);
}
private bool IsPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i <= Math.Sqrt(n); i++)
if (n % i == 0) return false;
return true;
}

private int[] FactorialSeries(int n)


{
int[] series = new int[n];
for (int i = 1; i <= n; i++)
series[i - 1] = Factorial(i);
return series;
}

[STAThread]
static void Main()
{
Application.Run(new CalculationForm());
}
}
Explanation:
 The form contains buttons to compute factorial, check primality,
and generate a factorial series for the entered number.

14. Demonstrate User-Defined Exception


Description:
In C#, user-defined exceptions allow developers to create custom
exceptions by inheriting from the Exception class.
Code Implementation:
csharp
Copy code
using System;
public class AgeException : Exception
{
public AgeException(string message) : base(message)
{
}
}

class UserDefinedExceptionExample
{
public static void CheckAge(int age)
{
if (age < 18)
{
throw new AgeException("Age must be 18 or older.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}

static void Main()


{
try
{
Console.WriteLine("Enter your age:");
int age = int.Parse(Console.ReadLine());
CheckAge(age);
}
catch (AgeException ex)
{
Console.WriteLine("User-defined exception caught: " +
ex.Message);
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
}
Explanation:
 The AgeException class is a user-defined exception.
 The method CheckAge throws this exception if the input age is
less than 18.

15. Develop a Registration Form with All Validation


Controls
Description:
Create a Windows form application for user registration with validation
for fields like name, email, password, and phone number.
Code Implementation:
csharp
using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;

public class RegistrationFormWithValidation : Form


{
private TextBox nameBox, emailBox, passwordBox, phoneBox;
private Button submitButton;

public RegistrationFormWithValidation()
{
this.Text = "Registration Form with Validation";

Label nameLabel = new Label { Text = "Name:", Top = 20, Left = 10 };


nameBox = new TextBox { Top = 20, Left = 100 };

Label emailLabel = new Label { Text = "Email:", Top = 60, Left = 10 };


emailBox = new TextBox { Top = 60, Left = 100 };

Label passwordLabel = new Label { Text = "Password:", Top = 100,


Left = 10 };
passwordBox = new TextBox { Top = 100, Left = 100, PasswordChar
= '*' };
Label phoneLabel = new Label { Text = "Phone:", Top = 140, Left =
10 };
phoneBox = new TextBox { Top = 140, Left = 100 };

submitButton = new Button { Text = "Submit", Top = 180, Left =


100 };
submitButton.Click += new EventHandler(OnSubmit);

Controls.Add(nameLabel);
Controls.Add(nameBox);
Controls.Add(emailLabel);
Controls.Add(emailBox);
Controls.Add(passwordLabel);
Controls.Add(passwordBox);
Controls.Add(phoneLabel);
Controls.Add(phoneBox);
Controls.Add(submitButton);
}

private void OnSubmit(object sender, EventArgs e)


{
string name = nameBox.Text;
string email = emailBox.Text;
string password = passwordBox.Text;
string phone = phoneBox.Text;

if (string.IsNullOrWhiteSpace(name))
{
MessageBox.Show("Name cannot be empty.");
return;
}

if (!Regex.IsMatch(email, @"^\S+@\S+\.\S+$"))
{
MessageBox.Show("Invalid email format.");
return;
}

if (password.Length < 6)
{
MessageBox.Show("Password must be at least 6 characters
long.");
return;
}
if (!Regex.IsMatch(phone, @"^\d{10}$"))
{
MessageBox.Show("Phone number must be 10 digits.");
return;
}

MessageBox.Show("Registration Successful!");
}

[STAThread]
static void Main()
{
Application.Run(new RegistrationFormWithValidation());
}
}

16. Create a Web Service for All Arithmetic Operations


ArithmeticWebService.asmx.cs:
csharp
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ArithmeticWebService : WebService
{
[WebMethod]
public double Add(double a, double b)
{
return a + b;
}

[WebMethod]
public double Subtract(double a, double b)
{
return a - b;
}

[WebMethod]
public double Multiply(double a, double b)
{
return a * b;
}
[WebMethod]
public double Divide(double a, double b)
{
if (b == 0)
throw new System.DivideByZeroException("Cannot divide by
zero.");
return a / b;
}
}

17) Application to Find Factorial Value


Description: A web application that calculates the factorial of a given
integer.
Controls Used: TextBox for input, Button to trigger calculation, Label to
display the result.

Html
<asp:TextBox ID="txtNumber" runat="server" placeholder="Enter a
number"></asp:TextBox>
<asp:Button ID="btnCalculate" runat="server" Text="Find Factorial"
OnClick="btnCalculate_Click" />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>

Csharp
protected void btnCalculate_Click(object sender, EventArgs e)
{
int number = int.Parse(txtNumber.Text);
long factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial *= i;
}
lblResult.Text = "Factorial: " + factorial;
}

18) Application to Perform Money Conversion


Description: Converts a given amount from one currency to another.
Controls Used: TextBox for amount, DropDownList for currency
selection, Button for conversion, Label for result.

Html
<asp:TextBox ID="txtAmount" runat="server" placeholder="Enter
amount"></asp:TextBox>
<asp:DropDownList ID="ddlCurrency" runat="server">
<asp:ListItem Value="USD">USD</asp:ListItem>
<asp:ListItem Value="EUR">EUR</asp:ListItem>
<asp:ListItem Value="INR">INR</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnConvert" runat="server" Text="Convert"
OnClick="btnConvert_Click" />
<asp:Label ID="lblConvertedAmount" runat="server"
Text=""></asp:Label>

Csharp
protected void btnConvert_Click(object sender, EventArgs e)
{
double amount = double.Parse(txtAmount.Text);
string currency = ddlCurrency.SelectedValue;
double convertedAmount = 0;
switch (currency)
{
case "USD":
convertedAmount = amount * 1.2; // Example conversion rate
break;
case "EUR":
convertedAmount = amount * 1.1;
break;
case "INR":
convertedAmount = amount * 90; // Hypothetical rate
break;
}
lblConvertedAmount.Text = "Converted Amount: " +
convertedAmount;
}

19) Application to Display Roots of a Quadratic Equation


 Description: Finds and displays the roots of a quadratic equation
ax^2 + bx + c = 0.

 Controls Used: TextBox for coefficients a, b, and c, Button for


calculation, Label for result.

Html
<asp:TextBox ID="txtA" runat="server" placeholder="Enter value of
a"></asp:TextBox>
<asp:TextBox ID="txtB" runat="server" placeholder="Enter value of
b"></asp:TextBox>
<asp:TextBox ID="txtC" runat="server" placeholder="Enter value of
c"></asp:TextBox>
<asp:Button ID="btnCalculateRoots" runat="server" Text="Find Roots"
OnClick="btnCalculateRoots_Click" />
<asp:Label ID="lblRoots" runat="server" Text=""></asp:Label>
Csharp
protected void btnCalculateRoots_Click(object sender, EventArgs e)
{
double a = double.Parse(txtA.Text);
double b = double.Parse(txtB.Text);
double c = double.Parse(txtC.Text);
double discriminant = b * b - 4 * a * c;
if (discriminant < 0)
{
lblRoots.Text = "No Real Roots";
}
else
{
double root1 = (-b + Math.Sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.Sqrt(discriminant)) / (2 * a);
lblRoots.Text = $"Roots: {root1}, {root2}";
}
}

20) Temperature Conversion with Dropdown List and


ListBox Controls
Description: Converts temperature from Celsius to Fahrenheit or vice
versa.

Controls Used: TextBox for temperature, DropDownList for conversion


type, ListBox for selecting output unit, Button for conversion, Label for
result.

Html
<asp:TextBox ID="txtTemp" runat="server" placeholder="Enter
temperature"></asp:TextBox>
<asp:DropDownList ID="ddlConvertFrom" runat="server">
<asp:ListItem Value="Celsius">Celsius</asp:ListItem>
<asp:ListItem Value="Fahrenheit">Fahrenheit</asp:ListItem>
</asp:DropDownList>
<asp:ListBox ID="lstConvertTo" runat="server">
<asp:ListItem Value="Celsius">Celsius</asp:ListItem>
<asp:ListItem Value="Fahrenheit">Fahrenheit</asp:ListItem>
</asp:ListBox>
<asp:Button ID="btnConvertTemp" runat="server" Text="Convert"
OnClick="btnConvertTemp_Click" />
<asp:Label ID="lblTempResult" runat="server" Text=""></asp:Label>
Csharp
protected void btnConvertTemp_Click(object sender, EventArgs e)
{
double temp = double.Parse(txtTemp.Text);
string convertFrom = ddlConvertFrom.SelectedValue;
string convertTo = lstConvertTo.SelectedValue;
double convertedTemp = 0;

if (convertFrom == "Celsius" && convertTo == "Fahrenheit")


{
convertedTemp = (temp * 9 / 5) + 32;
}
else if (convertFrom == "Fahrenheit" && convertTo == "Celsius")
{
convertedTemp = (temp - 32) * 5 / 9;
}
else
{
convertedTemp = temp; // No conversion
}
lblTempResult.Text = $"Converted Temperature: {convertedTemp}°
{convertTo}";
}

You might also like