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

Alvin Compile

The document contains exercises related to programming in C# for a Data Structures and Algorithms course, including code, flowcharts, and pseudocode for various tasks such as determining if a number is odd or even, printing multiplication tables, calculating the sum of natural numbers, and loan payment details. Each exercise is structured with a clear layout, showcasing the code implementation followed by flowcharts and pseudocode for better understanding. The exercises aim to enhance programming skills and understanding of algorithms in practical scenarios.

Uploaded by

Ps Bongabong
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)
11 views67 pages

Alvin Compile

The document contains exercises related to programming in C# for a Data Structures and Algorithms course, including code, flowcharts, and pseudocode for various tasks such as determining if a number is odd or even, printing multiplication tables, calculating the sum of natural numbers, and loan payment details. Each exercise is structured with a clear layout, showcasing the code implementation followed by flowcharts and pseudocode for better understanding. The exercises aim to enhance programming skills and understanding of algorithms in practical scenarios.

Uploaded by

Ps Bongabong
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/ 67

CpE 222

BSCpE 2F1

Submitted by: Alvin R. Amparo


Course: BS Computer Engineering 2F1
Subject: Data Structures and Algorithms
Date: May 21, 2025
EXERCISE 1 (Odd or Even Code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EXERCISE_1_DSA
{
class Program
{
static void Main(string[] args)
{
int a;

Console.Write("enter a number: ");


string input =Console.ReadLine();

if (int.TryParse(input, out a))


{
if (a % 2 == 0)
Console.WriteLine("the number is EVEN");
else
Console.WriteLine("the numebr is ODD");
}
else
{
Console.WriteLine("Error, please enter a valid number");
}
Console.ReadKey();
}
}
}
EXERCISE 1 (Odd or Even Flow Chart)
EXERCISE (Odd or Even Pseudocode)

1. START

2. DECLARE a AS INTEGER
3. DECLARE input AS STRING

4. DISPLAY "Enter a number: "


5. READ input

6. IF input can be converted to an integer THEN


6.1 SET a = converted integer
7. IF a MODULO 2 EQUALS 0 THEN
7.1 DISPLAY "The number is EVEN"
8. ELSE
8.1 DISPLAY "The number is ODD"
9. END IF
10. ELSE
10.1 DISPLAY "Error, please enter a valid number."
11. END IF

12. WAIT for user to press a key


13. END
EXERCISE 2 (Prints its Multiplication Table up to a Specified Range Code)

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

namespace EXERCISE_2_DSA
{
class Program
{
static void Main(string[] args)
{
int R, C;

Console.Write("Enter a number for Row: ");


R = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a number for column: ");
C = Convert.ToInt32(Console.ReadLine());

for (int i = 1; i <= C; i++)


{
Console.WriteLine();
for (int j = 1; j <= R; j++)
{
Console.Write("{0}\t", i * j);
}
}
Console.ReadKey();
}
}
}
EXERCISE 2 (Prints its Multiplication Table up to a Specified Range Flow Chart)
EXERCISE 2 (Prints its Multiplication Table up to a Specified Range Pseudocode)

1. START

2. DECLARE R AS INTEGER
3. DECLARE C AS INTEGER

4. DISPLAY "Enter a number for Row: "


5. READ R

6. DISPLAY "Enter a number for Column: "


7. READ C

8. FOR i FROM 1 TO C DO
8.1 PRINT NEW LINE
8.2 FOR j FROM 1 TO R DO
8.3 DISPLAY (i * j) followed by a tab
8.4 END FOR
9. END FOR

10. WAIT for user to press any key


11. END
EXERCISE 3 (Calculates the SUM of the First n Natural Numbers Code)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Exercise3try
{
class Program
{
static void Main(string[] args)
{
int n1, answer;
answer = 0;
do
{
Console.Clear();
Console.Write("Enter any positive number: ");
n1 = Convert.ToInt32(Console.ReadLine());
if (n1 <= 0)
{
Console.Write("Try again, positive number only");
Console.ReadLine();
Console.Clear();
}
}
while (n1 <= 0);
{
for (int number = 1; number <= n1; number++)
{
answer += number;
Console.Write(number);
if (number < n1)
Console.Write(" + ");
}
Console.WriteLine(" = " + answer);
Console.ReadLine();
}
}
}
}
EXERCISE 3 (Calculates the SUM of the First n Natural Numbers Flow Chart)
EXERCISE 3 (Calculates the SUM of the First n Natural Numbers Pseudocode)

1. START

2. DECLARE n1 AS INTEGER
3. DECLARE answer AS INTEGER ← 0

4. REPEAT
4.1 CLEAR screen
4.2 DISPLAY "Enter any positive number: "
4.3 READ n1

5. IF n1 <= 0 THEN
5.1 DISPLAY "Try again, positive number only"
5.2 WAIT for user to press a key
5.3 CLEAR screen
6. END IF

7. UNTIL n1 > 0

8. FOR number FROM 1 TO n1 DO


8.1 answer ← answer + number
8.2 DISPLAY number

9. IF number < n1 THEN


9.1 DISPLAY " + "
10. END IF
10.1 END FOR

11. DISPLAY " = " + answer

12. WAIT for user to press a key


13. END
EXERCISE 6 (AMOUNT AND PERCENTAGE OF LOAN AND YEARS TO BE PAID CODE)

Console.WriteLine(" Month | Monthly Payment |


Interest | Total Paid | Remaining Balance |");
using System;
using System.Collections.Generic; Console.WriteLine("____________________________________
____________________________________________________
using System.Linq; ________________|");
using System.Text; for (int i = 1; i <= month; i++)
namespace ACTIVITY_6_DSA {
{ double interesPmonth, principlepermonth;
class Program interesPmonth = Rmain_bal * rate;
{ principlepermonth = Monthly_P - interesPmonth;
static void Main(string[] args) Total_P += Monthly_P + interesPmonth;
{ Rmain_bal -= principlepermonth;
double loanamount, perinterest; Total_PIR += interesPmonth;
int tyears; Console.WriteLine(" {0,-14} | {1, -22:0.00} | {2, -15:0.00}
| {3, -16:0.00} | {4, -16:0.00} |", i, Monthly_P, Total_PIR,
Console.Write("Enter a value for LOAN AMOUNT: ");
Total_P, Rmain_bal);
loanamount = Convert.ToDouble(Console.ReadLine());
}
Console.Write("Enter a value for PERCENTAGE
Console.WriteLine("____________________________________
INTEREST: ");
____________________________________________________
perinterest = Convert.ToDouble(Console.ReadLine()); ________________|");

Console.Write("Enter a value for TOTAL YEARS TO BE


PAID: ");
double T_loanamount = Total_PIR + loanamount;
tyears = Convert.ToInt32(Console.ReadLine());
int month = tyears * 12;
Console.WriteLine("\nOriginal Loan Amount: {0}",
double rate; loanamount);

rate = (perinterest / 100) / 12; Console.WriteLine("Total Loan Amount (Including


Interest): {0:C2}", T_loanamount);
double Monthly_P = loanamount * (rate * Math.Pow(1 +
rate, month)) / (Math.Pow(1 + rate, month) - 1); Console.WriteLine("Total Payable Amount: {0:C2} ",
Total_P);
double Total_P = 0, Total_PIR = 0, Rmain_bal =
loanamount;
Console.WriteLine("\nLoan Payment Details:"); Console.ReadKey();
}
Console.WriteLine("____________________________________
}
____________________________________________________
________________|"); }
EXERCISE 6 (AMOUNT AND PERCENTAGE OF LOAN AND YEARS TO BE PAID FLOWCHART)
EXERCISE 6 (AMOUNT AND PERCENTAGE OF LOAN AND YEARS TO BE PAID Pseudocode)
1. START

2. DECLARE loanamount AS DOUBLE


3. DECLARE perinterest AS DOUBLE
4. DECLARE tyears AS INTEGER

5. DISPLAY "Enter a value for LOAN AMOUNT: "


6. READ loanamount

7. DISPLAY "Enter a value for PERCENTAGE INTEREST: "


8. READ perinterest

9. DISPLAY "Enter a value for TOTAL YEARS TO BE PAID: "


10. READ tyears

11. SET month = tyears * 12


12. SET rate = (perinterest / 100) / 12

13. CALCULATE Monthly_P = loanamount * (rate * (1 + rate)^month) / ((1 + rate)^month - 1)

14. SET Total_P = 0


15. SET Total_PIR = 0
16. SET Rmain_bal = loanamount

17. DISPLAY "Loan Payment Details Table Header"

18 FOR i FROM 1 TO month DO


18. 1 CALCULATE interesPmonth = Rmain_bal * rate
18.2 CALCULATE principlepermonth = Monthly_P - interesPmonth
18.3 ADD Monthly_P + interesPmonth TO Total_P
18.4 SUBTRACT principlepermonth FROM Rmain_bal
18.5 ADD interesPmonth TO Total_PIR

18.6 DISPLAY Month number, Monthly_P, Total_PIR, Total_P, Rmain_bal


19. END FOR

20. CALCULATE T_loanamount = Total_PIR + loanamount


21. DISPLAY "Original Loan Amount: " + loanamount
22. DISPLAY "Total Loan Amount (Including Interest): " + T_loanamount (in currency format)
23. DISPLAY "Total Payable Amount: " + Total_P (in currency format)
24. WAIT for user to press a key

25. END
EXERCISE 7 (AMOUNT AND PERCENTAGE OF LOAN AND YEARS TO BE PAID CODE)

Console.WriteLine("____________________________________
using System; ____________________________________");
using System.Collections.Generic;
using System.Linq; for ( int loanmonths = 1; loanmonths <= months;
loanmonths++)
using System.Text;
{

namespace Loan
double interespermonth, principlepermonth;
{
interespermonth = R_Balance * rate;
class Program
principlepermonth = M_payment - interespermonth;
{
T_Paid += M_payment + interespermonth;
static void Main(string[] args)
R_Balance -= principlepermonth;
{
T_Irate += interespermonth;
t_mpayment += M_payment;
double percent, rate, loan, T_Paid, R_Balance, T_Irate,
t_mpayment, t_int, paid, balance;
int year; Console.WriteLine(" {0,-7} | {1, -15:0.00} | {2, -8:0.00} |
{3, -10:0.00} | {4, -10:0.00} |", loanmonths, M_payment,
interespermonth, T_Paid, R_Balance);
Console.Write("Enter Amount of Loan: "); if (loanmonths % 12 == 0)
loan = Convert.ToDouble(Console.ReadLine()); {
Console.Write("Enter Percentage: ");
percent = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Loan Duration (in years): "); t_int = T_Irate;
year = Convert.ToInt32(Console.ReadLine()); paid = T_Paid;
balance = R_Balance;
int months = year*12;
Console.WriteLine("-------------------------------------------------------------
rate= (percent/100)/12;
-----------");
Console.WriteLine("YEAR {0}: | {1, -15:0.00} | {2,
double M_payment = loan*(rate * Math.Pow(1 + rate, -8:0.00} | {3, -10:0.00} | {4, -10:0.00} |", loanmonths/12 ,
months))/ (Math.Pow(1 + rate, months) - 1); t_mpayment, t_int, paid, balance);

Console.WriteLine("-------------------------------------------------------------
T_Paid = 0; -----------");

T_Irate = 0; }

R_Balance = loan;
t_mpayment = 0; }

t_int=0;
paid=0; double T_LAmount = T_Irate + loan;

balance = 0; Console.Write("\nOriginal Loan Amount: {0:0.00}", loan);


Console.Write("\nTotal Loan Amount (Including Interest):
{0:0.00}", T_LAmount );
Console.WriteLine("\nLoan Payment Details:");
Console.Write("\nTotal Payable Amount: {0:0.00} ",
T_Paid);
Console.WriteLine("____________________________________
____________________________________"); Console.ReadLine();

Console.WriteLine(" Month | Monthly Payment | Interest | }


Total Paid
EXERCISE | Remaining Balance |"); AND PERCENTAGE OF
7 (AMOUNT LOAN AND YEARS TO BE PAID FLOWCHART)
}
EXERCISE 7 (AMOUNT AND PERCENTAGE OF LOAN AND YEARS TO BE PAID PSEUDOCODE)
1. START 23.2 CALCULATE principlepermonth = M_payment -
interespermonth

2. DECLARE loan, percent, rate AS DOUBLE


23.3 ADD M_payment + interespermonth TO T_Paid
3. DECLARE year, months AS INTEGER
23.4 SUBTRACT principlepermonth FROM R_Balance
4. DECLARE M_payment, T_Paid, T_Irate, R_Balance AS
DOUBLE 23.5 ADD interespermonth TO T_Irate
5. DECLARE t_mpayment, t_int, paid, balance AS DOUBLE 23. 6 ADD M_payment TO t_mpayment

6. DISPLAY "Enter Amount of Loan: " 24. DISPLAY loanmonths, M_payment, interespermonth,
T_Paid, R_Balance
7. READ loan

25. IF loanmonths MODULO 12 EQUALS 0 THEN


8. DISPLAY "Enter Percentage: "
25.1 SET t_int = T_Irate
9. READ percent
25.2 SET paid = T_Paid
25.3 SET balance = R_Balance
10. DISPLAY "Enter Loan Duration (in years): "
11. READ year
25.4 DISPLAY "Yearly Summary for Year " + (loanmonths /
12)
12. SET months = year * 12 25.5 DISPLAY t_mpayment, t_int, paid, balance
13. SET rate = (percent / 100) / 12

25.6 DISPLAY year separator


14. CALCULATE M_payment = loan * (rate * (1 + rate)^months) / 25.7 END IF
((1 + rate)^months - 1)
26. END FOR

15. SET T_Paid = 0


27. CALCULATE T_LAmount = T_Irate + loan
16. SET T_Irate = 0
17. SET R_Balance = loan
28. DISPLAY "Original Loan Amount: " + loan
18. ET t_mpayment = 0
29. DISPLAY "Total Loan Amount (Including Interest): " +
19. SET t_int = 0 T_LAmount
20. SET paid = 0 29. DISPLAY "Total Payable Amount: " + T_Paid
21. SET balance = 0

30. WAIT for user to press a key


22. DISPLAY "Loan Payment Details Table Header"
23. FOR loanmonths FROM 1 TO months DO 31. END
23.1 CALCULATE interespermonth = R_Balance * rate
EXERCISE 8 (LOAN APPLICATION CODE)
using System; loan_amount[count] =
Convert.ToDouble(Console.ReadLine());
using System.Collections.Generic;
Console.Write("Enter Interest Rate: ");
using System.Linq;
interest_rate[count] =
using System.Text; Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Years To Pay: ");
namespace LOAN_APPLICATION_DSA year[count] =
Convert.ToInt32(Console.ReadLine());
{
class Program
Console.WriteLine("Loan Recorded
{ Successfully!");
static void Main(string[] args) Console.Write("Press Any Key To Continue!");
{ Console.ReadKey();
int choices, maxloan = 100, count = 0; count++;
string[] names = new string[maxloan]; }
double[] loan_amount = new double[maxloan]; else
double[] interest_rate =new double[maxloan]; Console.WriteLine("Loan storage is full! Cannot
add more records.");
int[] year = new int[maxloan];
break;

do
case 2:
{
Console.Clear();
Console.Clear();
Console.WriteLine("You selected View All
Console.WriteLine("\n-------------------------------");
Record");
Console.WriteLine("-------------MENU--------------");
Console.WriteLine("\n---Loan Records---");
Console.WriteLine("-------------------------------");
if (count == 0)
Console.WriteLine("1. Add Loan Record");
{
Console.WriteLine("2. View All Records");
Console.WriteLine("No records found.");
Console.WriteLine("3. Search Loan Records");
}
Console.WriteLine("4. Delete Loan Record");
Console.WriteLine("5. Exit");
else
Console.WriteLine("\nEnter Your Choice: ");
{
for (int i = 0; i < count; i++)
choices = Convert.ToInt32(Console.ReadLine());
{
double principal = loan_amount[i];
double annualRate = interest_rate[i];
switch (choices)
int years = year[i];
{

case 1:
double monthlyRate = (annualRate / 100) /
Console.Clear(); 12;

if (count < maxloan) int totalMonths = years * 12;

{
Console.Write("You selected Add Loan double monthlyPayment = (principal *
Record"); monthlyRate * Math.Pow(1 + monthlyRate, totalMonths))
/(Math.Pow(1 + monthlyRate, totalMonths) - 1);
Console.Write("\nEnter Name: ");
names[count] = Console.ReadLine();
double totalPayment = monthlyPayment *
Console.Write("Enter Loan Amount: "); totalMonths;
Console.WriteLine("\nLoan Record
Found!");
Console.WriteLine("------------------------------------------------------------- Console.WriteLine("Name: " + names[i]);
-----------------------------------------------------------");
Console.WriteLine("Loan Amount: " +
Console.WriteLine("|Name | Loan loan_amount[i]);
Amount | Interest Rate | Years To Pay | Monthly
Payment | Total Payment |"); Console.WriteLine("Interest Rate: " +
interest_rate[i]);
Console.WriteLine(String.Format("{0,-12} |
{1,-17} | {2,-19} | {3,-18} | {4,-21} | {5,-0} ", names[i] , Console.WriteLine("Years to Pay: " +
loan_amount[i] , interest_rate[i] , year[i] , year[i]);
( Math.Round(monthlyPayment, 2)) , ( Math.Round(totalPayment,
2)))); Console.WriteLine("Monthly Payment: " +
Math.Round(monthlyPayment, 2));

Console.WriteLine("------------------------------------------------------------- Console.WriteLine("Total Payment: " +


-----------------------------------------------------------"); Math.Round(totalPayment, 2));

} found = true;

} break;

Console.Write("Press Any Key To Continue!"); }

Console.ReadKey(); }

break; if (!found)
{

case 3: Console.WriteLine("No record for " +


searchName);
{
}
string searchName;
Console.Clear();
Console.Write("Press Any Key To Continue!");
Console.WriteLine("You selected Search Loan
Record"); Console.ReadKey();

Console.Write("Enter the Name: "); break;

searchName = Console.ReadLine(); }

bool found = false; case 4:


{

for (int i = 0; i < count; i++) string deleteName;

{ Console.Clear();

if (names[i] == searchName) Console.WriteLine("You selected Delete Loan


Record");
{
Console.Write("Enter the Name to delete: ");
deleteName = Console.ReadLine();
double principal = loan_amount[i];
bool deleted = false;
double annualRate = interest_rate[i];
int years = year[i];
for (int i = 0; i < count; i++)
{
double monthlyRate = (annualRate / 100) /
12; if (names[i] == deleteName)

int totalMonths = years * 12; {

double monthlyPayment = (principal *


monthlyRate * Math.Pow(1 + monthlyRate, totalMonths)) /
for (int j = i; j < count - 1; j++)
(Math.Pow(1 +
{
monthlyRate, totalMonths) - 1);
names[j] = names[j + 1];
double totalPayment = monthlyPayment *
totalMonths; loan_amount[j] = loan_amount[j + 1];
interest_rate[j] = interest_rate[j + 1]; Console.ReadKey();
year[j] = year[j + 1]; break;
} }
case 5:
count--; {
deleted = true; Console.WriteLine("You selected Exit,BYE!");
Console.WriteLine("Loan record for " + break;
deleteName + " has been deleted.");
}
break;
}
}
}
}
while (choices != 5);
if (!deleted)
{
Console.ReadKey();
Console.WriteLine("No record found for " +
deleteName); }

} }
}

Console.Write("Press Any Key To Continue!");


EXERCISE 8 (LOAN APPLICATION Flowchart)
EXERCISE 8 (LOAN APPLICATION Pseudocode
START WAIT for key press
BREAK
SET maxloan = 100
SET count = 0 CASE 2:
DISPLAY "View All Records"
DECLARE: IF count == 0 THEN
names[maxloan] as string DISPLAY "No records found."
loan_amount[maxloan] as double ELSE
interest_rate[maxloan] as double FOR i FROM 0 TO count - 1 DO
year[maxloan] as int SET principal = loan_amount[i]
SET annualRate = interest_rate[i]
REPEAT SET years = year[i]
CLEAR screen
DISPLAY main menu: COMPUTE monthlyRate = (annualRate / 100) / 12
1. Add Loan Record COMPUTE totalMonths = years * 12
2. View All Records
3. Search Loan Records COMPUTE monthlyPayment =
4. Delete Loan Record (principal * monthlyRate * (1 +
monthlyRate)^totalMonths) /
5. Exit
((1 + monthlyRate)^totalMonths - 1)

PROMPT user for choice


COMPUTE totalPayment = monthlyPayment *
READ choices totalMonths

SWITCH choices: DISPLAY record with Name, Loan Amount, Interest


Rate,
Years, Monthly Payment, and Total Payment
CASE 1:
END FOR
IF count < maxloan THEN
END IF
DISPLAY "Add Loan Record"
WAIT for key press
PROMPT "Enter Name"
BREAK
READ names[count]

CASE 3:
PROMPT "Enter Loan Amount"
DISPLAY "Search Loan Record"
READ loan_amount[count]
PROMPT "Enter Name"
READ searchName
PROMPT "Enter Interest Rate"
SET found = false
READ interest_rate[count]

FOR i FROM 0 TO count - 1 DO


PROMPT "Enter Years to Pay"
IF names[i] == searchName THEN
READ year[count]
COMPUTE monthlyPayment and totalPayment
(same as above)
INCREMENT count DISPLAY the loan details
DISPLAY "Loan Recorded Successfully!" SET found = true
ELSE BREAK
DISPLAY "Loan storage is full!" END IF
END IF END FOR
DISPLAY "Record deleted"
IF NOT found THEN BREAK
DISPLAY "No record for" + searchName END IF
END IF END FOR
WAIT for key press
BREAK IF NOT deleted THEN
DISPLAY "No record found"
CASE 4: END IF
DISPLAY "Delete Loan Record" WAIT for key press
PROMPT "Enter Name to delete" BREAK
READ deleteName
SET deleted = false CASE 5:
DISPLAY "Exit, BYE!"
FOR i FROM 0 TO count - 1 DO BREAK
IF names[i] == deleteName THEN
FOR j FROM i TO count - 2 DO END SWITCH
COPY data from j+1 to j for all arrays
END FOR UNTIL choices == 5
DECREMENT count
SET deleted = true END
F ACTIVITY 1 (INFORMATION SYSTEM CODE)
using System; case "2":
using System.Collections.Generic; deletename();
using System.Linq; break;
using System.Text; case "3":
using System.Threading.Tasks; show();
break;
namespace FActivity_1 case "4":
{ countgender();
class Person break;
{ case "5":
public string Name { get; set; } return;
public int Age { get; set; } default:
public string Gender { get; set; } Console.WriteLine("Invalid choice. Please try
again."); break;
}
public Person(string name, int age, string gender)
}
{
}
Name = name;
Age = age;
static void inputdetails()
Gender = gender;
{
}
Console.Clear();
}
Console.Write("Enter Name: ");
class Program
string name = Console.ReadLine();
{
Console.Write("Enter Age: ");
static Stack<Person> mstack = new Stack<Person>();
int age;
static Stack<Person> fstack = new Stack<Person>();
if (!int.TryParse(Console.ReadLine(), out age))
{
static void Main(string[] args)
Console.WriteLine("Invalid age input.");
{
return;
while (true)
}
{
Console.Write("Enter Gender (Male/Female): ");
Console.Clear();
string gender = Console.ReadLine().Trim().ToLower();
Console.WriteLine("\nMenu");
Console.WriteLine("1. Input Name, Age, Gender");
Console.WriteLine("2. Delete Name");
if (gender == "male")
Console.WriteLine("3. Show All");
mstack.Push(new Person(name, age, "Male"));
Console.WriteLine("4. Count by Gender");
else if (gender == "female")
Console.WriteLine("5. Exit");
fstack.Push(new Person(name, age, "Female"));
Console.Write("Choose an option: ");
else
Console.WriteLine("Invalid gender. Please enter Male
string choice = Console.ReadLine(); or Female.");
switch (choice) Console.ReadKey();
{ }
case "1":
inputdetails(); static void deletename()
break; {
Console.Clear(); {
Console.Write("Enter gender (Male/Female) to display and Console.WriteLine("No males in the stack.");
delete from: ");
}
string gender = Console.ReadLine().Trim().ToLower();
}
else if (gender == "female")
if (gender == "male")
{
{
if (fstack.Count > 0)
if (mstack.Count > 0)
{
{
Console.WriteLine("\nFemale Stack:");
Console.WriteLine("\nMale Stack:");
Console.WriteLine("+----------------------+-------+");
Console.WriteLine("+----------------------+-------+");
Console.WriteLine("| Name | Age |");
Console.WriteLine("| Name | Age |");
Console.WriteLine("+----------------------+-------+");
Console.WriteLine("+----------------------+-------+");
foreach (Person person in fstack)
foreach (Person person in mstack)
{
{
Console.WriteLine("| {0,-20} | {1,-5} |",
Console.WriteLine("| {0,-20} | {1,-5} |", person.Name, person.Age);
person.Name, person.Age);
}
}
Console.WriteLine("+----------------------+-------+");
Console.WriteLine("+----------------------+-------+");
Console.Write("\nEnter name of the person to delete:
Console.Write("\nEnter name of the person to delete: ");
");
string nameToDelete = Console.ReadLine().Trim();
string nameToDelete = Console.ReadLine().Trim();

bool found = false;


bool found = false;
Stack<Person> temporaryStack = new
Stack<Person> temporaryStack = new Stack<Person>();
Stack<Person>();

while (fstack.Count > 0)


while (mstack.Count > 0)
{
{
Person person = fstack.Pop();
Person person = mstack.Pop();
if (person.Name.Equals(nameToDelete,
if (person.Name.Equals(nameToDelete, StringComparison.OrdinalIgnoreCase))
StringComparison.OrdinalIgnoreCase))
{
{
Console.WriteLine("Removed: {0}",
Console.WriteLine("Removed: {0}", person.Name);
person.Name);
found = true;
found = true;
break;
break;
}
}
temporaryStack.Push(person);
temporaryStack.Push(person);
}
}
while (temporaryStack.Count > 0)
while (temporaryStack.Count > 0)
fstack.Push(temporaryStack.Pop());
mstack.Push(temporaryStack.Pop());

if (!found)
if (!found)
Console.WriteLine("Person not found in Female
Console.WriteLine("Person not found in Male stack.");
stack.");
}
}
else
else
{
Console.WriteLine("No females in the stack.");
} Console.WriteLine("\nAll Persons in Stack:");
} if (mstack.Count == 0 && fstack.Count == 0)
else Console.WriteLine("No persons in the stack.");
{ else
Console.WriteLine("Invalid gender input. Please enter {
'Male' or 'Female'.");
Console.WriteLine("+----------------------+-------+---------+");
}
foreach (Person person in mstack.ToArray())
Console.WriteLine("| {0,-20} | {1,-5} | {2,-7} |",
Console.ReadKey(); person.Name, person.Age, person.Gender);
} foreach (Person person in fstack.ToArray())
static void show() Console.WriteLine("| {0,-20} | {1,-5} | {2,-7} |",
person.Name, person.Age, person.Gender);
{
Console.WriteLine("+----------------------+-------+---------+");
Console.Clear();
}
Console.WriteLine("Male Stack:");
Console.ReadKey();
if (mstack.Count == 0)
}
Console.WriteLine("No males in the stack.");
static void countgender()
else
{
{
Console.Clear();
Console.WriteLine("+----------------------+-------+");
int malecount = mstack.Count;
foreach (Person person in mstack.ToArray())
int femalecount = fstack.Count;
Console.WriteLine("| {0,-20} | {1,-5} |", person.Name,
person.Age); int totalcount = malecount + femalecount;
Console.WriteLine("+----------------------+-------+"); string male = "Male: " + malecount.ToString();
} string female = "Female: " + femalecount.ToString();
Console.WriteLine("\nFemale Stack:"); string total = "Total: " + totalcount.ToString();
if (fstack.Count == 0) Console.WriteLine("Count by Gender:");
Console.WriteLine("No females in the stack."); Console.WriteLine(male);
else Console.WriteLine(female);
{ Console.WriteLine(total);
Console.WriteLine("+----------------------+-------+---------+");
foreach (Person person in fstack.ToArray()) Console.ReadKey();
Console.WriteLine("| {0,-20} | {1,-5} |", person.Name, }
person.Age);
}
Console.WriteLine("+----------------------+-------+---------+");
}
}
F ACTIVITY 1 (INFORMATION SYSTEM FLOWCHART)
F ACTIVITY 1 (INFORMATION SYSTEM PSEUDOCODE)
START WAIT for key press
BREAK
DEFINE class Person:
- Name (string) CASE "2": // Delete name from gender stack
- Age (int) CLEAR screen
- Gender (string) PROMPT for gender (Male/Female)
CONSTRUCTOR (name, age, gender) READ gender
CONVERT gender to lowercase
DECLARE two stacks:
- mstack for males IF gender == "male" THEN
- fstack for females IF mstack is not empty THEN
DISPLAY all names and ages in mstack
LOOP forever: PROMPT for name to delete
CLEAR screen READ nameToDelete
DISPLAY menu:
1. Input Name, Age, Gender INITIALIZE temporaryStack
2. Delete Name SET found = false
3. Show All
4. Count by Gender WHILE mstack not empty DO
5. Exit POP person
IF person.Name == nameToDelete THEN
PROMPT for choice DISPLAY "Removed"
READ choice SET found = true
BREAK
SWITCH (choice): ELSE
PUSH person to temporaryStack
CASE "1": // Input details
CLEAR screen WHILE temporaryStack not empty
PROMPT for name PUSH back to mstack
READ name
PROMPT for age IF not found
READ age (validate if integer) DISPLAY "Person not found"
IF invalid THEN
DISPLAY error and RETURN ELSE
PROMPT for gender (Male/Female) DISPLAY "No males in the stack"
READ gender
CONVERT gender to lowercase ELSE IF gender == "female" THEN
IF fstack is not empty THEN
IF gender == "male" THEN DISPLAY all names and ages in fstack
PUSH new Person to mstack PROMPT for name to delete
ELSE IF gender == "female" THEN READ nameToDelete
PUSH new Person to fstack
ELSE INITIALIZE temporaryStack
DISPLAY "Invalid gender" SET found = false
WHILE fstack not empty DO DISPLAY contents of fstack
POP person
IF person.Name == nameToDelete THEN DISPLAY all persons from both stacks (name, age,
gender)
DISPLAY "Removed"
SET found = true
WAIT for key press
BREAK
BREAK
ELSE
PUSH person to temporaryStack
CASE "4": // Count by Gender
CLEAR screen
WHILE temporaryStack not empty
COUNT males in mstack
PUSH back to fstack
COUNT females in fstack
DISPLAY male count
IF not found
DISPLAY female count
DISPLAY "Person not found"
DISPLAY total count

ELSE
WAIT for key press
DISPLAY "No females in the stack"
BREAK
ELSE
DISPLAY "Invalid gender input"
CASE "5":
EXIT program
WAIT for key press
BREAK
DEFAULT:
DISPLAY "Invalid choice"
CASE "3": // Show All
CLEAR screen
END LOOP
DISPLAY contents of mstack
F EXERCISE 2 (PET SYSTEM CODE)

using System; Console.Write("Choose 1-6: ");


using System.Collections.Generic;
using System.Linq; string choice = Console.ReadLine();
using System.Text; switch (choice)
using System.Collections; {
case "1": AddName(); break;
namespace Stack_Pet_information case "2": DeleteName(); break;
{ case "3": SearchName(); break;
case "4": DisplayStack(); break;
case "5": CountStack(); break;
class Pet case "6": UpdatePet(); break;
{ case "7": return;
public string Name { get; set; } default: Console.WriteLine("Invalid choice. Try
again."); break;
public string Type { get; set; }
}
public int Age { get; set; }
}
public string Gender { get; set; }
}

public Pet(string name, string type, int age, string gender)


static void AddName()
{
{
Name = name;
Console.Clear();
Type = type;
Console.Write("Enter Name: ");
Age = age;
string name = Console.ReadLine();
Gender = gender;
Console.Write("Enter Type: ");
}
string type = Console.ReadLine();
}
Console.Write("Enter Age: ");
int age;
class Program
{
if (!int.TryParse(Console.ReadLine(), out age))
static Stack<Pet> maleStack = new Stack<Pet>();
{
static Stack<Pet> femaleStack = new Stack<Pet>();
Console.WriteLine("Invalid age input.");
return;
static void Main()
}
{
Console.Write("Enter Gender (Male/Female): ");
while (true)
string gender = Console.ReadLine().Trim().ToLower();
{
Console.Clear();
if (gender == "male")
Console.WriteLine("========MENU========");
{
Console.WriteLine("1. Add new pet");
maleStack.Push(new Pet(name, type, age, ",Male"));
Console.WriteLine("2. Remove Pet");
Console.WriteLine("\n" + name + " was Added
Console.WriteLine("3. Search Pet info"); Successfully.");
Console.WriteLine("4. Show All Pet"); }
Console.WriteLine("5. Show System Count"); else if (gender == "female")
Console.WriteLine("6. Update Pet info"); {
Console.WriteLine("7. Exit"); femaleStack.Push(new Pet(name, type, age,
",Female"));
Console.WriteLine("\n" + name + " was Added Console.ReadKey();
Successfully.");
}
}

static void SearchName()


else
{
Console.Clear();
Console.WriteLine("Invalid gender. Please enter Male
or Female."); Console.Write("Enter name to search: ");
string name = Console.ReadLine();

Console.Write("Press any key to continue.....");


Console.ReadKey(); bool found = false;

} foreach (Pet Pet in maleStack)


if (Pet.Name.Equals(name,
StringComparison.OrdinalIgnoreCase))
static void DeleteName()
{
{
Console.WriteLine("Found: " + Pet.Name + "Type: " +
Console.Clear(); Pet.Type + ", Age: " + Pet.Age + ", Gender: " + Pet.Gender);
Console.Write("Enter gender to delete from found = true;
(Male/Female): ");
break;
string gender = Console.ReadLine().Trim().ToLower();
}

if (gender == "male")
foreach (Pet Pet in femaleStack)
{
if (Pet.Name.Equals(name,
if (maleStack.Count > 0) StringComparison.OrdinalIgnoreCase))
{ {
Pet removed = maleStack.Pop(); Console.WriteLine("Found: " + Pet.Name + "Type: " +
Pet.Type + ", Age: " + Pet.Age + ", Gender: " + Pet.Gender);
Console.WriteLine(removed.Name + " was
removed."); found = true;
} break;
else }
Console.WriteLine("No males in the stack.");
} if (!found)
else if (gender == "female") {
{ Console.WriteLine("Name not found.");
if (femaleStack.Count > 0) }
{ Console.Write("Press any key to continue......");
Pet removed = femaleStack.Pop(); Console.ReadKey();
Console.WriteLine(removed.Name + " was }
removed.");
}
static void DisplayStack()
else
{
Console.WriteLine("No females in the stack.");
Console.Clear();
}
else Console.WriteLine("===================================
==============");
{
Console.WriteLine("Male Pets Stack:");
Console.WriteLine("Invalid gender input.");
if (maleStack.Count == 0)
}
Console.WriteLine("No Pets students in the stack.");
Console.Write("Press any key to continue......");
else
foreach (Pet Pet in maleStack.ToArray()) maleCount++;
Console.WriteLine(Pet.Name + ", Type: " + Pet.Type }
+ ", Age: " + Pet.Age);
foreach (var student in femaleStack)
{
Console.WriteLine("\
n================================================") femaleCount++;
;
}
Console.WriteLine("Total Male Pets:" + maleCount);
Console.WriteLine("Female Pets Stack:");
Console.WriteLine("Total Female Pets:" + femaleCount);
if (femaleStack.Count == 0)
int total = maleCount + femaleCount;
Console.WriteLine("No female Pets in the stack.");
Console.WriteLine("Total Pets:" + total);
else
Console.WriteLine("\
foreach (Pet Pet in femaleStack.ToArray()) n===========================================");

Console.WriteLine(Pet.Name + ", Type: " + Pet.Type Console.Write("Press any key to continue......");


+ ", Age: " + Pet.Age);

Console.ReadKey();
Console.WriteLine("\
n================================================")
;
}
static void UpdatePet()
Console.WriteLine("\nAll Students in Stack:");
{
if (maleStack.Count == 0 && femaleStack.Count == 0)
Console.Clear();
Console.WriteLine("No Students in the stack.");
Console.Write("Enter the name of the pet to update: ");
else
string name = Console.ReadLine();
{
foreach (Pet Pet in maleStack.ToArray())
Console.WriteLine(Pet.Name + ", Type: " + Pet.Type
bool updated = false;
+ ", Age: " + Pet.Age + ", Gender: " + Pet.Gender);
Stack<Pet> tempMale = new Stack<Pet>();
while (maleStack.Count > 0)
foreach (Pet Pet in femaleStack.ToArray())
{
Console.WriteLine(Pet.Name + ", Type: " + Pet.Type
+ ", Age: " + Pet.Age + ", Gender: " + Pet.Gender); Pet pet = maleStack.Pop();
Console.ReadKey(); if (pet.Name.Equals(name,
StringComparison.OrdinalIgnoreCase))
}
{
}
Console.Write("Enter new name: ");
pet.Name = Console.ReadLine();
Console.Write("Enter new age: ");
static void CountStack()
pet.Age = int.Parse(Console.ReadLine());
{
Console.Write("Enter new gender (Male/Female): ");
Console.Clear();
pet.Gender = Console.ReadLine();
Console.WriteLine("=======Pet Count=======");
Console.Write("Enter new type of pet: ");
Console.WriteLine("\
n========================================"); pet.Type = Console.ReadLine();

int maleCount = 0;
int femaleCount = 0; if (pet.Gender.ToLower() == "female")
{
foreach (var student in maleStack) femaleStack.Push(pet);
{ updated = true;
continue; {
} maleStack.Push(pet);
updated = true;
updated = true; continue;
} }
tempMale.Push(pet);
} updated = true;
}
while (tempMale.Count > 0) tempFemale.Push(pet);
maleStack.Push(tempMale.Pop()); }

while (tempFemale.Count > 0)


Stack<Pet> tempFemale = new Stack<Pet>(); femaleStack.Push(tempFemale.Pop());
while (femaleStack.Count > 0)
{ if (updated)
Pet pet = femaleStack.Pop(); Console.WriteLine("Information updated successfully.");
if (pet.Name.Equals(name, else
StringComparison.OrdinalIgnoreCase))
Console.WriteLine("Pet not found.");
{
Console.ReadLine();
Console.Write("Enter new name: ");
pet.Name = Console.ReadLine();
}
Console.Write("Enter new age: ");
pet.Age = int.Parse(Console.ReadLine());
}
Console.Write("Enter new gender (Male/Female): ");
}
pet.Gender = Console.ReadLine();

if (pet.Gender.ToLower() == "male")
F EXERCISE 2 (PET SYSTEM FLOWCHART)
F EXERCISE 2 (PET SYSTEM PSEUDOCODE)

START PROGRAM ---

DECLARE maleStack as stack of Pet FUNCTION DeleteName()


DECLARE femaleStack as stack of Pet PROMPT gender to delete from
IF gender is male AND maleStack not empty THEN
REPEAT FOREVER POP from maleStack
CLEAR screen DISPLAY removed name
DISPLAY Menu: ELSE IF gender is female AND femaleStack not empty THEN
1. Add new pet POP from femaleStack
2. Remove Pet DISPLAY removed name
3. Search Pet info ELSE
4. Show All Pet DISPLAY "Invalid gender or empty stack"
5. Show System Count WAIT for key press
6. Update Pet info END FUNCTION
7. Exit
PROMPT user to choose option ---

SWITCH based on choice: FUNCTION SearchName()


CASE "1": CALL AddName() PROMPT name to search
CASE "2": CALL DeleteName() SET found = false
CASE "3": CALL SearchName()
CASE "4": CALL DisplayStack() FOR each pet in maleStack
CASE "5": CALL CountStack() IF pet.Name equals input THEN
CASE "6": CALL UpdatePet() DISPLAY pet info
CASE "7": EXIT PROGRAM SET found = true
DEFAULT: DISPLAY "Invalid choice" BREAK

END REPEAT FOR each pet in femaleStack


IF pet.Name equals input THEN
--- DISPLAY pet info
SET found = true
FUNCTION AddName() BREAK
PROMPT name, type, age, gender
IF gender is male THEN IF NOT found THEN
PUSH new Pet to maleStack DISPLAY "Pet not found"
DISPLAY "Added successfully" WAIT for key press
ELSE IF gender is female THEN END FUNCTION
PUSH new Pet to femaleStack
DISPLAY "Added successfully" ---
ELSE
DISPLAY "Invalid gender" FUNCTION DisplayStack()
WAIT for key press DISPLAY all male pets
END FUNCTION IF maleStack empty THEN display "No male pets"
DISPLAY all female pets ELSE
IF femaleStack empty THEN display "No female pets" PUSH to TEMP stack
SET updated = true
DISPLAY all pets from both stacks ELSE
WAIT for key press PUSH to TEMP stack
END FUNCTION END WHILE
RESTORE maleStack from TEMP
---
TEMP stack for femaleStack
FUNCTION CountStack() WHILE femaleStack not empty
SET maleCount = number of pets in maleStack POP pet
SET femaleCount = number of pets in femaleStack IF pet.Name equals input THEN
SET total = maleCount + femaleCount PROMPT new name, age, gender, type
IF new gender is male THEN
DISPLAY maleCount, femaleCount, total PUSH to maleStack
WAIT for key press ELSE
END FUNCTION PUSH to TEMP stack
SET updated = true
--- ELSE
PUSH to TEMP stack
FUNCTION UpdatePet() END WHILE
PROMPT name to update RESTORE femaleStack from TEMP
SET updated = false
IF updated THEN
TEMP stack for maleStack DISPLAY "Update successful"
WHILE maleStack not empty ELSE
POP pet DISPLAY "Pet not found"
IF pet.Name equals input THEN WAIT for key press
PROMPT new name, age, gender, type END FUNCTION
IF new gender is female THEN
PUSH to femaleStack END PROGRAM
F ACTIVITY 2 code
using System; {
using System.Collections.Generic; case 1: Console.Clear(); NewPet(); break;
using System.Linq; case 2: Console.Clear(); SearchItem(); break;
using System.Text; case 3: Console.Clear(); DeleteItem(); break;
using System.Threading.Tasks; case 4: Console.Clear(); UpdateItems(); break;
case 5: Console.Clear(); DisplayItems(); break;
case 6: Console.Clear(); CounterGender(); break;
namespace F_Activity2 case 7: Console.WriteLine("\nExiting..."); break;
{ }
class Program
{ if (choice != 7)
static Stack<Item> itemStack = new Stack<Item>(); {
static Item[] petArray = new Item[100];
static int petCount = 0; Console.WriteLine("\nBack to MENU. Press any key
to continue...");
Console.ReadKey();
static void Main(string[] args)
}
{
int choice;
} while (choice != 7);
do
}
{
Console.Clear();
static void NewPet()
{
Console.Write("\n======= M E N U =======\n");
if (petCount >= petArray.Length)
Console.ResetColor();
{
Console.WriteLine("\n1. Add New Pet");
Console.WriteLine("\nArray is full! Cannot add more
Console.WriteLine("2. Search Pet Info"); pets.");
Console.WriteLine("3. Remove Pet"); return;
Console.WriteLine("4. Update Pet Info"); }
Console.WriteLine("5. Show all Pets");
Console.WriteLine("6. Show System Count"); Item newpet = new Item();
Console.WriteLine("7. EXIT");
Console.Write("\nEnter your choice: "); Console.Write("\nEnter Pet Name: ");
newpet.Name = Console.ReadLine();
Console.Write("Enter Pet Type: ");
if (!int.TryParse(Console.ReadLine(), out choice) || newpet.Type = Console.ReadLine();
choice < 1 || choice > 7)
Console.Write("Enter Age: ");
{
newpet.Age = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Enter Gender: ");
Console.WriteLine("\nINVALID INPUT. Please enter a
number between 1 and 7."); newpet.Gender = Console.ReadLine();
Console.ResetColor();
Console.ReadKey(); petArray[petCount++] = newpet;
continue; itemStack.Push(newpet);
}
Console.WriteLine("\nPet added successfully.");
switch (choice) }
string name = Console.ReadLine();
static void DeleteItem() bool found = false;
{
if (itemStack.Count == 0) for (int i = 0; i < petCount; i++)
{ {
Console.WriteLine("\nStack is empty. No pets to if (petArray[i].Name.Equals(name,
remove."); StringComparison.OrdinalIgnoreCase))
return; {
} Item item = petArray[i];
Console.WriteLine("\nPet Found: " + item.Name + ",
Type: " + item.Type + ", Age: " + item.Age + ", Gender: " +
Item topItem = itemStack.Peek(); item.Gender);
Console.WriteLine("\nAre you sure you want to remove found = true;
pet: " + topItem.Name + "? (Y/N)");
break;
string confirm = Console.ReadLine();
}
}
if (confirm.Equals("Y",
StringComparison.OrdinalIgnoreCase))
{ if (!found)
Item removed = itemStack.Pop(); Console.WriteLine("\nPet Not Found.");
bool found = false; }

for (int i = 0; i < petCount; i++) static void UpdateItems()


{ {
if (petArray[i].Name.Equals(removed.Name, Console.Write("Enter the name of pet you want to update:
StringComparison.OrdinalIgnoreCase)) ");
{ string name = Console.ReadLine();
for (int j = i; j < petCount - 1; j++) bool found = false;
petArray[j] = petArray[j + 1];
for (int i = 0; i < petCount; i++)
petArray[--petCount] = null; {
found = true; if (petArray[i].Name.Equals(name,
StringComparison.OrdinalIgnoreCase))
break;
{
}
Item item = petArray[i];
}
Console.WriteLine("\nCurrent Info: Name: " +
item.Name + ", Type: " + item.Type + ", Age: " + item.Age + ",
Gender: " + item.Gender);
Console.WriteLine("\nPet " + removed.Name + "
removed successfully.");
} Console.Write("\nEnter New Pet Name: ");
else item.Name = Console.ReadLine();
{ Console.Write("Enter Pet Type: ");
Console.WriteLine("\nDeletion cancelled."); item.Type = Console.ReadLine();
} Console.Write("Enter Age: ");
} item.Age = Console.ReadLine();
Console.Write("Enter Gender: ");
static void SearchItem() item.Gender = Console.ReadLine();
{
Console.Write("\nEnter Pet Name to Search: "); Console.WriteLine("\nPet Information UPDATED.");
found = true;
break; for (int i = 0; i < petCount; i++)
} {
} if (petArray[i].Gender.Equals("Male",
StringComparison.OrdinalIgnoreCase))
maleCount++;
if (!found)
else if (petArray[i].Gender.Equals("Female",
Console.WriteLine("Pet Not Found."); StringComparison.OrdinalIgnoreCase))
} femaleCount++;
else
static void DisplayItems() othersCount++;
{ }
if (petCount == 0)
{ Console.WriteLine("\nGender Count:");
Console.WriteLine("\nNo pets in the system."); Console.WriteLine("Male: " + maleCount);
return; Console.WriteLine("Female: " + femaleCount);
} Console.WriteLine("Others: " + othersCount);
Console.WriteLine("Total: " + (maleCount + femaleCount +
othersCount));
Console.WriteLine("\nAll Pets:");
}
for (int i = 0; i < petCount; i++)
{
class Item
Item item = petArray[i];
{
Console.WriteLine("Name: " + item.Name + ", Type: " +
item.Type + ", Age: " + item.Age + ", Gender: " + item.Gender); public string Name;
} public string Type;
} public string Age;
public string Gender;
static void CounterGender() }
{ }
int maleCount = 0, femaleCount = 0, othersCount = 0; }
F ACTIVITY 2 Flowchart
F ACTIVITY 2 Pseudocode

START IF input is invalid THEN


DISPLAY "Invalid Input"
DECLARE itemStack AS Stack of Item CONTINUE
DECLARE petArray[100] AS Array of Item ENDIF
DECLARE petCount AS Integer = 0
SWITCH choice
FUNCTION Main CASE 1: CALL NewPet
DO CASE 2: CALL SearchItem
DISPLAY Main Menu CASE 3: CALL DeleteItem
PROMPT user for choice CASE 4: CALL UpdateItems
CASE 5: CALL DisplayItems ENDIF
CASE 6: CALL CounterGender ELSE
CASE 7: DISPLAY "Exiting..." DISPLAY "Deletion cancelled"
END SWITCH ENDIF
END FUNCTION
IF choice IS NOT 7 THEN
DISPLAY "Back to MENU" FUNCTION SearchItem
WAIT for user input PROMPT user for pet name
ENDIF FOR each item in petArray
WHILE choice IS NOT 7 IF item name matches THEN
END FUNCTION DISPLAY pet details
RETURN
FUNCTION NewPet ENDIF
IF petCount >= 100 THEN ENDFOR
DISPLAY "Array is full" DISPLAY "Pet Not Found"
RETURN END FUNCTION
ENDIF
FUNCTION UpdateItems
CREATE newPet AS Item PROMPT user for pet name
PROMPT for Pet Name, Type, Age, Gender FOR each item in petArray
ASSIGN values to newPet IF item name matches THEN
DISPLAY current info
STORE newPet in petArray[petCount] PROMPT for new Name, Type, Age, Gender
INCREMENT petCount UPDATE item details
PUSH newPet to itemStack DISPLAY "Information Updated"
RETURN
DISPLAY "Pet added successfully" ENDIF
END FUNCTION ENDFOR
DISPLAY "Pet Not Found"
FUNCTION DeleteItem END FUNCTION
IF itemStack is empty THEN
DISPLAY "No pets to remove" FUNCTION DisplayItems
RETURN IF petCount == 0 THEN
ENDIF DISPLAY "No pets"
RETURN
GET topItem from itemStack ENDIF
PROMPT user to confirm deletion
FOR each item in petArray
IF user confirms THEN DISPLAY pet info
POP item from stack ENDFOR
SEARCH petArray for item by name END FUNCTION
IF found THEN
REMOVE item from array FUNCTION CounterGender
DECREMENT petCount SET maleCount, femaleCount, othersCount TO 0
DISPLAY "Pet removed"
FOR each item in petArray
IF gender is Male THEN DISPLAY gender counts and total
INCREMENT maleCount END FUNCTION
ELSE IF gender is Female THEN
INCREMENT femaleCount CLASS Item
ELSE DECLARE Name, Type, Age, Gender AS String
INCREMENT othersCount END CLASS
ENDIF
ENDFOR END
BST code
using System; {
if (root == null || root.Key == key)
class Node return root;
{
public int Key; if (key < root.Key)
public Node Left, Right; return SearchRec(root.Left, key);
else
public Node(int item) return SearchRec(root.Right, key);
{ }
Key = item;
Left = Right = null; public void Delete(int key)
} {
} Root = DeleteRec(Root, key);
}
class BinarySearchTree
{ private Node DeleteRec(Node root, int key)
public Node Root; {
if (root == null) return root;
public void Insert(int key)
{ if (key < root.Key)
Root = InsertRec(Root, key); root.Left = DeleteRec(root.Left, key);
} else if (key > root.Key)
root.Right = DeleteRec(root.Right, key);
private Node InsertRec(Node root, int key) else
{ {
if (root == null) if (root.Left == null) return root.Right;
return new Node(key); if (root.Right == null) return root.Left;

if (key < root.Key) root.Key = MinValue(root.Right);


root.Left = InsertRec(root.Left, key); root.Right = DeleteRec(root.Right, root.Key);
else if (key > root.Key) }
root.Right = InsertRec(root.Right, key);
else return root;
Console.WriteLine("Value " + key + " already exists. }
Skipping...");

private int MinValue(Node node)


return root;
{
}
int min = node.Key;
while (node.Left != null)
public bool Search(int key)
{
{
min = node.Left.Key;
return SearchRec(Root, key) != null;
node = node.Left;
}
}
return min;
private Node SearchRec(Node root, int key)
}
for (int i = 0; i < count; i++)
public void InOrder() {
{ Console.Write("Enter value #" + (i + 1) + ": ");
InOrderRec(Root); string valInput = Console.ReadLine();
Console.WriteLine(); int val;
} if (int.TryParse(valInput, out val))
{
private void InOrderRec(Node root) bst.Insert(val);
{ Console.WriteLine("Added " + val);
if (root != null) }
{ else
InOrderRec(root.Left); {
Console.Write(root.Key + " "); Console.WriteLine("Invalid number.
Skipping.");
InOrderRec(root.Right);
}
}
}
}
}
}
else
{
class Program
Console.WriteLine("Invalid count.");
{
}
static void Main()
Console.ReadKey();
{
break;
BinarySearchTree bst = new BinarySearchTree();

case "2":
while (true)
Console.Write("Enter number to search: ");
{
string searchInput = Console.ReadLine();
Console.Clear();
int searchVal;
Console.WriteLine("\nChoose an operation:");
if (int.TryParse(searchInput, out searchVal))
Console.WriteLine("1 - Add");
{
Console.WriteLine("2 - Search");
bool found = bst.Search(searchVal);
Console.WriteLine("3 - Delete");
if (found)
Console.WriteLine("4 - Show In-Order Traversal");
Console.WriteLine("Found " + searchVal);
Console.WriteLine("0 - Exit");
else
Console.Write("Your choice: ");
Console.WriteLine(searchVal + " not found");
string choice = Console.ReadLine();
}
else
switch (choice)
{
{
Console.WriteLine("Invalid number.");
case "1":
}
Console.Write("How many nodes do you want to
add? "); Console.ReadKey();
string input = Console.ReadLine(); break;
int count;
if (int.TryParse(input, out count)) case "3":
{ Console.Write("Enter number to delete: ");
string deleteInput = Console.ReadLine(); bst.InOrder();
int deleteVal; Console.ReadKey();
if (int.TryParse(deleteInput, out deleteVal)) break;
{
bst.Delete(deleteVal); case "0":
Console.WriteLine("Deleted " + deleteVal + " (if it Console.WriteLine("Exiting...");
existed)");
return;
}
else
default:
{
Console.WriteLine("Invalid choice.");
Console.WriteLine("Invalid number.");
Console.ReadKey();
}
break;
Console.ReadKey();
}
break;
}
}
case "4":
}
Console.WriteLine("In-Order Traversal:");
BST Flowchart
BST Pseudocode
START RETURN SearchRec(root.Left, key)
ELSE
CLASS Node RETURN SearchRec(root.Right, key)
DECLARE Integer Key END FUNCTION
DECLARE Node Left, Right
FUNCTION Delete(key)
CONSTRUCTOR Node(item) SET Root = DeleteRec(Root, key)
SET Key = item END FUNCTION
SET Left = null
SET Right = null FUNCTION DeleteRec(root, key)
END CLASS IF root IS null THEN
RETURN root
CLASS BinarySearchTree END IF
DECLARE Node Root
IF key < root.Key THEN
FUNCTION Insert(key) SET root.Left = DeleteRec(root.Left, key)
CALL InsertRec(Root, key) AND ASSIGN TO Root ELSE IF key > root.Key THEN
END FUNCTION SET root.Right = DeleteRec(root.Right, key)
ELSE
FUNCTION InsertRec(root, key) IF root.Left IS null THEN
IF root IS null THEN RETURN root.Right
RETURN new Node(key) ELSE IF root.Right IS null THEN
END IF RETURN root.Left

IF key < root.Key THEN SET root.Key = MinValue(root.Right)


SET root.Left = InsertRec(root.Left, key) SET root.Right = DeleteRec(root.Right, root.Key)
ELSE IF key > root.Key THEN END IF
SET root.Right = InsertRec(root.Right, key)
ELSE RETURN root
DISPLAY "Value already exists" END FUNCTION
END IF
FUNCTION MinValue(node)
RETURN root SET min = node.Key
END FUNCTION WHILE node.Left IS NOT null
SET min = node.Left.Key
FUNCTION Search(key) SET node = node.Left
RETURN SearchRec(Root, key) IS NOT null END WHILE
END FUNCTION RETURN min
END FUNCTION
FUNCTION SearchRec(root, key)
IF root IS null OR root.Key == key THEN FUNCTION InOrder()
RETURN root CALL InOrderRec(Root)
END IF PRINT new line
END FUNCTION
IF key < root.Key THEN
FUNCTION InOrderRec(root) CALL bst.Search(value)
IF root IS NOT null THEN DISPLAY "Found" or "Not found"
CALL InOrderRec(root.Left) ELSE
PRINT root.Key DISPLAY "Invalid"
CALL InOrderRec(root.Right) WAIT for key press
END IF
END FUNCTION CASE "3":
END CLASS PROMPT for value to delete
IF valid THEN
FUNCTION Main CALL bst.Delete(value)
CREATE BinarySearchTree bst DISPLAY "Deleted if exists"
ELSE
LOOP FOREVER DISPLAY "Invalid"
DISPLAY menu options WAIT for key press
PROMPT user for choice
CASE "4":
SWITCH user input DISPLAY "In-order traversal"
CASE "1": CALL bst.InOrder()
PROMPT for number of nodes to add WAIT for key press
FOR each node
PROMPT for value CASE "0":
IF valid THEN DISPLAY "Exiting..."
CALL bst.Insert(value) EXIT PROGRAM
DISPLAY "Added"
ELSE DEFAULT:
DISPLAY "Invalid" DISPLAY "Invalid choice"
END FOR WAIT for key press
WAIT for key press END SWITCH
END LOOP
CASE "2": END FUNCTION
PROMPT for value to search
IF valid THEN END
AVL Code
using System;
Node RotateLeft(Node x)
class Node {
{ Node y = x.Right;
public int Key; Node T2 = y.Left;
public Node Left;
public Node Right; y.Left = x;
public int Height; x.Right = T2;

public Node(int key) x.Height = Math.Max(Height(x.Left), Height(x.Right)) + 1;


{ y.Height = Math.Max(Height(y.Left), Height(y.Right)) + 1;
Key = key;
Height = 1; return y;
} }
}
Node Insert(Node node, int key)
class AVLTree {
{ if (node == null)
Node root; return new Node(key);

int Height(Node node) if (key < node.Key)


{ node.Left = Insert(node.Left, key);
return node == null ? 0 : node.Height; else if (key > node.Key)
} node.Right = Insert(node.Right, key);
else
int GetBalance(Node node) return node;
{
return node == null ? 0 : Height(node.Left) - node.Height = 1 + Math.Max(Height(node.Left),
Height(node.Right); Height(node.Right));
} int balance = GetBalance(node);

Node RotateRight(Node y) if (balance > 1 && key < node.Left.Key)


{ return RotateRight(node);
Node x = y.Left;
Node T2 = x.Right; if (balance < -1 && key > node.Right.Key)
return RotateLeft(node);
x.Right = y;
y.Left = T2; if (balance > 1 && key > node.Left.Key)
{
y.Height = Math.Max(Height(y.Left), Height(y.Right)) + 1; node.Left = RotateLeft(node.Left);
x.Height = Math.Max(Height(x.Left), Height(x.Right)) + 1; return RotateRight(node);
}
return x;
} if (balance < -1 && key < node.Right.Key)
{ }
node.Right = RotateRight(node.Right);
return RotateLeft(node); if (root == null)
} return root;

return node; root.Height = 1 + Math.Max(Height(root.Left),


Height(root.Right));
}
int balance = GetBalance(root);

Node MinValueNode(Node node)


if (balance > 1 && GetBalance(root.Left) >= 0)
{
return RotateRight(root);
Node current = node;
while (current.Left != null)
if (balance > 1 && GetBalance(root.Left) < 0)
current = current.Left;
{
return current;
root.Left = RotateLeft(root.Left);
}
return RotateRight(root);
}
Node Delete(Node root, int key)
{
if (balance < -1 && GetBalance(root.Right) <= 0)
if (root == null)
return RotateLeft(root);
return root;

if (balance < -1 && GetBalance(root.Right) > 0)


if (key < root.Key)
{
root.Left = Delete(root.Left, key);
root.Right = RotateRight(root.Right);
else if (key > root.Key)
return RotateLeft(root);
root.Right = Delete(root.Right, key);
}
else
{
return root;
if (root.Left == null || root.Right == null)
}
{
Node temp = root.Left ?? root.Right;
bool Search(Node node, int key)
{
if (temp == null)
if (node == null)
{
return false;
temp = root;
if (key == node.Key)
root = null;
return true;
}
if (key < node.Key)
else
return Search(node.Left, key);
root = temp;
return Search(node.Right, key);
}
}
else
{
void InOrder(Node node)
Node temp = MinValueNode(root.Right);
{
root.Key = temp.Key;
if (node != null)
root.Right = Delete(root.Right, temp.Key);
{
}
InOrder(node.Left); Console.WriteLine("\nAVL Tree Menu:");
Console.Write(node.Key + " "); Console.WriteLine("1. Add");
InOrder(node.Right); Console.WriteLine("2. Search");
} Console.WriteLine("3. Delete");
} Console.WriteLine("4. Show In-Order");
Console.WriteLine("5. Exit");
public void Add(int key) Console.Write("Enter choice: ");
{ choice = int.Parse(Console.ReadLine());
root = Insert(root, key);
} switch (choice)
{
public void Remove(int key) case 1:
{ Console.Write("Enter value to add: ");
root = Delete(root, key); value = int.Parse(Console.ReadLine());
} tree.Add(value);
break;
public void ShowInOrder() case 2:
{ Console.Write("Enter value to search: ");
InOrder(root); value = int.Parse(Console.ReadLine());
Console.WriteLine(); tree.SearchKey(value);
} break;
case 3:
public void SearchKey(int key) Console.Write("Enter value to delete: ");
{ value = int.Parse(Console.ReadLine());
if (Search(root, key)) tree.Remove(value);
Console.WriteLine("Found."); break;
else case 4:
Console.WriteLine("Not found."); Console.Write("In-order Traversal: ");
} tree.ShowInOrder();
} break;
case 5:
class Program Console.WriteLine("Exiting...");
{ break;
static void Main() default:
{ Console.WriteLine("Invalid choice!");
AVLTree tree = new AVLTree(); break;
int choice, value; }
} while (choice != 5);
do }
{ }

AVL Flowchart
AVL Pseudocode
FUNCTION Main()
CREATE AVLTree tree
DECLARE INTEGER choice, value

DO
PRINT menu:
1. Add
2. Search
3. Delete
4. Show In-Order
5. Exit

PROMPT user for choice

SWITCH (choice)
CASE 1:
PROMPT for value
CALL tree.Add(value)
CASE 2:
PROMPT for value
CALL tree.SearchKey(value)
CASE 3:
PROMPT for value
CALL tree.Remove(value)
CASE 4:
PRINT "In-order Traversal: "
CALL tree.ShowInOrder()
CASE 5:
PRINT "Exiting..."
DEFAULT:
PRINT "Invalid choice!"

WHILE choice != 5
END FUNCTION
ADT Code
using System; }

enum Color { Red, Black } private void InOrderPrint(Node node)


{
class Node if (node != null)
{ {
public int Data; InOrderPrint(node.Left);
public Node Left, Right; string color = node.Color == Color.Red ? "R" : "B";
public Color Color; Console.Write(node.Data + "[" + color + "] ");
InOrderPrint(node.Right);
public Node(int data) }
{ }
Data = data;
Color = Color.Red; public void Search(int data)
} {
} bool found = SearchNode(root, data) != null;
if (found)
class SimpleRedBlackTree Console.WriteLine(data + " found!");
{ else
private Node root; Console.WriteLine(data + " not found.");
}
public void Add(int data)
{ private Node SearchNode(Node node, int data)
root = Insert(root, data); {
root.Color = Color.Black; while (node != null)
Console.WriteLine("Added " + data); {
} if (data == node.Data) return node;
else if (data < node.Data) node = node.Left;
private Node Insert(Node node, int data) else node = node.Right;
{ }
if (node == null) return new Node(data); return null;
}
if (data < node.Data)
node.Left = Insert(node.Left, data); public void Remove(int data)
else if (data > node.Data) {
node.Right = Insert(node.Right, data); root = DeleteNode(root, data);
Console.WriteLine("Removed " + data + " (if it existed)");
return node; }
}
private Node DeleteNode(Node node, int data)
public void InOrder() {
{ if (node == null) return null;
Console.Write("In-Order: ");
InOrderPrint(root); if (data < node.Data)
Console.WriteLine(); node.Left = DeleteNode(node.Left, data);
else if (data > node.Data) break;
node.Right = DeleteNode(node.Right, data);
else case 2:
{ Console.Write("Enter value to remove: ");
if (node.Left == null) return node.Right; value = Convert.ToInt32(Console.ReadLine());
if (node.Right == null) return node.Left; tree.Remove(value);
break;
Node min = FindMin(node.Right);
node.Data = min.Data; case 3:
node.Right = DeleteNode(node.Right, min.Data); Console.Write("Enter value to search: ");
} value = Convert.ToInt32(Console.ReadLine());
return node; tree.Search(value);
} break;

private Node FindMin(Node node) case 4:


{ tree.InOrder();
while (node.Left != null) node = node.Left; break;
return node;
} case 0:
} Console.WriteLine("Exiting...");
break;
class Program
{ default:
static void Main() Console.WriteLine("Invalid option.");
{ break;
var tree = new SimpleRedBlackTree(); }
int choice, value;
} while (choice != 0);
do }
{ }
Console.WriteLine("\n--- Red-Black Tree Console ---");
Console.WriteLine("1. Add");
Console.WriteLine("2. Remove");
Console.WriteLine("3. Search");
Console.WriteLine("4. Show InOrder");
Console.WriteLine("0. Exit");
Console.Write("Choose: ");
choice = Convert.ToInt32(Console.ReadLine());

switch (choice)
{
case 1:
Console.Write("Enter value to add: ");
value = Convert.ToInt32(Console.ReadLine());
tree.Add(value);
ADT Flowchart
ADT Pseudocode
Start
Create an empty RedBlackTree

Repeat
Display menu:
1. Add
2. Remove
3. Search
4. Show InOrder
0. Exit
Input choice

If choice = 1 then
Input value
Call Add(value)
Else if choice = 2 then
Input value
Call Remove(value)
Else if choice = 3 then
Input value
Call Search(value)
Else if choice = 4 then
Call InOrder()
Else if choice = 0 then
Display "Exiting..."
Else
Display "Invalid option"
Until choice = 0
End
Activity 3 graph code
using System; Console.WriteLine("Vertex " + vertex + " added.");
using System.Collections.Generic; }
}
class Program
{ static void AddEdge(int a, int b)
static Dictionary<int, List<int>> graph = new Dictionary<int, {
List<int>>();
if (!graph.ContainsKey(a)) AddVertex(a);
if (!graph.ContainsKey(b)) AddVertex(b);
static void Main()
{
graph[a].Add(b);
InitializeGraph();
graph[b].Add(a);
AddVertex(6);
Console.WriteLine("Edge added between " + a + " and " + b
AddEdge(5, 6); + ".");
RemoveEdge(1, 4); }

Console.WriteLine("Updated Adjacency List:"); static void RemoveEdge(int a, int b)


DisplayGraph(); {
if (graph.ContainsKey(a)) graph[a].Remove(b);
Console.WriteLine("\nConnectivity Check: Is there a path if (graph.ContainsKey(b)) graph[b].Remove(a);
from 1 to 6?");
Console.WriteLine("Edge removed between " + a + " and " +
if (IsConnected(1, 6)) b + ".");
{ }
Console.WriteLine("Yes, there is a path from 1 to 6.");
} static void DisplayGraph()
else {
{ foreach (var node in graph)
Console.WriteLine("No, there is no path from 1 to 6."); {
} Console.Write("Node " + node.Key + ": ");
foreach (var neighbor in node.Value)
Console.ReadLine(); {
} Console.Write(neighbor + " ");
}
static void InitializeGraph() Console.WriteLine();
{ }
graph[1] = new List<int> { 2, 3, 4 }; }
graph[2] = new List<int> { 1, 5 };
graph[3] = new List<int> { 1, 5 }; static bool IsConnected(int start, int target)
graph[4] = new List<int> { 1, 5 }; {
graph[5] = new List<int> { 2, 3, 4 }; var visited = new HashSet<int>();
} var queue = new Queue<int>();
queue.Enqueue(start);
static void AddVertex(int vertex) visited.Add(start);
{
if (!graph.ContainsKey(vertex)) while (queue.Count > 0)
{ {
graph[vertex] = new List<int>(); int current = queue.Dequeue();
if (current == target) queue.Enqueue(neighbor);
return true; }
}
foreach (var neighbor in graph[current]) }
{
if (!visited.Contains(neighbor)) return false;
{ }
visited.Add(neighbor); }
Activity 3 Graph Flowchart
Activity 3 Graph Pseudocode
Start
Call InitializeGraph()
Call AddVertex(6)
Call AddEdge(5, 6)
Call RemoveEdge(1, 4)

Display "Updated Adjacency List:"


Call DisplayGraph()

Display "Connectivity Check: Is there a path from 1 to 6?"


If IsConnected(1, 6) then
Display "Yes, there is a path from 1 to 6."
Else
Display "No, there is no path from 1 to 6."

End
Activity 1 Graph Code
using System; visited.Add(neighbor);
using System.Collections.Generic; queue.Enqueue(neighbor);
}
class Program }
{ }
static Dictionary<string, List<string>> graph = new }
Dictionary<string, List<string>>();

static void DFS(string start)


static void Main()
{
{
var visited = new HashSet<string>();
var stack = new Stack<string>();
graph["A"] = new List<string> { "B", "C" };
graph["B"] = new List<string> { "A", "C", "E" };
stack.Push(start);
graph["C"] = new List<string> { "A", "B", "D" };
graph["D"] = new List<string> { "C", "E" };
while (stack.Count > 0)
graph["E"] = new List<string> { "B", "D" };
{
string node = stack.Pop();
Console.WriteLine("BFS Traversal from A:");
BFS("A");
if (!visited.Contains(node))
{
Console.WriteLine("\nDFS Traversal from A:");
Console.Write(node + " ");
DFS("A");
visited.Add(node);

Console.ReadLine();
}
var neighbors = new List<string>(graph[node]);
neighbors.Reverse();
static void BFS(string start)
{
foreach (var neighbor in neighbors)
var visited = new HashSet<string>();
{
var queue = new Queue<string>();
if (!visited.Contains(neighbor))
{
visited.Add(start);
stack.Push(neighbor);
queue.Enqueue(start);
}
}
while (queue.Count > 0)
}
{
}
string node = queue.Dequeue();
}
Console.Write(node + " ");
}

foreach (var neighbor in graph[node])


{
if (!visited.Contains(neighbor))
{
Activity 1 Graph Flowchart
Activity 1 Graph Pseudocde

Start
Initialize graph:
graph["A"] ← ["B", "C"]
graph["B"] ← ["A", "C", "E"]
graph["C"] ← ["A", "B", "D"]
graph["D"] ← ["C", "E"]
graph["E"] ← ["B", "D"]

Display "BFS Traversal from A:"


Call BFS("A")

Display "DFS Traversal from A:"


Call DFS("A")
End
Activity 2 Graph Code
using System; foreach (var neighbor in graph[node])
using System.Collections.Generic; {
var newPath = new List<string>(path);
class Program newPath.Add(neighbor);
{ queue.Enqueue(newPath);
static Dictionary<string, List<string>> graph = new }
Dictionary<string, List<string>>();
}
}
static void Main()
{
Console.WriteLine("No path found.");
}
graph["Manila"] = new List<string> { "Quezon", "Makati" };
}
graph["Quezon"] = new List<string> { "Manila", "Pasig" };
graph["Makati"] = new List<string> { "Manila", "Pasig",
"Taguig" };
graph["Pasig"] = new List<string> { "Quezon", "Makati",
"Taguig" };
graph["Taguig"] = new List<string> { "Makati", "Pasig" };

Console.WriteLine("BFS Path from Manila to Taguig:");


BFS("Manila", "Taguig");

Console.ReadLine();
}

static void BFS(string start, string goal)


{
var visited = new HashSet<string>();
var queue = new Queue<List<string>>();
queue.Enqueue(new List<string> { start });

while (queue.Count > 0)


{
var path = queue.Dequeue();
string node = path[path.Count - 1];

if (!visited.Contains(node))
{
visited.Add(node);

if (node == goal)
{
Console.WriteLine(string.Join(" -> ", path));
Activityreturn;
2 Graph Pseudocode
}
Start
Create an empty graph (dictionary of string to list of strings)
"Taguig" → ["Makati", "Pasig"]
Add connections:
"Manila" → ["Quezon", "Makati"] Display "BFS Path from Manila to Taguig:"
"Quezon" → ["Manila", "Pasig"] Call BFS("Manila", "Taguig")
"Makati" → ["Manila", "Pasig", "Taguig"] End
"Pasig" → ["Quezon", "Makati", "Taguig"]
Activity 2 Graph Flowchart

You might also like