Nothing Special   »   [go: up one dir, main page]

C# Hands-On

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 19

C# HANDS_ON

1) Find Square and Cube

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

namespace Methods2 //DO NOT Change namespace name


{
public class Program //DO NOT Change class 'Program' name
{
public static void Main(string[] args) //DO NOT Change 'Main' method
Signature
{
//Implement your code here
Console.WriteLine("Enter a Number");
double num = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Square of " + num + " is " + FindSquare(num));
Console.WriteLine("Cube of " + num + " is " + FindCube(num));
}
//Implement methods here. Keep the method 'public' and 'static'
public static double FindSquare(double num){
return (num*num);
}
public static double FindCube(double num){
return (num*num*num);
}
}
}

2) Max Value of Signed Byte

using System;

public class Program //DO NOT change the class name


{
//implement code here
static void Main(string[] args)
{
sbyte number = 125;
Console.WriteLine("Value of number: " + number);
number = sbyte.MaxValue;
Console.WriteLine("Largest value stored in a signed byte : " + number);
}
}

3) Age Calculation

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

namespace DateEx1 //DO NOT CHANGE the namespace name


{
public class Program //DO NOT CHANGE the class name
{
public static void Main(string[] args) //DO NOT CHANGE the 'Main' method
signature
{
Console.WriteLine("Enter the date of birth (dd-mm-yyyy): ");
//Implement code here
DateTime dob=DateTime.ParseExact(Console.ReadLine(),"dd-mm-yyyy",null);
string dt=dob.ToString("dd-mm-yyyy");
Console.WriteLine(calculateAge(dt));
}

public static int calculateAge(string dateOfBirth)


{
//Implement code here

int birthyear=Int32.Parse(dateOfBirth.Substring(6,4));
int birthmonth=Int32.Parse(dateOfBirth.Substring(3,2));
int birthdate=Int32.Parse(dateOfBirth.Substring(0,2));
var t=DateTime.Today;
var a=(t.Year*100+t.Month)*100+t.Day;
var b=(birthyear*100+birthmonth)*100+birthdate;
return (a-b-400)/10000;
}
}
}

4) StringConcatenateCoding exercise

using System;

public class Program //DO NOT change the class name


{
//implement code here
public static void Main(string[] args)
{
string first_name, last_name, fullName;

Console.WriteLine("\"Enter first name");


first_name = Console.ReadLine();

Console.WriteLine("Enter last name");


last_name = Console.ReadLine();

fullName = first_name + " " + last_name;


Console.WriteLine("Full name : {0}", fullName);
}
}

5) Quiz Competition

using System;

namespace JaggedArray
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter the number of teams:");
int teams = Convert.ToInt32(Console.ReadLine());

int[][] teamsArray = new int[teams][];

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


{
Console.WriteLine("No.of attempts for team {0}", (i+1));
int attempt = Convert.ToInt32(Console.ReadLine());
teamsArray[i] = new int[attempt];
}

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


{
Console.WriteLine("Enter the score for team {0}", (i+1));
for(int j=0; j<teamsArray[i].Length; j++)
teamsArray[i][j] =
Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine(GetTotalScore(teamsArray));
}

public static String GetTotalScore(int[][] array)


{
String res = "";

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


{
int sum=0;
for(int j=0; j<array[i].Length; j++)
{
sum += array[i][j];
res += "Team " + (i+1) + " Total Score is " + sum +
". ";
}
}
return res;
}
}
}

6) Reverse a Sentence

using System;

public class Program //DO NOT change the class name


{
//implement code here
public static void Main(string[] args)
{
string sentence, reverse="";

Console.WriteLine("Enter a string");
sentence = Console.ReadLine();

string[] temp = sentence.Split();


for(int i = temp.Length-1; i >= 0; i--)
{
reverse += temp[i] + " ";
}
Console.WriteLine(reverse);
}
}

7) Account Details

using System;
public class Account
{
private int id;
private string accountType;
private double balance;

public int Id
{
get{ return id;}
set{ id = value;}
}

public string AccountType


{
get{ return accountType;}
set{ accountType = value;}
}
public double Balance
{
get{ return balance;}
set{ balance = value;}
}
public Account(){}
public Account(int id, string accountType, double balance)
{
this.id = id;
this.accountType = accountType;
this.balance = balance;
}

public bool WithDraw(double amount)


{
if(balance>amount)
{
balance -= amount;
return true;
}
return false;
}
public string GetDetails()
{
return ("Account Id: " + id + "\nAccount Type: " + accountType + "\
nBalance: "+balance);
}
}
public class Program
{
static void Main(string[] args)
{
int id;
string accountType;
double balance, withdraw;

Account ac = new Account();

Console.WriteLine("Enter account id");


id = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter account type");


accountType = Console.ReadLine();

Console.WriteLine("Enter account balance");


balance = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter amount to withdraw");


withdraw = Convert.ToDouble(Console.ReadLine());

ac = new Account(id, accountType, balance);


Console.WriteLine(ac.GetDetails());

if(ac.WithDraw(withdraw))
{
Console.WriteLine("New Balance: " + ac.Balance);
}
}
}

8) Openable Interface

using System;

public interface IOpenable


{
String OpenSesame();
}

public class TreasureBox : IOpenable


{
public String OpenSesame()
{
return "Congratulations , Here is your lucky win";
}
}

public class Parachute : IOpenable


{
public String OpenSesame()
{
return "Have a thrilling experience flying in air";
}
}

public class Program


{
public static void Main(string[] args)
{
TreasureBox t = new TreasureBox();
Parachute p = new Parachute();

Console.WriteLine("Enter the letter found in the paper");


char ch = Console.ReadLine()[0];

if(ch == 'T')
Console.WriteLine(t.OpenSesame());
else if(ch == 'P')
Console.WriteLine(p.OpenSesame());
}
}

9) Game Inheritance

using System;

public class Game


{
public string Name { get; set; }
public int MaxNumPlayers { get; set; }

public override string ToString()


{
return ("Maximum number of players for " + Name + " is " + MaxNumPlayers);
}
}

public class GameWithTimeLimit : Game


{
public int TimeLimit { get; set; }

public override string ToString()


{
Console.WriteLine(base.ToString());
return ("Time Limit for " + Name + " is " + TimeLimit + " minutes");
}
}

public class Program


{
public static void Main(string[] args)
{
Game g = new Game();
GameWithTimeLimit gt = new GameWithTimeLimit();

Console.WriteLine("Enter a game");
g.Name = Console.ReadLine();

Console.WriteLine("Enter the maximum number of players");


g.MaxNumPlayers = int.Parse(Console.ReadLine());

Console.WriteLine("Enter a game that has time limit");


gt.Name = Console.ReadLine();

Console.WriteLine("Enter the maximum number of players");


gt.MaxNumPlayers = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the time limit in minutes");
gt.TimeLimit = int.Parse(Console.ReadLine());

Console.WriteLine(g.ToString());
Console.WriteLine(gt.ToString());
}
}

10) Calculator Program

using System;

public class Calculator


{
public int Addition(int a, int b)
{
return a + b;
}

public int Subtraction(int a, int b)


{
return a - b;
}

public int Multiplication(int a, int b)


{
return a * b;
}

public double Division(int a, int b, out double remainder)


{
remainder = a % b;
return Convert.ToInt32(a / b);
}
}

public class Program


{
public static void Main(string[] args)
{
Calculator c = new Calculator();

Console.WriteLine("Enter the operator");


char op = Console.ReadLine()[0];

Console.WriteLine("Enter the operands");


int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());

switch(op)
{
case '+':
Console.WriteLine("Result of {0} {1} {2} is {3}", num1, op, num2,
c.Addition(num1, num2));
break;
case '-':
Console.WriteLine("Result of {0} {1} {2} is {3}", num1, op, num2,
c.Subtraction(num1, num2));
break;
case '*':
Console.WriteLine("Result of {0} {1} {2} is {3}", num1, op, num2,
c.Multiplication(num1, num2));
break;
case '/':
double remainder;
Console.WriteLine("Result of {0} {1} {2} is {3}\nRemainder = {4}",
num1, op, num2, c.Division(num1, num2, out remainder), remainder);
break;
default:
Console.WriteLine("Invalid Operator");
break;
}
}
}

11) Extract Book Code

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

/*
Substring(Int32)
Retrieves a substring from this instance. The substring starts at a specified
character position and continues to the end of the string.
Substring(Int32, Int32)
Retrieves a substring from this instance. The substring starts at a specified
character position and has a specified length.
*/

namespace ExtractBookCode //Do not change the namespace name


{
public class Program //Do not change the class name
{
public static void Main(String[] arg) //Do not change the method
signature
{
//Implement code here
string bookCode;

Console.WriteLine("Enter the book code of length 18");


bookCode = Console.ReadLine();

if (bookCode.Length == 18)
{
if(bookCode.Substring(0,3) == "101" || bookCode.Substring(0,3) ==
"102" || bookCode.Substring(0,3) == "103")
Console.WriteLine("Department Code : {0}",
bookCode.Substring(0,3));
else
Console.WriteLine(" Invalid Department Code");

int year = Convert.ToInt32(bookCode.Substring(3,4));


if(year>=1900 && year<=2020)
Console.WriteLine("Year of Publication : {0}", year);
else
Console.WriteLine("Invalid Year");

long pages = Int64.Parse(bookCode.Substring(7,5));


if(pages >= 00001 && pages<=99999)
Console.WriteLine("Number of Pages : {0}", pages);
else
Console.WriteLine("Invalid Page Numbers");

char ch = Convert.ToChar(bookCode.Substring(12,1));
if(Char.IsLetter(ch))
{
if(Char.IsNumber(Convert.ToChar(bookCode.Substring(13,1))) &&
Char.IsNumber(Convert.ToChar(bookCode.Substring(14,1))) &&
Char.IsNumber(Convert.ToChar(bookCode.Substring(15,1))) &&
Char.IsNumber(Convert.ToChar(bookCode.Substring(16,1))) &&
Char.IsNumber(Convert.ToChar(bookCode.Substring(17,1))))
{
Console.WriteLine("Book ID : " + bookCode.Substring(12,6));
}
} else
{
Console.WriteLine("Invalid Book ID");
}
}
else
Console.WriteLine("Invalid Book Code");
}
}
}

12) Registration Form

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

namespace ProgFundamentals1 //DO NOT CHANGE the name of namespace


{
public class Program //DO NOT CHANGE the name of class 'Program'
{
public static void Main(string[] args) //DO NOT CHANGE 'Main'
Signature
{
//Fill the code here
Console.Write("Enter your name:");
string name=Console.ReadLine();
Console.Write("Enter your age:");
int age=Convert.ToInt32(Console.ReadLine());
Console.Write("Enter your Country:");
string country=Console.ReadLine();
Console.Write("Welcome "+name+". Your age is "+age+" and you are from
"+country);
}
}
}

13) Boolean Result


using System;

public class Program //DO NOT change the class name


{
static void Main(string[] args)
{
//implement code here
Console.WriteLine("Enter the value for x");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the value for y");
int y = Convert.ToInt32(Console.ReadLine());
bool result = x < y;
Console.WriteLine("x is less than y is " + result);
}
}

14) Generate Bill Details

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

namespace ProgFundamentals2 //DO NOT change the namespace name


{
public class Program //DO NOT change the class name
{
public static void Main(string[] args) //DO NOT change the 'Main'
method signature
{
//Implement the code here
int pizzaprice = 200;
int puffprice = 40;
int pepsiprice = 120;
Console.WriteLine("Enter the number of pizzas bought :");
int numpizza = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the number of puffs bought :");
int numpuff = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the number of pepsi bought :");
int numpepsi = Convert.ToInt32(Console.ReadLine());
int pizzatotal = numpizza * pizzaprice;
int pufftotal = puffprice * numpuff;
int pepsitotal = pepsiprice * numpepsi;
int total = pizzatotal + pufftotal + pepsitotal;
double gst = 0.12 * total;
double cess = 0.05 * total;
Console.WriteLine();
Console.WriteLine("Bill Details");
Console.WriteLine();
Console.WriteLine("Cost of Pizzas :" + pizzatotal);
Console.WriteLine("Cost of Puffs :" + pufftotal);
Console.WriteLine("Cost of Pepsis :" + pepsitotal);
Console.WriteLine("GST 12% : " + gst);
Console.WriteLine("CESS 5% : " + cess);
Console.WriteLine("Total Price :" + total);
}
}
}

15) Flight Status

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

namespace DateEx2 //DO NOT CHANGE the namespace name


{
public class Program //DO NOT CHANGE the class name
{
/* Dictionary values are hard-coded. Do NOT change **/
static Dictionary<string, DateTime> flightSchedule = new Dictionary<string,
DateTime>(){
{"ZW346",
Convert.ToDateTime("13:54:10")},
{"AT489",
Convert.ToDateTime("16:30:00")},
{"BR267",
Convert.ToDateTime("21:15:30")}};

public static void Main(string[] args) //DO NOT CHANGE the 'Main' method
signature
{
//Implement your code here
string flightNumber;
string timeLeft;

Console.WriteLine("Enter the Flight Number :");


flightNumber = Console.ReadLine();

timeLeft = flightStatus(flightNumber);
Console.WriteLine(timeLeft);

public static string flightStatus(string flightNo) //DO NOT CHANGE the


'flightStatus' method signature
{

//Implement your code here


if (flightSchedule.ContainsKey(flightNo))
{
DateTime departureTime = flightSchedule[flightNo];
if (DateTime.UtcNow < departureTime)
{
TimeSpan ts = departureTime.Subtract(DateTime.UtcNow);
return "Time to flight " + ts.ToString();
}
else
return "Flight Already Left";
}
else
return "Invalid Flight Number";
}

}
}

16) Product Details:

Product.cs

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

public class Product


{
public string _productName;
public string _serialNumber;
public DateTime _purchaseDate;
public double _cost;

// Implement 4-Argument Constructor


public Product(string _productName, string _serialNumber, DateTime
_purchaseDate, double _cost)
{
this._productName = _productName;
this._serialNumber = _serialNumber;
this._purchaseDate = _purchaseDate;
this._cost = _cost;
}

// Implement Properties
public string ProductName
{
set { this._productName = value; }
get { return this._productName; }
}
public string SerialNumber
{
set { this._serialNumber = value; }
get { return this._serialNumber; }
}
public DateTime PurchaseDate
{
set { this._purchaseDate = value; }
get { return this._purchaseDate; }
}
public double Cost
{
set { this._cost = value; }
get { return this._cost; }
}
public override string ToString()
{
return String.Format("{0,-15}{1,-15}{2,-15}{3,-15}", ProductName,
SerialNumber, String.Format("{0:d}", PurchaseDate), Cost);
}
}
Program.cs

using System;
using System.Collections;
using System.Globalization;
using System.IO;

public class Program //DO NOT CHANGE the name of class 'Program'
{
public static void Main(string[] args) //DO NOT CHANGE 'Main' Signature
{

//Fill the code here


StreamReader reader = new StreamReader("input.csv");
string data = "";
Product p = null;
ArrayList arlobj = new ArrayList();
while ((data = reader.ReadLine()) != null)
{
string[] info = data.Split(',');
string productName = info[0].Trim();
string serialNumber = info[1].Trim();
DateTime purchaseDate = DateTime.ParseExact(info[2].Trim(), "dd-MM-
yyyy", null);
double cost = Double.Parse(info[3].Trim());
p = new Product(productName, serialNumber, purchaseDate, cost);
arlobj.Add(p);

}
Console.WriteLine("{0}", String.Format("{0,-15}{1,-15}{2,-15}{3,-15}",
"Product Name", "Serial Number", "Purchase Date", "Cost"));
foreach (var obj in arlobj)
{
Product prd = (Product)obj;
Console.WriteLine("{0}", prd.ToString());
}
}

17) Vehicles Released in Certain Years:

Vehicle.cs

/******** FOR REFERENCE ONLY. DO NOT CHANGE *************/


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

namespace LinqApp1
{
public class Vehicle
{
public String VehicleId{get; set; }
public String VehicleName{ get; set; }
public String Brand { get; set; }
public int ReleaseYear { get; set; }

public Vehicle(String vehicleId, String vehicleName, String brand,int


releaseYear)
{
this.VehicleId = vehicleId;
this.VehicleName = vehicleName;
this.Brand = brand;
this.ReleaseYear = releaseYear;
}

}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace LinqApp1 //DO NOT CHANGE the namespace name


{

public class Program //DO NOT CHANGE the class name


{
/* DO NOT CHANGE this 'List' declaration with initialized values */
public static List<Vehicle> VehicleList = new List<Vehicle>()
{
new Vehicle("HO345","CRV","Honda",2015),
new Vehicle("HY562","Creta","Hyundai",2017),
new Vehicle("RE198","Duster","Reanult",2014),
new Vehicle("MA623","Spacio","Suzuki",2014),
new Vehicle("TR498","Nexon","Tata",2015),
new Vehicle("TR981","Zest","Tata",2016),
new Vehicle("HO245","WRV","Honda",2018)

};

static void Main(string[] args) //DO NOT Change this 'Main' signature
{
//Implement your code here
Console.WriteLine("Enter From Year:");
int fromYear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter To Year:");
int toYear = Convert.ToInt32(Console.ReadLine());
GetVehicleName(fromYear, toYear);
}

//Implement the method 'GetVehicleName' here


public static void GetVehicleName(int fromYear, int toYear)
{
IEnumerable<Vehicle> vehicles = from vehicle in VehicleList where
vehicle.ReleaseYear >= fromYear && vehicle.ReleaseYear <= toYear select vehicle;
foreach (Vehicle vehicle in vehicles)
Console.WriteLine(vehicle.VehicleName);
}

/* DO NOT CHANGE this ParameterExpression */


public static ParameterExpression variableExpr =
Expression.Variable(typeof(IEnumerable<Vehicle>), "sampleVar");

public static Expression GetMyExpression(int fromYear, int toYear)


{
Expression assignExpr = Expression.Assign(variableExpr,
Expression.Constant(from vehicle in VehicleList where vehicle.ReleaseYear >=
fromYear && vehicle.ReleaseYear <= toYear select vehicle));
return assignExpr;
}

}
}

18) Workshop Trainee Management:

Program.cs

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

namespace ADO_Net_App1
{
//Do not change any code under this class
public class Program
{
static void Main(string[] args)
{
TraineeBO objTraineeBO = new TraineeBO();
TraineeBL objTraineeBL = new TraineeBL();
string traineeName = string.Empty;
string batchCode = string.Empty;
int numberOfTrainees =0;

try
{
Console.WriteLine("Enter number of trainees:");
numberOfTrainees = int.Parse(Console.ReadLine());
}
catch(FormatException traineeNumberException)
{
Console.WriteLine(traineeNumberException.Message);
Environment.Exit(0);
}

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


{
try
{
Console.WriteLine("\nEnter Trainee Name:");
traineeName = Console.ReadLine();
if (string.IsNullOrEmpty(traineeName))
throw new Exception("Trainee Name can not be null or
empty");
else
objTraineeBO.TraineeName = traineeName;
}
catch (Exception nameException)
{
Console.WriteLine(nameException.Message);
Environment.Exit(0);
}

try
{
Console.WriteLine("Enter Trainee Id:");
objTraineeBO.TraineeId = long.Parse(Console.ReadLine());
}
catch(FormatException idException)
{
Console.WriteLine(idException.Message);
Environment.Exit(0);
}

try
{
Console.WriteLine("Enter Trainee Batch Code:");
batchCode = Console.ReadLine();
if (string.IsNullOrEmpty(batchCode))
throw new Exception("Batch Code can not be null or empty");
else
objTraineeBO.BatchCode = batchCode;
}
catch(Exception batchCodeException)
{
Console.WriteLine(batchCodeException.Message);
Environment.Exit(0);
}

bool insertResult = objTraineeBL.SaveTraineeDetails(objTraineeBO);


if (insertResult == true)
{
Console.WriteLine("Trainee Details Successfully added to
database");
}
else
{
Console.WriteLine("Trainee insertion failed..Duplicate
TraineeId present or wrong application logic");
Console.WriteLine("Try Again");
i--;

}
}
}
}
}
DBConnection.cs

//This is for your reference. DO NOT change this file


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

namespace ADO_Net_App1
{
public class DBConnection
{
public static String connStr = "User Id=admin;Password=admin;Data
Source=localhost:1521/XE;";
}
}

TraineeBO.cs

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

namespace ADO_Net_App1
{
public class TraineeBO
{
//Write your code here
public long traineeId;
public string traineeName;
public string batchCode;

public long TraineeId { get; set; }


public string TraineeName { get; set; }
public string BatchCode { get; set; }

public TraineeBO()
{

public TraineeBO(long traineeId, string traineeName, string batchCode)


{
this.traineeId = traineeId;
this.traineeName = traineeName;
this.batchCode = batchCode;
}
}
}

TraineeDA.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using System.Configuration;

namespace ADO_Net_App1
{
public class TraineeDA
{
public string ConnectionString
{
get
{
return DBConnection.connStr;
}
}

public bool AddTraineeDetails(TraineeBO objBO)


{

try
{
OracleConnection con = new OracleConnection(ConnectionString);
con.Open();
string query = "insert into tblTrainee values(" + objBO.TraineeId +
",'" + objBO.TraineeName + "','" + objBO.BatchCode + "')";
OracleCommand cmd = new OracleCommand(query, con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
return true;
else
return false;
}
catch(Exception e)
{
return false;
}
}

//Write your code here


}
}

TraineeBL.cs

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

namespace ADO_Net_App1
{
public class TraineeBL
{
public bool SaveTraineeDetails(TraineeBO objBO)
{
TraineeDA tDA = new TraineeDA();
bool res = tDA.AddTraineeDetails(objBO);
if (res)
return true;
else
return false;
}
}
}

19) Ticket Reservation for Summer:

Program.cs

You might also like