Final Exam (C#)
Final Exam (C#)
Chapter(13)
Strings and Text Processing
1. Find all occurrences of a particular substring within another string. (5
marks)
using System;
class SubstringWithinAnotherString
{
static void Main(string[] args)
{
string quote = "The main intent of the \"Intro C#\"" +
" book is to introduce the C# programming to newbies.";
string keyword = "C#";
int index = quote.IndexOf(keyword);
while (index != -1)
{
Console.WriteLine("{0} found at index: {1}", keyword, index);
index = quote.IndexOf(keyword, index + 1);
}
}
}
2. Write down a console program to split a string by a separator or an array
of possible separators. (5 marks)
using System;
class SplittingtheStringBySeparator
{
static void Main(string[] args)
{
string listOfStudents = "MyatPan, KyawKyi, ZawKyi, NyanKyi";
char[] separators = new char[] { ' ', ',', '.' };
string[] studentsArr = listOfStudents.Split(separators);
foreach (string stu in studentsArr)
{
if (stu != "")
{
Console.WriteLine(stu);
}
}
}
}
3. Write a program that reads a string, reverse it and prints it to the console.
For example: "introduction" >>> "noitcudortni". (5marks)
using System;
class ReverseString
{
static void Main(string[] args)
{
string text = "introduction";
2
}
static string ReverseText(string text)
{
StringBuilder sb = new StringBuilder();
for (int i = text.Length - 1; i >= 0; i--)
{
sb.Append(text[i]);
}
return sb.ToString();
}
}
4. How to extract all capital Letters from a text using c# program.( 5marks)
using System;
namespace ConsoleAppExtrectUpperCase
{
class Program
{
static void Main(string[] args)
{
string line = "Extracting All Capital Letters from a Text";
string upChar = ExtractCapitals(line);
Console.WriteLine(upChar); //EACLT
}
public static string ExtractCapitals(string str)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
if (char.IsUpper(ch))
{
result.Append(ch);
}
}
return result.ToString();
}
}
}
3
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.
using System;
class Program
{
Chapter-14
Defining Classes
6. Define a class Student, which contains the following information about
students: full name, course, subject, university, e-mail and phone number.
(5marks)
using System;
class Student
{
string stuName,course,subject,university,email;
4
string phNumber;
public Student(string name, string cu, string sub, string uni, string
em, string ph)
{
stuName = name;
course = cu;
subject = sub;
university = uni;
email = em;
phNumber = ph;
}
static void Main(string[] args)
{
Student stu = new Student("Bo Bo",
"IT","Programming","GTC(MDY)","[email protected]","0940000123");
Console.WriteLine("Student Name : " + stu.stuName);
Console.WriteLine("Course : " + stu.course);
Console.WriteLine("Subject : " + stu.subject);
Console.WriteLine("University : " + stu.university);
Console.WriteLine("Email : " + stu.email);
Console.WriteLine("Phone No. : " + stu.phNumber);
7. Create a class that quickly calculates the square root of an integer and
returns the whole part of the result, which is also an integer. (10 marks)
using System;
namespace ConsoleAppSquareCalculateCh14
{
static class SqrtPrecalculated
{
public const int MaxValue = 1000;
private static int[] sqrtValues;
static SqrtPrecalculated()
{
sqrtValues = new int[MaxValue + 1];
for (int i = 0; i < sqrtValues.Length; i++)
{
sqrtValues[i] = (int)Math.Sqrt(i);
}
}
public static int GetSqrt(int value)
{
if ((value < 0) || (value > MaxValue))
{
throw new ArgumentOutOfRangeException(String.Format("The
argument should be in range [0...{0}].",MaxValue));
}
return sqrtValues[value];
}
}
5
class SqrtTest
{
static void Main()
{
Console.WriteLine(SqrtPrecalculated.GetSqrt(254));
}
}
}
8. Write a program that customers can order different amounts of coffee, as
the coffee machine has predefined values “small” – 100 ml, “normal” –
150 ml and “double” – 300 ml. (10 marks)
using System;
namespace ConsoleAppEnumCoffeeExample
{
public enum CoffeeSize
{
Small = 100, Normal = 150, Double = 300
}
public class Coffee
{
public CoffeeSize size;
public Coffee(CoffeeSize size)
{
this.size = size;
}
public CoffeeSize Size
{
get { return size; }
}
static void Main()
{
Coffee normalCoffee = new
Coffee(CoffeeSize.Normal);
Coffee doubleCoffee = new
Coffee(CoffeeSize.Double);
Console.WriteLine("The {0} coffee is {1} ml.",
normalCoffee.Size, (int)normalCoffee.Size);
Console.WriteLine("The {0} coffee is {1} ml.",
doubleCoffee.Size, (int)doubleCoffee.Size);
}
}
}
}
public class AnimalShelter
6
{
private const int DefaultPlacesCount = 20;
private Dog[] animalList;
private int usedPlaces;
public AnimalShelter() : this(DefaultPlacesCount)
{
}
public AnimalShelter(int placesCount)
{
this.animalList = new Dog[placesCount];
this.usedPlaces = 0;
}
public void Shelter(Dog newAnimal)
{
if (this.usedPlaces >= this.animalList.Length)
{
throw new InvalidOperationException("Shelter is full.");
}
this.animalList[this.usedPlaces] = newAnimal;
this.usedPlaces++;
}
public Dog Release(int index)
{
if (index < 0 || index >= this.usedPlaces)
{
throw new ArgumentOutOfRangeException(
"Invalid cell index: " + index);
}
Dog releasedAnimal = this.animalList[index];
for (int i = index; i < this.usedPlaces - 1; i++)
{
this.animalList[i] = this.animalList[i + 1];
}
this.animalList[this.usedPlaces - 1] = null;
this.usedPlaces--;
return releasedAnimal;
}
static void Main()
{
AnimalShelter dogsShelter = new AnimalShelter(10);
Dog dog1 = new Dog();
Dog dog2 = new Dog();
Dog dog3 = new Dog();
dogsShelter.Shelter(dog1);
dogsShelter.Shelter(dog2);
dogsShelter.Shelter(dog3);
}
7
10. Write a program an inner (nested) class is called a class that is declared
inside the body of another class. (10 marks)
using System;
public class OuterClass
{
private string name;
private OuterClass(string name)
{
this.name = name;
}
private class NestedClass
{
private string name;
private OuterClass parent;
public NestedClass(OuterClass parent, string name)
{
this.parent = parent;
this.name = name;
}
public void PrintNames()
{
Console.WriteLine("Nested name: " + this.name);
Console.WriteLine("Outer name: " + this.parent.name);
}
}
static void Main()
{
OuterClass outerClass = new OuterClass("outer");
NestedClass nestedClass = new
OuterClass.NestedClass(outerClass, "nested");
nestedClass.PrintNames();
}
}
11. Write a program define a class with name is Dog here own all the element
and results the element. (20 marks)
using System;
using System.IO;
class Program
{
public class Dog
{
public string name;
public Dog ()
{
8
}
public Dog(string name)
{
this.name = name;
}
public string Name
{
get { return name; }
set { name = value; }
}
secondDog.Name = secondDogName;
13. Write a program to enroll in a text file the numbers from 1 to 20, each
number on a separate line. (5marks)
using System;
using System.IO;
class FileWriter
{
static void Main(string[] args)
{
StreamWriter writer = new StreamWriter(@"D:\numbers.txt");
using (writer)
{
for (int i = 1; i <= 20; i++)
{
writer.WriteLine(i);
}
}
}
}
14. Write a program how to implement a simple program that counts how
many times a substring occurs in a text file. In the example, let’s look for
the substring "C#" in a text file as follows:
This is our "Intro to Programming in C#" book. In it you will learn the
basics of C# programming. You will find out how nice C# is. (20 marks)
using System;
using System.IO;
10
class Program
{
static void Main(string[] args)
{
string filename = @"D:\Sample txt files for C#\Sample.txt";
string word = "C#";
try
{
StreamReader reader = new StreamReader (filename);
{
int occurrences = 0;
string line = reader.ReadLine();
while (line != null)
{
int index = line.IndexOf(word);
while (index != -1)
{
occurrences++;
index = line.IndexOf(word, (index + 1));
}
line = reader.ReadLine();
}
Console.WriteLine(
"The word {0} occurs {1} times.", word, occurrences);
}
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("Cannot find file {0}",filename);
}
catch (IOException)
{
Console.Error.WriteLine("Cannot read file {0}", filename);
}
}
}
15. Write a program that reads a text file and prints its odd lines on the
console. (10 marks)
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string fileName = @"D:\Sample txt files for C#\oddLine.txt ";
try
{
StreamReader reader = new StreamReader(fileName);
using (reader)
{
int lineNumber = 0;
11
}
line = reader.ReadLine();
}
}
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File cannot find {0}",fileName);
}
}
}
16. Write a program that joins two text files and records the results in a third
file. (20 marks)
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string firstFile =@"D:\Sample txt files for C#\FirstFile.txt";
string secondFile = @"D:\Sample txt files for C#\SecondFile.txt";
string resultFile = @"D:\Sample txt files for C#\ResultFile.txt";
using (reader)
{
while ( line != null)
{
writer.WriteLine(line);
line = reader.ReadLine();
}
string line2 = reader2.ReadLine();
using (reader2)
{
12
line2 = reader2.ReadLine();
}
}
using (writer)
{
writer.WriteLine(line);
writer.WriteLine(line2);
}
}
}
17. Write a program that compares two text files with the same number of
rows line by line and prints the number of equal and the number of
different lines.(20 marks)
using System;
using System.IO;
class ConsoleAppCompareTwoTextFiles
{
static int lineCountForF1 = 0;
static int lineCountForF2 = 0;
static void Main(string[] args)
{
StreamReader reader1 = new StreamReader(@"D:\Sample txt
files for C#\FirstFile.txt");
StreamReader reader2 = new StreamReader(@"D:\Sample txt
files for C#\SecondFile.txt");
using (reader1)
{
string line = reader1.ReadLine();
while (line != null)
{
lineCountForF1++;
line = reader1.ReadLine();
}
}
using (reader2)
{
string line = reader2.ReadLine();
while (line != null)
{
lineCountForF2++;
line = reader2.ReadLine();
}
}
if (lineCountForF1 == lineCountForF2)
{
Console.WriteLine("Same number of Line");
}
else
13
Console.WriteLine("Different Line");
}
}
18. Write a program that reads a list of names from a text file, arranges them
in alphabetical order, and writes them to another file. The lines are written
one per row. (20 marks)
using System;
using System.IO;
class ReadnameAndWriteOrder
{
static void Main(string[] args)
{
string fileName = @"D:\Sample txt files for C#\ListOfName.txt";
string fileName2 = @"D:\Sample txt files for C#\
OrderOfName.txt";
try
{
StreamReader reader = new StreamReader(fileName);
StreamWriter writer = new StreamWriter(fileName2);
List<string> names = new List<string>();
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
names.Add(line);
line = reader.ReadLine();
}
names.Sort();
}
using (writer)
{
foreach (string s in names)
{
writer.WriteLine(s);
}
}
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not Found");
}
}
}
Chapter 16
14
shoppingList.Add("Olives");
shoppingList.Add("Water");
shoppingList.Add("Beer");
Console.WriteLine("We need to buy:");
for (int i = 0; i < shoppingList.Count; i++)
{
Console.WriteLine(shoppingList[i]);
}
}
}
}
20. Write a console program finding the prime numbers in a certain interval.
(15 marks)
using System;
using System.Collections.Generic;
class Program
{
static List<int> GetPrimes(int start, int end)
{
List<int> primesList = new List<int>();
for (int num = start; num <= end; num++)
{
bool prime = true;
double numSqrt = Math.Sqrt(num);
for (int div = 2; div <= numSqrt; div++)
{
if (num % div == 0)
{
prime = false;
break;
}
}
if (prime)
{
primesList.Add(num);
}
}
return primesList;
}
}
}
}
21. Write a console program for union and intersection list and print list for
union and intersection. (20 marks)
using System;
using System.Collections.Generic;
namespace ConsoleAppUnionAndInterSet
{
class Program
{
static List<int> Union( List<int> firstList, List<int> secondList)
{
List<int> union = new List<int>();
union.AddRange(firstList);
foreach (var item in secondList)
{
if (!union.Contains(item))
{
union.Add(item);
}
}
return union;
}
static List<int> Intersect(List<int> firstList, List<int> secondList)
{
List<int> intersect = new List<int>();
foreach (var item in firstList)
{
if (secondList.Contains(item))
{
intersect.Add(item);
}
}
return intersect;
}
static void PrintList(List<int> list)
{
Console.Write("{ ");
foreach (var item in list)
{
Console.Write(item);
Console.Write(" ");
}
Console.WriteLine("}");
}
static void Main(string[] args)
{
List<int> firstList = new List<int>();
firstList.Add(1);
firstList.Add(2);
firstList.Add(3);
18
firstList.Add(4);
firstList.Add(5);
Console.Write("firstList = ");
PrintList(firstList);
22. Write a console program for a simple example on how to use stack. (5
marks)
using System;
using System.Collections.Generic;
namespace ConsoleAppStack
{
class Program
{
static void Main(string[] args)
{
Stack<string> stack = new Stack<string>();
stack.Push("1. John");
stack.Push("2. Nicolas");
stack.Push("3. Mary");
stack.Push("4. George");
Console.WriteLine("Top " + stack.Peek());
Console.WriteLine(stack.Count);
while (stack.Count > 0)
{
string personName = stack.Pop();
Console.WriteLine(personName);
}
}
}
23. Write a program by using console to check whether the brackets are put
correctly for given expression 1 + (3 + 2 - (2+3)*4 - ((3+1)*(4-2))). (15
marks)
using System;
using System.Collections.Generic;
19
namespace ConsoleAppCheckBrackets
{
class Program
{
static void Main(string[] args)
{
string expression = "1 + (3 + 2 - (2+3)*4 - ((3+1)*(4-2)))";
Stack<int> stack = new Stack<int>();
bool correctBrackets = true;
for (int index = 0; index < expression.Length; index++)
{
char ch = expression[index];
if (ch == '(')
{
stack.Push(index);
}
else if (ch == ')')
{
if (stack.Count == 0)
{
correctBrackets = false;
break;
}
stack.Pop();
}
}
if (stack.Count != 0)
{
correctBrackets = false;
}
Console.WriteLine("Are the brackets correct? " +
correctBrackets);
}
}
}
24. Create a queue and add several elements to it and retrieve all elements
and print them on the console. (5marks)
using System;
using System.Collections.Generic;
namespace ConsoleAppQueue
{
class Program
{
static void Main(string[] args)
{
Queue<string> queue = new Queue<string>();
queue.Enqueue("Message One");
queue.Enqueue("Message Two");
queue.Enqueue("Message Three");
queue.Enqueue("Message Four");
20
7. Which of the following is the correct way to create an object of the class
Sample?
a) 1,3
b) 2,4
c) 1,2,3
d) 1,4
a) Class
b) class
c) System.Class
d) OOPS.class
10. Which is the correct way to declare an object of the class in C#?
22
a) Static Constructor
b) Private Constructor
c) Body Constructor
d) Parameterized Constructor
a) 2
b) 3
c) 4
d) 5
a) Polymorphism
b) Encapsulation
c) Abstraction
d) None of the above
using System;
namespace MyApplication {
class Program {
static void Main(string[] args) {
string[] mobiles = {"iPhone", "Samsung", "Vivo"};
Console.WriteLine(mobiles[-1]);
23
}
}
}
a) None
b) Warning
c) Exception
d) System.String[]
using System;
namespace MyApplication {
class Program {
static void Main(string[] args) {
string[] mobiles = {"iPhone", "Samsung", "Vivo"};
Console.WriteLine(mobiles[0] + mobiles[2]);
}}}
a) iPhoneVivo
b) iPhone+Vivo
c) Exception
d) iPhone Vivo
a) sort()
b) sorting()
c) Sort()
d) Sorting()
20. ……….. is used when you need last-in, first-out access of items.
a) List
b) Stack
c) Array
d) Queue
21. ……….. is used when you need a first-in, first-out access of items.
a) List
b) Stack
c) Array
24
d) Queue
22. The ……….. property gets or sets the number of elements that the
ArrayList can contain.
a) Count
b) Item
c) Capacity
d) Length
a) Pop()
b) Push()
c) Peek()
d) Clear()
24. Which data type is used to create a variable that should store text?
a) myString
b) string
c) str
d) Txt
a) length
b) Length
c) getLength()
d) length()
a) [ ]
b) { }
c) ( )
a) MyMethod()
b) MyMethod
c) (MyMethod)
d) myMethod[]
28. What is the correct way to create an object called myObj of MyClass?
29. What is the name of the 'special' class that represents a group of
constants?
a) emum
b) special
c) const
d) void
30. Which access modifier makes the code only accessible within the same
class?
a) abstract
b) private
c) public
d) final