Exercises C# Variables and Data Types Exercises
Exercises C# Variables and Data Types Exercises
Exercise 1: Write C# code to declare a variable to store the age of a person. Then the output of the program is
as an example shown below:
You are 20 years old.
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
int age = 20;// declaring variable and assign 20 to it.
Console.WriteLine("You are {0} years old.",age);
Console.ReadLine();
}
}
}
Exercise 2: Write C# code to declare two integer variables, one float variable, and one string variable and assign
10, 12.5, and "C# programming" to them respectively. Then display their values on the screen.
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{ int x;
float y;
string s;
x = 10;
y = 12.5f;
s = "C# programming";
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(s);
Console.ReadLine();
}}
}
Exercise 3: Write C# code to prompt a user to input his/her name and then the output will be shown as an example
below:
Hello John!
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
string name;
Console.Write("Please enter your name:");
name = Console.ReadLine();
Console.WriteLine("Hello {0}!", name);
Console.ReadLine();
}
}
}
C# operators
Exercise 5: Write a C# program that prompts the user to input three integer values and find the greatest value of the
three values.
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{int x,y,z;
Console.Write("Enter value 1:");
x = int.Parse(Console.ReadLine());
Console.Write("Enter value 2:");
y = int.Parse(Console.ReadLine());
Console.Write("Enter value 3:");
z = int.Parse(Console.ReadLine());
if (x > y)
if (x > z) Console.Write("The greatest value is:{0}.",x);
else Console.Write("The greatest value is:{0}.", z);
else if (y > z) Console.Write("The greatest value is:{0}.",y);
else Console.Write("The greatest value is:{0}.",z);
Console.ReadLine(); }}}
Exercise 6: Write a C# program that determines a student’s grade. The program will read three types of scores(quiz score,
mid-term score, and final score) and determine the grade based on the following rules:
-if the average score =90% =>grade=A
-if the average score >= 70% and <90% => grade=B
-if the average score>=50% and <70% =>grade=C
-if the average score<50% =>grade=F
Solution:
using System;
{class Program
{ static void Main(string[] args)
{ float quiz_score,mid_score,final_score, avg;
Console.Write("Enter quiz score:");
quiz_score=float.Parse(Console.ReadLine());
Console.Write("Enter mid-term score:");
mid_score = float.Parse(Console.ReadLine());
Console.Write("Enter final score:");
final_score = float.Parse(Console.ReadLine());
avg = (quiz_score +mid_score+final_score) / 3;
if (avg >= 90) Console.WriteLine("Grade A");
else if ((avg >= 70) && (avg < 90)) Console.WriteLine("Grade B");
else if ((avg >= 50) && (avg < 70)) Console.WriteLine("Grade C");
else if (avg < 50) Statements
Conditional Console.WriteLine("Grade F");
(Switch case)
else Console.WriteLine("Invalid input");Console.ReadLine(); }}}
Exercise 7: Write a C# program to detect key presses. If the user pressed number keys( from 0 to 9), the program will
display the the number that is pressed, otherwise the program will show "Not allowed".
Solution:
using System;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
char key;
Console.Write("Press a number key:");
key = (char)Console.Read();
switch (key)
{
case '0': Console.WriteLine("You pressed 0"); break;
case '1': Console.WriteLine("You pressed 1"); break;
case '2': Console.WriteLine("You pressed 2"); break;
case '3': Console.WriteLine("You pressed 3"); break;
case '4': Console.WriteLine("You pressed 4"); break;
case '5': Console.WriteLine("You pressed 5"); break;
case '6': Console.WriteLine("You pressed 6"); break;
case '7': Console.WriteLine("You pressed 7"); break;
case '8': Console.WriteLine("You pressed 8"); break;
case '9': Console.WriteLine("You pressed 9"); break;
default: Console.WriteLine("Not allowed!"); break;
}}}}
} For loop
}
}
Exercise 8: Write C# program to print the table of characters that are equivalent to the Ascii codes from 1 to 122.The
program will print the 10 characters per line.
Solution:
using System;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
int i =1;
while (i <=122)
{
Console.Write((char)i+"\t");
if (i % 10 == 0)
Console.Write("\n");
i++;
}
Console.ReadLine();
}}}
} Sorting
•C# Array(sorting) exercises
Exercise 9: By using the bubble sort algorithm, write C# code to sort an integer array of 10 elements in ascending.
Solution:
using System;
using System.Collections.Generic;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[10] { 23, 2, 3, 34, 6,1,24,45,78,8}; //unsorted data set
bubblesort(arr, 10); //sorting process using bubble sort
int i;
for (i = 0; i < 10; i++)
Console.Write(arr[i] + "\t"); //after sorting in ascending order
Console.ReadLine();
}
///bubble sort
Exercise 10: By using the sequential search algorithm, write C# code to search for an element of an integer array of
10 elements.
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace Csharp_exercises
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[10] { 23, 2, 3, 34, 6,1,24,45,78,8}; //data set
int pos,target;
Console.Write("Enter value to find:");
target = int.Parse(Console.ReadLine());
pos = seqsearch(arr, target, 10);
if (pos != -1)
Console.WriteLine("The target item was found at location:{0}", pos);
else
Console.WriteLine("The target item was not found in the list.\n");
Console.ReadLine();
}
///sequential search
static int seqsearch(int[] dataset, int target, int n)
{
int found = 0;
int i;
int pos = -1;
for (i = 0; i < n && found != 1; i++)
if (target == dataset[i]) { pos = i; found = 1; }
return pos;
}
}
}
Exercise 11. A two-dimensional array stores values in rows and columns. By using two-dimensional array, write C#
program to display a table of numbers as shown below:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{ printSeries();
Console.ReadLine();
}
public static void printSeries()
{
int[,] tArr = new int[5, 5];
int i, j;
for (i = 0; i < 5; i++) //assign values to the two-dimensional array
for (j = 0; j < 5; j++)
{
if (i == 0) tArr[i, j] = j + 1; //fill the first row
else if (i > 0 && j == 0)
tArr[i, j] = tArr[i - 1, 4] + 1; //fetching the value of the last cell in the previous row
else
tArr[i, j] = tArr[i, j - 1] + 1; //fill subsequent cells
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication10
{
Console.WriteLine("Do U Want to Switch On camera ? Press 'Y' for YES & ‘N’ for NO");
userChoice=Console.ReadLine();
m1.Click(userChoice);
}
}
}
Exercise 13: Customer using the services from a Vodafone company is facing a lot of network problem & wants
to give complain to the Company Authority. Assuming that the complains of the customer & responses of the
company authority are prestored in the form of string of messages. Create a class called CUSTOMER with static
methods as Complain( ) & Response( ). Also create a static GetRandomNumber( ) function which generates a
random number based on which the complains & responses are picked from string of messages. Show the output
in the form of a conversation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication14
{
class Program
{
public static Random r = new Random();
public static int GetRandomNumber(short upperlimit)
{
return r.Next(upperlimit);
}
public static string Complain()
{
string[] messages =new string[2]{"I have a complain for msgs delivery","Around 100"};
return messages[GetRandomNumber(2)];
}
public static string Response()
{
string[] messages =new string[2]{"How many msgs you have sent Sir,","Its a TRAI regulation ,you can
now only send 100 msgs per day"};
return messages[GetRandomNumber(2)];
}
static void Main(string[] args)
{
string[] messages = new string[2];
Console.WriteLine("{0}", Program.Complain());
Console.WriteLine("{0}", Program.Response());
Console.WriteLine("{0}", Program.Complain());
Console.WriteLine("{0}", Program.Response());
Console.ReadLine();
}
}
}
Exercise 14: Create the classes required to store data regarding different types of Courses. All courses
have name, duration and course fee. Some courses are part time where you have to store the timing for
course. Some courses are onsite where you have to store the company name and the no. of candidates
for the course. For onsite course the institute charges 10% more on the course fee. For part-time
course, institute offer 10% discount.
Provide constructors wherever required and use the following methods.
Print()
GetTotalFee()
Note: Populate the base class with GetTotalFee() which should be used by other classes.
Display the output in the following format:
ONSITE COURSES
CourseName Duration CourseFee Company No of
Name Candidates
Testing 3 months 20,000 Quest 50
Animation 4 months 90,000 ANTS 20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace st
{
abstract class Course
{
protected string name;
protected int duration;
protected int coursefee;
}
class OnsiteCourse : Course
{
private string company;
private int nostud;
public OnsiteCourse(string name, int duration, int coursefee, string company, int nostud)
: base(name, duration, coursefee)
{
this.company = company;
this.nostud = nostud;
}
}
class TestCourse
{
public static void Main()
{
Course c = new OnsiteCourse("ASP.NET", 30, 5000, "ABC Tech", 10);
c.Print();
Console.WriteLine(c.GetTotalFee());
Exercise 15:Write a program that reads name, and mobile_ no of a customer .The program
should throw an exception whenever a customer enters a mobile no which is less than ten
digits.
Design your own exception mechanism with appropriate name for custom exception.
using System;
using System.Text;
namespace ConsoleApplication8
{ class NoMatchException : ApplicationException
{ public NoMatchException()
{ }
public NoMatchException(string Message)
: base(Message)
{ }
public NoMatchException(string Message, System.Exception inner)
: base(Message, inner) { }
}
class MyApp
{public static void Main()
{ Console.WriteLine("Enter Name");
String name = Console.ReadLine();
try
{Console.WriteLine("Enter Phone No");
String str = Console.ReadLine();
if (str.Length < 10)
{
throw new NoMatchException("Inavalid phone no");
}
else if (str.Length > 10)
{
Console.WriteLine("InvalidcellNo");}
else
{
Console.WriteLine("Valid No"); }}
catch (NoMatchException e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();}}}}