0% found this document useful (0 votes)
31 views37 pages

Lab

Uploaded by

01fe22mca004
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 views37 pages

Lab

Uploaded by

01fe22mca004
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/ 37

1.

Write a C# program that provides methods for calculating the HYPOTENUSE of a


triangle & AREA of a circle. The methods should demonstrate the boxing & unboxing
techniques.
using System;

public class Program


{

public static double area(double r)


{
double circle = 2*3.142*r;
return circle;
}
public static double hypotenuese(double a, double b)
{
double hyp = Math.Sqrt(Math.Pow(a,2)+Math.Pow(b,2));
return hyp;
}
public static void Main()
{
int ch;
do{
Console.Write("\nEnter your choice");
Console.Write("\n 1.Circle 2.Hypotenuese 3.Exit\n");
ch=int.Parse(Console.ReadLine());

switch(ch)
{

case 1: Console.Write("Enter radius for circle");


double r = double.Parse(Console.ReadLine());
object o=r;
Console.Write("Area of circle:"+area(r));
double i =(double)o;
break;
case 2 : Console.Write("Enter 2 sides of a triangle ");
double c = double.Parse(Console.ReadLine());
double d = double.Parse(Console.ReadLine());
object o1=c;
object o2=d;
Console.Write("Hypotenuese of
atriangle:"+hypotenuese(c,d));
double j =(double)o1;
double k =(double)o2;
break;
case 3 : Console.Write("Exiting");
break;
default: Console.Write("Invalid choice");
break;
}

} while(ch<3);

}
}

Output:
2. C# program to convert a decimal no to its binary equivalent and vice versa using the
method. The program should illustrate the use of reference variables and output.

using System;

public class Program


{
public static void bin(int[] a, int n)
{
int i;
for (i = 0; n > 0; i++)
{
a[i] = n % 2;
n = n / 2;
}
Console.WriteLine("Binary Equivalent:");
for (i = i - 1; i >= 0; i--)
Console.Write(a[i]);
}

public static int[] dec(string a1)


{
int j, d = 0;
int[] binaryArray = new int[a1.Length];
for (j = 0; j < a1.Length; j++)
{
binaryArray[j] = a1[j] = = '1' ? 1 : 0;
d = d * 2 + binaryArray[j];
}

Console.WriteLine("\nDecimal Equivalent: " + d);


return binaryArray;
}

public static void Main()


{
int ch;
do
{
Console.WriteLine("\nEnter your choice");
Console.WriteLine(" 1. Decimal to Binary\n 2. Binary to Decimal\n 3. Exit");
ch = int.Parse(Console.ReadLine());

switch (ch)
{
case 1:
Console.WriteLine("Enter a decimal number:");
int n = int.Parse(Console.ReadLine());
int[] a = new int[10];
bin(a, n);
break;
case 2:
Console.WriteLine("Enter a binary number:");
string s = Console.ReadLine();
int[] a1 = dec(s);
break;
case 3:
Console.Write("Exiting");
break;
default:
Console.Write("Invalid choice");
break;
}

} while (ch < 3);


}
}

Output:
3. Write a C# program to create a shopping list of electronic goods and another of books.
Provide options to add an item at the specified location, to append an item, or to
delete an item. The shopping list has to be merged and sorted alphabetically.
using System;
using System.Collections.Generic;

public class Program


{
public static void Main(string[] args)
{
List<string> electronicGoods = new List<string>();
List<string> books = new List<string>();

// Options
int option;
do
{
Console.WriteLine("\nOptions:");
Console.WriteLine("1. Add item to electronic goods list at specified
location");
Console.WriteLine("2. Add item to books list at specified location");
Console.WriteLine("3. Append an item to electronic goods list");
Console.WriteLine("4. Append an item to books list");
Console.WriteLine("5. Delete an item from electronic goods list");
Console.WriteLine("6. Delete an item from books list");
Console.WriteLine("7. Merge and sort lists");
Console.WriteLine("8. Exit");

option = int.Parse(Console.ReadLine());

switch (option)
{
case 1:
Console.WriteLine("Enter electronic item to add:");
string electronicItem = Console.ReadLine();
Console.WriteLine("Enter index where to add:");
int electronicIndex = int.Parse(Console.ReadLine());
AddItemAtLocation(electronicGoods, electronicIndex, electronicItem);
break;
case 2:
Console.WriteLine("Enter book to add:");
string bookItem = Console.ReadLine();
Console.WriteLine("Enter index where to add:");
int bookIndex = int.Parse(Console.ReadLine());
AddItemAtLocation(books, bookIndex, bookItem);
break;
case 3:
Console.WriteLine("Enter electronic item to append:");
string electronicItemToAppend = Console.ReadLine();
AppendItem(electronicGoods, electronicItemToAppend);
break;
case 4:
Console.WriteLine("Enter book to append:");
string bookItemToAppend = Console.ReadLine();
AppendItem(books, bookItemToAppend);
break;
case 5:
Console.WriteLine("Enter electronic item to delete:");
string electronicItemToDelete = Console.ReadLine();
DeleteItem(electronicGoods, electronicItemToDelete);
break;
case 6:
Console.WriteLine("Enter book to delete:");
string bookItemToDelete = Console.ReadLine();
DeleteItem(books, bookItemToDelete);
break;
case 7:
MergeAndSortLists(electronicGoods, books);
break;
case 8:
Console.WriteLine("Exiting...");
break;
default:
Console.WriteLine("Invalid option");
break;
}

} while (option != 8);


}

static void AddItemAtLocation(List<string> list, int index, string item)


{
if (index >= 0 && index <= list.Count)
{
list.Insert(index, item);
Console.WriteLine("Item added successfully.");
}
else
{
Console.WriteLine("Invalid index.");
}
}

static void AppendItem(List<string> list, string item)


{
list.Add(item);
Console.WriteLine("Item appended successfully.");
}

static void DeleteItem(List<string> list, string item)


{
if (list.Remove(item))
{
Console.WriteLine("Item deleted successfully.");
}
else
{
Console.WriteLine("Item not found.");
}
}

static void MergeAndSortLists(List<string> list1, List<string> list2)


{
list1.AddRange(list2);
list1.Sort();
Console.WriteLine("Lists merged and sorted successfully.");
}
}
Output:
4. Design a C# structure customer, with data members-name, account number, balance,
and account status. Write a C# program to implement the above through structure
variables and display customer details categorized by account status

using System;

struct Customer
{
public string Name;
public int AccountNumber;
public double Balance;
public string AccountStatus;
}

public class Program


{
public static void Main(string[] args)
{
// Create an array of customers
Customer[] customers = new Customer[3];

// Populate customer data


customers[0].Name = "John";
customers[0].AccountNumber = 1001;
customers[0].Balance = 5000;
customers[0].AccountStatus = "Active";

customers[1].Name = "Alice";
customers[1].AccountNumber = 1002;
customers[1].Balance = 2000;
customers[1].AccountStatus = "Inactive";

customers[2].Name = "Bob";
customers[2].AccountNumber = 1003;
customers[2].Balance = 7000;
customers[2].AccountStatus = "Active";

// Display customer details categorized by account status


Console.WriteLine("Customers categorized by account status:");

Console.WriteLine("\nActive Accounts:");
foreach (Customer customer in customers)
{
if (customer.AccountStatus == "Active")
{
DisplayCustomerDetails(customer);
}
}

Console.WriteLine("\nInactive Accounts:");
foreach (Customer customer in customers)
{
if (customer.AccountStatus == "Inactive")
{
DisplayCustomerDetails(customer);
}
}
}

static void DisplayCustomerDetails(Customer customer)


{
Console.WriteLine("Name: {0}",customer.Name);
Console.WriteLine("Account Number: {0}",customer.AccountNumber);
Console.WriteLine("Balance: {0}",customer.Balance);
Console.WriteLine("Account Status: {0}\n",customer.AccountStatus);
}
}

Output:
5. Design an abstract class BankAccount with necessary data members. Derive the
following classes BankAccount->[current, fixed->[short, long], savings]. The savings
class provides with checkbook facility, withdrawal, and deposit facility. The current
class provides only a withdrawal and deposit facility. The fixed class is derived by 2
classes short-term (1-2yr @8%)and long-term (3-5yr @10%). Write a driver program
for this.

using System;

abstract class BankAccount


{
public int AccountNumber { get; }
public double Balance { get; protected set; }

public BankAccount(int accountNumber, double balance = 0.0)


{
AccountNumber = accountNumber;
Balance = balance;
}

public void Deposit(double amount)


{
if (amount <= 0)
{
Console.WriteLine("Deposit amount must be positive.");
return;
}

Balance += amount;
Console.WriteLine($"Deposited {amount}. New balance is {Balance}.");
}
public virtual void Withdraw(double amount)
{
if (amount <= 0 || amount > Balance)
{
Console.WriteLine("Insufficient balance or invalid amount.");
return;
}

Balance -= amount;
Console.WriteLine($"Withdrew {amount}. New balance is {Balance}.");
}

public abstract void DisplayAccountInfo();


}

class Current : BankAccount


{
public Current(int accountNumber, double balance = 0.0) : base(accountNumber,
balance) { }

public override void DisplayAccountInfo()


{
Console.WriteLine($"Current Account #{AccountNumber} - Balance:
{Balance}");
}
}

class Savings : BankAccount


{
public bool HasChequeBook { get; set; }
public Savings(int accountNumber, double balance = 0.0) : base(accountNumber,
balance)
{
HasChequeBook = true;
}

public override void DisplayAccountInfo()


{
Console.WriteLine($"Savings Account #{AccountNumber} - Balance:
{Balance}, Cheque Book: {(HasChequeBook ? "Yes" : "No")}");
}
}

class Fixed : BankAccount


{
public double InterestRate { get; }

public Fixed(int accountNumber, double balance, double interestRate) :


base(accountNumber, balance)
{
InterestRate = interestRate;
}

public override void Withdraw(double amount)


{
Console.WriteLine("Withdrawal not allowed from Fixed Deposit account before
maturity.");
}

public override void DisplayAccountInfo()


{
Console.WriteLine($"Fixed Account #{AccountNumber} - Balance: {Balance},
Interest Rate: {InterestRate * 100}%");
}
}

class Program
{
static void Main()
{
var accounts = new BankAccount[] {
new Savings(101, 1000),
new Current(102, 2000),
new Fixed(103, 5000, 0.08),
new Fixed(104, 10000, 0.10)
};

foreach (var account in accounts)


{
account.DisplayAccountInfo();
}

accounts[0].Deposit(500);
accounts[0].Withdraw(300);

accounts[1].Deposit(1000);
accounts[1].Withdraw(500);
}
}Output:
6. Design an interface in C# for displaying product details like product list, product
features, product color, and price. implement the interface for the product car and
mobile phone. write a program for this.
using System;

// Interface for displaying product details


interface IProductDetails
{
void DisplayProductList();
void DisplayProductFeatures();
void DisplayProductColor();
void DisplayProductPrice();
}

// Car class implementing IProductDetails interface


class Car : IProductDetails
{
private string color;
private double price;

public Car(string color, double price)


{
this.color = color;
this.price = price;
}

public void DisplayProductList()


{
Console.WriteLine("Product: Car");
}

public void DisplayProductFeatures()


{
Console.WriteLine("Features: ");
Console.WriteLine("- Four Wheels");
Console.WriteLine("- Engine");
Console.WriteLine("- Seats");
// Add more features if needed
}

public void DisplayProductColor()


{
Console.WriteLine("Color: {0}",color);
}

public void DisplayProductPrice()


{
Console.WriteLine("Price: {0}",price);
}
}

// MobilePhone class implementing IProductDetails interface


class MobilePhone : IProductDetails
{
private string color;
private double price;

public MobilePhone(string color, double price)


{
this.color = color;
this.price = price;
}

public void DisplayProductList()


{
Console.WriteLine("Product: Mobile Phone");
}

public void DisplayProductFeatures()


{
Console.WriteLine("Features: ");
Console.WriteLine("- Touchscreen");
Console.WriteLine("- Camera");
Console.WriteLine("- Processor");
// Add more features if needed
}

public void DisplayProductColor()


{
Console.WriteLine("Color: {0}",color);
}

public void DisplayProductPrice()


{
Console.WriteLine("Price: {0}",price);
}
}

public class Program


{
public static void Main(string[] args)
{
// Read car details from console
Console.WriteLine("Enter car color:");
string carColor = Console.ReadLine();
Console.WriteLine("Enter car price:");
double carPrice = double.Parse(Console.ReadLine());

// Create car object


IProductDetails car = new Car(carColor, carPrice);
// Read mobile phone details from console
Console.WriteLine("Enter mobile phone color:");
string phoneColor = Console.ReadLine();
Console.WriteLine("Enter mobile phone price:");
double phonePrice = double.Parse(Console.ReadLine());

// Create mobile phone object


IProductDetails mobilePhone = new MobilePhone(phoneColor, phonePrice);

// Display details of Car


Console.WriteLine("Car Details:");
car.DisplayProductList();
car.DisplayProductFeatures();
car.DisplayProductColor();
car.DisplayProductPrice();

Console.WriteLine();

// Display details of Mobile Phone


Console.WriteLine("Mobile Phone Details:");
mobilePhone.DisplayProductList();
mobilePhone.DisplayProductFeatures();
mobilePhone.DisplayProductColor();
mobilePhone.DisplayProductPrice();
}
}
Output:
7. Design a C# class point(with 2 integer members x and y and necessary data
members).the class should overload binary operator(+,-),unary operator(+
+,--),equality operators(==,!=) and comparison operators(<,>).implement structured
exceptional handling for your class. write a driver program for this.
using System;

using System;

class Point
{
private int x;
private int y;

public Point(int x, int y)


{
this.x = x;
this.y = y;
}

// Binary operator overloading for addition


public static Point operator +(Point p1, Point p2)
{
return new Point(p1.x + p2.x, p1.y + p2.y);
}

// Binary operator overloading for subtraction


public static Point operator -(Point p1, Point p2)
{
return new Point(p1.x - p2.x, p1.y - p2.y);
}
// Unary operator overloading for increment (++point)
public static Point operator ++(Point p)
{
return new Point(p.x + 1, p.y + 1);
}

// Unary operator overloading for decrement (--point)


public static Point operator --(Point p)
{
return new Point(p.x - 1, p.y - 1);
}

// Equality operator overloading


public static bool operator ==(Point p1, Point p2)
{
return p1.x == p2.x && p1.y == p2.y;
}

public static bool operator !=(Point p1, Point p2)


{
return !(p1 == p2);
}

// Comparison operator overloading


public static bool operator <(Point p1, Point p2)
{
return (p1.x < p2.x) && (p1.y < p2.y);
}

public static bool operator >(Point p1, Point p2)


{
return (p1.x > p2.x) && (p1.y > p2.y);
}

// Display method
public void Display()
{
Console.WriteLine($"({x}, {y})");
}
}

class Program
{
static void Main(string[] args)
{

// Creating points
Point point1 = new Point(5, 10);
Point point2 = new Point(3, 7);

// Displaying results
Point sum = point1 + point2;
sum.Display();

Point difference = point1 - point2;


difference.Display();

Point incremented = ++point1;


incremented.Display();

Point decremented = --point2;


decremented.Display();

bool isEqual = (point1 == point2);


Console.WriteLine(isEqual);

bool isNotEqual = (point1 != point2);


Console.WriteLine(isNotEqual);

bool isLessThan = (point1 < point2);


Console.WriteLine(isLessThan);

bool isGreaterThan = (point1 > point2);


Console.WriteLine(isGreaterThan);

Console.ReadLine();
Console.ReadKey();
}
}

Output:
8. Design c# class Result to calculate the internal assessment marks of a
student(minor1+ minor2+assignment).Use the delegate feature for this application.
Write a driver program for this.

using System;

public delegate double CalculateInternalMarks(double minor1, double minor2, double


assignment);

public class Result


{
public double Minor1 { get; set; }
public double Minor2 { get; set; }
public double Assignment { get; set; }

public Result(double minor1, double minor2, double assignment)


{
Minor1 = minor1;
Minor2 = minor2;
` Assignment = assignment;
}

public double CalculateTotalMarks(CalculateInternalMarks calculateInternalMarks)


{
return calculateInternalMarks(Minor1, Minor2, Assignment);
}
}

public class Program


{
static double CalculateInternalAssessment(double minor1, double minor2, double
assignment)
{
// Calculate the total internal assessment marks
return minor1 + minor2 + assignment;
}

public static void Main(string[] args)


{
// Input marks from the user
Console.WriteLine("Enter marks for Minor 1:");
double minor1Marks = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter marks for Minor 2:");


double minor2Marks = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter marks for Assignment:");


double assignmentMarks = Convert.ToDouble(Console.ReadLine());

// Create a Result object


Result result = new Result(minor1Marks, minor2Marks, assignmentMarks);

// Use the delegate to calculate the internal assessment marks


CalculateInternalMarks calculateInternalMarks = new
CalculateInternalMarks(CalculateInternalAssessment);
double totalMarks = result.CalculateTotalMarks(calculateInternalMarks);

// Output the result


Console.WriteLine("Total Internal Assessment Marks: {0}", totalMarks);
}
}
Output:

Structured Query
To build any form of web application with database connectivity
Step 1

XAMPP makes it possible to create a local server with Apache and MySQL databases with
other features. Click on Start on Apache, and MySQL. The buttons turn the labels into Stop.

Step 2

Open your browser and type, localhost/phpmyadmin/


Step 3

 Click on Databases.
 Now, Under Create Database, Type the name of the new database we are going to
create.
 Create a Table
 You can view the table on the database from the Structure Option in the bar.

Step 4

 Install Visual Studio. The Professional Edition is free and can be accessed from the
Microsoft Official Website.
 Once installed, the Visual Studio Installer can be opened. Now, click on Launch.
Step 5

 Click on Create a New Project.


 Create the project for Windows Forms App in C#, .NET Framework with the Solution
name of your choice.

Step 6

 Go to Server Explorer. Double-click on Data Connections and Choose Add


Connections. You’ll be taken to Choose the Data Source Option.
 Under Data Source, we can see the MySQL Database option.
 The Server Name, User Name, Password, and Database Name are to be filled in.
 Remember, this is the same as that of your database on the localhost/phpmyadmin
 Server name which is “localhost”, a User name that is “root” and my password.
Remember, above we made the Database TestDB for this very experiment. Here, we
can use the lowercase name “testdb”.
 Click on Test Connection and as the success is prompted, choose OK.

Step 7

 We can see the localhost(testdb) database on our Data Connections


Step 8

 Create a web form using the tools from the toolbox


 Add a MySqData.Dll file by clicking on Add References from References tab in
Solution Explorer

Step 9

 Code snippet to make a web form work


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
string MyConnectionString = "Server=127.0.0.1;Database=testdb;Uid=root;Pwd=";
public Form1()
{
InitializeComponent();
}

private void label1_Click(object sender, EventArgs e)


{

private void button1_Click(object sender, EventArgs e)


{
int MobileNo;
string Mobile = textBox4.Text;
int.TryParse(Mobile, out MobileNo); //converting to the type string
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = (MySqlCommand)connection.CreateCommand();
cmd.CommandText = "INSERT INTO
signup(FirstName,LastName,Address,MobileNo)VALUES(@FirstName,@LastName,@Address,@Mobil
eNo)";
//cmd.Parameters.AddWithValue("@Id", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("@FirstName", textBox1.Text);
cmd.Parameters.AddWithValue("@LastName", textBox2.Text);
cmd.Parameters.AddWithValue("@Address", textBox3.Text);
cmd.Parameters.AddWithValue("@MobileNo", Mobile);
cmd.ExecuteNonQuery();

}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
LoadData();
}
}
}
private void LoadData()
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
connection.Open();
try
{
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM signup";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Clone();

}
}

}
}
}

Step 10

 Click on Run
 Enter the values in the respective fields
 Click on Submit button
 Observe the output in the datagridview
 The output found in datagridview is found is stored in Database

You might also like