0% found this document useful (0 votes)
11 views18 pages

Advanced Application Programming Assignment

The document discusses four programming assignments related to advanced application programming: 1. A program to print nested numbers in descending order using two loops. 2. A program that accepts user input of integers, stores them in an array, and determines which numbers are even or odd by passing them to a method. 3. A program that calculates the number of years it will take an amount of money to reach a target amount given the initial deposit, interest rate, and use of compound interest. 4. A program that models a supermarket transaction by creating an Item class with properties for code, price, quantity, and total cost. Items are added to a list, totals are calculated, and discounts are applied based

Uploaded by

Ruthwell Mugata
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
11 views18 pages

Advanced Application Programming Assignment

The document discusses four programming assignments related to advanced application programming: 1. A program to print nested numbers in descending order using two loops. 2. A program that accepts user input of integers, stores them in an array, and determines which numbers are even or odd by passing them to a method. 3. A program that calculates the number of years it will take an amount of money to reach a target amount given the initial deposit, interest rate, and use of compound interest. 4. A program that models a supermarket transaction by creating an Item class with properties for code, price, quantity, and total cost. Items are added to a list, totals are calculated, and discounts are applied based

Uploaded by

Ruthwell Mugata
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 18

Advanced Application Programming Lecturer

John Maina

Advanced Application Programming Assignments


1) Using nested loops, write code to produce the following output. (8 marks)
NB: Use only two loops.
12345678
1234567
123456
12345
1234
123
12
1

for (int i = 8; i >= 1; i--)


{
for (int j = 1; j <= i; j++)
{
Console.Write(j + " ");
}
Console.WriteLine();
}

2) Write a program that accepts a set of integers (the user decides how many) and then
stores them in an array. The main function then passes these values one by one to a
method called get_even which returns 1 if the integer is even and 0 if it is odd. The
main function should then specify which numbers were even, which ones were odd
and their respective totals. It should also specify how many numbers were odd and
how many were even. For example, if the user enters 25 34 56 17 14 20, the output
should be: -
25 is an odd number
34 is an even number
56 is an even number
17 is an odd number
14 is an even number
20 is an even number

There is a total of 2 odd numbers and their sum is 42.


There is a total of 4 even numbers and their sum is 124.
NB: All data input and output should be done in main. Don’t use % any where in the
main function (% can be used in the method). (10 marks)

using System;

1
Advanced Application Programming Lecturer
John Maina
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Prompt the user to enter a set of integers
Console.WriteLine("Please enter a set of integers, separated by spaces: ");
string input = Console.ReadLine();

// Split the input string into individual numbers


string[] numbers = input.Split(' ');

// Store the even and odd numbers in separate arrays


int[] evenNumbers = new int[numbers.Length];
int[] oddNumbers = new int[numbers.Length];

// Keep track of the total number of even and odd numbers


int evenCount = 0;
int oddCount = 0;

// Iterate over the numbers and determine whether each one is even or odd
foreach (string num in numbers)
{
int number = int.Parse(num);

if (get_even(number) == 1)
{
// The number is even, so add it to the evenNumbers array
evenNumbers[evenCount] = number;
evenCount++;
}
else

2
Advanced Application Programming Lecturer
John Maina
{
// The number is odd, so add it to the oddNumbers array
oddNumbers[oddCount] = number;
oddCount++;
}
}

// Print out the even and odd numbers


Console.WriteLine("Even numbers: ");
for (int i = 0; i < evenCount; i++)
{
Console.Write(evenNumbers[i] + " ");
}
Console.WriteLine();

Console.WriteLine("Odd numbers: ");


for (int i = 0; i < oddCount; i++)
{
Console.Write(oddNumbers[i] + " ");
}
Console.WriteLine();

// Calculate the sum of the even and odd numbers


int evenSum = 0;
int oddSum = 0;
for (int i = 0; i < evenCount; i++)
{
evenSum += evenNumbers[i];
}
for (int i = 0; i < oddCount; i++)
{
oddSum += oddNumbers[i];
}

3
Advanced Application Programming Lecturer
John Maina

// Print out the sum of the even and odd numbers


Console.WriteLine("There is a total of " + evenCount + " even numbers and
their sum is " + evenSum);
Console.WriteLine("There is a total of " + oddCount + " odd numbers and
their sum is " + oddSum);
}

// This method returns 1 if the given number is even and 0 if it is odd


static int get_even(int number)
{
if (number % 2 == 0)
{
return 1;
}
else
{
return 0;
}
}
}
}

3) Write a program that accepts the amount of money deposited in a bank account, the
annual interest rate and the target amount (The amount of money the account holder
wants to have in the account after a period of time) and then calculates the number of
years it will take for the money to accumulate to the targeted amount. NB: 1) The
interest being earned is Compound Interest. 2) Don’t use the formula for calculating
compound interest.
For example if the money deposited is 10000 and the target amount is 20000 and the
account earns an interest rate (compound) of 10% pa, then the output should be: -
It will take 8 years for your money to reach your target.
By the end of this period, the amount in your account will be 21435.89 (10 marks)

using System;

namespace BankAccount

4
Advanced Application Programming Lecturer
John Maina
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the amount of money deposited in the account:");
double deposit = double.Parse(Console.ReadLine());

Console.WriteLine("Enter the annual interest rate in percentage (without the


'%' sign):");
double interestRate = double.Parse(Console.ReadLine());

Console.WriteLine("Enter the target amount:");


double targetAmount = double.Parse(Console.ReadLine());

// Convert the interest rate from percentage to a decimal value (e.g. 10% ->
0.1)
interestRate = interestRate / 100;

int years = 0;
double currentAmount = deposit;

// Keep increasing the amount in the account each year


// until it reaches or exceeds the target amount
while (currentAmount < targetAmount)
{
currentAmount += currentAmount * interestRate;
years++;
}

Console.WriteLine($"It will take {years} years for your money to reach your
target.");
Console.WriteLine($"By the end of this period, the amount in your account
will be {currentAmount:F2}.");
}
}
}

5
Advanced Application Programming Lecturer
John Maina
4) Making use of object orientation write a program that stores and evaluates the total
cost for items bought from a supermarket. The cashier should enter the following: -
Product code, Price and Quantity. The total price should be evaluated as follows: -
Total cost = Price * Quantity
If the total cost per item is more than 20,000 there is a discount of 14% on that item
and a discount of 10% on an item whose total cost is between 10,000 and 20,000. No
discount is given on items whose total cost is less than 10,000
NB: The cashier should decide how many Items he/she wants to work with. If he/she
chooses 3, for example, the output should take the format shown below.
Item Code Price Quantity Total Cost Discount Net
109 6000 4 24000 3360 20640
201 900 8 7200 0 7200
127 600 20 12000 1200 10800
The total amount payable is 38640
NB: Your class should have constructors (including default constructor) and a
destructor. It should also have properties to set and return price, quantity and total
cost. Set item code to read only. (15 marks)

class Item
{
// read-only property for the product code
public int ProductCode { get; }

// property for the price of the item


public int Price { get; set; }

// property for the quantity of the item


public int Quantity { get; set; }

// constructor to initialize the object with the product code, price, and quantity
public Item(int productCode, int price, int quantity)
{
ProductCode = productCode;
Price = price;
Quantity = quantity;
}

6
Advanced Application Programming Lecturer
John Maina

// method to calculate the total cost of the item


public int CalculateTotalCost()
{
return Price * Quantity;
}
}

class Supermarket
{
// list of Item objects to store the items in the supermarket
private List<Item> items = new List<Item>();

// method to add an item to the list


public void AddItem(Item item)
{
items.Add(item);
}

// method to calculate the total amount payable for all the items in the list
public int CalculateTotalAmountPayable()
{
int total = 0;

// calculate the total cost of each item and add any applicable discounts
foreach (Item item in items)
{
int totalCost = item.CalculateTotalCost();

if (totalCost > 20000)


{
total += totalCost * (1 - 0.14);
}

7
Advanced Application Programming Lecturer
John Maina
else if (totalCost > 10000)
{
total += totalCost * (1 - 0.10);
}
else
{
total += totalCost;
}
}

return total;
}
}

class Program
{
static void Main(string[] args)
{
// create a new instance of the Supermarket class
Supermarket supermarket = new Supermarket();

// loop to allow the cashier to enter the details of each item


while (true)
{
Console.Write("Enter the product code (or 0 to finish): ");
int productCode = int.Parse(Console.ReadLine());

5) Rewrite the program above making use of arrays only i.e. don’t use object
orientation your program. (10 marks)

using System;
using System.Collections;

8
Advanced Application Programming Lecturer
John Maina
namespace Supermarket
{
class Item
{
// Property to get and set the item code
public int Code { get; }

// Property to get and set the item price


public int Price { get; set; }

// Property to get and set the item quantity


public int Quantity { get; set; }

// Property to get and set the total cost for the item
public int TotalCost
{
get
{
return Price * Quantity;
}
}

// Property to get the discount for the item


public int Discount
{
get
{
int total = TotalCost;

if (total > 20000)


{
return (int)(total * 0.14);
}

9
Advanced Application Programming Lecturer
John Maina
else if (total > 10000)
{
return (int)(total * 0.1);
}
else
{
return 0;
}
}
}

// Property to get the net cost for the item after the discount
public int Net
{
get
{
return TotalCost - Discount;
}
}

// Constructor to initialize the item code


public Item(int code)
{
this.Code = code;
}
}

class Program
{
static void Main(string[] args)
{
// Create an ArrayList to store the items
ArrayList items = new ArrayList();

10
Advanced Application Programming Lecturer
John Maina

// Prompt the user for the number of items


Console.Write("Enter the number of items: ");
int numItems = int.Parse(Console.ReadLine());

// Loop to input the details for each item


for (int i = 0; i < numItems; i++)
{
// Create a new item and add it to the ArrayList
Item item = new Item(i + 1);
items.Add(item);

// Prompt the user for the item price and quantity


Console.Write("Enter the price for item {0}: ", item.Code);
item.Price = int.Parse(Console.ReadLine());

Console.Write("Enter the quantity for item {0}: ", item.Code);


item.Quantity = int.Parse(Console.ReadLine());
}

// Print the table header


Console.WriteLine("Item Code\tPrice\tQuantity\tTotal Cost\tDiscount\tNet");

// Print the details for each item


foreach (Item item in items)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", item.Code, item.Price,
item.Quantity, item.TotalCost, item.Discount, item.Net);
}

// Calculate the total amount payable


int total = 0;
foreach (Item item in items)

11
Advanced Application Programming Lecturer
John Maina
{
total += item.Net;
}
Console.WriteLine("The total amount payable is {0}", total);
}
}
}

6) Write a program that accepts a set of numbers (The user decides how many) and
stores them in array. The program should the sort all the numbers in the array in
ascending order. It should output the numbers in the array before sorting and then
again after sorting. (10 marks)

using System;

namespace SortArray

class Program

static void Main(string[] args)

// Prompt the user to enter the number of elements in the array

Console.Write("Enter the number of elements in the array: ");

int n = int.Parse(Console.ReadLine());

// Create an array with the specified number of elements

int[] arr = new int[n];

12
Advanced Application Programming Lecturer
John Maina

// Prompt the user to enter the numbers in the array

Console.WriteLine("Enter the numbers in the array: ");

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

arr[i] = int.Parse(Console.ReadLine());

// Sort the array in ascending order

Array.Sort(arr);

// Output the numbers in the array before sorting

Console.WriteLine("The numbers in the array before sorting are: ");

foreach (int num in arr)

Console.Write(num + " ");

// Output the numbers in the array after sorting

Console.WriteLine("\nThe numbers in the array after sorting are: ");

foreach (int num in arr)

Console.Write(num + " ");

13
Advanced Application Programming Lecturer
John Maina
}

7) Write a program that accepts two numbers and swaps them. Both input and output
should be done in the main method and the swapping (actual swapping) should be
done in a method called swapNumbers. Output the two numbers in the main method
before and after swapping. (7 marks)

using System;

namespace SwapNumbers

class Program

static void Main(string[] args)

Console.WriteLine("Enter the first number: ");

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

Console.WriteLine("Enter the second number: ");

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

Console.WriteLine("Before swapping: ");

Console.WriteLine("First number: {0}", num1);

Console.WriteLine("Second number: {0}", num2);

swapNumbers(ref num1, ref num2);

14
Advanced Application Programming Lecturer
John Maina

Console.WriteLine("After swapping: ");

Console.WriteLine("First number: {0}", num1);

Console.WriteLine("Second number: {0}", num2);

static void swapNumbers(ref int num1, ref int num2)

int temp = num1;

num1 = num2;

num2 = temp;

8) Write a (unique) C# program using the concept of object orientation to illustrate the
following concept in Object Oriented programming. Indicate with comments where
each of these concepts/techniques is used in your program. (15 marks)
a) Inheritance.
b) Overloading.
c) Overriding.
d) Encapsulation.
e) Constructors (Including default constructors)
f) Destructor.
g) Properties.
h) Error handling – try catch

using System;

namespace OOPConcepts
{
// Base class "Shape" with protected member variables for height and width
public class Shape
{
// Protected variables can be accessed by derived classes

15
Advanced Application Programming Lecturer
John Maina
protected double height;
protected double width;

// Default constructor
public Shape()
{
this.height = 0;
this.width = 0;
}

// Overloaded constructor that takes in height and width as parameters


public Shape(double height, double width)
{
this.height = height;
this.width = width;
}

// Method to calculate the area of a shape


// This method will be overridden by derived classes
public virtual double CalculateArea()
{
return 0;
}

// Destructor to clean up any resources used by the Shape object


~Shape()
{
// Perform cleanup tasks here
}
}

// Derived class "Rectangle" that inherits from the base "Shape" class
public class Rectangle : Shape
{
// Default constructor that calls the base class default constructor
public Rectangle() : base()
{
}

// Overloaded constructor that takes in height and width as parameters


// This constructor calls the base class overloaded constructor
public Rectangle(double height, double width) : base(height, width)
{
}

// Property to get and set the height of a rectangle

16
Advanced Application Programming Lecturer
John Maina
public double Height
{
get
{
return this.height;
}
set
{
this.height = value;
}
}

// Property to get and set the width of a rectangle


public double Width
{
get
{
return this.width;
}
set
{
this.width = value;
}
}

// Overridden method to calculate the area of a rectangle


public override double CalculateArea()
{
// Calculate the area of the rectangle and return the result
return this.height * this.width;
}
}

class Program
{
static void Main(string[] args)
{
try
{
// Create a rectangle object and set its height and width
Rectangle rectangle = new Rectangle(10, 20);

// Calculate the area of the rectangle and print the result


Console.WriteLine("Area of rectangle: " + rectangle.CalculateArea());
}
catch (Exception ex)

17
Advanced Application Programming Lecturer
John Maina
{
// Catch any exceptions and print the error message
Console.WriteLine("Error: " + ex.Message);
}
}
}
}

* * * * * All the best – JM * * * * *

18

You might also like