0% found this document useful (0 votes)
148 views40 pages

All Programs

The document contains code examples demonstrating different object-oriented programming concepts in C#, including defining classes with properties and methods, creating objects, and passing parameters. It shows how to define classes for representing employees with name, ID, department and position properties, as well as retail items with description, quantity and price. Constructors are used to initialize objects and properties are accessed via getter and setter methods.

Uploaded by

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

All Programs

The document contains code examples demonstrating different object-oriented programming concepts in C#, including defining classes with properties and methods, creating objects, and passing parameters. It shows how to define classes for representing employees with name, ID, department and position properties, as well as retail items with description, quantity and price. Constructors are used to initialize objects and properties are accessed via getter and setter methods.

Uploaded by

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

1

Method call
namespace ConsoleApplication1
{

class testMethods
{
static double readValue(
string prompt, // prompt for the user double low,
double low, // lowest allowed value double high
double high) // highest allowed value
{
double result = 0;
do
{
Console.WriteLine(prompt + " between " + low + " and " + high);
string resultString = Console.ReadLine();
result = double.Parse(resultString);
}
while ((result < low) || (result > high));
return result;
}

2

public static void Main()
{
double aNumber = 30;
aNumber = readValue("please enter the input", 65, 259);
Console.WriteLine("The number is: {0}", aNumber);
Console.Read();
}
}
}

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

namespace ConsoleApplication1
{

class SimpleMath
{
public int AddTwoNumbers(int number1, int number2)
{
3

return number1 + number2;
}

public int MultiplyTwoNumbers(int number1, int number2)
{
return number1 * number2;
}

public int SquareANumber(int number)
{
return number * number;
}

// three different waay of passing parameters
// in, out, ref
static public void justPassing(int a, out int b, ref int c)
{
Console.WriteLine("--- inside justPassing Method ---");
Console.WriteLine("a= {0} c={1}", a, c);
a = a + 10;
b = 20;
c = c + 30;
4

Console.WriteLine("--- changing the parameters--");
Console.WriteLine("a= {0} b={1} c={2}", a, b, c);
Console.WriteLine("--- leaving justPassing Method ---");
}

static void Main()
{
int num1;
int num2;
int res;
string tmp;

// creating an object of Simple Math
// becuase the methods are not static we need to call them
// through an object and not by Class name
SimpleMath moto = new SimpleMath();

Console.WriteLine(moto.AddTwoNumbers(5, 7));

// reading num1
Console.WriteLine("enter num1: ");
tmp = Console.ReadLine();
5

num1 = Convert.ToInt32(tmp);

// reading num2
Console.WriteLine("enter num2: ");
tmp = Console.ReadLine();
num2 = Convert.ToInt32(tmp);

// call addition through object and then print results
res = moto.AddTwoNumbers(num1, num2);
Console.WriteLine("num1= {0} + num2={1} res= {2}", num1, num2, res);

// call multiplication through object and then print results
res = moto.MultiplyTwoNumbers(num1, num2);
Console.WriteLine("num1= {0} * num2={1} res= {2}", num1, num2, res);

double square = moto.SquareANumber(10);
Console.WriteLine("square of {0} is {1}", 10, square);

// examining parameter passing
int x = 1;
int y = 2;
int z = 3;
6

Console.WriteLine("\n\n\n--- before calling justPassing method--");
Console.WriteLine("x= {0} y={1} z={2}", x, y, z);
justPassing(x, out y, ref z);
Console.WriteLine("--- after returning from justPassing method--");
Console.WriteLine("x= {0} y={1} z={2}", x, y, z);
Console.Read(); }}}
using System;

/* The Employee class stores data about an employee. */

public class Employee
{
private string name; // Employee's name
private int idNumber; // Employee's ID number
private string department; // Employee's department
private string position; // Employee's job title

/* The following default constructor assigns an empty
* string to the name, department, and position fields,
* and assigns 0 to the idNumber field.
*/
public Employee()
7

{
name = "";
idNumber = 0;
department = "";
position = "";
}

/* The following constructor accepts arguments for the
* employee's name, ID number, department, and position.
*/
public Employee(string n, int id, string dept, string pos)
{
name = n;
idNumber = id;
department = dept;
position = pos;
}

/* The following constructor accepts arguments for the
* employee's name and ID number. The department and position
* fields are initialized with an empty string.
*/
8

public Employee(string n, int id)
{
name = n;
idNumber = id;
department = "";
position = "";
}

/* Mutator for the name field. */
public void SetName(string n)
{
name = n;
}

/* Mutator for the idNumber field. */
public void SetIdNumber(int id)
{
idNumber = id;
}
/* Mutator for the department field. */
public void SetDepartment(string dept)
{
9

department = dept;
}
/* Mutator for the position field. */
public void SetPosition(string pos)
{
position = pos;
}
/* Accessor for the name field. */
public string GetName()
{
return name;
}

/* Accessor for the idNumber field. */
public int GetIdNumber()
{
return idNumber;
}

/* Accessor for the department field. */
public string GetDepartment()
{
10

return department;
}

/* Accessor for the position field. */
public string GetPosition()
{
return position;
}
}

public class EmployeeDemo
{
public static void Main()
{
// Create three Employee objects.
Employee susan = new Employee("Susan Meyers", 47899, "Accounting",
"Vice President");
Employee mark = new Employee("Mark Jones", 39119, "IT", "Programmer");
Employee joy = new Employee("Joy Rogers", 81774, "Manufacturing",
"Engineer");

// Display the first employee's data.
11

Console.WriteLine("Name: " + susan.GetName());
Console.WriteLine("ID Number: " + susan.GetIdNumber());
Console.WriteLine("Department: " + susan.GetDepartment());
Console.WriteLine("Position: " + susan.GetPosition());
Console.WriteLine();

// Display the second employee's data.
Console.WriteLine("Name: " + mark.GetName());
Console.WriteLine("ID Number: " + mark.GetIdNumber());
Console.WriteLine("Department: " + mark.GetDepartment());
Console.WriteLine("Position: " + mark.GetPosition());
Console.WriteLine();

// Display the third employee's data.
Console.WriteLine("Name: " + joy.GetName());
Console.WriteLine("ID Number: " + joy.GetIdNumber());
Console.WriteLine("Department: " + joy.GetDepartment());
Console.WriteLine("Position: " + joy.GetPosition());
Console.WriteLine();
Console.Read();
}
}
12



using System;
public class RetailItem
{

private string description; // Item description

private int unitsOnHand; // Number of units on hand

private double price; // Unit price



/**

This constructor initializes the item's

description with an empty string, units on hand

to 0, and price to 0.0.

13

*/

public RetailItem()
{

description = "";

unitsOnHand = 0;

price = 0.0;

}



/**
026
This constructor initializes the item's
027
description, units on hand, and price with
028
values passed as arguments.
14

029
@param d The item's description.
030
@param u The number of units on hand.
031
@param p The item's price.
032
*/



public RetailItem(string d, int u, double p)
{

description = d;

unitsOnHand = u;

price = p;

}

15

public void SetDescription(string d)
{

description = d;
}
public void setUnitsOnHand(int u)
{

unitsOnHand = u;

}


public void setPrice(double p)
{

price = p;
}

public string getDescription()
{

16

return description;

}

public int getUnitsOnHand()
{

return unitsOnHand;

}


public double getPrice()
{

return price;

}

}


17

public class RetailItemDemo
{

public static void Main()
{

// Create the first item. Use the no-arg constructor.

RetailItem item1 = new RetailItem();

item1.SetDescription("Jacket");

item1.setUnitsOnHand(12);

item1.setPrice(59.95);



// Create the second item. Use the constructor

RetailItem item2 = new RetailItem("Designer Jeans", 40, 34.95);

18



// Create the third item. Use the no-arg constructor.

RetailItem item3 = new RetailItem();




// Display the info for item1.

Console.WriteLine("Item #1");

Console.WriteLine("Description: " + item1.getDescription());

Console.WriteLine("Units on hand: " + item1.getUnitsOnHand());

Console.WriteLine("Price: " + item1.getPrice());


// Display the info for item2.

19

Console.WriteLine("\nItem #2");

Console.WriteLine("Description: " + item2.getDescription());

Console.WriteLine("Units on hand: " + item2.getUnitsOnHand());

Console.WriteLine("Price: " + item2.getPrice());



// Display the info for item3.

Console.WriteLine("\nItem #3");

Console.WriteLine("Description: " + item3.getDescription());

Console.WriteLine("Units on hand: " + item3.getUnitsOnHand());

Console.WriteLine("Price: " + item3.getPrice());
Console.Read();

}
20


}


Item #1
Description: Jacket
Units on hand: 12
Price: 59.95

Item #2
Description: Designer Jeans
Units on hand: 40
Price: 34.95

Item #3
Description:
Units on hand: 0
Price: 0

/*
This program stores in an array the hours worked by
five employees who all make the same hourly wage.
21

Overtime wages are paid for hours greater than 40.
*/

using System;

public class Overtime
{
public static void Main()
{
const int EMPLOYEES = 5; // Number of employees
int[] hours = new int[EMPLOYEES]; // Array of hours
double payRate, // Hourly pay rate
grossPay, // Gross pay
overtime; // Overtime wages



// Get the hours worked by each employee.
Console.WriteLine("Enter the hours worked by five " +
"employees who all earn the same " +
"hourly rate.");

22

for (int i = 0; i < EMPLOYEES; i++)
{
Console.Write("Employee #{0}:", (i + 1));
hours[i] = Convert.ToInt32(Console.ReadLine());
}

// Get each the hourly pay rate.

Console.Write("Enter the hourly rate for each employee: ");

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

// Display each employee's gross pay.

Console.WriteLine("Here is the gross pay for each employee:");
for (int i = 0; i < EMPLOYEES; i++)
{
if (hours[i] > 40)
{
// Calculate base pay
grossPay = 40 * payRate;

23

// Calculate overtime pay
overtime = (hours[i] - 40) * (1.5 * payRate);

// Add base pay and overtime pay
grossPay += overtime;
}
else
grossPay = hours[i] * payRate;

Console.WriteLine("Employee #{0}: {1:C2}", (i + 1), grossPay);
Console.Read();
}
}
}
Enter the hours worked by five employees who all earn the same hourly rate.
Employee #1:50
Employee #2:505
Employee #3:23
Employee #4:213
Employee #5:123
Enter the hourly rate for each employee: 20
Here is the gross pay for each employee:
24

Employee #1: 1,100.00

/*
This program demonstrates a two-dimensional array.
*/

using System;

public class CorpSales
{
public static void Main()
{

double[,] sales = new double[3, 4];
double totalSales = 0.0;



// Create a DecimalFormat object.

Console.WriteLine("This program will calculate the total sales of");
25

Console.WriteLine("all the company's divisions. Enter the following sales
data:");

// Nested loops to fill the array with quarterly
// sales figures for each division.
for (int div = 0; div < 3; div++)
{
for (int qtr = 0; qtr < 4; qtr++)
{
Console.Write("Division {0}, Quarter {1}: $", (div + 1),
(qtr + 1));

sales[div, qtr] = Convert.ToDouble(Console.ReadLine());
}
Console.WriteLine(); // Print blank line.
}

// Nested loops to add all the elements of the array.
for (int div = 0; div < 3; div++)
{
for (int qtr = 0; qtr < 4; qtr++)
{
26

totalSales += sales[div, qtr];
}
}

// Display the total sales.
Console.WriteLine("The total sales for the company are {0:C2}", totalSales);

Console.Read();
}
}



This program will calculate the total sales of
all the company's divisions. Enter the following sales data:
Division 1, Quarter 1: $3
Division 1, Quarter 2: $3
Division 1, Quarter 3: $3
Division 1, Quarter 4: $3

Division 2, Quarter 1: $3
Division 2, Quarter 2: $3
27

Division 2, Quarter 3: $3
Division 2, Quarter 4: $3

Division 3, Quarter 1: $3
Division 3, Quarter 2: $3
Division 3, Quarter 3: $3
Division 3, Quarter 4: $3

The total sales for the company are 36.00

ARRAYS

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

namespace ConsoleApplication7
{
class TwoDimensionalArray
{
int[,] a2d;
28


public TwoDimensionalArray()
{
a2d = new int[4, 5];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
{
a2d[i, j] = i + j;
Console.WriteLine(a2d[i, j]);
}
}
public TwoDimensionalArray(int x, int y)
{
a2d = new int[x, y];
Console.WriteLine("--------Created using x y--------------------");
}
public TwoDimensionalArray(int x)
{
a2d = new int[x, 5];
Console.WriteLine("--------Created using x--------------------");
}
public TwoDimensionalArray add(TwoDimensionalArray x, int a,
29

out float b, ref string c)
{
TwoDimensionalArray y;
y = x;
b = 3.5f;
c = "xxxxx";
Console.WriteLine("-in add--{0} {1} {2}", a, b, c);
return y;
}

// summing over the rows

public int[] sumRow()
{
int[] sum = new int[a2d.GetLength(0)];
int k = 0;
for (int i = 0; i < a2d.GetLength(0); i++)
{
for (int j = 0; j < a2d.GetLength(1); j++)
{
sum[k] = sum[k] + a2d[i, j];

30

}
k++;
}
return sum;
}
static void Main()
{
// create 2 d
TwoDimensionalArray a = new TwoDimensionalArray();
int[] res = new int[4];
res = a.sumRow();
Console.WriteLine("----------------------------");
for (int i = 0; i < 4; i++)
Console.WriteLine(res[i]);

Console.WriteLine("----------------------------");

Console.Read();
}
}


31


}


using System;
namespace ConsoleApplication1
{
class whileTest
{
static int[] input()
{
int[] a = new int[10];
for (int i = 0; i < 10; i++)
a[i] = i;
return a;
}

static void Main(string[] args)
{
int[] b;
int i = 0;
b = input();
32



// You can assign a variable in the while-loop condition statement.
while (i < b.Length)
{
// In the while-loop body, both i and value are equal.
Console.WriteLine("array b[{0}] = {1}", i, b[i]);
i++;
}
Console.WriteLine("\ncalling output\n");
output(b);
Console.Read();
}

static void output(int[] c)
{
for (int i = 0; i < c.Length; i++)
Console.WriteLine("array c[{0}] = {1}", i, c[i]);
}
}
}

33

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// create an array of Atest with 10 elements
Atest[] t = new Atest[10];
// create and initialize each element of the array
for (int i = 0; i < 10; i++)
t[i] = new Atest(10 - i);
// print the elements of the array
for (int i = 0; i < 10; i++)
Console.WriteLine(t[i].GetA());
Console.WriteLine("--- sort low ---");
Array.Sort(t, AtestCompareLow);
for (int i = 0; i < 10; i++)
34

Console.WriteLine(t[i].GetA());
Console.WriteLine("---- sort high --- ");
Array.Sort(t, AtestCompareHigh);
for (int i = 0; i < 10; i++)
Console.WriteLine(t[i].GetA());
// a better way of printing
Console.WriteLine("---- better way of printing an object --- ");
for (int i = 0; i < 10; i++)
t[i].print();
Console.Read();

}
public static int AtestCompareLow(Atest x, Atest y)
{
if (x.GetA() > y.GetA())
return 1;
else if (x.GetA() < y.GetA())
return -1;
else
return 0;
}
public static int AtestCompareHigh(Atest x, Atest y)
35

{
if (x.GetA() > y.GetA())
return -1;
else if (x.GetA() < y.GetA())
return 1;
else
return 0;
}
}

class Atest
{
private int a;
public Atest(int x)
{
a = x;
}
public Atest()
{
a = 0;
}
public void SetA(int x)
36

{
a = x;
}

public int GetA()
{
return a;
}
public void print()
{
Console.WriteLine(a);
}
}
}




// arrays.cs
using System;
class DeclareArraysSample
{
37

public static void Main()
{
// Single-dimensional array
int[] numbers = new int[5];

// Multidimensional array
string[,] names = new string[5, 4];

// Array-of-arrays (jagged array)
byte[][] scores = new byte[5][];

// Create the jagged array
for (int i = 0; i < scores.Length; i++)
{
scores[i] = new byte[i + 3];
}

// Print length of each row
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
}
38

Console.Read();
}
}



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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//Enum Variables
weeks w1 = weeks.Sunday;
//Print out their values:
Console.WriteLine(w1);
string s = Console.ReadLine();
39


switch (s)
{
case "Sunday": w1 = weeks.Sunday;
break;
case "Monday": w1 = weeks.Monday;
break;
case "Tuesday": w1 = weeks.Tuesday;
break;
case "Wednesday": w1 = weeks.Wednesday;
break;
case "Thursday": w1 = weeks.Thursday;
break;
case "Friday": w1 = weeks.Friday;
break;
case "Saturday": w1 = weeks.Saturday;
break;
default:
Console.WriteLine("Your day {0} is not whats needed.", s);
break;
}
Console.WriteLine("The Day is {0}", w1);
40

Console.Read();

}
enum weeks
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
}
}

You might also like