Вы находитесь на странице: 1из 76

# 1.

## Write programs to create a console application

a) Write a program which reads Principal amount, Rate of interest and Time from user and calculate Simple Interest,
Compound Interest and the difference between them.

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

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

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

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");

}
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
{
{
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();
}
}

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 : ");
r.reverse(ref str);
}
}
}

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;

## for (int i = 0; i < CheckString.Length / 2; i++)

{
if (CheckString[i] != CheckString[strMaxIndex - i])
{
returnfalse;
}
}
returntrue;
}
publicstaticvoid Main(string[] args)
{
Console.Write("\n Enter a string you want to check : ");
string str = Console.ReadLine();
if (CheckPalindrome(str))
{
Console.WriteLine("\n {0} is a Palindrome String.", str);
}
Else
{
Console.WriteLine("\n {0} is not a Palindrome String.", str);
}
}
}
}

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 = ");
Console.WriteLine("\n Decimal Number = " + decNum);
oct.decToOctal(decNum);
}
}
}
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 : ");
Console.WriteLine("\nFrequency of the = " + counting.CountStringOccurrences(str,
"a"));
}
}
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();

## Console.Write("\n\n Enter the value of length = ");

Console.Write("\nEnter the value of breadth = ");

ar = fun.area(length, breadth);

}
}
}
Output:

## d) Displays the multiplication table of number.

using System;
namespace ConsoleApp2
{
classtable
{
publicstaticvoidMain()
{
int tb, num;
Console.Write("\n Enter the number to generate its table = ");
Console.WriteLine("\n Table of " + num + " is : ");
for (int i = 1; i <= 10; i++)
{
tb = num * i;
Console.WriteLine(" " + num + " * " + i + " = " + tb);
}
}
}
}
Output:

e) Reverses a number.

using System;
namespace ConsoleApp2
{
classReverse
{
publicstaticvoidMain()
{
int rev = 0, rem, num;
Console.Write("\n Enter a number = ");
for (int i = num; i > 0; i = i / 10)
{
rem = i % 10;
rev = rev * 10 + rem;
}

## Console.WriteLine("\n Reverse of the number = " + rev);

}
}
}
Output:
Q4. WAP in C# to enter a path of a directory and list all the files in the directory.

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

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

## int numLength = number.Length;

//sorting an array

flag = false;

## if (number[j + 1] > number[j])

temp = number[j];

## number[j] = number[j + 1];

number[j + 1] = temp;

flag = true;
}

//Sorted array

## foreach (int num in number)

Console.Write("\t {0}",num);

OUTPUT:
b. Insertion Sort.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace InsertionSort

class Program

## Console.Write(numarray[k] + " ");

Console.Write("\n");

## for (int i = 1; i< max; i++)

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(numarray[k] + " ");

Console.Write("\n");

//Console.Write("/*** " + (i + 1).ToString() + " numbers from the begining of the array are input and they
are sorted ***/\n");

## Console.Write("Sorted [" + (i + 1).ToString() + "] element: ");

Console.Write(numarray[i]);

Console.Write("\n");

return 0;

## static void Main(string[] args)

InsertionSorting();

}
OUTPUT:

c. Quicksort

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace QuickSort

class QuickSort

while (true)

## while (numbers[left] < pivot)

left++;
while (numbers[right] > pivot)

right--;

## int temp = numbers[right];

numbers[right] = numbers[left];

numbers[left] = temp;

else

return right;

// For Recusrion

if (pivot > 1)

## int[] numbers = new int[max];

for (int i = 0; i< max; i++)

## Console.Write("Input int array : ");

Console.Write("\n");

## Console.Write(numbers[k] + " ");

Console.Write("\n");

## for (int i = 0; i< max; i++)

Console.WriteLine(numbers[i]);

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;

## if (numbers[left] <= numbers[mid])

temp[pos++] = numbers[left++];

else

temp[pos++] = numbers[mid++];

## while (left <= eol)

temp[pos++] = numbers[left++];

## while (mid <= right)

temp[pos++] = numbers[mid++];

## for (i = 0; i< num; i++)

numbers[right] = temp[right];

right--;
}

int mid;

## Console.Write("Input int array : ");

Console.Write("\n");

## Console.Write(numbers[k] + " ");

Console.Write("\n");

## Console.WriteLine("MergeSort By Recursive Method");

SortMerge(numbers, 0, max - 1);

## for (int i = 0; i< max; i++)

Console.WriteLine(numbers[i]);

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

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

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();

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

## static String orOp()

{
for (int i = 0; i< 4; i++)
{
if ((x[i] == 1) | (y[i] == 1))
z[i] = 1;
else
z[i] = 0;
}
return "OR Operation......";
}
static void notOp()
{
Console.WriteLine("NOT Operation......\nX\tZ\n\n0\t1\n1\t0\n");
}
static String nandOp()

{
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) +
" = ");
total = total + s[j];
}

## perc = (total / max) * 100;

Console.WriteLine("\nTotal = " + total);
Console.WriteLine("Percentage = " + perc + "%\n");

a[i] = perc;
}

Array.Sort(a);
foreach (float a in a)
{
Console.Write(a);
Console.Write(' ');
}

## Console.WriteLine("\n\nHighest Percentage = " + a[9] + "%");

Console.WriteLine("Lowest Percentage = " + a[0] + "%");
Console.WriteLine("\nAfter excluding highest and lowest Percentage : ");
for (int i = 2; i < 9; i++)
{
if(a[i] != a[0] && a[i] != a[9])
{
Console.WriteLine(a[i] + "%");
}
}
}
}
classstu
{
publicstaticvoidMain(String[] args)
{
student ob = newstudent();
ob.calc();
}
}

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++)
Console.WriteLine("enter Array 2 elements:");
for (inti = 0; i< 5; i++)
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]);
}
}
}
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.leap();
}
int y;
{
Console.WriteLine("Enter the Year: ");
}
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);
}
}
}
}

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;

## Console.Write("\n Enter Your Pin Number = ");

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");

## Console.Write("\n Enter your choice = ");

switch (choice)
{
case 1:
Console.WriteLine("\n Your balance in Rs : {0} ", amount);
break;
case 2:
Console.Write("\n Enter the amount to withdraw = ");
if (withdraw % 100 != 0)
{
Console.WriteLine("\n Please enter the amount multiples of 100");
}
elseif (withdraw > (amount - 500))
{ {
Console.WriteLine("\n Insufficient balance");
}
else

## amount = amount - withdraw;

Console.WriteLine("\n Your current balance is {0}", amount);

break;
case 3:
Console.Write("\n Enter the amount to deposit it = ");
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);
}
}
}

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.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();
}

## privatevoid btncalcResult_Click(object sender, EventArgs

{
sno = int.Parse(txtStuNo.Text);
cs = int.Parse(txtCS.Text);
java = int.Parse(txtJava.Text);
cg = int.Parse(txtCG.Text);
sname = Convert.ToString(txtStuName.Text);

## tot = cs + java + cg;

txtTotal.Text = tot.ToString();

average = tot / 3;

txtAvg.Text = average.ToString();

## if (average >= 40 || average <= 100)

{
txtResult.Text = "Pass";
}
else
{
txtResult.Text = "Fail";
}
}

## privatevoid btnclr_Click(object sender, EventArgs e)

{
txtStuNo.Text = " ";
txtStuName.Text = " ";
txtCS.Text = " ";
txtJava.Text = " ";
txtCG.Text = " ";
txtTotal.Text = " ";
txtAvg.Text = " ";
txtResult.Text = " ";
}

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

## privatevoid btnpalindrome_Click(object sender, EventArgs e)

{
num = int.Parse(txtInput.Text);
temp = num;

## for (int i = num; i > 0; i = i / 10)

{
rem = i % 10;
rev = rev * 10 + rem;
}
if (temp == rev)
{
txtResult.Text = "Palindrome";
}
else
{
txtResult.Text = "Not Palindrome";
}
}

## private void btnfibonacci_Click(object sender, EventArgs e)

{
string result = null;
num = int.Parse(txtInput.Text);
int firstNum = 0, secondNum = 1, thirdNum;

{

## thirdNum = firstNum + secondNum;

result += Convert.ToString(thirdNum) + " ";
firstNum = secondNum;
secondNum = thirdNum;

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

## privatevoid btnbin_Click(object sender, EventArgs e)

{
int binaryNum = 0;

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

## private void btnoct_Click(object sender, EventArgs e)

{
int octaNum = 0;

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

## private void btnhexa_Click(object sender, EventArgs e)

{
int hexaNum = 0;

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();

## for (int i = 0; i <ch.Length; i++)

{
if (char.IsDigit(ch[i]))
{
digits++;
}
elseif (char.IsLetter(ch[i]))
{
Char++;
}
elseif (ch[i] == ' ' || ch[i] == '\n' || ch[i] == '\t')
{
words++;
}
else
{
spChar++;
}
}
txtWords.Text = words.ToString();
txtChar.Text = Char.ToString();
txtDigits.Text = digits.ToString();
txtSpChar.Text = spChar.ToString();
}
private void btnClr_Click(object sender, EventArgs e)
{
txtWords.Text = " ";
txtChar.Text = " ";
txtDigits.Text = " ";
txtSpChar.Text = " ";
}
}
} Output:-
f. 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 14f
{
public partial classcrpt : Form
{
publiccrpt()
{
InitializeComponent();
FillComboBox();
}

private voidFillComboBox()
{
Dictionary<string, string> test = new Dictionary<string, string>();
cmbprice.DataSource = new BindingSource(test, null);
cmbprice.DisplayMember = "Value";
cmbprice.ValueMember = "Key";
cmbprice.SelectedIndex = 0;
}

## private void btnCal_Click(object sender, EventArgs e)

{
string length = txtlength.Text;
string width = txtwidth.Text;
string price = ((KeyValuePair<string, string>)cmbprice.SelectedItem).Value;
if (string.IsNullOrEmpty(length))
{
}
elseif (string.IsNullOrEmpty(width))
{
}
else
{
lblTotalPrice.Text = Convert.ToString(Convert.ToInt32(length) *
Convert.ToInt32(width) * Convert.ToInt32(price));
}
}

## private void btClr_Click(object sender, EventArgs e)

{
txtlength.Text = txtwidth.Text = lblTotalPrice.Text = "";
cmbprice.SelectedIndex = 0;
}
}
}
Output:-
15.. Design a class to represent a bank account. Include following members:
Data members: - Name of depositor, Account Number, Type of Account, Balance amount in the account, and
Methods: - To assign initial values, To deposit an amount, To withdrawal an amount after checking balance,
To display name and the balance. Write a C# program to demonstrate the working of the various class
members.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;

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: ");
}

void amountDeposit()
{
Console.Write("Enter the amount have to deposite: "); Double 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");

## Console.Write("\nEnter your choice: ");

switch (choice)
{
case 1:
ob.amountDeposit();
ob.checkBalance();
break;
case 2:
ob.amountWithdraw();
ob.checkBalance();
break;
case 3:
Console.Write("\nHello " + ob.name + " ");
ob.checkBalance();
break;
default:
Console.Write("\nPlease enter a valid choice...");
continue;
}
} while (choice != 4);
}
}
}

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

## public void displayDetails(string furniture)

{
Console.WriteLine("\n\n Descriptions of the " + furniture + ":\n");
if (furniture == "Sofa")
{
price = 26000;
weight = 44;
int size = 55;
warranty = 12;
Console.WriteLine(" Price of the " + furniture + " = " + price);
Console.WriteLine(" Size of the " + furniture + " = " + size + " inches ");
Console.WriteLine(" Weight of the " + furniture + " = " + weight + " kgs");
Console.WriteLine(" Warranty Period of the " + furniture + " is = " + warranty
+”months");
}
elseif (furniture == "Coat & Hat Rack")
{
price = 14000;
weight = 20;
warranty = 7;
int length = 14;
Console.WriteLine(" Price of the " + furniture + " = " + price);
Console.WriteLine(" Length of the " + furniture + " = " + length);
Console.WriteLine(" Weight of the " + furniture + " = " + weight + " kgs");
Console.WriteLine(" Warranty Period of the " + furniture + " is = " + warranty + "
months");
}
elseif (furniture == "Bed")
{
price = 27499;
weight = 85;
warranty = 36;
Console.WriteLine(" Price of the " + furniture + " = " + price);
Console.WriteLine(" Weight of the " + furniture + " = " + weight + " kgs");
Console.WriteLine(" Warranty Period of the " + furniture + " is = " + warranty + "
months");
}
else
{
Console.WriteLine(" "+ furniture + " is out of stock ");
}
}

## Public void discount( string furniture)

{
if (price >= 1000)
{
double discount = price * 0.20;
double discountedPrice = price - discount;
Console.WriteLine("\n The Price of " + furniture + " after 20% discount = " +
discountedPrice);
}
}

## Public static void Main(string[] args)

{
Furniture f = newFurniture();
string furniture;
Console.Write("\n\n Enter the type of Furniture : ");

f.displayDetails(furniture);
f.discount(furniture);

}
}
}

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>();
cmbprice.DataSource = new BindingSource(test, null);
cmbprice.DisplayMember = "Value";
cmbprice.ValueMember = "Key";
cmbprice.SelectedIndex = 0;
}

## private void btnCal_Click(object sender, EventArgs e)

{
string length = txtlength.Text;
string width = txtwidth.Text;
string price = ((KeyValuePair<string, string>)cmbprice.SelectedItem).Value;
if (string.IsNullOrEmpty(length))
{
}
elseif (string.IsNullOrEmpty(width))
{
}
else
{
lblTotalPrice.Text = Convert.ToString(Convert.ToInt32(length) *
Convert.ToInt32(width) * Convert.ToInt32(price));
}
}

## private void btClr_Click(object sender, EventArgs e)

{
txtlength.Text = txtwidth.Text = lblTotalPrice.Text = "";
cmbprice.SelectedIndex = 0;
}
}
}
Output:
19.Write a program to input a complex number that has three parts- real, imaginary and
i_imaginary. Overload unary ++ & -- operator to increment/decrement the complex number. + and -
operators to add and substract two complex numbers.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;

namespace 19
{
class complex
{
int real, imaginary, i_imaginary;
public voidget()
{
Console.WriteLine("enter real:");
Console.WriteLine("enter imaginary:");
Console.WriteLine("enter i_imaginary:");

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

}
}

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.Sort();

Console.WriteLine("sorted array:");
foreach(int s in l1)
Console.WriteLine(s);
}
}
}

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());

## 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());

## Console.WriteLine("compound interest is "+c_i);

int result = c_i - s_i;
Console.WriteLine("difference between copount interest and simple interest is"+result);

}
}
}
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");
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--];
}

}
public cvoidsempty()
{
if (top == -1)
{
Console.WriteLine("stack underflow");
}
else
{
for (int i = 0; i <= top; i++)
{
Console.WriteLine("items are" + ele[i]);
}
}
}

## static void Main(string[] args)

{
Program p = newProgram();

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
{

## static void Main(string[] args)

{
EventMessageClass obj = newEventMessageClass();
obj.OnMyMessageEvt();
}
}

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.Xml;

using System.Xml.Linq;

namespace 24

class Program

Student[] std =

};

select s;

{

## Console.WriteLine("Name: {0}\nRoll No.: {1}\nMarks: {2}", s.Name, s.Roll, s.Marks);

Console.WriteLine("........................");

class Student

Name = n;

Roll = r;

## XmlElement rec = xmlDoc.CreateElement("Student");

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

## Console.WriteLine("Name: {0}\nRoll No.: {1}\nMarks: {2}\nInserted Successfully.....", Name, Roll, Marks);

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:");
Console.WriteLine("enter denominator:");
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());
}
}

}
}
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.Xml;
using System.Xml.Linq;

namespace 26
{
class Program
{

## static void Main(string[] args)

{

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

## var sInfo = from s in std

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("........................");
}

}
}

class Student
{
public String Name { get; set; }
public String Roll { get; set; }
public String Marks { get; set; }

## public Student(String n, String r, String m)

{
Name = n;

Roll = r;
Marks = m;
String strFile = @"E:\C#\winform\ConsoleApplication17\ConsoleApplication17\XMLFile1.xml";
XmlDocumentxmlDoc = new XmlDocument(); xmlDoc.Load(strFile);

## XmlElement root = xmlDoc.DocumentElement;

XmlElement rec = xmlDoc.CreateElement("Student");
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);
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

## int highScoreCount = scores.Where(n => n > 0).Count();

Console.WriteLine("\n\n{0} Numbers are Positive", highScoreCount);

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;
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.................................................");
}
}
}
}

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

## foreach (int n in q1)

{
Console.WriteLine(n);
}

}

}
}

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();
Console.WriteLine("SID \t\tSNAME\t\t SGENDER");
Console.WriteLine("==============================================");

{
Console.Write(reader.GetInt32(0) + "\t \t");
Console.Write(reader.GetString(1).ToString() + "\t \t ");
}

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

## Нижнее меню

### Получите наши бесплатные приложения

Авторское право © 2021 Scribd Inc.