C# Onwords11
C# Onwords11
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Q1.cs
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter the principle amount");
int p = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the rate of interest");
int r = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the time period");
int t = Convert.ToInt32(Console.ReadLine());
int s_i = p * r * t/100 ;
Console.WriteLine("simple intrest is" + s_i);
Console.WriteLine("number of times interest is compounded in a year");
int n = Convert.ToInt32(Console.ReadLine());
int c_i = ((p*(1 + r / n) ^ n*t)- p);
Console.WriteLine("compound interest is "+c_i);
int result = c_i - s_i;
Console.WriteLine("difference between copount interest and simple interest is"+result);
Console.ReadLine();
}
}
}
OUTPUT:
b) To Store the following sequence using concept of arrays 1, 4, 13, 40, 121…. 2, 10, 50, 250, 1250, 6250….
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace _1bb.cs
{
classProgram
{
int terms;
Program()
{
Console.Write("enter the number of terms");
terms = Convert.ToInt32(Console.ReadLine());
}
void seq1()
{
int p = 1;
int[] a = newint[terms];
for (inti = 0; i< terms; i++)
{
a[i] = p;
p = (p * 3) + 1;
}
Console.WriteLine("the first sequence is \n");
for (inti = 0; i< terms; i++)
Console.Write(a[i] + "\t");
Console.ReadLine();
}
void seq2()
{
int p = 2;
int[] a = newint[terms];
for (inti = 0; i< terms; i++)
{
a[i] = p;
p *= 5;
}
Console.WriteLine("the second sequence is \n");
for (inti = 0; i< terms; i++)
Console.Write(a[i] + "\t");
Console.ReadLine();
}
staticvoid Main(string[] args)
{
Programob = newProgram();
ob.seq1();
ob.seq2();
}
}
}
OUTPUT:
2.Write a program to using functions with different parameter types:
a) Print prime numbers between 1 and number passed as argument.
using System;
namespace Calculate
{
classPrime
{
publicvoidprimeNumber(int endNum)
{
bool isPrime = true;
Console.WriteLine("\n Prime Numbers are : ");
for (int i = 2; i <= endNum; i++)
{
for (int j = 2; j <= endNum; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.Write(" " + i + "\t");
}
isPrime = true;
}
}
}
classNumber
{
publicstaticvoid Main(string[] args)
{
Prime p = newPrime();
p.primeNumber(endNum:9);
Console.ReadLine();
}
}
OUTPUT:
b) Reverse the string passed
using System;
namespace Calculate
{
classReverse
{
publicvoidreverse(refstring str)
{
int Length = str.Length - 1;
string reverse = " ";
while (Length >= 0)
{
Reverse = reverse + str[Length];
Length--;
}
Console.WriteLine("\n Reverse word is : {0} ", reverse);
}
}
classPass
{
publicstaticvoid Main(string[] args)
{
Reverse r = newReverse();
string str;
Console.Write("\n Enter a string : ");
str = Console.ReadLine();
r.reverse(ref str);
Console.ReadLine();
}
}
}
OUTPUT:
c) Check the string entered is a palindrome string.
using System;
namespace CsFileCode
{
classCheck
{
staticboolCheckPalindrome(string CheckString)
{
if (CheckString == null || CheckString.Length == 0)
{
returnfalse;
}
int strMaxIndex = CheckString.Length - 1;
OUTPUT:
d) Display Octal value of the number passed.
using System;
namespace Calculate
{
classOctal
{
publicvoiddecToOctal(int decNum)
{
Int octalNum = 0, i = 1;
while (decNum != 0)
{
octalNum += (decNum % 8) * i;
decNum /= 8;
i *= 10;
}
Console.WriteLine("\n After converting Decimal Number to Octal Number is = " + octalNum);
}
publicstaticvoid Main(string[] args)
{
Octal oct = newOctal();
int decNum;
Console.Write("\n Enter a decimal value = ");
decNum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n Decimal Number = " + decNum);
oct.decToOctal(decNum);
Console.ReadLine();
}
}
}
3. Write a program to Create and Use Assemblies Using the Command Line with the following user defined
functions:
a) C# Program to Generate Random Numbers.
using System;
namespace Calculate
{
classRandom
{
publicintGenerateRandomNumber(int minimumNumber, int maximumNumber)
{
Random random = newRandom();
returnrandom.Next(minimumNumber, maximumNumber);
}
publicstaticvoidMain(String[] args)
{
Random random = newRandom();
int randomNumber = random.GenerateRandomNumber(1, 50);
}
}
}
Output:
b) Find the Frequency of the a Word in a given Sentence.
using System;
namespace Calculate
{
classFrequency
{
publicstaticvoidMain(string [] args)
{
string str;
Console.Write("\n Enter the String : ");
str = Console.ReadLine();
Console.WriteLine("\nFrequency of the = " + counting.CountStringOccurrences(str,
"a"));
Console.ReadLine();
}
}
publicstaticclasscounting
{
publicstaticintCountStringOccurrences(string text, string pattern)
{
int count = 0, i = 0;
while ((i = text.IndexOf(pattern, i)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
}
}
Output:
c) Find the area of rectangle.
using System;
namespace Area
{
classFunc
{
publicintarea(int length, int breadth)
{
int ar = length * breadth;
return (ar);
}
}
classProgram
{
staticvoid Main(string[] args)
{
Func fun = newFunc();
ar = fun.area(length, breadth);
using System;
namespace ConsoleApp2
{
classtable
{
publicstaticvoidMain()
{
int tb, num;
Console.Write("\n Enter the number to generate its table = ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n Table of " + num + " is : ");
for (int i = 1; i <= 10; i++)
{
tb = num * i;
Console.WriteLine(" " + num + " * " + i + " = " + tb);
}
Console.ReadLine();
}
}
}
Output:
e) Reverses a number.
using System;
namespace ConsoleApp2
{
classReverse
{
publicstaticvoidMain()
{
int rev = 0, rem, num;
Console.Write("\n Enter a number = ");
num = Convert.ToInt32(Console.ReadLine());
for (int i = num; i > 0; i = i / 10)
{
rem = i % 10;
rev = rev * 10 + rem;
}
using System;
using System.IO;
class Program
{
static void Main()
{
Console.Write("Enter name of directory to show the files: ");
String path = Console.ReadLine();
DirectorySearch(path);
Console.ReadLine();
}
public static void DirectorySearch(string dir)
{
try
{
foreach (string f in Directory.GetFiles(dir))
{
Console.WriteLine(Path.GetFileName(f));
}
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(Path.GetFileName(d));
DirectorySearch(d);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
OUTPUT:
Q5. WAP in C# to move or copy files and folders form one path to another.
using System;
using System.IO;
class Program
{
static void Main()
{
DirectoryInfo sourceinfo = new DirectoryInfo(@"C:\Users\Sanjeev\Desktop\C# lab file");
DirectoryInfo target = new DirectoryInfo(@"C:\Users\Sanjeev\Desktop\New folder (2)");
if (!Directory.Exists(target.FullName))
{
Directory.CreateDirectory(target.FullName);
}
Console.WriteLine("\nfiles are coping.....\nFROM " + sourceinfo + " TO " + target);
foreach (FileInfo fi in sourceinfo.GetFiles())
{
if (fi.Length != 0)
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
Console.WriteLine("\nfiles are copied...\nFROM "+sourceinfo+" TO "+ target);
Console.ReadKey();
}
}
OUTPUT:
Q6. WAP to enter path of file with copy in another directory. Check which file was last modified and updates
the copy.
using System;
using System.IO;
class Program
{
static void Main()
{
Console.Write("Enter the name of directory with path: ");
var path = Console.ReadLine();
DirectoryInfo sourceinfo = new DirectoryInfo(path);
foreach (FileInfo fi in sourceinfo.GetFiles())
{
var created = fi.CreationTime;
var lastmodified = fi.LastWriteTime;
Console.WriteLine("\n"+fi.Name+" is Created: "+created);
Console.WriteLine(fi.Name+" Last Modified"+lastmodified);
}
Console.ReadKey();
}
}
OUTPUT:
7. Write programs to sort array of integers using
a. Bubble Sort
b. Insertion Sort.
c. Quicksort
d. Merge Sort
a) Bubble sort.
using System;
namespace SortingExample
class Program
int temp;
//sorting an array
flag = false;
temp = number[j];
number[j + 1] = temp;
flag = true;
}
//Sorted array
Console.Write("\t {0}",num);
Console.Read();
OUTPUT:
b. Insertion Sort.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InsertionSort
class Program
numarray[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("\n");
int j = i;
while (j > 0)
if (numarray[j - 1] >numarray[j])
{
int temp = numarray[j - 1];
numarray[j - 1] = numarray[j];
numarray[j] = temp;
j--;
else
break;
Console.Write("\n");
//Console.Write("/*** " + (i + 1).ToString() + " numbers from the begining of the array are input and they
are sorted ***/\n");
Console.Write(numarray[i]);
Console.Write("\n");
return 0;
InsertionSorting();
Console.ReadLine();
}
OUTPUT:
c. Quicksort
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuickSort
class QuickSort
while (true)
left++;
while (numbers[right] > pivot)
right--;
numbers[right] = numbers[left];
numbers[left] = temp;
else
return right;
// For Recusrion
if (pivot > 1)
numbers[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("\n");
Console.Write("\n");
Console.WriteLine(numbers[i]);
Console.ReadLine();
OUTPUTl:
d. Merge Sort
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MergeSort
class MergeSort
static public void MainMerge(int[] numbers, int left, int mid, int right)
pos = left;
temp[pos++] = numbers[left++];
else
temp[pos++] = numbers[mid++];
temp[pos++] = numbers[left++];
temp[pos++] = numbers[mid++];
numbers[right] = temp[right];
right--;
}
int mid;
numbers[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("\n");
Console.Write("\n");
Console.WriteLine(numbers[i]);
Console.ReadLine();
OUTPUT:
8.WAP to create two method MinVal() and MaxVal() that takes variable no of arguments and returns the min
and max value.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace Q8.cs
{
classProgram
{
voidminval()
{
int min = 0;
int[] num = newint[6];
Console.WriteLine("enter numbers");
for (inti = 0; i< 6; i++)
{
num[i] = Int32.Parse(Console.ReadLine());
}
min = num[0];
for (inti = 1; i< 6; i++)
{
if (num[i] < min)
{
min = num[i];
}
}
Console.WriteLine("minimum value is" + min);
voidmaxval()
{
int max = 0;
int[] num = newint[6];
Console.WriteLine("enter numbers");
for (inti = 0; i< 6; i++)
{
num[i] = Int32.Parse(Console.ReadLine());
}
max = num[0];
for (inti = 1; i< 6; i++)
{
if (num[i] >max)
{
max = num[i];
}
}
Console.WriteLine("maximum value is" + max);
}
staticvoid Main(string[] args)
{
Program p = newProgram();
p.minval();
p.maxval();
}
}
OUTPUT:
9.. WAP to generate a truth table of a two input AND, OR, NOT, NAND, XNOR gate.
using System;
class Program
{
static int[] x = { 0, 0, 1, 1 };
static int[] y = { 0, 1, 0, 1 };
static int[] z = { 0, 0, 0, 0 };
static String opName;
static void Main(string[] args)
{
opName = andOp();
printVal();
opName = orOp();
printVal();
notOp();
opName = nandOp();
printVal();
opName = xnorOp();
printVal();
Console.ReadKey();
}
static String andOp()
{
for(int i=0; i<4; i++)
{
if ((x[i] == 1) & (y[i] == 1))
z[i] = 1;
else
z[i] = 0;
}
return "AND Operation......";
}
{
for (int i = 0; i< 4; i++)
{
if ((x[i] == 1) & (y[i] == 1))
z[i] = 0;
else
z[i] = 1;
}
return "NAND Operation......";
}
static String xnorOp()
{
for (int i = 0; i< 4; i++)
{
if (x[i] == y[i])
z[i] = 1;
else
z[i] = 0;
}
return "XNOR Operation......";
}
static void printVal()
{
Console.WriteLine(opName + "\nX\tY\tZ\n");
for (int i = 0; i< 4; i++)
Console.WriteLine(x[i] + "\t" + y[i] + "\t" + z[i]);
Console.WriteLine("\n");
}
}
OUTPUT:
10.Write a program to accept 10 marks of students in a subject out of 10. Calculate the % of marks
of each student out of 100 and store in second array. Display the % marks of all the students
excluding the highest and lowest marks.
using System;
namespace ConsoleApp1
{
classstudent
{
int[] s = newint[10];
float[] a = newfloat[10];
int max = 1000;
publicvoidcalc()
{
for (int i = 0; i < 10; i++)
{
float total = 0;
float perc;
Console.WriteLine("Enter the marks for student no. " + (i + 1) + ":");
for (int j = 0; j < 10; j++)
{
Console.WriteLine("Enter the marks for subject no. " + (j + 1) +
" = ");
s[j] = Int32.Parse(Console.ReadLine());
total = total + s[j];
}
a[i] = perc;
}
Array.Sort(a);
foreach (float a in a)
{
Console.Write(a);
Console.Write(' ');
}
Output:
11.WAP to input two int arrays, divide the elements of first array by each corresponding element of second and
print the result. Handle the appropriate exceptions if any.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace 11
{
classprogram23
{
publicstaticvoidMain(String[] args)
{
int[] a = newint[5];
int[] b = newint[5];
float[] c=newfloat[5];
Console.WriteLine("enter Array 1 elements:");
for (inti = 0; i< 5; i++)
a[i] = Int32.Parse(Console.ReadLine());
Console.WriteLine("enter Array 2 elements:");
for (inti = 0; i< 5; i++)
b[i] = Int32.Parse(Console.ReadLine());
try
{
for (inti = 0; i< 5; i++)
{
if(b[i]!=0)
c[i] = (a[i] / b[i]);
else
thrownewSystem.DivideByZeroException("division by zero");
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("result:");
for (inti = 0; i< 5; i++)
Console.WriteLine(c[i]);
Console.ReadLine();
}
}
}
OUTPUT:
12. C# Program to Check Whether the Entered Year is a Leap Year or Not.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 12
{
class leapyear
{
static void Main(string[] args)
{
leapyear obj = new leapyear();
obj.readdata();
obj.leap();
}
int y;
public void readdata()
{
Console.WriteLine("Enter the Year: ");
y = Convert.ToInt32(Console.ReadLine());
}
public void leap()
{
if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
{
Console.WriteLine("{0} is a Leap Year", y);
}
else
{
Console.WriteLine("{0} is not a Leap Year", y);
}
Console.ReadLine();
}
}
}
Output:
13. C# Program to Display the ATM Transaction
using System;
namespace 13
{
class ATM
{
publicstaticvoidMain()
{
int amount = 1000, deposit, withdraw;
int choice, pin = 0, x = 0;
do
{
Console.WriteLine("\n\t ********Welcome to ATM Service**************\n");
Console.WriteLine("\t\t\t 1. Check Balance\n");
Console.WriteLine("\t\t\t 2. Withdraw Cash\n");
Console.WriteLine("\t\t\t 3. Deposit Cash\n");
Console.WriteLine("\t\t\t 4. Quit\n");
Console.WriteLine("\t *********************************************\n\n");
switch (choice)
{
case 1:
Console.WriteLine("\n Your balance in Rs : {0} ", amount);
break;
case 2:
Console.Write("\n Enter the amount to withdraw = ");
withdraw = int.Parse(Console.ReadLine());
if (withdraw % 100 != 0)
{
Console.WriteLine("\n Please enter the amount multiples of 100");
}
elseif (withdraw > (amount - 500))
{ {
Console.WriteLine("\n Insufficient balance");
}
else
break;
case 3:
Console.Write("\n Enter the amount to deposit it = ");
deposit = int.Parse(Console.ReadLine());
amount = amount + deposit;
Console.WriteLine("\n Your balance is {0}", amount);
break;
case 4:
Console.WriteLine("\n Thank you for using the ATM");
break;
}
}
while (choice <= 4);
Console.ReadLine();
}
}
}
OUTPUT:
14. Use window forms to create the following applications also make Flow graph for the same:
a. Age calculator
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;
namespace 14a
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int d=0, m=0, y=0, mrem;// drem;
var d1 = dateTimePicker1.Value;//ToShortDateString();
var d2 = dateTimePicker2.Value;//ToShortDateString();
TimeSpants = d2 - d1;
int days = ts.Days;
if (days > 365)
{
y = days / 365;
mrem = days % 365;
m = mrem / 12;
d = mrem % 12;
}
else if (days < 365 & days > 30)
{
m = days / 12;
d = days % 12;
}
else
d = days;
MessageBox.Show("Current age is "+y+" Year "+m+" Month "+d+" Days");
}
}
} output:-
b.Simple Calculator
using System;
using System.Windows.Forms;
namespace 14b
{
public partial class Form1 : Form
{
private double accumulator = 0;
private char lastOperation;
public Form1()
{
InitializeComponent();
}
private void Operator_Pressed(object sender, EventArgs e)
{
(sender as Button).Text[0];
if (operation == 'C')
{
accumulator = 0;
}
else
{
double currentValue = double.Parse(Display.Text); switch
(lastOperation)
{
case '+': accumulator += currentValue; break;
case '-': accumulator -= currentValue; break;
case 'ร—': accumulator *= currentValue; break;
case 'รท': accumulator /= currentValue; break;
default: accumulator = currentValue; break;
}
}
lastOperation = operation;
Display.Text = operation == '=' ?accumulator.ToString() : "0";
}
private void Number_Pressed(object sender, EventArgs e)
{
string number = (sender as Button).Text;
Display.Text = Display.Text == "0" ? number : Display.Text + number;
}
} output:-
C.Result Computation:
using System;
namespace 14c
{
publicpartialclassResultCompute : Form
{
int cs, cg, java, tot, average, sno;
string sname;
publicResultCompute()
{
InitializeComponent();
}
txtTotal.Text = tot.ToString();
average = tot / 3;
txtAvg.Text = average.ToString();
}
}
Output:-
d. Perform the following Tasks:
1. Check Palindrome
2. Find Fibonacci
using System;
namespace 14d
{
public partial classcal : Form
{
int num, rev = 0, rem, temp;
publiccal()
{
InitializeComponent();
}
}
txtResult.Text = result;
}
}
}
Output:
e.Convert Decimal to Binary, Octal, Hexadecimal.
using System;
usingSystem.Windows.Forms;
namespace WindowsFormsApp1
{
public partial classCovertion : Form
{
int num;
int rem, i = 1;
publicCovertion()
{
InitializeComponent();
}
num = Convert.ToInt32(txtInput.Text);
while(num != 0)
{
rem = num % 2;
num = num / 2;
binaryNum = binaryNum + rem * i;
i = i * 10;
}
txtResult.Text = Convert.ToString(binaryNum);
}
num = Convert.ToInt32(txtInput.Text);
while (num != 0)
{
rem = num % 8;
num = num / 8;
octaNum = octaNum + rem * i;
i = i * 10;
}
txtResult.Text = Convert.ToString(octaNum);
}
num = Convert.ToInt32(txtInput.Text);
while (num != 0)
{
rem = num % 16;
num = num / 16;
hexaNum = hexaNum + rem * i;
i = i * 10;
}
txtResult.Text = Convert.ToString(hexaNum);
}
}
}
Output:
\
e.Perform the appropriate task on the string Entered.
using System;
namespace 14e
{
public partial classStrComp : Form
{
public StrComp()
{
InitializeComponent();
}
private void btnComp_Click(object sender, EventArgs e)
{
int digits = 0, words = 0, spChar = 0, Char = 0, sp = 0;
char[] ch = txtStr.Text.ToCharArray();
using System;
namespace 14f
{
public partial classcrpt : Form
{
publiccrpt()
{
InitializeComponent();
FillComboBox();
}
private voidFillComboBox()
{
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("10", "10");
test.Add("20", "20");
test.Add("30", "30");
cmbprice.DataSource = new BindingSource(test, null);
cmbprice.DisplayMember = "Value";
cmbprice.ValueMember = "Key";
cmbprice.SelectedIndex = 0;
}
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespace 15
{
` classBankAccount
{
string name;
doubleacNo;
stringacType;
staticdouble amount;
BankAccount()
{
Console.Write("Enter name of depositor: "); name = Console.ReadLine();
Console.Write("Enter the account number: "); acNo = Double.Parse(Console.ReadLine());
Console.Write("Enter the type of account: "); acType = Console.ReadLine();
Console.Write("Enter the balance amount: ");
amount = Double.Parse(Console.ReadLine());
}
void amountDeposit()
{
Console.Write("Enter the amount have to deposite: "); Double addAmt =
Double.Parse(Console.ReadLine());
amount += addAmt;
}
void amountWithdraw()
{
Console.Write("Enter the amount have to withdraw: "); Double wtdAmt = Double.Parse(Console.ReadLine()); if
(amount >wtdAmt)
{
amount -= wtdAmt;
Console.Write("\nWithdrawal successful... ");
}
else
Console.Write("\nSorry...\nYour Balance Amount is less than Withdrawal Amount ");
}
void checkBalance()
{
Console.Write("Your current balance is: " + amount);
}
class main
{
static voidMain()
{
BankAccountob = newBankAccount();
int choice;
do
{
Console.WriteLine("\n\n1.Amount Deposite\n2.Amount withdraw\n3.Balance Enquery\n4.Exit");
}
OUTPUT:-
17. WAP to create a class furniture, which should contain a function, DisplayDetails(). The function should be
reused to display the description of the type of furniture accepted from a user. The class should also contain a
function Discount(), which should calculate the discount at 20% to be given when the price of the furniture is
equal or more than $1000.
using System;
namespace 17
{
class Furniture
{
int price, weight, warranty;
string colour;
f.displayDetails(furniture);
f.discount(furniture);
Console.ReadLine();
}
}
}
Output:-
18. Create window form application for purchasing carpet. Allow the length and width of a room
to be entered using textbox controls and take a combo box to display different prices of carpet per
square yard. Calculate and Display the total cost to carpet the room.
using System;
namespace 18
{
public partial classcrpt : Form
{
public crpt()
{
InitializeComponent();
FillComboBox();
}
private voidFillComboBox()
{
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("10", "10");
test.Add("20", "20");
test.Add("30", "30");
cmbprice.DataSource = new BindingSource(test, null);
cmbprice.DisplayMember = "Value";
cmbprice.ValueMember = "Key";
cmbprice.SelectedIndex = 0;
}
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace 19
{
class complex
{
int real, imaginary, i_imaginary;
public voidget()
{
Console.WriteLine("enter real:");
real = Int32.Parse(Console.ReadLine());
Console.WriteLine("enter imaginary:");
imaginary = Int32.Parse(Console.ReadLine());
Console.WriteLine("enter i_imaginary:");
i_imaginary = Int32.Parse(Console.ReadLine());
}
public voidprint()
{
Console.WriteLine("complex number is:" + real + " + " + imaginary + " i +" + i_imaginary);
}
public static complex operator +(complex c1, complex c2)
{
complex tmp = newcomplex();
tmp.real = c1.real + c2.real;
tmp.imaginary = c1.imaginary + c2.imaginary;
tmp.i_imaginary = c1.i_imaginary + c2.i_imaginary;
returntmp;
}
publicstatic complex operator -(complex c1, complex c2)
{
complex tmp = newcomplex();
tmp.real = c1.real - c2.real;
tmp.imaginary = c1.imaginary - c2.imaginary;
tmp.i_imaginary = c1.i_imaginary - c2.i_imaginary;
return tmp;
}
public static complex operator ++(complex c1)
{
complex tmp = newcomplex();
tmp.real = c1.real + 1;
tmp.imaginary = c1.imaginary + 1;
tmp.i_imaginary = c1.i_imaginary + 1;
return tmp;
}
public static complex operator --(complex c1)
{
complex tmp = newcomplex();
tmp.real = c1.real - 1;
tmp.imaginary = c1.imaginary - 1;
tmp.i_imaginary = c1.i_imaginary - 1;
return tmp;
}
static void Main(string[] args)
{
complex c1 = newcomplex();
complex c2 = newcomplex();
complex c3 = newcomplex();
c1.get();
c2.get();
c3 = c1 + c2;
c3.print();
c3 = c1 - c2;
c3.print();
c3++;
c3.print();
c3--;
c3.print();
Console.ReadLine();
}
}
}
OUTPUT:-
20.. Write a program of sorting an array. Declare single dimensional array and accept 5 integer values from the
user. Then sort the input in ascending order and display output using generics.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespace 20
{
classprogram22
{
public static voidMain(String[] args)
{
List<int> l1=newList<int>();
Console.WriteLine("enter values:");
for (inti = 0; i<= 4; i++)
{
l1.Add(Int32.Parse(Console.ReadLine()));
l1.Sort();
Console.WriteLine("sorted array:");
foreach(int s in l1)
Console.WriteLine(s);
Console.ReadLine();
}
}
}
OUTPUT:-
21. Write a program to accept 10 marks of students in a subject out of 10. Calculate the % of marks
of each student out of 100 and store in second array. Display the % marks of all the students
excluding the highest and lowest marks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 21
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter the principle amount");
int p = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the rate of interest");
int r = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the time period");
int t = Convert.ToInt32(Console.ReadLine());
Console.ReadLine();
}
}
}
OUTPUT:-
22. Define an interface named istack with the following methods:-
(i) Push and pop elements from stack.
(ii) Check whether the stack is empty or not.
Implement the stack with the help of arrays and if the size of the array becomes too
small to hold the elements, create a new one. Test this interface by inheriting it in its
subclass.
using System;
usingSystem.Collections.Generic;
using System.Linq;
using System.Text;
namespace 22
{
Interface istack
{
` voidpush(int x);
intpop();
void sempty();
class Program:istack
{
int[] ele;
int top;
int max;
public Program()
{
Console.WriteLine("enter the size of array");
int n=Convert.ToInt32(Console.ReadLine());
ele=newint[n];
top = -1;
max = n;
}
public void push(int y)
{
if (top == max - 1)
{
Console.WriteLine("stack overflow");
}
else
{
ele[++top] = y;
}
}
public intpop()
{
if (top == - 1)
{
Console.WriteLine("stack underflow");
return -1;
}
else
{
Console.WriteLine("poped element is"+ele[top]);
return ele[top--];
}
Console.ReadLine();
}
public cvoidsempty()
{
if (top == -1)
{
Console.WriteLine("stack underflow");
}
else
{
for (int i = 0; i <= top; i++)
{
Console.WriteLine("items are" + ele[i]);
}
}
Console.ReadLine();
}
p.push(10);
p.push(20);
p.push(30);
p.push(40);
p.sempty();
p.pop();
p.pop();
}
}
}
OUTPUT:-
23. Create a class MyMessageEvent with two methods as event handlers Handler() and
Message(). Declare a Delegate MyEvtHDel and a class EventMessageClass with a event
MyMessageEvt and a method OnMyMessageEvt to trigger the event and call the event handlers
methods when the event is fired.
using System;
namespace 23
{
public delegate void MyEvtHDel();
classProgram
{
class MyMessageEvent
{
public voidHandler()
{
Console.WriteLine("\n\n Event Handler is called");
}
publicvoidMessage()
{
Console.WriteLine("\n\n Message is called");
}
}
classEventMessageClass : MyMessageEvent
{
publicevent MyEvtHDel MyMessageEvt;
publicvoidOnMyMessageEvt()
{
MyMessageEvt += newMyEvtHDel(Handler);
MyMessageEvt += newMyEvtHDel(Message);
MyMessageEvt.Invoke();
}
}
}
Output:
24. Write a C# program to add elements to a XML file (Student database) and retrieve values form the
XML file where student name starts with ‘A’ and ‘D’ using LINQ.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace 24
class Program
Student[] std =
};
select s;
Console.ReadKey();
class Student
Name = n;
Roll = r;
root.AppendChild(rec);
XmlElementrecName = xmlDoc.CreateElement("Name");
XmlTexttxtName = xmlDoc.CreateTextNode(Name);
root.LastChild.AppendChild(recName);
root.LastChild.LastChild.AppendChild(txtName);
XmlElementrecRoll = xmlDoc.CreateElement("Roll");
XmlTexttxtRoll = xmlDoc.CreateTextNode(Roll);
root.LastChild.AppendChild(recRoll);
root.LastChild.LastChild.AppendChild(txtRoll);
XmlElementrecMarks = xmlDoc.CreateElement("Marks");
XmlTexttxtMarks = xmlDoc.CreateTextNode(Marks);
root.LastChild.AppendChild(recMarks);
root.LastChild.LastChild.AppendChild(txtMarks);
xmlDoc.Save(strFile);
Output :-
25.Create a class called Fraction that can be used to represent the ratio of two integers. Include appropriate
constructor, properties and methods. If the denominator becomes zero, throw and handle appropriate exception.
Create another class to test the fraction class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 25
{
class fraction : Exception
{
int n, d;
public fraction(int n, int d)
{
this.n = n;
this.d = d;
}
public void calFraction()
{
float f;
f=(float)n/d;
Console.WriteLine("fraction is:{0}",f);
}
}
class program14
{
static void Main(string[] args)
{
int num, den;
try
{
Console.WriteLine("enter numerator:");
num = Int32.Parse(Console.ReadLine());
Console.WriteLine("enter denominator:");
den = Int32.Parse(Console.ReadLine());
if (den == 0)
throw new System.DivideByZeroException("division by zero");
else
{
fraction f = new fraction(num, den);
f.calFraction();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
}
}
OUTPUT:-
26.Write an XML document for students with 5 record entries. Read the records in C# file and also insert a new record in
the file. And then display students record in class using LINQ.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace 26
{
class Program
{
Student[] std =
{
new Student("Akash", "01", "98"),
new Student("Ramu", "05", "88"),
new Student("Dhawan", "02", "90"),
new Student("Raghav", "03", "95"),
new Student("Rakhi", "06", "78")
};
select s;
Console.WriteLine("\nAfter reading data from .xml file.......");
foreach (Student s in sInfo)
{
Console.WriteLine("Name: {0}\nRoll No.: {1}\nMarks: {2}", s.Name, s.Roll, s.Marks);
Console.WriteLine("........................");
}
Console.ReadKey();
}
}
class Student
{
public String Name { get; set; }
public String Roll { get; set; }
public String Marks { get; set; }
Roll = r;
Marks = m;
String strFile = @"E:\C#\winform\ConsoleApplication17\ConsoleApplication17\XMLFile1.xml";
XmlDocumentxmlDoc = new XmlDocument(); xmlDoc.Load(strFile);
XmlElementrecName = xmlDoc.CreateElement("Name");
XmlTexttxtName = xmlDoc.CreateTextNode(Name);
root.LastChild.AppendChild(recName);
root.LastChild.LastChild.AppendChild(txtName);
XmlElementrecRoll = xmlDoc.CreateElement("Roll");
XmlTexttxtRoll = xmlDoc.CreateTextNode(Roll);
root.LastChild.AppendChild(recRoll);
root.LastChild.LastChild.AppendChild(txtRoll);
XmlElementrecMarks = xmlDoc.CreateElement("Marks");
XmlTexttxtMarks = xmlDoc.CreateTextNode(Marks);
root.LastChild.AppendChild(recMarks);
root.LastChild.LastChild.AppendChild(txtMarks);
Console.WriteLine("Name: {0}\nRoll No.: {1}\nMarks: {2}\nInserted Successfully.....", Name, Roll, Marks);
xmlDoc.Save(strFile);
}
}
}
Output:-
28. WAP to obtain the positive values contained in an array of integer using LINQ.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Question19
scores[i] = Convert.ToInt32(Console.ReadLine());
OUTPUT:
29.WAP to create two classes product { pno and pname properties}, order { pno, orderno and quantity
properties.And fetch the product name of all the orders using LINQ.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication18
{
class Products
{
int pn;
String pnm;
public Products(int a, String b)
{
pn = a;
pnm = b;
}
public int pno{ get; set; }
public string pname{ get; set; }
}
class Orders
{
int pn;
int on;
int qnt;
public Orders(int a, int b, int c)
{
pn = a;
on = b;
qnt = c;
}
public int pno{ get; set; }
public int orderno{ get; set; }
public int quantity { get; set; }
}
class Temp
{
public int pn;
public String pnm;
public int on;
public int qnt;
public Temp(int a, String b, int c, int d)
{
pn = a;
pnm = b;
on = c;
qnt = d;
}
}
class Program
{
static void Main(string[] args)
{
Products[] products = { new Products(01, "Shirt"), new Products(02, "Jeans"), new Products(03, "T-Shirt") };
Orders[] orders = { new Orders(01, 9801, 50), new Orders(02, 9805, 30), new Orders(03, 9891, 100)
};
var prod = from product in products join order in orderson product.pno equals order.pno
select new Temp(product.pno, product.pname, order.orderno, order.quantity);
foreach(Temp t in prod)
{
Console.WriteLine("\nName: " + t.pnm +"\nProduct No.: "+t.pn+"\nOrder No.: "+t.on+"\nQuantity:
"+t.qnt+"\n.................................................");
}
Console.ReadKey();
}
}
}
OUTPUT:-
30.WAP that uses order by to retrieve the values in an int array in ascending order using LINQ.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespacec 30
{
classprogram30
{
public static void Main(String[] args)
{
int[] arr = { 1, -2, 5, -7, 3 };
Console.Read();
}
}
}
OUTPUT:-
31.Write a C# Program to connect the console based program to ADO.NET and solve the result through the LINQ
query.
using System;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
class Program
{
static void Main(string[] args)
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\C#\\32\\sample.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
string sql = "select SID, SNAME, SGENDER from student";
OleDbCommandcmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();
Console.WriteLine("SID \t\tSNAME\t\t SGENDER");
Console.WriteLine("==============================================");
while (reader.Read())
{
Console.Write(reader.GetInt32(0) + "\t \t");
Console.Write(reader.GetString(1).ToString() + "\t \t ");
Console.Write(reader.GetString(2).ToString() + "\n");
}
reader.Close();
conn.Close();
}
}
OUTPUT:-
32. Write a windows form application to connect to ADO.NET (Emp database) and insert, update and
delete records in the database also write functionality to retrieve the data from database. Create the
usecase diagram, DFD and Flow graph for the same.
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 System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=d:\\DB\\student.mdb");
public Form1()
{
InitializeComponent();
display();
}
public void display()
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=d:\\DB\\student.mdb");
conn.Open();
OleDbCommandcmd = new OleDbCommand("SELECT * from student", conn); OleDbDataAdapter
da = new OleDbDataAdapter(cmd); DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
conn.Open();
OleDbCommandcmd = new OleDbCommand("insert into student values(" +
Convert.ToInt32(textBox1.Text) + ",'" + textBox3.Text + "','" + textBox2.Text + "');",conn);
cmd.ExecuteNonQuery();
conn.Close();
display();
MessageBox.Show("Record inserted");
}
private void button4_Click(object sender, EventArgs e)
{
conn.Open();
var name = textBox2.Text;
var addr = textBox3.Text;
var id = Convert.ToInt32(textBox1.Text);
OleDbCommandcmd = new OleDbCommand("UPDATE student SET StudName ="+name+", Address ="+addr+" WHERE
StudNo="+id+";", conn);
cmd.Parameters.Clear();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("StudName", textBox2.Text);
cmd.Parameters.AddWithValue("Address", textBox3.Text);
\cmd.Parameters.AddWithValue("id", Convert.ToInt32(textBox1.Text));
cmd.ExecuteNonQuery();
conn.Close();
display();
MessageBox.Show("Record Updated");
}
private void button3_Click(object sender, EventArgs e)
{
var id = Convert.ToInt32(textBox1.Text);
conn.Open();
OleDbCommandcmd = new OleDbCommand("DELETE from student WHERE StudNo = "+id+";",
conn);
cmd.ExecuteNonQuery();
conn.Close();
display();
MessageBox.Show("Record Deleted ");
}
}
}
Output :-