0% found this document useful (0 votes)
289 views13 pages

Exercises C# Variables and Data Types Exercises

The document contains examples of C# code to demonstrate various programming concepts like variables, data types, operators, conditional statements, loops, arrays, classes, and objects. The final example shows how to create a MOBILE class with member variables for company name, price and model. It also creates a CAMERA class with a member variable for megapixels and a method to switch the camera on/off. The C# application allows the user to choose to switch the camera on or off for a MOBILE object and displays the appropriate message

Uploaded by

Akshay Mane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
289 views13 pages

Exercises C# Variables and Data Types Exercises

The document contains examples of C# code to demonstrate various programming concepts like variables, data types, operators, conditional statements, loops, arrays, classes, and objects. The final example shows how to create a MOBILE class with member variables for company name, price and model. It also creates a CAMERA class with a member variable for megapixels and a method to switch the camera on/off. The C# application allows the user to choose to switch the camera on or off for a MOBILE object and displays the appropriate message

Uploaded by

Akshay Mane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

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 4 Write C# code to produce the output shown below:


x value y value expression result
10 5 x=y+3 x=8
10 5 x=y-2 x=3
10 5 x=y*5 x=25
10 5 x=x/y x=2
10 5 x=x%y x=0
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=10;int y=5;
Console.WriteLine("Result:");
Console.WriteLine("x value\t\ty value\t\tExpressions\tResult");
Console.WriteLine("{0,-8}\t{1,-8}\tx=y+3 \t x={2,-8}",x,y,y + 3);
Console.WriteLine("{0,-8}\t{1,-8}\tx=y-2 \t x={2,-8}", x, y, y-2);
Console.WriteLine("{0,-8}\t{1,-8}\tx=y*5 \t x={2,-8}", x, y, y*5);
Console.WriteLine("{0,-8}\t{1,-8}\tx=x/y \t x={2,-8}", x, y, (float)x/y);
Console.WriteLine("{0,-8}\t{1,-8}\tx=x%y \t x={2,-8}", x, y, x%y)
Console.ReadLine(); }}}
CONDITIONAL Statements

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

static void bubblesort(int[] dataset, int n)


{
int i, j;
for (i = 0; i < n; i++)
for (j = n - 1; j > i; j--)
if (dataset[j] < dataset[j - 1])
{
int temp = dataset[j];
dataset[j] = dataset[j - 1];
dataset[j - 1] = temp;
}
}
}
}
C# Array(searching) exercises

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
}

for(i=0;i<5;i++){ //print the array


for(j=0;j<5;j++)
Console.Write("{0}\t",tArr[i,j]);
Console.WriteLine();
}}
}
}
Exercise 12:Design a class called MOBILE with the following members:
CompanyName, Price, Model
Create another class called CAMERA with members as megapixel, switchOnCamera( ).Build a C# application which contains an instance of
CAMERA in a MOBILE class. Based on users choice either switch ON/OFF the CAMERA. Display appropriate message whether the camera is
ON/OFF along with the details of mobile & camera.

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

namespace ConsoleApplication10
{

public class MOBILE


{
public string companyName;
public float price;
public string model;
private CAMERA takephoto=new CAMERA( ); // Instance of CAMERA

public void Click(string status)


{
takephoto.switchOnCamera(status) ;
}
public MOBILE()
{
}
public MOBILE(string cname,int mprice,string mmodel)
{
companyName = cname;
price = mprice;
model = mmodel;
}
}
public class CAMERA{
public string MegaPixel;
public void switchOnCamera(string state)
{
Console.WriteLine(" {0}", state);
bool status = state.Equals('Y');
Console.WriteLine("{0}",status);
if(state.Equals('Y'))
{
Console.WriteLine(" CAMERA IS ON.. U CAN CLICK PHOTO");
}
else
{
Console.WriteLine("CAMERA IS OFF ! .. ");
}
}
}
public class MOBILEAPP
{
public static void Main(string[ ] args)
{
string userChoice;
MOBILE m1=new MOBILE("Samsung",8500,"S1100");
Console.WriteLine("Name : {0}",m1.companyName);
Console.WriteLine("Price:{0}",m1.price);
Console.WriteLine("Model:{0}",m1.model);

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

PART TIME COURSES


CourseName Duration CourseFee Timings
Animation 6 months 50,000 6pm-8pm
SAP 1 year 2 Lakh 7pm-9pm

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;

public Course(string name, int duration, int coursefee)


{
this.name = name;
this.duration = duration;
this.coursefee = coursefee;
}

public virtual void Print()


{
Console.WriteLine(name);
Console.WriteLine(duration);
Console.WriteLine(coursefee);
}

public abstract int GetTotalFee();


}}

class ParttimeCourse : Course


{
private string timings;
class ParttimeCourse : Course
{
private string timings;

public ParttimeCourse(string name, int duration, int coursefee, string timings) :


base(name,duration,coursefee)
{
this.timings = timings;
}

public override void Print()


{
base.Print();
Console.WriteLine(timings);
}

public override int GetTotalFee()


{
return (int) (coursefee * 0.90); // 10% discount
}

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

public override void Print()


{
base.Print();
Console.WriteLine(company);
Console.WriteLine(nostud);
}

public override int GetTotalFee()


{
return (int)(coursefee * 1.1); // 10% more
}
}

}
class TestCourse
{
public static void Main()
{
Course c = new OnsiteCourse("ASP.NET", 30, 5000, "ABC Tech", 10);
c.Print();
Console.WriteLine(c.GetTotalFee());

c = new ParttimeCourse("C#", 30, 3000, "7-8pm");


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

You might also like