C# Practice Problems

Here is a list of C# practice problems

 

C# Practice Exercises

Prepared by

Dr. Osman Khalid

http://osman.pakproject.com

References:                                                            Updated on 17th June 2016

(1)           Fundamentals of Computer Programming with C# (Svetlin Nakov & Co.)

(2)           Free online resources

(3)           Personal resources.

 

 

  1. Write a console application that prints your first and last name on the console. [SOLUTION]
  2. Write a program that prints the following numbers on the console 1, 101, 1001, each on a new line, up to total of 10 numbers. [SOLUTION]
  3. Write a program that prints on the console the current date and time.
  4. Write a program that prints the square root of 12345.
  5. Write a program that prints the first 100 members of the sequence 2, -3, 4, -5, 6, -7, 8.
  6. Write a program that reads your age from the console and prints your age after 10 years.
  7. Declare several variables by selecting for each one of them the most appropriate of the types sbyte, byte, short, ushort, int, uint, long and ulong in order to assign them the following values: 52,130; -115; 4825932; 97; -10000; 20000; 224; 970,700,000; 112; -44; -1,000,000; 1990; 123456789123456789.
  8. Which of the following values can be assigned to variables of type float, double and decimal: 5, -5.01, 34.567839023; 12.345; 8923.1234857; 3456.091124875956542151256683467?
  9. Write a program, which compares correctly two real numbers with accuracy at least 000001.
  10. Initialize a variable of type int with a value of 256 in hexadecimal format (256 is 100 in a numeral system with base 16).
  11. Declare a variable isMale of type bool and assign a value to it depending on your gender.
  12. Declare two variables of type string with values “Hello” and “World”. Declare a variable of type object. Assign the value obtained of concatenation of the two string variables (add space if necessary) to this variable. Print the variable of type object.
  13. Declare two variables of type string and give them values “Hello” and “World”. Assign the value obtained by the concatenation of the two variables of type string (do not miss the space in the middle) to a variable of type object. Declare a third variable of type string and initialize it with the value of the variable of type object (you should use type casting).
  14. Declare two variables of type string and assign them a value “The “use” of quotations causes difficulties.” (without the outer quotes). In one of the variables use quoted string and in the other do not use it.
  15. Write a program to print a figure in the shape of a heart by the sign “o“.
  16. Write a program that prints on the console isosceles triangle which sides consist of the copyright character “©“.
  17. A company dealing with marketing wants to keep a data record of its employees. Each record should have the following characteristic – first name, last name, age, gender (‘m’ or ‘f’) and unique employee number (27560000 to 27569999). Declare appropriate variables needed to maintain the information for an employee by using the appropriate data types and attribute names.
  18. Declare two variables of type int. Assign to them values 5 and 10 respectively. Exchange (swap) their values and print them.
  19. Write an expression that checks whether an integer is odd or even.
  20. Write a Boolean expression that checks whether a given integer is divisible by both 5 and 7, without a remainder. [SOLUTION]
  21. Write an expression that looks for a given integer if its third digit (right to left) is 7.
  22. Write an expression that checks whether the third bit in a given integer is 1 or 0. [SOLUTION]
  23. Write an expression that calculates the area of a trapezoid by given sides a, b and height h.
  24. Write a program that prints on the console the perimeter and the area of a rectangle by given side and height entered by the user.
  25. The gravitational field of the Moon is approximately 17% of that on the Earth. Write a program that calculates the weight of a man on the moon by a given weight on the Earth.
  26. Write an expression that checks for a given point {x, y} if it is within the circle K({0, 0}, R=5). Explanation: the point {0, 0} is the center of the circle and 5 is the radius.
  27. Write an expression that checks for given point {x, y} if it is within the circle K({0, 0}, R=5) and out of the rectangle [{-1, 1}, {5, 5}]. Clarification: for the rectangle the lower left and the upper right corners are given.
  28. Write a program that takes as input a four-digit number in format abcd (e.g. 2011) and performs the following actions:

– Calculates the sum of the digits (in our example 2+0+1+1 = 4).

– Prints on the console the number in reversed order: dcba (in our example 1102).

– Puts the last digit in the first position: dabc (in our example 1201).

– Exchanges the second and the third digits: acbd (in our example 2101).

  1. Write a program that checks if a given number n (1 < n < 100) is a prime number (i.e. it is divisible without remainder only to itself and 1).
  2. Write a program that reads from the console three numbers of type int and prints their sum.
  3. Write a program that reads from the console the radius r” of a circle and prints its perimeter and area.
  4. A given company has name, address, phone number, fax number, web site and manager. The manager has name, surname and phone number. Write a program that reads information about the company and its manager and then prints it on the console.
  5. Write a program that reads from the console two integer numbers (int) and prints how many numbers between them exist, such that the remainder of their division by 5 is 0. Example: in the range (14, 25) there are 3 such numbers: 15, 20 and 25.
  6. Write a program that reads five integer numbers and prints their sum. If an invalid number is entered the program should prompt the user to enter another number.
  7. Write a program that reads five numbers from the console and prints the greatest of them.
  8. Write a program that reads an integer number n from the console. After that reads n numbers from the console and prints their sum.
  9. Write a program that reads an integer number n from the console and prints all numbers in the range [1…n], each on a separate line.
  10. Write a program that prints on the console the first 100 numbers in the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, …
  11. Write a program that calculates the sum (with precision of 0.001) of the following sequence: 1 + 1/2 – 1/3 + 1/4 – 1/5 + …

 

  1. Write an if-statement that takes two integer variables and exchanges their values if the first one is greater than the second one.
  2. Write a program that shows the sign (+ or ) of the product of three real numbers, without calculating it. Use a sequence of if
  3. Write a program that finds the biggest of three integers, using nested if
  4. Sort 3 real numbers in descending order. Use nested if
  5. Write a program that asks for a digit (0-9), and depending on the input, shows the digit as a word (in English). Use a switch
  6. Write a program that gets the coefficients a, b and c of a quadratic equation: ax2 + bx + c, calculates and prints its real roots (if they exist). Quadratic equations may have 0, 1 or 2 real roots.
  7. Write a program that finds the greatest of given 5 numbers.
  8. Write a program that, depending on the user’s choice, inputs int, double or string If the variable is int or double, the program increases it by 1. If the variable is a string, the program appends “*” at the end. Print the result at the console. Use switch statement.
  9. We are given 5 integer numbers. Write a program that finds those subsets whose sum is 0. Examples:

– If we are given the numbers {3, -2, 1, 1, 8}, the sum of -2, 1 and 1 is 0.

– If we are given the numbers {3, 1, -7, 35, 22}, there are no subsets with sum 0.

  1. Write a program that applies bonus points to given scores in the range [1…9] by the following rules:

– If the score is between 1 and 3, the program multiplies it by 10.

– If the score is between 4 and 6, the program multiplies it by 100.

– If the score is between 7 and 9, the program multiplies it by 1000.

– If the score is 0 or more than 9, the program prints an error message.

  1. Write a program that converts a number in the range [0…999] to words, corresponding to the English pronunciation. Examples:

– 0 –> “Zero”

– 12 –> “Twelve”

– 98 –> “Ninety eight”

– 273 –> “Two hundred seventy three”

– 400 –> “Four hundred”

– 501 –> “Five hundred and one”

– 711 –> “Seven hundred and eleven”

  1. Write a program that prints on the console the numbers from 1 to N. The number N should be read from the standard input.
  2. Write a program that prints on the console the numbers from 1 to N, which are not divisible by 3 and 7 simultaneously. The number N should be read from the standard input.
  3. Write a program that reads from the console a series of integers and prints the smallest and largest of them.
  4. Write a program that prints all possible cards from a standard deck of cards (there are 52 cards: 4 suits of 13 cards).
  5. Write a program that reads from the console number N and print the sum of the first N members of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, …
  6. Write a program that calculates N!/K! for given N and K (1<K<N).
  7. Write a program that calculates N!*K!/(N-K)! for given N and K (1<K<N).
  8. In combinatorics, the Catalan numbers are calculated by the following formula: for n ≥ 0. Write a program that calculates the nth Catalan number by given n.
  9. Write a program that for a given integers n and x, calculates the sum:
  10. Write a program that reads from the console a positive integer number N (N < 20) and prints a matrix of numbers as on the figures below:
  11. Write a program that calculates with how many zeroes the factorial of a given number ends. Examples:

N = 10 -> N! = 3628800 -> 2

N = 20 -> N! = 2432902008176640000 -> 4

Write a program that converts a given number from decimal to binary notation (numeral system).

 

  1. Write a program that converts a given number from binary to decimal notation.
  2. Write a program that converts a given number from decimal to hexadecimal notation.
  3. Write a program that converts a given number from hexadecimal to decimal notation.
  4. Write a program that by a given integer N prints the numbers from 1 to N in random order.
  5. Write a program that given two numbers finds their greatest common divisor (GCD) and their least common multiple (LCM). You may use the formula LCM(a, b) = |a*b| / GCD(a, b).
  6. Write a program that for a given number n, outputs a matrix in the form of a spiral:
  7. Write a program, which creates an array of 20 elements of type integer and initializes each of the elements with a value equals to the index of the element multiplied by 5. Print the elements to the console.
  8. Write a program, which reads two arrays from the console and checks whether they are equal (two arrays are equal when they are of equal length and all of their elements, which have the same index, are equal).
  9. Write a program, which finds the maximal sequence of consecutive equal elements in an array. E.g.: {1, 1, 2, 3, 2, 2, 2, 1} à{2, 2, 2}.
  10. Write a program, which finds the maximal sequence of consecutively placed increasing Example: {3, 2, 3, 4, 2, 2, 4} à{2, 3, 4}.
  11. Sorting an array means to arrange its elements in an increasing (or decreasing) order. Write a program, which sorts an array using the algorithm “selection sort“.
  12. Write a program, which finds the most frequently occurring element in an array. Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} à4 (5 times).
  13. Write a program, which creates square matrices like those in the figures below and prints them formatted to the console. The size of the matrices will be read from the console. See the examples for matrices with size of 4 x 4 and make the other sizes in a similar fashion:
  14. Write a program that converts Roman digits to Arabic
  15. Write a program that converts Arabic digits to Roman
  16. Write a method that returns the English name of the last digit of a given number. Example: for 512 prints “two“; for 1024 à”four“.
  17. Write a method that prints the digits of a given decimal number in a reversed order. For example 256, must be printed as 652.
  18. Write a recursive program that traverses the whole hard disk C:\ recursively and prints all folders and files.
  19. Write a program, which generates and prints on the console 10 random numbers in the range [100, 200].
  20. Write a program, which prints, on the console which day of the week is today.
  21. Write a program which by given two sides finds the hypotenuse of a right triangle. Implement entering of the lengths of the sides from the standard input, and for the calculation of the hypotenuse use methods of the class Math.
  22. Write a program, which calculates the count of workdays between the current date and another given date after the current (inclusive). Consider that workdays are all days from Monday to Friday, which are not public holidays, except when Saturday is a working day. The program should keep a list of predefined public holidays, as well as a list of predefined working Saturdays.
  23. You are given a sequence of positive integer numbers given as string of numbers separated by a space. Write a program, which calculates their sum. Example: “43 68 9 23 318” à461.
  24. Write a program that takes a positive integer from the console and prints the square root of this integer. If the input is negative or invalid print “Invalid Number” in the console. In all cases print “Good Bye”. Use try catch block.
  25. Write a method ReadNumber(int start, int end) that reads an integer from the console in the range [start…end]. In case the input integer is not valid or it is not in the required range throw appropriate exception. Using this method, write a program that takes 10 integers a1, a2, …, a10 such that 1 < a1 < … < a10 < 100.
  26. Write a method that takes as a parameter the name of a text file, reads the file and returns its content as string.
  27. Write a program that reads a string, reverse it and prints it to the console. For example: “introduction” à “noitcudortni“.
  28. Write a program that checks whether the parentheses are placed correctly in an arithmetic expression. Example of expression with correctly placed brackets: ((a+b)/5-d). Example of an incorrect expression: )(a+b)).
  29. Write a program that detects how many times a substring is contained in the text. For example, let’s look for the substring “in” in the text:

 

We are living in a yellow submarine. We don’t have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.

 

The result is 9 occurrences.

 

  1. A text is given. Write a program that modifies the casing of letters to uppercase at all places in the text surrounded by <upcase> and </upcase> Tags cannot be nested.

Example: Result:

 

  1. A string is given, composed of several “forbidden” words separated by commas. Also a text is given, containing those words. Write a program that replaces the forbidden words with asterisks. Sample text: Sample string containing the forbidden words: “C#,CLR,Microsoft“.

Sample result:

 

  1. Write a program that reads two dates entered in the format “month.year” and calculates the number of days between them.
  2. Write a program that reads the date and time entered in the format “month.year hour:minutes:seconds” and prints the date and time after 6 hours and 30 minutes in the same format.
  3. Define a class Student, which contains the following information about students: full name, course, subject, university, e-mail and phone number.
  4. Declare several constructors for the class Student, which have different lists of parameters (for complete information about a student or part of it). Data, which has no initial value to be initialized with null. Use nullable types for all non-mandatory data.
  5. Add a static field for the class Student, which holds the number of created objects of this class.
  6. Add a method in the class Student, which displays complete information about the student.
  7. Modify the current source code of Student class so as to encapsulate the data in the class using properties.
  8. Add an enumeration BatteryType, which contains the values for type of the battery (Li-Ion, NiMH, NiCd, …) and use it as a new field for the class Battery.
  9. There is a book library. Define classes respectively for a book and a library. The library must contain a name and a list of books. The books must contain the title, author, publisher, release date and ISBN-number. In the class, which describes the library, create methods to add a book to the library, to search for a book by a predefined author, to display information about a book and to delete a book from the library. Write a test class, which creates an object of type library, adds several books to it and displays information about each of them. Implement a test functionality, which finds all books authored by Stephen King and deletes them. Finally, display information for each of the remaining books.

 

  1. Write a generic class GenericList<T>, which holds a list of elements of type T. Store the list of elements into an array with a limited capacity that is passed as a parameter of the constructor of the class. Add methods to add an item, to access an item by index, to remove an item by index, to insert an item at given position, to clear the list, to search for an item by value and to override the method ToString().
  2. Write a program that reads from the console a sequence of positive integer numbers. The sequence ends when empty line is entered. Calculate and print the sum and the average of the sequence. Keep the sequence in List<int>.
  3. Implement a hash-table, maintaining triples (key1, key2, value) and allowing quick search by the pair of keys and adding of triples.
  4. Implement a hash-table, allowing the maintenance of more than one value for a specific key.
  5. Implement the data structure PriorityQueue<T>, which offers quick execution of the following operations: adding an element, extracting the smallest element.
  6. We are given a school. The school has classes of students. Each class has a set of teachers. Each teacher teaches a set of courses. The students have a name and unique number in the class. Classes have a unique text identifier. Teachers have names. Courses have a name, count of classes and count of exercises. The teachers as well as the students are people. Your task is to model the classes (in terms of OOP) along with their attributes and operations define the class hierarchy and create a class diagram with Visual Studio.
  7. Define a class Human with properties “first name” and “last name”. Define the class Student inheriting Human, which has the property “mark”. Define the class Worker inheriting Human with the property “wage” and “hours worked”. Implement a “calculate hourly wage” method, which calculates a worker’s hourly pay rate based on wage and hours worked. Write the corresponding constructors and encapsulate all data in properties.
  8. Initialize an array of 10 students and sort them by mark in ascending order. Use the interface IComparable<T>.
  9. Initialize an array of 10 workers and sort them by salary in descending order.
  10. Define an abstract class Shape with abstract method CalculateSurface() and fields width and height. Define two additional classes for a triangle and a rectangle, which implement CalculateSurface(). This method has to return the areas of the rectangle (height*width) and the triangle (height*width/2). Define a class for a circle with an appropriate constructor, which initializes the two fields (height and width) with the same value (the radius) and implement the abstract method for calculating the area. Create an array of different shapes and calculate the area of each shape in another array.
  11. Implement the following classes: Dog, Frog, Cat, Kitten and Tomcat. All of them are animals (Animal). Animals are characterized by age, name and gender. Each animal makes a sound (use a virtual method in the Animal class). Create an array of different animals and print on the console their name, age and the corresponding sound each one makes.
  12. A bank holds different types of accounts for its customers: deposit accounts, loan accounts and mortgage Customers can be individuals or companies. All accounts have a customer, balance and interest rate (monthly based). Deposit accounts allow depositing and withdrawing of money. Loan and mortgage accounts allow only depositing. All accounts can calculate their interest for a given period (in months). In the general case, it is calculated as follows: number_of_months * interest_rate. Loan accounts have no interest rate during the first 3 months if held by individuals and during the first 2 months if held by a company. Deposit accounts have no interest rate if their balance is positive and less than 1000. Mortgage accounts have ½ the interest rate during the first 12 months for companies and no interest rate during the first 6 months for individuals. Your task is to write an object-oriented model of the bank system. You must identify the classes, interfaces, base classes and abstract actions and implement the interest calculation functionality.
  13. Read about the Abstract Factory design pattern and implement it in C#.
  14. Write a class Student with the following properties: first name, last name and age. Write a method that for a given array of students finds those, whose first name is before their last one in alphabetical order. Use LINQ.
  15. Create a LINQ query that finds the first and the last name of all students, aged between 18 and 24 years including. Use the class Student from the previous exercise.
  16. By using the extension methods OrderBy(…) and ThenBy(…) with lambda expression, sort a list of students by their first and last name in descending order. Rewrite the same functionality using a LINQ query.
  17. Write a program that prints to the console all numbers from a given array (or list), that are multiples of 7 and 3 at the same time. Use the built-in extension methods with lambda expressions and then rewrite the same using a LINQ query.
  18. Write an extension method for the class String that capitalizes all letters, which are the beginning of a word in a sentence in English. For example: “this iS a Sample sentence.” should be converted to “This Is A Sample Sentence.“.
  19. Create a hash-table to hold a phone book: a set of person names and their phone numbers (e.g. Kate Wilson à +3592981981, +3598862536; Alex & Co. à 1-800-ALEX; Steve Milton à +496023456). Fill enough random data (e.g. 50,000 key-value pairs). Measure how much time it takes to perform searching by key in the hash-table using its native search capabilities, using the extension methods Contains(…) and IEnumerable.Where(…). Can you explain the difference? (HINT: Dictionary<string, List<string>> )

 

  1. We are given HTML file named html. Write a program, which removes all HTML tags and retains only the text inside them. Output should be written into the file Problem1.txt.

 

  1. Write a method IntegerPower( base, exponent ) that returns the value of base exponent. For example, IntegerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer, and base is an integer. Method IntegerPower should use for or while to control the calculation. Do not use any Math library methods. Create a Console application that reads integer values from console for base and exponent from the user and performs the calculation with the IntegerPower
  2. Create a class named Calculation and in it define a method Hypotenuse that calculates the length of the hypotenuse of a right triangle when the other two sides are given. The method should take two arguments of type double and return the hypotenuse as a double. Incorporate this method into a console application that reads integer values for side1 and side2 from user and performs the calculation with the Hypotenuse Determine the length of the hypotenuse for each of the following triangles:

Triangle   Side 1   Side 2

1      3.0   4.0

2      5.0   12.0

3      8.0   15.0

  1. A Time value stores a time of day such as 10:05 or 00:45 as the number of minutes since midnight (that is, 605 and 45 in these examples). A struct type Time can be declared as follows:

public struct Time {

private readonly int minutes;

public Time(int hh, int mm) {

this.minutes = 60 * hh + mm;

}

public override String ToString() {

return minutes.ToString();

}

}

 

  1. Create a console aplication called TestTime. Modify the Main method to declare variables of type Time, assign values of type Time to them, and print the Time value using Console.WriteLine. Compile and run your program.
  2. Create a class called Complex for performing arithmetic with complex numbers. Write a driver program to test your class. Complex numbers have the form

 

realPart + imaginaryPart * i

 

where i is . Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods for each of the following:

  1. a) Addition of two Complex numbers. The real parts are added together and the imaginary parts are added together.
  2. b) Subtraction of two Complex numbers. The real part of the right operand is subtracted from the real part of the left operand and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
  3. c) Printing of Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.
  4. Write a console application that implements a Square. Class Square should contain an instance property Side that has get and set accessors for private Provide two constructors: one that takes no arguments and another that takes a side length as a value. Write an application class that tests class Square’s functionality.
  5. Using Delegates Write a method IntegerPower( base, exponent ) that returns the value of base exponent. For example, IntegerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer, and base is an integer. Method IntegerPower should use for or while to control the calculation. Do not use any Math library methods. Create a Console application that reads integer values from console for base and exponent from the user and performs the calculation with the IntegerPower
  6. Use operator overloading. Create a class called Complex for performing arithmetic with complex numbers. Write a Main to test your class. Complex numbers have the form realPart + imaginaryPart * i where i is
  7. a) Addition of two Complex numbers. The real parts are added together and the imaginary parts are added together.
  8. b) Subtraction of two Complex numbers. The real part of the right operand is subtracted from the real part of the left operand and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
  9. c) Printing of Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.
  10. Write a program that take seconds from user. Then cast the seconds in resulting hours:minutes.

Example:

int secs = 105;

HourMin hours_mins = (HourMin) secs;

// output will be: 1:45

 

HINT: Use implicit or explicit type casting.

 

  1. Write program of a virtual ping application. The IP addresses are to be stored in a text file, that your program will read and ping the ips.

e.g.,    addresses1.txt

3

192.168.1.10

192.168.1.20

172.18.10.30

 

 

 

 

 

Where 3 is the number of IPs to ping.

  1. Your program should open file for reading, and if file is not found, then throw the FileNotFound exception

 

  1. If the file is not in correct format, e-g it doesn’t have an integer in first line OR, it is not having as many ips as the integer number at top, in that case throw an exception, PingerFileFormatException

 

  1. If the any ip from the list is not in the proper format, i.e., 0-254]. [0-254]. [0-254]. [0-254], then there should be an exception thrown by the application as PingerIPFormatException

 

  1. If we encounter an ip in file whose first part is 100, e-g 100.192.168.20, then there should be an exception thrown as PingerIPTypeException

 

  1. Finally, you will implement this example by coding a class, PingerFileReader , which maintains the connection to the ip addresses file and retrieves data from it. You will code this class in a very safe way, which means that its methods will all throw exceptions if they are called inappropriately; for example, if a method that will read a file is called before the file has even been opened. For this purpose, you will write another exception class, UnexpectedException .
  1. Write a program that calls a function and passes it two numbers. The numbers are added and result is returned and displayed.
  2. What is difference between using out and ref Write a program that passes a function a variable, using (1) out, (2) ref and then the function stores 100 in the variable.
  3. Suppose you have a list of five cities, create the list and display it using foreach loop.
  4. Suppose you ask user to enter “yes” or “no”, and pass the user answer, to a class, in which a function is defined to check what user has entered, using case statement. If user entered “yes” answer should be “yes entered”, if user entered “no” output should be “ no entered”

 

  1. Question: We have 2 Matrices:

 

 

2
3

A =

2
3

B =

 

The matrices are made using Jagged Arrays and if  A[0,0] > B[0,0] then Matrix A is greater than Matrix B.

 

User operator overloading to find out the sum of A and B, and check if A > B.

 

HINT: JAGGED ARRAYS

  1. If we have a nested try catch block as given here

 

 

 

Explain how the exceptions occurring at points A, B, C, D will be handled.

  1. Write a program that asks user to enter password, and if password is incorrectly entered, an exception is thrown, InvalidPasswordException. Create a user defined custom class InValidPasswordException to handle this exception.
  2. Write a simple program creating a thread, in c#.

 

  1. Write a program that declares an interface, with one function void Square(int), and one property, to return the value of number, whose square is calculated by Square function. Also create the main function.
  2. Give a short example with c# syntax of abstract class, with main function.
  3. Create a base class and its one derived class. In base class define a function, that is printing “hello”, and then use base class function into derived class, such that after the derived function is called, the output is “hello World”. Use c# syntax, and also write a main function to call function of derived class.
  4. We have 2 Matrices:

 

 

2
3

A =

2
3

B =

The matrices are made using Jagged Arrays and if  A[i,j] = = B[i,j] then Matrix A is equal to Matrix B, where i,j=0,1

Use operator overloading to find out the sum of A and B, and check if A = B.

  1. Write a program that take hours:minutes from user. Then cast the hours:minutes in resulting secs.

Example:  HourMin hours_mins2 = new HourMin(1, 45);

int secs2 = (int)hours_mins2; // output will be: secs2=105

  1. Using Delegates write a method IntegerMultiply( num1, num2 ) that returns the value of num1 x num2

For example, IntegerMultiply( 3, 4 ) = 3 * 4.

  1. Use operator overloading. Create a class called Complex for performing addition of two complex numbers.

Complex numbers have the form

realPart + imaginaryPart * i

The real parts are added together and the imaginary parts are added together.

  1. A delegate is declared as: delegate string DelegateTest(string val);
  2. Write the program that defines delegate using an anonymous method.
  3. Write a program that creates a registry key MY_REGISTRY_KEY1, under the Registry key HKEY_LOCAL_MACHINE (HKLM). It then creates another registry key MY_REGISTRY_KEY2 under MY_REGISTRY_KEY1. The program then asks user to enter two values: height (of type int), and color (of type string). Now program should ask user to enter his/her choice. If user enters “1”, then the program should ask user for new values of height and color and old values should be modified (overwritten). If user enters “2”, the values of height and color should simply display from registry, and if user enters “3”, the registry values should be deleted, and finally if user enters “4”, the registry key MY_REGISTRY_KEY2 should be deleted.
  4. Write a program that creates hundred threads using for loop. The thread function thread_func is defined in a class MyThreadClass. Each thread is passed an integer number that is the for loop counter variable ctr and the thread_func is printing the message “I am thread number 1” or “I am thread number 2” and so on.
  5. Suppose two matrices X and Y are already input by the user. Write a program to perform swapping of matrices such that rows of X become columns of Y and columns of X become rows of Y. Make sure dimensions are valid or not. No need to show the resultant matrices.
  6. We have an array of strings:

string [,] myarray = { {“one”, “2”, “three”}, {“four”, “five”, “6”},

                       {“7”, “eight”, “9”}};

Write a program that takes a string value as input from user, and search the string value in the above array. If the string value is found, the program should show the indexes value on which the string was found, and show the message “found”. Otherwise, the message should display as “not found”. No need to re-write the above array, just write the searching part as asked in question.

  1. Suppose, a C# program takes as input 3 arguments in command line (dos window), and display them on screen (when enter is pressed by user). Write code of the program. Use foreach loop to display the arguments.
  2. Create a property named StudentName. Define set and get parts, to set and get a string variable named name. In main function, set a value in property, and then display the value from property using WriteLine.
  3. Define a class Teacher with two variables: name, and age. Define a function void SetRecord(string,int) to set values in name and age. Define a function GetRecord() to display values of name and age.
  4. Write a program that declares an interface named as The interface has signatures of one function void Square(int num), and one property SQRTNUM with integer return type. The property does not set value. In derived class named MyClass from the interface IMyInterface, the function Square takes value of num from main() and store its square in a variable int mysqr declared in the derived class. The value of mysqr is returned to main() through property SQRTNUM. Write complete code of Interface IMyInterface, derived class MyClass, and Main function. We assume that Main is already defined in Program class, so no need to define Program Class.
  5. Create a base class MyBaseClass and its one derived class MyDerivedClass. In the base class, define a virtual function show(), that is returning a string “hello”. Override base class function in derived class, such that after the derived function is called, the output is “hello World”. Use c# syntax, and also write a main function to call function of derived class. (Hint: “World” is added as new functionality by derived class function)
  6. We have a base class, Matrix that declares a 2 dimensional array variable int[,] matrix for matrix The class also declares two variables int rows and int cols to store matrix dimensions. Write a function GetMatrix in Matrix class to take a matrix input, by asking for matrix dimensions, and the values of matrix. Write another function, ShowMatrix that shows the Matrix values entered by the user. The program should allow the user (in Main function) to input as many number of matrices as the user wants. Use a loop in Main to input matrices and a loop in Main to output matrices. (Hint: Use matrix array in main function, just like you did in assignment.)
  7. Consider a windows form with following components: (a) textBox1, (b) textBox2, (c) comboBox1, (d) button1, and (e) button2. Write the code for following operations:- (1) When button1 is pressed, value of textBox1 is written in textBox2. (2) When button2 is pressed, value of comboxBox1 is written in textBox2. (3) When an item in comboBox1 is selected, the value of selected item is assigned to textBox1. Just write the function definitions for (1), (2), and (3), no need to define class. Use the following function names/signatures:-

private void button1_Click(object sender, EventArgs e)

private void button2_Click(object sender, EventArgs e)

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

  1. A number variable “x” is called an even number if “x%2=0”. Given an array of integers, named, myArray. Write a program that counts the number of even elements in the
  2. Declare and initialize a 3-dimentional integer array myArray with 2 main-rows, 3 sub-rows, and 4 columns.
  3. We have a following jagged array. Use nested for loop to iterate the array to print array values.

int[][] jagged = new int[3][];

jagged[0] = new int[2] { 1, 2 };

jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 };

jagged[2] = new int[3] { 9, 10, 11 };

 

  1. Given a program:

public static void Main()

{

int j = 20;

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

{

int j = 30;

Console.WriteLine(j + i);

}

}

 

Create a debug/trace table showing the values of i and j for every loop iteration. The table should be like the following:

 

Iteration# i j j+i
0

 

  1. Create a program that passes two integer variables dividend and divisor to a function named Divide with the following signature: public static Tuple<int, int> Divide(int dividend, int divisor).

The Divide function computes the division result  (dividend/divisor) and remainder  (dividend%divisor). The function stores the result and remainder in a Tuple and return Tuple object to the Main function. The Main function should display the value of result and remainder.

  1. Suppose we have a Matrix class, that declared a variable int [,] matrix = new int[2,2]; User is asked to input as many matrices as much (s)he likes, and the program should compute sum of the (2-dim) matrices using “+” operator overloading. Write full code of the program.

HINT: The signature of operator overloading function is:  public static Matrix operator + (Matrix m) {

You might need to declare an array of Matrix class or an ArrayList in Main, whatever you feel easy. Also you need to define a function “GetInput” in Matrix class to take input of values for variable matrix

  1. In a windows Form application, suppose we have a variable named “timer1” of Timer We have a button with ID btnCT on the form, and a textbox with ID, txtcount. By default txtcount is showing value 0, and btnCT is showing text “Start” (as indicated on left of below figure). When “Start” is pressed, the timer function starts incrementing the value of txtcount, and the text of btnCT is changed to “Stop” (see middle figure of the below diagram). When user presses “Stop” button, the timer should stop, and button text should be changed to “Start”. If user again presses “Start”, the value of “txtcount” should start increasing from the last updated value.
  2. You just need to write the code of the following timer event handler:

private void timer1_Tick(object sender, EventArgs e)

{

//Your code here

}

 

 

  1. For the below form, write the asp.net code to store values of the form in database. Suppose you already have declared a SqlConnection object named “con”, and SqlCommand object named “com”. Just write the code for “Save” button’s event handler to save values in database. No need to initialize “con” as we assume it is already initialized with connection string. The database table name is “users” with two fields: primary key userid varchar(50), and birthyear varchar(10). No need to write code for data entry checks.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  1. For the following form given below, create the following programs:

 

  • Create a windows form application for the above form connected with database MS SQL database file (.mdf)
  • Create a ASP.NET form application for the above form connected with database MS SQL database file (.mdf)
  • Create a WPF application for the above form connected with database MS SQL database file (.mdf)
  • Create a ASP.NET MVC form application for the above form connected with database MS SQL database file (.mdf)

 

  1. Write a program in C# console application that asks user to perform following matrix operations.
  2. Matrix Multiplication: User should input two 2-dimensional matrices of dynamic size, means, rows and columns of each matrix must be taken as input by the user (as Console.Readline()).

If  the rows and columns sizes are not violating matrix multiplication rules, the matrices must be multiplied, otherwise, an error message should be shown to the user that the matrices’ dimensions are violating matrix multiplication rules.

  1. Matrix Addition: User should input two 2-dimensional matrices of dynamic size, means, rows and columns of each matrix must be taken as input by the user.

If the rows and columns sizes are not violating matrix addition rules, the matrices must be added, otherwise, an error message should be shown to the user that the matrices’ dimensions are violating matrix addition rules.

  1. Matrix Subtraction: Same as (2), except that the matrix subtraction operation should be done.
  2. Matrix Division: Same as (2), except that the matrix division operation should be done.
  3. Matrix Swapping: Take two dynamic matrices as input from user. Swap the entries of both matrices, such that the row1, row2, row3,…,rowN of matrix1 should become col1, col2, col3,…., colM of matrix2, and row1, row2, row3,…, rowN of matrix2 should become col1, col2,col3,…,colN of matrix.

Example:

Matrix 1

Matrix 2

After swap operation, the output would be something similar to that:

Matrix 1

Matrix 2

#######################################################

When the program is started, it should display the following menu:

 

Matrix Operations

[1] Multiplication

[2] Addition

[3] Subtraction

[4] Division

[5] Swapping

 

Enter your option:  1

 

 

Matrix Entry

Enter rows of M1:  5

Enter cols of M1:  5

 

Enter rows of M2:  5

Enter cols of M2:  5

 

Enter M1[1,1]: 10

Enter M1[1,2]: 20

…..

…..

…..

 

The error case will be something like this:

Matrix Entry

Enter rows of M1:  5

Enter cols of M1:  5

 

Enter rows of M2:  5

Enter cols of M2:  6

 

Input Error: Number columns of M1 must be equal to number rows of M2 for multiplication.

 

…..

….

….

 

  1. The program should ask user to enter as many matrices as much the user want. For each matrix, the user should also enter the dimensions. The program should multiply the matrices, following proper matrix multiplication rules.

HINT: Create a class Matrix.

In main function, use a do-while loop that ask users to keep on entering matrices unless the while condition fails.

  1. Create a partial class MyBigClass. The class should be defined in 4 separate C# files with names: file1.cs, file2.cs, file3.cs, file4.cs.

Define a function in each of the file with prototype:

void display();

In each of the file, the display function should print a string telling which function is called.

For example in file1.cs the function should output: “This is file1”

In file2.cs the function should output: “This is file2”, and so on.

On compile time, the program must compile the 4 files into a single class MyBigClass.

  1. Write a program that declares and initializes a 4-dimentional array, means, array is not input by the user, it is initialized at the declaration time. Use for loops to display the elements of the array.
  2. See my tutorial “Create a contact us page in asp.net” on pakproject.com

1: Create following asp.net form application, performing operations on databases. Use html table to align the input fields in the form. The form must have following fields:

Field name Form field Database Type Remarks
Name Text box varchar Set a limit of maximum 100 chars on text box.
Age Drop down list int By default no value should be selected
Title Radio button with following values:

(a) Mr. (b) Miss, (c) Ms

int

 

Note: In database, store 1 for Mr., 2 for Miss, and 3 for MS.

By default no value should be selected. Allow only single value selection
Movies Checkbox

(a) fun, (b) horror, (c) thriller

Varchar Allows multiple selection. By default no value is selected
Books List box

(a) english, (b) urdu, (c) persian

varchar Allows multiple selection. By default no value is selected.
Description Text area Varchar Allows to write at least 3 lines of text
Save information Button –N/A– A button, when pressed should save the above data  in database.

2: Create a asp.net form to display the above information stored in database. Use GridView Control to display information, where the string text should be shown, not the numeric values for “Title”.

NOTE: Make sure the “RequiredFieldvalidation” check must be there for all the fields. No blank entries should be allowed in database.

 

  1. See the calculator application of Windows (the non-scientific one) and make the same application in windows forms.