⛅ Table of Contents Table of Contents Overview Part 1: Temperature Converter Part 2: The Weekly Forecast Part 3: Putting it all together Feedback Survey Submitting Instructions Overview For this assignment, we’re focusing on using template functions and lambdas effectively! Download the starter code here. Part 1: Temperature Converter The Stanford Daily has just put up a listing for a new job as the campus weatherman! Since you ran out of your meal plan dollars for the quarter after eating at TAP twice, you decide to apply. However, they request that for the interview applicants present the day’s weather forecast with high and low temperatures in both Fahrenheit and Celsius. Rather than worry about handling the conversions on the fly, you decide to write a program to do it for you! For this part of the assignment, you will write a template function called convert_f_to_c. The function should take in one temperature in Fahrenheit and convert to its corresponding temperature in Celsius. If you’ve forgotten the conversion, the equation is: (degrees Fahrenheit – 32) * 5/9 Since the interviewer didn’t tell you what format to expect the weather in, this function must be a template function that can take in any numerical type (such as ints, doubles, floats, etc..). It should, however, always return the result as a double. Notes/tips: ● Remember the format for making a template function! Always use template
Acknowledgement: This project is based on a lab developed by Professor Wenliang Du at Syracuse University. Professor Du has kindly allowed us to use this lab (see copyright notice below for his lab development).Copyright c 2006 – 2020 Wenliang Du, Syracuse University. The development of this document is funded by the National Science Foundation’s Course, Curriculum, and Laboratory Improvement (CCLI) program under Award No. 0618680 and 0231122. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation. A copy of the license can be found at http://www.gnu.org/licenses/fdl.html Set-UID is an important mechanism in Unix operating systems. When a Set-UID program is run, it assumes the program owner’s privileges. For example, if the program’s owner is root, when anyone having execute permission runs this program, the program gains the root’s privileges during its execution. Set-UID allows us to do many useful things, but unfortunately, it can also be exploited in several ways. Therefore, the objective of this project is two-fold: One quick point to keep in mind as you work on various tasks – If a question asks whether your program is running as a root, it assumes that you will run the program as a CS6238 user, not root (we all know a program will run with root privileges when launched in the root terminal). This is an exploration lab. Your main task is to experiment with the Set-UID mechanism in Linux and write a lab report that describes your findings. You will be provided with a VM to complete the tasks. The VM will be shared on Canvas and mirror links will be made available. The password for the “cs6238” user is “cs6238” and to login as root use the command “sudo su” with password “cs6238”. You are required to accomplish the following tasks in Linux: Note: If you cannot find /bin/zsh in your operating system, please use the following commands to install it:For Ubuntu:sudo apt-get install zsh Note: in our pre-built Ubuntu VM image, zsh is already installed. Setup for remaining tasks: As you will find out from the previous task, /bin/bash has certain built-in protection that prevents the abuse of the Set-UID mechanism. To see what could be done prior to such a protection scheme was implemented, we are going to use a different shell program called /bin/zsh. In some Linux distributions (such as Fedora and Ubuntu), /bin/sh is a symbolic link to /bin/bash. To use zsh, we need to link /bin/sh to /bin/zsh. Execute the following commands to change the default shell to zsh: su (Enter root password)cd /bin rm shln -s zsh sh The system(const char *cmd) library function can be used to execute a command within a program. The way system(cmd) works is by invoking the /bin/sh program, and then letting the shell program execute cmd. Because of the invoked shell program, calling system() within a Set-UID program is extremely dangerous. This is because the actual behavior of the shell program can be affected by environment variables, such as PATH; these environment variables are under user’s control. By changing these variables, malicious users can control the behavior of the Set-UID program. The program below is supposed to execute the /bin/ls command; however, the programmer only uses the relative path for the ls command, rather than the absolute path: #include int main(){ system(“ls”); return 0;} Background: Bob works for an auditing agency, and he needs to investigate a company for a suspected fraud. For the investigation purposes, Bob needs to be able to read all the files in the company’s Unix system; on the other hand, to protect the integrity of the system, Bob should not be able to modify any file. To achieve this goal, Charlie, the sysadmin, wrote a special set-root-uid program (see below), and then gave execute permission to Bob. This program requires Bob to type a file name at the command line, and then it will run /bin/cat to display the specified file. Since the program is running as root, it can display any file Bob specifies. However, since the program has no write operations, Charlie is very sure that Bob cannot use this special program to modify any file. #include (Hint: remember that system() invokes /bin/sh, and then runs the command within the shell environment. We have tried the environment variable in the previous task; here let us try a different attack. Please pay attention to the special characters used in a normal shell environment). To make sure Set-UID programs are safe from the manipulation of the LD PRELOAD environment variable, the runtime linker (ld.so) will ignore this environment variable if the program is a Set-UID root program, except for some conditions. We will figure out what these conditions are in this task. (step 1) Let us build a dynamic link library. Create the following program, and name it mylib.c. It basically overrides the sleep() function in libc: (step 2) We can compile the above program using the following commands: gcc -fPIC -g -c mylib.c gcc -shared -Wl,-soname,libmylib.so.1 -o libmylib.so.1.0.1 mylib.o -lc (step 3) Now, set the LD PRELOAD environment variable using the following command: export LD_PRELOAD=./libmylib.so.1.0.1 (step 4) Compile the following program (put this program in the same directory as libmylib.so.1.0.1): /* myprog.c */ int main(){ sleep(1); return 0;} (step 5) Please run myprog under the following conditions and observe what happens. Based on your observations, describe when the runtime linker will ignore the LD PRELOAD environment variable, and explain why. To be more secure, Set-UID programs usually call setuid() system call to permanently relinquish their root privileges. However, sometimes, this is not enough. Compile the following program and make the program a set-root-uid program. Run it in a normal user account and describe what you have observed. Will the file /etc/zzz be modified? Please explain your observations. /* Now, assume that the child process is compromised, malicious attackers have injected the following statements into this process */ write (fd, “Malicious Data”, 14); close (fd);}} Submission: You need to submit a detailed lab report describing what you have done for each task and what you have observed. You are also required to write explanations for your observations.
Overview This programming assignment has two main learning goals. First, the assignment will provide you with an example of an automated reasoning inference procedure for first-order logic implemented in Python. You will be able to explore the use of such an inference procedure by populating the knowledge base with various sentences. Second, and more prominently, this assignment will give you practice translating English sentences into first-order logic definite clauses. You will produce a knowledge base of facts and rules that communicate some general knowledge that has been provided to you, and you will provide these sentences in a form that they may be directly used by the provided Python inference engine. Submission for Evaluation To complete this assignment, you must generate one Python script file, called “knowledge.py”. That file is to contain a global variable, called monster sentences, initialized to contain a list of strings, with each string encoding a sentence in first-order logic. This is the only file that you should submit for evaluation. To submit your completed assignment for evaluation, log onto the class site on CatCourses and navigate to the “Assignments” section. Then, locate “Programming Assignment #2” and select the option to submit your solution for this assignment. Provide your single program file as an attachement. Do not upload any other files as part of this submission. Comments to the teaching team should appear as header comments in your Python source code file. Submissions must arrive by 11:59 P.M. on Friday, November 11th. Please allow time for potential system slowness immediately prior to this deadline. You may submit assignment solutions multiple times, and only the most recently submitted version will be evaluated. As discussed in the course syllabus, late assignments will not be evaluated and will receive no credit. 1 If your last submission for this assignment arrives by 11:59 P.M. on Tuesday, November 8th, you will receive a 10% bonus to the score that you receive for this assignment. This bonus is intended to encourage you to try to complete this assignment early. Activities Domain You are to provide a Python script file that defines the global variable monster sentences and initializes it to a list of strings, with each string being a first-order logic sentence. These sentences are to capture the domain knowledge provided below. The domain of this knowledge base is a fictional murder that took place in the cemetery last night. Somebody has been killed, and the possible villians include vampires, werewolves, and witches. You will be writing first-order logic sentences that reflect general knowledge about these monsters and the terrible things that they do to their victims. To test your knowledge base, the details of a specific homicide will be encoded as additional logical sentences, and the inference engine will be asked if the identity of the murderer (or murderers) can be deduced from the provided knowledge. If you translate the given English sentences correctly, the culprit will be caught (at least in some cases). Knowledge You are to translate the following statements into first-order logic definite clauses: • Celene is a vampire. • Mario is a werewolf. • Mildred is a witch. • Bob, Lin, and Maurice are people. • A person who is dead is a victim. • All vampires, werewolves, and witches are monsters. • Any monster present at the crime scene is a suspect. • If a vampire is suspected and the victim was bitten, then the vampire killed the victim. • If a werewolf is suspected and the victim was eaten, then the werewolf killed the victim. • If a witch is suspected and the victim was poisoned, then the witch killed the victim. • If a victim is drained of blood but has an intact body, then the victim was bitten. 2 • If a victim is drained of blood and has body pieces missing (i.e., is incomplete), then the victim was eaten. • If a victim’s body is intact, and the victim’s skin complexion is green, blue, or purple, or if it is pale with boils, then the victim was poisoned. • If a victim’s skin complexion is pale and the body is either cold or punctured, then the victim is drained of blood. • If a victim’s body is complete (i.e., not incomplete), then the victim is not dismembered or disemboweled. These English sentences contain all of the knowledge to be encoded in the knowledge base. No additional knowledge should appear in your list of logical sentences. Ontology The first-order logic sentences to be produced must use only the following ontology of constants and predicate symbols: • Bob, Celene, Lin, Mario, Maurice, Mildred : constant symbols referring to individuals • Pale, Blue, Green, Purple : constant symbols for skin complexion colors • Bitten(x) : true iff x has been bitten • Boils(x) : true iff the skin of x has boils • Cold(x) : true iff the body of x is cold to the touch • Complexion(x, y) : true iff the skin of x has the complexion color y • Dead(x) : true iff x is dead • Disemboweled(x) : true iff the body of x is missing internal organs • Dismembered(x) : true iff the body of x is missing limbs • Drained(x) : true iff the body of x has been drained of blood • Eaten(x) : true iff x has been eaten • Incomplete(x) : true iff the body of x is missing parts • Intact(x) : true iff the body of x is relatively whole and intact • Killed(x, y) : true iff x murdered y • Monster(x) : true iff x is a monster 3 • Person(x) : true iff x is a person • Poisoned(x) : true iff x has been poisoned • Present(x) : true iff x was present at the crime scene • Punctured(x) : true iff the body of x has puncture wounds • Suspect(x) : true iff x is a murder suspect • Vampire(x) : true iff x is a vampire • Victim(x) : true iff x was the victim of a murder • Werewolf(x) : true iff x is a werewolf • Witch(x) : true iff x is a witch In the descriptions of these predicates, “iff” is shorthand for “if and only if”. Note that capitalization matters. Constants and predicate symbols must start with a capital letter. Variables are all lowercase. You should not introduce any other constants or predicates (or function symbols) beyond those explicitly listed in this ontology. Translation The knowledge provided as English sentences is to be translated into a list of first-order logic sentences. These will be gathered, along with sentences describing the specific murder case, in order to produce a Python object of the class FolKB (first-order logic knowledge base). Note that every sentence must be a definite clause. The inference engine that you are given implements a backward chaining algorithm that only works on knowledge bases consisting of definite clauses. Other kinds of first-order logic sentences are not allowed. Also note that the number of first-order logic sentences needed to encode the provided knowledge need not be the same as the number of presented English sentences. In particular, it is not unusual for a single English sentence to be translated into multiple first-order logic definite clauses. A template of the “knowledge.py” file is provided for you. Your only task is to set the value of the monster sentences variable to a list of your definite clauses, with each sentence given as a string. In these strings, the conjunction operator is the ampersand (“&”), and the disjunction operator is the vertical bar (“|”). The implication operator is two equal signs followed by a greaterthan sign (“==>”). Example sentences appear in the template script file. Testing The given “main.py” Python script provides a driver for testing the program. This file defines a specific murder case as a collection of definite clauses. These are concatenated to the monster sentences list, and the result is used to create a FolKB object. This knowledge base is then passed to the inference engine’s ASK function (“fol bc ask”), along with a query 4 concerning acts of murder: “Killed(killer, victim)”. If this query can be proven from the knowledge base for some values of the variable killer and the variable victim, the inference procedure will output the values of these variables that allow the Killed query to be inferred. You can test your list of sentences by temporarily modifying “main.py” to specify different situations in the global variable case sentences. Different cases will exercise your first-order logic sentences in different ways, producing different results. Once you submit your solution, the teaching team will test it by examining the results from various carefully selected murder cases. The code for the backward chaining inference engine is contained in the file “logic.py”. This Python script makes use of classes and functions in the script file “utils.py”. These two files, along with “knowledge.py” and “main.py”, are needed to execute the inference procedure, testing your solution. With the exception of initializing monster sentences, your solution must work without modifying these files in any way. These files are provided to you in a ZIP archive file called “PA2.zip”, which is available in the “Assignments” section of the class CatCourses site, under “Programming Assignment #2”. The contents of these Python code files will be briefly discussed during a laboratory session, and comments in these files should assist in your understanding of the provided code. Questions are welcome, however, and they should be directed to the teaching team. While a single test case appears in the “main.py” script, this case is insufficient to fully test your knowledge base. It is possible for your solution to contain serious errors but still perform well on this example. Thus, part of this assignment includes coming up with as many good test cases as possible and ensuring that your solution produces appropriate output for all of them. Your test cases will not be submitted for evaluation, but the quality of your solution will likely depend on the breadth of testing that you perform. Your submission will be evaluated for accuracy. Note that, as discussed in the course syllabus, submissions that fail to run without crashing on the laboratory PyCharm IDE will not be evaluated and will receive no credit. As for all assignments in this class, submitted solutions should reflect the understanding and effort of the individual student making the submission. Not a single line of computer code (or single first-order logic sentence) should be shared between course participants. If there is ever any doubt concerning the propriety of a given interaction, it is the student’s responsibility to approach the instructor and clarify the situation prior to the submission of work results. Also, conversations with fellow students, or any other person (including members of the teaching team), should be explicitly mentioned in submitted assignments (e.g., in comments in the submitted source code files). These comments should also explicitly mention any written resources, including online resources, that were used to complete the exercise. Citations should clearly identify the source of any help received (e.g., “Dr. David Noelle” instead of “the professor”, “The Python 3 Tutorial at docs.python.org/3/tutorial/” instead of “Python documentation”). Failure to appropriately cite sources is called plagiarism, and it will not be tolerated! Policy specifies that detected acts of academic dishonesty must result minimally with a zero score on the assignment, and it may result in a failing grade in the class. Please see the course syllabus for details. The members of the teaching team stand ready to help you with the learning process embodied by this assignment. Please do not hesitate to request their assistance.
Overview This programming assignment has three main learning goals. First, the assignment will provide you with an opportunity to practice your skills developing Python programs in the PyCharm integrated development environment (IDE).Second, this assignment will provide you with some experience in implementing basic heuristic search algorithms, including greedy best-first search and A* search. For comparison, you will also implement the uninformed uniform-cost search algorithm.Third, this assignment requires you to design an admissible heuristic function in the domain of searching for a shortest path on a map. This will provide you with some experience exploring the features that make for good heuristic functions. A foundational understanding of these basic approaches to heuristic search will support your learning of more advanced techniques later in this class.In summary, you will implement the uniform-cost search, greedy best-first search, and A* search algorithms in Python in the context of a simple shortest-path map search problem. These implementations will also support the optional checking of repeated states during search. You will also design an admissible heuristic function, with the goal of demonstrating a substantial improvement in performance over uninformed search methods.Submission for Evaluation To complete this assignment, you must generate four Python script files: “heuristic.py”, “ucost.py”, “greedy.py”, and “astar.py”. The first of these files should implement a good admissible heuristic function for the map search problem. A skeletal template for this file will be provided to you. The remaining three files should implement the search algorithms referenced in their names, as described below. These are the only four files that you should submit for evaluation. To submit your completed assignment for evaluation, log onto the class site on CatCourses and navigate to the “Assignments” section. Then, locate “Programming Assignment #1” and select the 1 option to submit your solution for this assignment. Provide your four program files as four separate attachments. Do not upload any other files as part of this submission. Comments to the teaching team should appear as header comments in your Python source code files. Submissions must arrive by 11:59 P.M. on Friday, October 28th. Please allow time for potential system slowness immediately prior to this deadline. You may submit assignment solutions multiple times, and only the most recently submitted version will be evaluated. As discussed in the course syllabus, late assignments will not be evaluated and will receive no credit. If your last submission for this assignment arrives by 11:59 P.M. on Tuesday, October 25th, you will receive a 10% bonus to the score that you receive for this assignment. This bonus is intended to encourage you to try to complete this assignment early.Activities You are to provide Python functions that implement the following three search algorithms: uniformcost search, greedy best-first search, and A* search. Your provided Python source code must be compatible with provided Python utility code which implements simple road maps, allowing your search algorithms to be used to find the shortest routes between locations on such maps. Indeed, your assignment solution will be evaluated by combining your submitted files with copies of the provided utility files and testing the resulting complete program against a variety of test cases. In other words, your solution must work with the provided utilities, without any modifications to these provided files.More specifically, you are to provide the following functions in the corresponding files, implementing the corresponding algorithms: Function File Algorithm uniform cost search “ucost.py” uniform-cost search greedy search “greedy.py” greedy best-first search a star search “astar.py” A* search The source code for each of these functions should be very similar to that for the others. Rough pseudocode for these functions has been provided during class meetings. These functions must have the following features . . .• takes two or three arguments: 1. problem — a RouteProblem object 2. h — a HeuristicFunction object (not included in uniform cost search) 3. repeat check — a boolean indicating if repeated state checking is to be done • implements the pseudocode for generic search provided during class lectures • deviates from this pseudocode only by performing repeated state checking if and only if the repeat check argument is True• in particular, the goal test is performed on a search tree node just before it is expanded • makes use of a Frontier object to maintain the search tree fringe • returns a search tree node corresponding to a solution, or None if no solution is found In general, your functions should allow the provided “main.py” script to output correct solutions (including path cost and expansion count statistics) for any map search problem provided as input to it. Note that this means that the functions that you implement should write no output, as this will clutter the output produced by the “main.py” script. If you include any statements that write output in your code (perhaps as tools for debugging) these should be removed prior to submitting your code files for evaluation. You may receive no credit for your submitted solution if it produces extraneous output. In addition to these search algorithm functions, you must also provide a definition for a class called HeuristicFunction, in a file named “heuristic.py”, that implements an admissible heuristic function that can be quickly calculated. You are required to design this heuristic function by yourself, and the quality of your heuristic function will have a substantial influence on how your submitted assignment is evaluated.Your heuristic function must absolutely be admissible, but it should otherwise reflect as accurate an estimate of the residual path cost from a given search tree node as possible, given the constraint of rapid calculation. Note that locations have longitude and latitude coordinates that may assist in this process. Also note that, for the purpose of this assignment, the cost assigned to road segments is to be taken as a time cost. In other words, the goal of the search is to find the shortest path in terms of travel time, and each road segment is labeled with the time it takes to traverse that segment. This means that any measure of physical distance will not suffice as an admissible heuristic function, as such measures do not reflect an estimate of the remaining travel time to the destination. If you cannot think of a solution that is admissible regardless of the units of the map measurements, you may assume that location coordinates are measured in miles from an origin point and road segment costs are expressed in minutes. If you make an assumption about the units of measurement, or any other assumptions, you should indicate this fact in a comment in your submitted “heuristic.py” file. Keep in mind that your search algorithms should work for any valid map search problems provided as input to them.The Python utility code that you are required to use is provided in a ZIP archive file called “PA1.zip” which is available in the “Assignments” section of the class CatCourses site, under “Programming Assignment #1”. These utilities include: • RoadMap class — This class encodes a simple road map, involving locations connected by road segments. Each location has a name and coordinates, which can be conceived as longitude and latitude. Each road segment represents a one-way connection from one location to another. Each road segment has a name and a cost of traversal. • RouteProblem class — This class encapsulates a formal specification of a search problem. It includes a RoadMap, as well as a starting location and goal location. It also provides a goal test function called is goal.• Node class — This class implements a node in a search tree. Each node has a corresponding location, a parent node, and a road segment used to get from the location of the parent to the location of the node. (Note that the root of the search tree, corresponding to the starting location, has no parent or road segment.) Each node also tracks its own depth in the search tree, as well as the partial path cost from the root of the treee to the node. Each node also records the value of the heuristic evaluation function applied to the node’s location. The class provides an expand function, which expands the node.• Frontier class — This class implements the frontier, or fringe, of a search tree. The root node of a search tree is provided upon creation, initially populating the frontier with that one node. These objects are implemented as priority queues, releasing nodes in order of increasing values of some measure. At the time of the creation, the measure to be used to sort the nodes in the frontier must be specified: ’g’ (partial path cost), ’h’ (heuristic evaluation function value), or ’f’ (the sum of the other two measures). This class provides functions to add a node to the frontier and pop a node from the frontier, as well as testing if the frontier is empty or if it contains a node with a matching location. The contents of these utility files will be discussed during a laboratory session, and comments in these files should assist in your understanding of the provided code. Questions are welcome, however, and should be directed to the teaching team.Your implementations of all three search algorithms should largely mirror the generic search algorithm presented during class lectures. Specifically, your code must test for goal attainment just prior to expanding a node (not just prior to insertion into the frontier). No repeated state checking should be done unless the repeat check argument is True. When repeated state checking is being done, a child node should only be discarded if its state matches that of a previously seen node. (To be clear, a child node with a state that matches that of a node currently in the frontier may or may not be discarded due to repeated state checking, depending on the specific algorithm being implmented and the relative “costs” of the two nodes.) Note that the algorithm presented in class will require a slight modification to allow for the disabling of repeated state checking, based on the boolean argument provided to the search function. In general, your implementations should not depend on recursion to traverse the search tree, and they should make explicit use of a Frontier object to keep track of the fringe.In order to obtain some confidence that your search algorithms work for any valid map search problems provided as input to them, as required, it is very likely that you will have to test your solution on a variety of test cases. A simple test case appears in the “main.py” script, but this test case is insufficient to fully test your code. It is possible for your code to contain serious errors but still perform well when using the provided example map. Thus, part of this assignment includes coming up with as many distinct difficult search problems as possible and ensuring that your solution produces appropriate output for all of them. Your test cases will not be submitted for evaluation, but the quality of your submitted Python source code files will likely depend on the breadth of testing that you perform. Your submission will be evaluated primarily for accuracy, with efficiency being a secondary consideration. Your source code will be examined, however, and the readability and style of yourimplementation will have a substantial influence on how your assignment is evaluated. As a rough rule of thumb, consider the use of good software writing practices as accounting for approximately 10% to 20% of the value of this exercise. Please use the coding practices exemplified in the provided utility files as a guide to appropriate readability and style. Note also that, as discussed in the course syllabus, submissions that fail to run without crashing on the laboratory PyCharm IDE will not be evaluated and will receive no credit.As for all assignments in this class, submitted solutions should reflect the understanding and effort of the individual student making the submission. Not a single line of computer code should be shared between course participants. This is not a group assignment. If there is ever any doubt concerning the propriety of a given interaction, it is the student’s responsibility to approach the instructor and clarify the situation prior to the submission of work results. Also, helpful conversations with fellow students, or any other person (including members of the teaching team), should be explicitly mentioned in submitted assignments (e.g., in comments in the submitted source code files). These comments should also explicitly mention any written resources, including online resources, that were used to complete the exercise. Citations should clearly identify the source of any help received (e.g., “Dr. David Noelle” instead of “a member of the teaching team”, “The Python Tutorial at docs.python.org/3/tutorial/” instead of “Python documentation”). Failure to appropriately cite sources is called plagiarism, and it will not be tolerated! Policy specifies that detected acts of academic dishonesty must result minimally with a zero score on the assignment, and it may result in a failing grade in the class. Please see the course syllabus for details. To be clear, please note that all of the following conditions must hold for a submitted solution to receive any credit: • solution submitted by the due date • solution runs without crashing on the laboratory PyCharm IDE • solution produces no extraneous output • solution works with unmodified utility code, as provided • solution does not include code written by another person (with or without modifications) • solution explicitly cites all help received, whether from a person or some other source While partial credit will be given for submissions that meet these conditions, failure to meet one or more of these conditions will result in no credit and, in the case of academic dishonesty, may result in a failing grade in the course. Please see the course syllabus for details. The members of the teaching team stand ready to help you with the learning process embodied by this assignment. Please do not hesitate to request their assistance.Uniform-Cost Search function SEARCH(problem) returns a solution node or failure node
This initial programming assignment has two primary learning goals. First, the assignment will provide you with an opportunity to exercise your knowledge of Python program generation in the PyCharm integrated development environment (IDE) that will be used throughout this course. In this way, this assignment will provide practice in some of the fundamental skills that will be needed to successfully complete future programming assignments.Second, this assignment will provide you with experience in implementing basic uninformed search algorithms, namely breadth-first search and depth-first search. A solid understanding of these basic approaches to search will form an important foundation for knowledge of the more advanced techniques to be covered in this class. In summary, you will implement both breadth-first search and depth-first search algorithms in Python in the context of a simple shortest-path map search problem. These implementations will also support the optional checking for repeated states during search.Submission for Evaluation To complete this assignment, you must generate two Python script files: bfs.py and dfs.py. The first of these files should implement a breadth-first search algorithm, and the second should implement a depth-first search algorithm, as described below.These are the only two files that you should submit for evaluation.To submit your completed assignment for evaluation, log onto the class site on CatCourses and navigate to the “Assignments” section. Then, locate “Programming Assignment #0” and select the option to submit your solution for this assignment. Provide your two program files as two separate attachments. Do not upload any other files as part of this submission. Comments to the teaching team should appear as header comments in your Python source code files. Submissions must arrive by 11:59 P.M. on Friday, October 7th. Please allow time for potential system slowness immediately prior to this deadline. You may submit assignment solutions multipletimes, and only the most recently submitted version will be evaluated. As discussed in the course syllabus, late assignments will not be evaluated and will receive no credit. If your last submission for this assignment arrives by 11:59 P.M. on Tuesday, October 4th, you will receive a 10% bonus to the score that you receive for this assignment. This bonus is intended to encourage you to try to complete this assignment early.Activities You are to provide a Python function that implements the breadth-first search algorithm and another that implements the depth-first search algorithm. Your provided Python source code must be compatible with provided Python utility code which implements simple road maps, allowing your search algorithms to be used to find the shortest routes between locations on such maps. Indeed, your assignment solution will be evaluated by combining your submitted files with copies of the provided utility files and testing the resulting complete program against a variety of test cases. In other words, your solution must work with the provided utilities, without any modifications to these provided files.More specifically, you are to provide a function called BFS in a source code file named “bfs.py”, and you are to provide a function called DFS in a source code file named “dfs.py”. The first of these functions is to implement a breadth-first search algorithm, and the second is to implement a depth-first search algorithm. Both functions must have the following features . . . • takes two arguments: 1. problem — a RouteProblem object 2. repeat check — a boolean indicating if repeated state checking is to be done • implements the pseudocode for generic search provided during class lectures • deviates from this pseudocode only by performing repated state checking if and only if the repeat check argument is True• in particular, the goal test is performed on a search tree node just before it is expanded • makes use of a Frontier object to maintain the search tree fringe • returns a search tree node corresponding to a solution, or None if no solution is foundIn general, your functions should allow the provided “main.py” script to output correct solutions (including path cost and expansion count statistics) for any map search problem provided as input to it. Note that this means that the functions that you implement should write no output, as this will clutter the output produced by the “main.py” script. If you include any statements that write output in your code (perhaps as tools for debugging) these should be removed prior to submitting your code files for evaluation. You may receive no credit for your submitted solution if it produces extraneous output.The Python utility code that you are required to use is provided in a ZIP archive file called “PA0.zip” which is available in the “Assignments” section of the class CatCourses site, under “Programming Assignment #0”. These utilities include: • RoadMap class — This class encodes a simple road map, involving locations connected by road segments. Each location has a name and coordinates, which can be conceived as longitude and latitude. Each road segment represents a one-way connection from one location to another. Each road segment has a name and a cost of traversal.• RouteProblem class — This class encapsulates a formal specification of a search problem. It includes a RoadMap, as well as a starting location and goal location. It also provides a goal test function called is goal.• Node class — This class implements a node in a search tree. Each node has a corresponding location, a parent node, and a road segment used to get from the location of the parent to the location of the node. (Note that the root of the search tree, corresponding to the starting location, has no parent or road segment.) Each node also tracks its own depth in the search tree, as well as the partial path cost from the root of the treee to the node. The class provides an expand function, which expands the node.• Frontier class — This class implements the frontier, or fringe, of a search tree. The root node of a search tree is provided upon creation, initially populating the frontier with that one node. If the queue argument is False at the time of creation, the frontier is implemented as a stack. Otherwise, it is implemented as a queue. The class provides functions to add a node to the frontier and pop a node from the frontier, as well as testing if the frontier is empty or if it contains a node with a matching location.The contents of these utility files will be discussed during a laboratory session, and comments in these files should assist in your understanding of the provided code. Questions are welcome, however, and should be directed to the teaching team.Your implementations of both breadth-first search and depth-first search should largely mirror the generic search algorithm presented during class lectures. Note that this algorithm deviates from the “BREADTH-FIRST-SEARCH” pseudocode provided in the course textbook, Russell & Norvig (2020) (Figure 3.9). Specifically, your code must test for goal attainment just prior to expanding a node (not just prior to insertion into the frontier). No repeated state checking should be done unless the repeat check argument is True. When repeated state checking is being done, a child node should be discarded if its location matches that of a previously expanded node or of a node currently in the frontier.The provided “main.py” script includes an example map, which you may use to perform initial tests of your code. It is important that your search functions perform correctly when given any possible map, however, so your code should be tested on additional maps of your own design that potentially contain unusual features. It is possible for your code to contain serious errors but still perform well on the provided test example.Your submission will be evaluated primarily for accuracy, with efficiency being a secondary consideration. Your source code will be examined, however, and the readability and style of yourimplementation will have a substantial influence on how your assignment is evaluated. As a rough rule of thumb, consider the use of good software writing practices as accounting for approximately 10% to 20% of the value of this exercise. Please use the coding practices exemplified in the provided utility files as a guide to appropriate readability and style. Note also that, as discussed in the course syllabus, submissions that fail to run without crashing on the laboratory PyCharm IDE will not be evaluated and will receive no credit.As for all assignments in this class, submitted solutions should reflect the understanding and effort of the individual student making the submission. Not a single line of computer code should be shared between course participants. This is not a group assignment. If there is ever any doubt concerning the propriety of a given interaction, it is the student’s responsibility to approach the instructor and clarify the situation prior to the submission of work results.Also, helpful conversations with fellow students, or any other person (including members of the teaching team), should be explicitly mentioned in submitted assignments (e.g., in comments in the submitted source code files).These comments should also explicitly mention any written resources, including online resources, that were used to complete the exercise. Citations should clearly identify the source of any help received (e.g., “Dr. David Noelle” instead of “a member of the teaching team”, “The Python Tutorial at docs.python.org/3/tutorial/” instead of “Python documentation”).Failure to appropriately cite sources is called plagiarism, and it will not be tolerated! Policy specifies that detected acts of academic dishonesty must result minimally with a zero score on the assignment, and it may result in a failing grade in the class. Please see the course syllabus for details.To be clear, please note that all of the following conditions must hold for a submitted solution to receive any credit: • solution submitted by the due date • solution runs without crashing on the laboratory PyCharm IDE • solution produces no extraneous output • solution works with unmodified utility code, as provided • solution does not include code written by another person (with or without modifications) • solution explicitly cites all help received, whether from a person or some other source While partial credit will be given for submissions that meet these conditions, failure to meet one or more of these conditions will result in no credit and, in the case of academic dishonesty, may result in a failing grade in the course.The members of the teaching team stand ready to help you with the learning process embodied by this assignment. Please do not hesitate to request their assistance.Generic Search function SEARCH(problem) returns a solution node or failure node
This laboratory exercise has two primary learning goals. First, the exercise will provide you with an opportunity to practice your skills for Python program generation in the PyCharm integrated development environment (IDE) that will be used throughout this course. In this way, this exercise will provide practice in some of the fundamental skills that will be needed to successfully complete future programming assignments.Second, this exercise will give you an opportunity to assess your preparation for future assignments. This exercise should be easy for you. If you do not find it fairly easy, then you should contact the instructor to discuss the possibility that you are not yet prepared to successfully complete the course programming assignments. Future programming assignments will be much more difficult.In this exercise, you will be given Python code that implements a road map data structure. You are required to implement one method for this data structure which calculates the total path cost (e.g., travel time) for a given path on the map.Submission for Evaluation To complete this assignment, you must generate one Python script file: “map.py”. Your file should be a minor augmentation of a template version of “map.py” which will be provided to you.In future programming assignments, you will submit your solutions via the “Assignments” section of the class CatCourses site. For this initial practice excercise, your solution will not be submitted to the teaching team for evaluation. Instead, you may receive feedback on your solution through interactions with the instructor and/or the teaching assistants. Some laboratory session time will be devoted to providing such feedback.Activities You are to provide a Python function that calculates the path cost (e.g., travel time) of a path through a given road map. Your provided Python source code must be compatible with the provided Python utility code which implements simple road maps. You should not modify provided source code files except to implement the body of the required path cost function.More specifically, you are to provide a function called path cost in a source code file named “map.py”. This function is a method on the provided RoadMap class. Your function should have the following features . . . • takes two arguments beyond the RoadMap object: 1. start — a symbolic name for the starting location for the path of interest 2. road list — a Python list of symbolic road segment names, describing the path to be taken from the starting location • returns the sum of the costs of the listed road segments, as recorded in the RoadMap object • returns zero if the arguments do not describe a valid path through the map which is encoded in the RoadMap objectIn general, your function should allow the provided “main.py” script to output correct solutions for any path through any map encoded as a RoadMap object. The function that you implement should write no output, as this will clutter the output produced by the “main.py” script. If you include any statements that write output in your code (perhaps as tools for debugging) these should be removed prior to completion of your solution.The Python utility code that you are required to use is provided in a ZIP archive file called “EX1.zip” which is available in the “Files” section of the class CatCourses site, under “Laboratory Exercise #1”. This utility code provides a class which encodes a simple road map, involving locations connected by road segments. Each location has a name and coordinates, which can be conceived as longitude and latitude. Each road segment represents a one-way connection from one location to another. Each road segment has a name and a cost of traversal. The contents of these utility files will be discussed during a laboratory session, and comments in these files should assist in your understanding of the provided code. Questions are welcome, however, and should be directed to the teaching team.The provided “main.py” script includes an example map, which you may use to perform initial tests of your code. It is important that your function performs correctly when given any possible map, however, so your code should be tested on additional maps of your own design that potentially contain unusual features. It is possible for your code to contain serious errors but still perform well when using the single provided test case. The members of the teaching team stand ready to help you with the learning process embodied by this exercise. Please do not hesitate to request their assistance.
Overview In this project, we will use all the topics we have learn about C to write a program to solve Word Search Puzzles.The main program (wordsearch.c) is given to you. Your primary task is to implement the searchPuzzle() function to complete the program. When the program starts, it will read the puzzle grid from a text file and save it as a 2-D character array. The first number in the text file containing the puzzle grid indicates the size of the grid. For instance, a 5 means the puzzle is a 5 × 5 grid. The program will then ask the user for the word to search and store it in the variable word. The program should then print the original puzzle grid and search for the word in the puzzle. The program should finally print whether the search word is found, and if so, the search path as described below.searchPuzzle(char**, char*) – This function is the core of solving the puzzle. It takes in the puzzle grid to find the search word input by the user (the 2nd argument) and prints the phrase Word found! and the path(s) if the word is found. If the word is not found, then it prints Word not found. The search will happen in a case insensitive manner and all directions are allowed. The letters in the found word (i.e., the path) must be one index away from each other either in row or column or both as shown in the sample runs.• YOU MUST NOT USE ANY ARRAY NOTATION ([]) IN THIS PROGRAM! • YOU MUST NOT USE ANY LIBRARY FUNCTIONS TO CONVERT CHARACTERS INTO LOWER/UPPER CASE! • YOUR OUTPUT FORMATTING MUST EXACTLY MATCH THE SAMPLE RUN IN TERMS OF SPACING, WORDING OF PROMPTS AND NEWLINES! Feel free to create any helper functions and additional arrays to simplify your searchPuzzle function. To help further explain the expected behavior of your code, some examples follow along with explanation of the output: Sample Run (user input shown in blue, with each run separated by a dashed line): —————————————————-SAMPLE RUN 1 (./wordsearch puzzle1.txt) Enter the word to search: HelLo Printing puzzle before search: W E B M O I L H L L M L Z E L M Y E K O A O A B A Word found! Printing the search path: 0 0 0 0 5 0 0 1 3 4 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0—————————————————-SAMPLE RUN 2 (./wordsearch puzzle2.txt) Enter the word to search: bAnANa Printing puzzle before search: J Z I M O B O T H N G A E R B Q P W M A E K O Z A T N R A E E N O B T K Word found! Printing the search path: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 642 0 0 0 0 0 0 53 0 0 0 0 0 0 0 0 0 —————————————————-SAMPLE RUN 3 (./wordsearch puzzle3.txt) Enter the word to search: deTeR Printing puzzle before search: J Z I D O E T H N E E R Z T R M D P K O A T F R A Word found! Printing the search path: 0 0 0 1 0 4 3 0 0 42 2 5 0 3 5 0 1 0 0 0 0 0 0 0 0 —————————————————-SAMPLE RUN 4 (./wordsearch puzzle3.txt) Enter the word to search: color Printing puzzle before search: J Z I D O E T H N E E R Z T R M D P K O A T F R A Word not found! Explanation of Sample Runs Please note that for the first sample run shown above, the path output is not unique, but your solution needs to output only one of the many viable paths if those paths overlap in the first letter (‘H’). For example, other paths for this puzzle are as follows (which need not be output by your solution): 0 0 0 0 5 or 0 0 0 0 0 0 0 1 0 4 0 0 1 0 3 0 0 0 2 3 0 0 0 2 4 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0For the second sample run, finding the word in the puzzle involves backtracking. Your solution must print the path as shown. Here 642 denotes that the character at this location is the 2nd, 4th and 6th in the search path. Your program may also output 246 instead of 642 at this location (and subsequently, 35 instead of 53 at the other location shown in the output). For the third sample run, the program produces two path outputs as these paths do not overlap in the first letter (‘D’). This is only a bonus feature and is worth 10 extra points (in addition to the 100 total points).For the basic solution, your program need not produce multiple paths and a single one will suffice. Note that there is one more possible solution that is not shown since one of the paths overlaps in the first letter of the path shown in the sample run output: 0 0 0 1 0 0 3 0 0 42 42 5 0 3 5 0 1 0 0 0 0 0 0 0 0Testing Your Program After compiling wordsearch.c, run the program by typing ./wordsearch puzzle1.txt, where wordsearch is the executable file, and puzzle1.txt is the text file containing the puzzle grid. Feel free to create your own text files for test cases.What to hand in When you are done with this lab assignment, submit all your work by emailing it to me as an attachment. Before you send your submission to me, make sure you have done the following: • Your code compiles and runs on a Linux machine (without the need for special libraries). • Attached wordsearch.c and any additional test files, pseudocode, idea sketches, notes, etc.
Overview In this lab, we will investigate how cache is organized in a CPU. Getting Started Before we begin any activities, create a directory (Lab_10) inside the CSE31 directory we created in the first lab. You will save all your work from this lab here. Note that all the files shown in green below are the ones you will be submitting for this assignment. You must have a clear idea of how to answer the TPS questions before leaving lab to receive participation score.TPS (Think-Pair-Share) activity 1: Discuss questions 1 – 8 (30 minutes) while paired with your classmates assigned by your TA (you will be assigned to groups of 3-4 students) and record your answers in a text file named tpsAnswers.txt under a section labelled “TPS 1” (you will continue to use this file to record your answers to all the TPS questions that follow in the lab handout):1. What is cache? Why do we need cache? 2. There are generally 2 practical ways to organize a cache: Direct-mapped cache and N-way set associative cache. In both types of cache, data at a specific address of the main memory (RAM) are mapped to a pre-defined location in the cache. A “Block” is the basic unit of data being mapped between the main memory and cache. The size of a block depends on the specification of a cache. Every time data is transferred between cache and the main memory, it is a block of data being transferred. In this exercise, we will explore the Direct-mapped cache.3. In a Direct-mapped cache, the cache is organized as a hash table. Addresses of the main memory are mapped to the indices of the cache (block numbers) using a modulo operator (%) as the hash function. As a result, we can divide a memory address into 3 fields: tag, index, offset. 4. Offset bits tell us how many bytes of data are in a block. These bits are the right-most bits of the memory address. You can consider this as the number of columns of data in a cache. With a specific value of the offset bits from an address, we know which column of a block we are trying to access. Given the block size of a cache is 16B (bytes), how many bits do we need for offset? What is the number of bits in offset as a function of block size? Is it practical to have a cache of block size = 1 byte?5. Index bits tell us how many blocks there are in a cache. These bits are the next right-most bits of the memory address after the offset bits. You can consider this as the number of blocks (rows) of data in a cache. With a specific value of the index bits from an address, we know which block (row) we are trying to access. Given there are 64 blocks in a cache, how many index bits do we need? What is the number of bits in index as a function of number of blocks?6. Once you know the number of blocks and the block size of a cache, do you know the total size of the cache? How? 7. Since the size of cache is always smaller than the size of the main memory, the sum of bits of the offset and index of a cache will be less than the number of bits in an address of the main memory. What do we do to the left-over bits from the address? Why are they important?8. Given a memory address of 20 bits (during Intel 8086 era), 128B of direct-mapped cache, and 8B block size, answer the following questions: a. How big is this main memory? b. How many offset bits? c. How many blocks are there in the cache? d. How many index bits? e. How many tag bits?f. Draw the layout of the cache: including tags, valid bits, dirty bits, and data blocks. g. What is the number of bits per row of the cache (number of bits being used in a row: tag, valid bit, dirty bits, and data block)?Your TA will “invite” one of you randomly after the activity to share what you have discussed.TPS activity 2: Discuss questions 1 – 4 (30 minutes) with your TPS partners in your assigned breakout room and record your answers in tpsAnswers.txt under a section labelled “TPS 2”: 1. What is the disadvantage of a Direct-mapped cache? What kind of cache miss will it introduce? 2. To overcome this problem, we can allow multiple blocks of data to occupy the same set of a cache. Note that we use “set” here instead of index of cache. In this organization, we group N blocks (rows) of cache into a set and allow more than one block of data to stay within a set. The layout of the cache remains the same as its direct-mapped version, but the difference is that every N blocks are now being grouped into a set.3. The memory address is still partitioned into the same 3 fields, but the index bits now refer to the set number. Given a cache with 1024 blocks and the associativity is 4 (4 blocks per set), how many index bits do we need? What is the number of bits in index as a function of number of blocks and associativity?4. Given a memory address of 20 bits (during Intel 8086 era), 128B of 2-way cache, and 8B block size, answer the following questions: a. How big is this main memory? b. How many offset bits? c. How many blocks are there in the cache? d. How many sets are there in the cache? e. How many index bits? f. How many tag bits?g. Draw the layout of the cache: including tags, valid bits, dirty bits, and data blocks. Indicate the sets with a different color (or a thicker) boarder. h. What is the number of bits per row of the cache (number of bits being used in a row: tag, valid bit, dirty bits, and data block)?Your TA will “invite” one of you randomly after the activity to share what you have discussed. Individual Assignment 1: Cache in Your Computer Download and install CPUID and find out details about the cache(s) in your computer. • For Windows: CPU-Z: https://www.cpuid.com/softwares/cpu-z.html • For Mac: MacCPUID: https://www.intel.com/content/www/us/en/download/674424/maccpuid.html • For Linux: https://www.tecmint.com/check-linux-cpu-information/ Answer the following questions in a text file named individualAssign1.txt: 1. How many levels of caches does your CPU have (L1, L2, L3, etc.)? Is there separate L1 cache for data and instructions? 2. How big is each level of cache? 3. What is the block size (sometimes it is called line size)? 4. Are the caches direct-mapped or set associative? If set associative, how many ways? 5. With L1 data cache, how many tag bits, index bits, and offset bits?Collaboration You must credit anyone you worked with in any of the following three different ways: 1. Given help to 2. Gotten help from 3. Collaborated with and worked togetherWhat to hand in When you are done with this lab assignment, submit all your work through CatCourses. Before you submit, make sure you have done the following: • Attached your individualAssign1.txt and tpsAnswers.txt. • Filled in your collaborator’s name (if any) in the “Comments…” textbox at the submission page. Also, remember you DO NOT NEED TO demonstrate to the TA or instructor for this assignment.
Overview In this lab, we will continue to work with procedures (or functions) in MIPS. We will learn about how to apply register conventions to recursive functions.Getting Started Before we begin any activities, create a directory (Lab_8) inside the CSE31 directory we created in the first lab. You will save all your work from this lab here. Note that all the files shown in green below are the ones you will be submitting for this assignment. You must have a clear idea of how to answer the TPS questions before leaving lab to receive participation score.TPS (Think-Pair-Share) activity 1: Discuss questions 1 – 6 (20 minutes) while paired with your classmates assigned by your TA (you will be assigned to groups of 3-4 students) and record your answers in a text file named tpsAnswers.txt under a section labelled “TPS 1” (you will continue to use this file to record your answers to all the TPS questions that follow in the lab handout): 1. Load fib.s in MARS and study the code. This is the same program we worked on during Lab 06. 2. Recall that fib.s calculates the 13th Fibonacci number (n = 13). Now let us make this program more generic so it will calculate the n th Fibonacci number, where n can be any number from a user input.3. From Lab 06, we have learned how to print out statements in MIPS. Insert instructions in fib.s so that the program will print out “Please enter a number:” at the beginning of the program to prompt user for input.4. In the program, $t3 was used to store the value of n. Now, let us read in a user input and save that value into $t3. Do a search in the MARS documentations to find out how to use syscall to read an INTEGER from a user. Again, you must store the value into $t3.5. Since the program now reads a number from a user, do we need to declare n in the .data segment of the program? How about the la and lw instructions regarding n? Comment out those instructions so they will not mess up your program. 6. Assemble the program and test it with different numbers to see if it runs correctly (you may use the original fib.s to verify your results.). Your TA will “invite” one of you randomly after the activity to share what you have discussed.In Lab 07, we understood how register conventions can help us manage registers in procedures. Let us find out how we can follow register conventions in recursive functions. TPS activity 2: Discuss questions 1 – 6 (30 minutes) with your TPS partners in your assigned group and record your answers in tpsAnswers.txt under a section labelled “TPS 2”: 1. Study recursion.c and trace the program. Without running the program, what will be the output if 5 is entered? Compile and run recursion.c in a terminal (or any IDE) and verify your answer. 2. Load recursion.s in MARS. This is the MIPS version of recursion.c. Do not assemble and run this program – the program is incomplete. Study the main function and discuss with your partner(s) about what it does (compare it with the C version). A lot of instructions are missing, and we will fill them out in the following steps.3. Since the recursion.c prompts to a user for input, insert instructions in recursion.s so the program will prompt the same statement to a user. 4. Insert statements for the program to read in a value from a user. What register should we use to store that value? (Hint: you will use it as the argument for your recursion function call.) 5. Next, the main function calls recursion with the correct input argument. After returning from recursion, we need to print out the returned value. What register do we expect the returned value to be stored in? However, the syscall for printing out a value is also using the same register. What can we do?6. Based on your answer from step 5, insert the correct instructions to print out the returned value before jumping to the end of program. 7. Now, let us complete the recursion function. The stack pointer was moved to create extra storage for the function. How many integer values are reserved in this storage? What is the first thing to be stored in this stack frame? Insert a statement to accomplish this.8. Based on the branch statement under label recursion, update the returning value. Again, you must use the correct register to store the returning value. 9. Based on the branch statement under label not_minus_one, update the returning value. Again, you must use the correct register to store the returning value. 10. When the input argument is not 0 or -1, the program will call recursion 2 times. This happens in the code under label not_zero. Why do we need to save $a0 into the stack? 11. Insert a statement to update the input argument for the next recursion call.12. After returning from the last recursion, the program is about to call the next recursion. However, the last recursion came back with a returned value. What will happen to if we call recursion right away? Insert statements to prevent this from happening. 13. Now the program is ready to call recursion again. Insert statements to update the next input argument. 14. After returning from the second recursion call, insert statements to update the final value to be returned to main.15. Before returning to main, a value needs to be retrieved so the program can return to the correct location of the code. What is this value? Insert a statement under the label end_recur to retrieve this value Your TA will “invite” one of you randomly after the activity to share what you have discussed.Individual Assignment 1: Create recursion1.s Study recursion1.c and translate the same program in MIPS following register convention. You can compare the output of your MIPS program with that of recursion1.c. Save your program as recursion1.s. Collaboration You must credit anyone you worked with in any of the following three different ways: 1. Given help to 2. Gotten help from 3. Collaborated with and worked together What to hand in When you are done with this lab assignment, submit all your work through CatCourses. Before you submit, make sure you have done the following: • Attached fib.s, recursion.s, recursion1.s and tpsAnswers.txt. • Filled in your collaborator’s name (if any) in the “Comments…” textbox at the submission page. Also, remember to demonstrate your code to the TA or instructor before the end of the grace period.
Overview In this lab, we will continue to familiarize ourselves with programming MIPS using MARS. We will focus on memory accesses and control flow. Getting Started Before we begin any activities, create a directory (Lab_6) inside the CSE31 directory we created in the first lab. You will save all your work from this lab here. Note that all the files shown in green below are the ones you will be submitting for this assignment. You must have a clear idea of how to answer the lab activities before leaving lab to receive participation score. Memory in MARS? MARS not only simulates a MIPS CPU, it also simulates the memory so the CPU can work with it. We will revisit fib.s from Lab 05 in this exercise. Load fib.s into MARS and assemble the code. TPS (Think-Pair-Share) activity 1: Discuss questions 1 – 12 (25 minutes) while paired with your classmates assigned by your TA (you will be assigned to groups of 3-4 students) and record your answers in a text file named tpsAnswers.txt under a section labelled “TPS 1” (you will continue to use this file to record your answers to all the TPS questions that follow in the lab handout): 1. Once fib.s is assembled, open the Execute tab (it should be opened by default after assembled). Two segments of memory are displayed here: Text Segment and Data Segment. What are the starting addresses of Text Segment and Data Segment? Give your answers in Hex format. 2. The Text Segment shows you how each actual machine code is stored in the memory (again it is simulated) and its corresponding MIPS code. Two types of MIPS code are shown here: Basic and Source. We call the Basic one True Assembly Language, and the Source one MIPS Assembly Language. From the display, what can you tell about the difference between the two in terms of their relationship with the machine code? We will cove this topic in future lectures. 3. Now, let us take a look at the Data Segment. How much difference in bytes are there between 2 address locations (again, the addresses are in Hex)? 4. For each address location, how many columns are there? 5. What can you tell about the relationship between the address difference and the number of columns at each address location? 6. From the source code, how do you create a new variable/label named m and set it to 20? 7. Save and assemble your file. At what address is the value of m stored? 8. Besides numbers, we can also initialize strings for the program to use. Search from the Internet on how to declare a string named str1 and set it to “I love CSE31!” 9. Insert the declaration of str1 in your code and assemble it. From the Data Segment, we can see that the string is occupying 3 address locations. At what addresses is str1 stored? 10. str1 is stored as numerical values in the memory. Check the ASCII box and observe how it is stored. Does the display of characters agree with what you have learned from Lab 04 about how an array of characters is stored? 11. In order to print str1, we will need to use syscall function. Search the Internet to find out how to print str1. 12. Now let us go back to the program. Search from the Internet to find out what “la $t3, n” does. What will be the value stored in $t3 after running this instruction? From this we can see that we cannotuse the initialized variables (labels) directly in our MIPS program. We need to use la, then lw to save the value into a register Your TA will “invite” one of you randomly after the activity to share what you have discussed. Create compare.s Write a new piece of MIPS program named compare.s and complete the following exercise. TPS activity 2: Discuss questions 1 – 8 (25 minutes) with your TPS partners in your assigned group and record your answers in tpsAnswers.txt under a section labelled “TPS 2”: 1. From lectures, we have learned that we can perform different inequality comparisons (, =) by using only slt, beq, and bne instructions. Why not having one instruction for each inequality in MIPS? 2. Declare a new variable/label (n) and set it to 25. 3. Insert instructions to declare the following strings: a. str1: “Less than ” b. str2: “Less than or equal to ” c. str3: “Greater than ” d. str4: “Greater than or equal to ” 4. Insert instructions to read in an integer from users. Search from the Internet on how to use syscall to do it. 5. Insert code so the program will compare if the user input is less than n. If it is, output “Less than”. 6. Insert code so the program will compare if the user input is greater than or equal to n. If it is, output “Greater than or equal to”. 7. Now comment out your code from steps 5 and 6. Insert code so the program will compare if the user input is greater than n. If it is, output “Greater than”. 8. Insert code so the program will compare if the user input is less than or equal to n. If it is, output “Less than or equal to”. Individual Assignment 1: Create sumAll.s Create a new MIPS program that will ask a user to enter a number repeatedly. This program will calculate 2 sums: even_sum (sum of all even numbers) and odd_sum (sum of all odd numbers). The program will stop when the user enters a ‘0’ and print out both sums (even if they are zero). You may NOT use any the following instructions in your solution: div, and, or, andi, or ori. You will be using a loop to determine when to end the program. In MIPS, ALL types of loop can be implemented with a branch statement (beq or bne). Therefore, write a pseudocode to describe your approach to this problem before writing the MIPS code. It is VERY SIMILAR to the average.c you created in Lab 01.Save your code as sumAll.s. Sample Run (user input shown in blue, with each run separated by a dashed line): ——————————————————————————-SAMPLE RUN 1 Please enter a number: 1 Please enter a number: 2 Please enter a number: 3 Please enter a number: -1 Please enter a number: -2 Please enter a number: -3 Please enter a number: 0 Sum of even numbers is: 0 Sum of odd numbers is: 0 ——————————————————————————-SAMPLE RUN 2 Please enter a number: 1 Please enter a number: 2 Please enter a number: 3 Please enter a number: -7 Please enter a number: -8 Please enter a number: 0 Sum of even numbers is: -6 Sum of odd numbers is: -3 Collaboration You must credit anyone you worked with in any of the following three different ways: 1. Given help to 2. Gotten help from 3. Collaborated with and worked togetherWhat to hand in When you are done with this lab assignment, submit all your work through CatCourses. Before you submit, make sure you have done the following: • Attached compare.s, sumAll.s and tpsAnswers.txt. • Filled in your collaborator’s name (if any) in the “Comments…” textbox at the submission page. Also, remember to demonstrate your code to the TA or instructor before the end of the grace period.
Overview In this lab, we will get ourselves familiar with the programming environment we will use for MIPS programming. Getting Started Before we begin any activities, create a directory (Lab_5) inside the CSE31 directory we created in the first lab. You will save all your work from this lab here. Note that all the files shown in green below are the ones you will be submitting for this assignment. You must have a clear idea of how to answer the lab activities before leaving lab to receive participation score.Since we cannot manipulate the CPU inside our computers directly (none of us use MIPS CPU, and for security reasons), we need a software to simulate a MIPS CPU for us. The simulator we are using is called MARS. TPS (Think-Pair-Share) activity 1: Discuss questions 1 – 4 (25 minutes) while paired with your classmates assigned by your TA (you will be assigned to groups of 3-4 students) and record your answers in a text file named tpsAnswers.txt under a section labelled “TPS 1” (you will continue to use this file to record your answers to all the TPS questions that follow in the lab handout): 1. Before we use a new tool, we will need to find out how to use it. MARS DOES NOT mean that MIPS is an alien language (well, sort of). Work with your partner and find out what MARS stands for. 2. Since you have found out what MARS stands for, you probably have found out the webpage of MARS as well. Visit the download page and download MARS in your computer. To run MARS, just doubleclick the downloaded jar file. You will need Java to run it. Note: MARS is not pre-installed in the lab computers, so you need to download it if you are using a lab computer. But before running the jar file you will have to mark the file as user-executable. To do this, navigate to the folder where you have downloaded the jar file and run the command chmod u+x Mars4_5.jar. After this, you may double-click the jar file to run it.3. From the Tutorial materials page (you can find the link to it from the home page), save both tutorial materials (MARS feature map and MARS tutorial) as well as Fibonacci.asm in your Lab_5 folder. 4. Follow Part 1 : Basic MARS Use in the tutorial using Fibonacci.asm and discuss the following questions: a. How do you load an assembly file? b. How do you assemble (compile) the program? c. How do you run the assembled program? d. Can you run a program before assembling it? e. If you want to run the assembled program line by line, how to do it? f. How do you run the program again after it has finished running?The sample program from the tutorial looks too complicated. Let us use a simpler version of it. Load fib.s (yes, you can save your assembly programs as .s files instead) into MARS and assemble the code. Note that Fibonacci number calculation is as follows: fib[0] = 0; fib[1] = 1; Lab 05: Intro to MIPS CSE-031-01 Points: 20 fib[n] = fib[n-1] + fib[n-2];TPS activity 2: Discuss questions 1 – 8 (25 minutes) with your TPS partners in your assigned group and record your answers in tpsAnswers.txt under a section labelled “TPS 2”: 1. What do the .data, .word, .text directives mean (i.e., what do you put in each section)? 2. What does line 10 do? 3. What does line 15 do? 4. How do you set a breakpoint in MARS? Set breakpoint on line 15 and list the steps of achieving this. 5. After your program stops because of a breakpoint, how do you continue to execute your code? How do you step through your code?6. How can you find out the content of a register? How do you modify the value of a register manually while running the program? 7. At what address is n stored in memory? Calculate the 13th fib number by modifying this memory location.8. Line 19 and 21 use the syscall instruction. What is it and how do you use it? Your TA will “invite” one of you randomly after the activity to share what you have discussed. Individual Assignment 1: Create myFirstMIPS.s Write a new piece of MIPS code that, given a value in $s0, assign the following to the various $tX registers: $t0 = $s0 $t1 = $t0 – 1 $t2 = $t1 + $t0 $t3 = $t2 – 3 $t4 = $t3 + $t2 $t5 = $t4 – 5 $t6 = $t5 + $t4 $t7 = $t6 – 7In other words, for each register from $t1 to $t7, you program should store the difference of the previous $tX register value and an incremental constant. The $s0 register contains the initial value. Do not set the value of $s0 in your code. Instead, learn how to set it manually with MARS (Hint: question 6 in TPS 2). Save your code as myFirstMIPS.s.Collaboration You must credit anyone you worked with in any of the following three different ways: 1. Given help to 2. Gotten help from 3. Collaborated with and worked together What to hand in When you are done with this lab assignment, submit all your work through CatCourses. Before you submit, make sure you have done the following: • Attached myFirstMIPS.s and tpsAnswers.txt. • Filled in your collaborator’s name (if any) in the “Comments…” textbox at the submission page. Also, remember to demonstrate your code to the TA or instructor before the end of the grace period.
Overview In this lab, we will investigate some interesting facts about how C interacts with memory. You will continue to practice the use of pointers to access memory. You can refer to chapter 5 and 6 of K&R for references on pointers. Getting Started Before we begin any activities, create a directory (Lab_3) inside the CSE31 directory we created last week. You will save all your work from this lab here. Note that all the files shown in green below are the ones you will be submitting for this assignment. You must have a clear idea of how to answer the lab activities before leaving lab to receive participation score. How Memory is Used From lecture, we’ve learned that there are 3 pools of memory for storing variables, based on the nature of their usage. TPS (Think-Pair-Share) activity 1: Discuss questions 1 – 4 (20 minutes) while paired with your classmates assigned by your TA (you will be assigned to groups of 3-4 students) and record your answers in a text file named tpsAnswers.txt under a section labelled “TPS 1” (you will continue to use this file to record your answers to all the TPS questions that follow in the lab handout): 1. Name the 3 pools for memory and what kind of variables will be stored in each pool. 2. Open mem.c with your favorite text editor and discuss the following questions with your partner: a. How many variables are declared? b. How many of them are pointers? What type of data does each pointer point to? c. Which pool of memory are these variables stored in? d. Which pool of memory will the pointer ptr point to in line 12. 3. Using a piece of paper (or a drawing app), draw the 3 pools of memory and indicate the locations (in which pool?) of the variables in mem.c using boxes (like what we did in lecture). Label the boxes with variable names, their content, and their addresses. You will need to insert extra code to obtain the addresses of these variables. 4. In the same drawing, use arrows to connect each pointer to its destination. Your TA will “invite” one of you randomly after the activity to share what you have discussed. Structures in C In this exercise, we will explore how structures are stored in memory. TPS activity 2: Discuss questions 1 – 3 with your TPS partners in your assigned group (20 minutes) and record your answers in tpsAnswers.txt under a section labelled “TPS 2”: 1. Open NodeStruct.c and discuss what this program does. 2. Insert extra code to print out the value of head, addresses of head, iValue, fValue, and next pointed by head. 3. Based on the addresses of the members of Node structure, what do you observe about how structures are stored in memory? What is the relationship between the pointer (head) and its destination (the Node structure)?Individual Assignment 1: Arrays and pointers As we have discussed in lecture, we can use array names as if they are pointers. Open array.c and complete the following tasks: 1. This program will store integers entered by a user into an array. It then calls bubbleSort to sort the array. Study the code in bubbleSort to refresh your memory on Bubble Sort algorithm and answer the following questions: a. Why do we need to pass the size of array to the function? b. Is the original array (the one being passed into the function) changed at the end of this function? c. Why do you think a new array (s_array) is needed to store the result of the sorted values (why not update the array as we sort)? Hint: look at what the main function does. 2. Once you understand how Bubble Sort works, re-write the code so that you are accessing the array’s content using pointer notations (*s_arr), i.e., you cannot use s_arr[j] anymore. Comment out the original code so the algorithm will not be run twice. 3. After the array is sorted, the program will ask user to enter a key to search for in the sorted array. It will then call bSearch to perform a Binary Search on the array. Complete the bSearch function so that it implements Binary Search recursively (no loop!). You must use pointer notations here as well. Pay attention to what is written in main so your bSearch will return an appropriate value. Individual Assignment 2: Cyclic Linked List In cyclic_ll.c, complete the function has_cycle() to implement the following algorithm for checking if a singly-linked list has a cycle. Recall that if p is a pointer to a struct, p->member refers to a member variable in the struct, and is equivalent to (*p).member. 1. Start with two pointers at the head of the list 2. On each iteration, increment the first pointer by one node and the second pointer by two nodes. If it is not possible to do one or both because of a null pointer, then we know there is an end to the list and there is therefore no cycle. 3. We know there is a cycle if a. The second pointer is the same as the first pointer b. The next node of the second pointer is pointed to by the first pointer The reason we know there is a cycle with the two conditions in 3) is that second pointer has wrapped around to the first one in the circle and we have detected it. After you have correctly implemented has_cycle, the program you get when you compile cyclic_ll.c will tell you that has_cycle agrees with what the program expected it to output. Collaboration You must credit anyone you worked with in any of the following three different ways: 1. Given help to 2. Gotten help from 3. Collaborated with and worked together. What to hand in When you are done with this lab assignment, submit all your work through CatCourses. Before you submit, make sure you have done the following: • Your code compiles and runs without the need for special libraries. • Attached mem.c, NodeStruct.c, array.c, cyclic_ll.c, and tpsAnswers.txt. • Filled in your collaborator’s name (if any) in the “Comments…” textbox at the submission page. Also, remember to demonstrate your code to the TA or instructor before the end of the grace period.
Overview In this lab, we will continue to investigate some of the interesting facts about how C interacts with memory. You will continue to practice the use of pointers to access memory. You can refer to chapter 5 and 6 of K&R for references on pointers. Getting Started Before we begin any activities, create a directory (Lab_4) inside the CSE31 directory we created last week. You will save all your work from this lab here. Note that all the files shown in green below are the ones you will be submitting for this assignment. You must have a clear idea of how to answer the lab activities before leaving lab to receive participation score. How Type-Casting Works with Memory From lecture, we have learned that an array is stored in a contiguous memory space. The address of each element of an array is assigned by the computer (operating system). TPS (Think-Pair-Share) activity 1: Discuss questions 1 – 10 (25 minutes) while paired with your classmates assigned by your TA (you will be assigned to groups of 3-4 students) and record your answers in a text file named tpsAnswers.txt under a section labelled “TPS 1” (you will continue to use this file to record your answers to all the TPS questions that follow in the lab handout): 1. Open MemCast.c, compile and run the program. What do you expect the program to print? (%x in printf allows an integer to be printed in Hex format). 2. Before changing the code, what do you expect the program to print if you print four_ints[0] again at the end of the program? 3. Insert a print statement to output four_ints[0] at the end of the program and verify your answer from (2). 4. Now add a print statement to the program so it will print out four_ints[1]. What does it print? Are you surprised (or lost) by the results? 5. Let us study the code carefully and investigate what happened. No, the memory did not go crazy. a. How many array(s) were allocated in this program? b. Are four_ints and four_c pointing to the same location? c. Verify your answer of (b) by printing out the values of four_ints and four_c. 6. Write a loop to print out the addresses and values (in Hex) of all the elements of four_ints. What is the difference in addresses between two consecutive elements? Discuss what this difference means. 7. Use a piece of paper to draw the layout of the array horizontally so that the smallest address begins from the RIGHT-hand-side. Indicate the address and value of each element based on the results of (6). You can draw it digitally. 8. Now, write a loop to print out the same information for four_c as you did in (6). What is the difference in addresses between two consecutive elements? Discuss what this difference means. 9. Use the same piece of paper (or file) from (7) to draw a similar structure for four_c. 10. By comparing the layout of the array pointed by the two pointers, what do you observe in terms of how C accesses memory when the index of an array is incremented? Your TA will “invite” one of you randomly after the activity to share what you have discussed.In C, a 1-dimensional array can be declared as a pointer pointed to a dynamically allocated memory location: int* array = (int*)malloc(n * sizeof(int)); // n is the size of array We can also use a double pointer (**) to construct a 2D array. In fact, a 2D array is just multiple rows of 1D arrays. You can also view it as an array of arrays as shown below: In the example above, each row is an array of int. Since each row is an array of int, we need an int* pointing to each row. As a result, we need to have an array of int* to point at different rows of int. TPS activity 2: Discuss questions 1 – 7 (25 minutes) with your TPS partners in your assigned group and record your answers in tpsAnswers.txt under a section labelled “TPS 2”: 1. Open Array2D.c. This program will create a n x n array of int. Explain what line #8 does. 2. Since every array must be allocated in the memory before it can be used, we need to allocate the rows one by one. To do this, we need to be able to access the pointers from the first array (pointed by arr). Assuming i is the index of that array, how do we access the ith value of the array? 3. Without using array notations ([]), insert code to complete allocating all the rows and initialize all contents to be 0. Your code should work with different values for n. Hint: if j is the index of each row, how do you access arr[i][j] in pointer notation? 4. To verify whether you have created your array correctly, we need a function to print out the array. The function printArray has been declared. It takes in both the array to be printed and size of array. Why do we need to pass the size as an argument? 5. Complete printArray so it prints out the content and layout of an array correctly. 6. Now, let us modify the content of the array. Insert code to make the array into a diagonal matrix that looks like the following (again, do not limit the size to 5): 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 0 0 0 4 0 0 0 0 0 5 7. Call printArray to print out your new array and verify result. Individual Assignment 1: Matrix Multiplication Now we know how 2D arrays work. Let us put them in practical use (you must not use any array notions ([]) in this assignment): 1. Open MatrixMult.c. and define in main() two n x n matrices (arrays) using malloc. 2. Implement printArray function so you can call it to print a 2D array. 3. In main(), call printArray to print out the 2 arrays you have defined in (1). 4. Implement matMult so it multiplies the 2 input arrays and return the resulting array. Pay attention to the input arguments and return type. 5. In main(), call matMult to multiply the 2 arrays you have defined in (1). 6. In main(), call printArray to print out the resulting array you receive in (5). 7. You will need to declare any variables that are necessary. Collaboration You must credit anyone you worked with in any of the following three different ways: 1. Given help to 2. Gotten help from 3. Collaborated with and worked together What to hand in When you are done with this lab assignment, submit all your work through CatCourses. Before you submit, make sure you have done the following: • Your code compiles and runs on a Linux machine (without the need for special libraries). • Attached MemCast.c, Array2D.c, MatrixMult.c, and tpsAnswers.txt. • Filled in your collaborator’s name (if any) in the “Comments…” textbox at the submission page. Also, remember to demonstrate your code to the TA or instructor before the end of the grace period.
Overview By now, you should have “mastered” the skills of coding and compiling your programs in a terminal. The next step is to further explore the tools we can use in the terminal to enhance our “programming experience”. The goal of this lab is to learn how to use GDB (or, optionally, LLDB in case you are using a MAC computer) to debug and fix errors in your programs. Note that if you are using LLDB, it is your responsibility to learn the We will practice the use of pointers and how they are related to memory. You can refer to chapter 5 of K&R for references on pointers. Getting Started Before we begin any activities, create a directory (Lab_2) inside the CSE31 directory we created last week. You will save all your works from this lab here. Note that all the files shown in green below are the ones you will be submitting for this assignment. You must have a clear idea of how to answer the lab activities before leaving lab to receive participation score. Tutorial in GDB and Setup GDB (or GNU Debugger) is a debugger for C and C++ (and many other languages) that runs on Linux systems. TPS (Think-Pair-Share) activity 1: Perform the following tasks while paired with your classmates assigned by your TA (you will be assigned to groups of 3-4 students): 1. Record your TPS partners’ names. 2. Independently search the internet for 3 online tutorials on how to setup and use GDB (or LLDB) in your system. 3. Share your tutorials with your TPS partners. 4. Bookmark your results in the browser of your computer. Your TA will “invite” one of you randomly after the activity to share what you have discussed. Setting up GDB: Follow the tutorials you have found (or the tutorials that have been made available through CatCourses) to setup GDB in your computer. Running GDB Copy your punishment.c file from Lab 1 into your Lab_2 directory. TPS activity 2: Discuss questions 1 – 8 with your TPS partners in your assigned group (15 minutes) and record your answers in a text file named tpsAnswers.txt under a section labelled “TPS 2” (you will continue to use this file to record your answers to all the TPS questions that follow in the lab handout): 1. How do you compile your punishment.c so that you can debug it using GDB (or LLDB for MAC)? Try it with your code and set the name of the executable to punish. 2. Once punishment.c is compiled, how do you load it in GDB (or LLDB for MAC)? Try it with your program. 3. Once punish is loaded, how do you run it in GDB (or LLDB for MAC)? Try to run your punish. 4. What are breakpoints? How do you set a breakpoint at a certain line of your program? Try to set a breakpoint in punishment.c where the for loop begins.5. Now run the program again. It should stop at the breakpoint you set in Q4. From here, how do you run the program line by line? Try to run the next 3 lines with your program. 6. While you are still running punish line by line, how can you see the value of a variable? Pick 3 variables in your program and display them in the terminal one by one. 7. Now that you are tired of running line by line, how do you let the program finish its run? Try to finish running your punish. 8. How do you exit from GDB (or LLDB for MAC)? Your TA will “invite” one of you randomly after the activity to share what you have discussed. Create pointers.c Use your favorite text editor to create a C program called pointers.c and copy the following code to your file: #include int main() { int x, y, *px, *py; int arr[10]; return 0; } TPS activity 3: Discuss questions 1 – 8 with your TPS partners in your assigned group (15 minutes) and record your answers in tpsAnswers.txt under a section labelled “TPS 3”: 1. How many variables were declared in the first line of main()? How many of them are pointers (and what are they)? 2. What will be the values of x, y, and arr[0] if you run the program? Validate your answer by running the program. Why do you think it happens that way? You will need to insert printf statements to display those values. 3. How do you prevent x, y, and the content of arr from having unexpected values? Try to fix them in the program. 4. The moment you have declared a variable, the program will allocate a memory location for it. Each memory location has an address. Now insert printf statements to display the addresses of x and y. 5. Now insert code so that px points to x and py points to y. Print out the values and addresses of those pointers using only the pointer variables (yes, pointers have addresses too!). You should see that the value of px is equal to the address of x, and the same is true for py and y. 6. As we have learned in lectures, an array name can be used as a pointer to access the content of the array. Write a loop to output the contents of arr by using arr as a pointer (do not use [] in your loop). 7. Are array names really the same as pointers? Let us find out! An array name points to the first element of an array, so arr should point to the address of arr[0]. Insert code to verify this. 8. Now print out the address of arr. Does the result make sense? Why? Your TA will “invite” one of you randomly after the activity to share what you have discussed. Individual Assignment 1: Segmentation Faults Recall what causes segmentation fault and bus errors from lecture and the textbooks. Common cause is an invalid pointer or address that is being dereferenced by the C program. Use the program average.c from the assignment page for this exercise. The program is intended to find the average of all the numbers inputted by the user. Currently, it has a bus error if you input more than one number. Make a copy of average.c as you will be using the original version of this file to demonstrate the steps for debugging during the demo. Name the copy average_original.c. Load average.c into GDB (or LLDB for MAC) with all the appropriate information and run it. GDB/LLDB will trap on the segmentation fault and give you back the prompt. First, find where the program execution ended by using backtrace (bt as shortcut) which will print out a stack trace. Find the exact line that caused the segmentation fault. Answer the following questions in a text file named assignAnswers.txt (you will continue to use this file to record your answers to all the assignment questions that follow in the lab handout) under a section labelled “Assignment 1”: 1. What line caused the segmentation fault? 2. How do you fix the line so it works properly? You can recompile the code and run the program again. The program now reads all the input values but the average calculated is still incorrect. Use GDB to fix the program by looking at the output of read_values. To do this, either set a breakpoint using the line number or set a breakpoint in the read_values function. Then continue executing till the end of the function and view the values being returned. Answer the following questions (in the text file assignAnswers.txt as mentioned above): 3. What is the bug here? 4. How do you fix it? Individual Assignment 2: Fix appendTest.c Compile appendTest.c from the assignment page and record your answers to the following questions in assignAnswers.txt while running the program under a section labelled “Assignment 2”: 1. Run the program with the following input: “HELLO!” for str1 and “hello!” for str2. Is the output expected? 2. Do not stop the program, enter “HI!” for str1 and “hi!” for str2. Is the output expected? What is the bug here? Try to fix the program so it will print the output correctly. 3. Do not stop the program, enter “Hello! How are you?” for str1 and “I am fine, thank you!” for str2. Is the output expected? Why do you think this happens? You do not need to fix this. You can now stop the program by pressing Ctrl-C. Individual Assignment 3: Complete arrCopy.c Study and complete arrCopy.c so that it outputs the following sample result in the same format. You must only insert code in the segments labelled with //Your code here. Contents of all arrays must be accessed through pointers, so you must not use any array notation ([]) in your code. Hint: Use dynamic memory allocations (malloc)! Your program must produce an output that exactly resembles the Sample Run, including identical wording of prompts, spacing, input locations, etc. Sample Run (user input shown in blue, with each run separated by a dashed line): ——————————————————————————-SAMPLE RUN 1 Enter the size of array you wish to create: 5 Enter array element #1: 1 Enter array element #2: 3 Enter array element #3: 5 Enter array element #4: 7 Enter array element #5: 9 Original array’s contents: 1 3 5 7 9 Copied array’s contents: 9 7 5 3 1 Collaboration You must credit anyone you worked with in any of the following three different ways: 1. Given help to 2. Gotten help from 3. Collaborated with and worked together What to hand in When you are done with this lab assignment, submit all your work through CatCourses. Before you submit, make sure you have done the following: • Your code compiles and runs on a Linux machine (without the need for special libraries). • Attached pointers.c, average.c, appendTest.c, arrCopy.c, assignAnswers.txt, and tpsAnswers.txt. • Filled in your collaborator’s name (if any) in the “Comments…” text-box at the submission page. Also, remember to demonstrate your code to the TA or instructor before the end of the grace period.
Overview Welcome to CSE31! This lab will help you be familiar with the C programming language and the tools available to you on Linux (and Linux-based) systems. In this exercise, you may do your work on the lab systems directly so to minimize any headaches in the beginning of this semester. It would be a good time this week for exploring your other options (e.g., setting up the coding environment in your own systems).The goal of this lab is to refresh your programming skills and create simple programs that will display output to the console, read input from the user, use conditional and loop statements in C, and perform some simple error handling.Note: You need to have a separate program for each of the parts of this lab. When you submit your assignment through CatCourses, make sure that ALL PARTS are included.Getting Started In this class, we will use the Linux terminal extensively, so you should get familiar with it as much as possible (there is plenty of information online). We recommend setting up a smart directory structure to save your assignments throughout the semester, but it is up to you about how you want to save your work.We will setup a CSE31 directory on the Desktop, a directory for the lab (i.e. Lab_1) inside it, and a directory inside the lab directory for each part of the lab (i.e. part1, part2, etc…). Note that all the files shown in green below are the ones you will be submitting for this assignment. You must have a clear idea of how to answer the lab activities before leaving lab to receive participation score.Tutorial in Linux As a software engineer (or a normal human), it is impossible to remember all the commands for Linux terminal. It is particularly true for those that you don’t use Linux often. So, where can you find the resources? TPS (Think-Pair-Share) activity 1: Perform the following tasks while paired with your classmates assigned by your TA (you will be assigned to groups of 3-4 students) and record your answers in a text file named tpsAnswers.txt under a section labelled “TPS 1” (you will continue to use this file to record your answers to all the TPS questions that follow in the lab handout): 1. Record your TPS partners’ names. 2. Independently search the internet for 3 online tutorials on how to use Linux terminal. 3. Share your tutorials with your TPS partners. 4. Bookmark your results in the browser of your computer.Create Lab_1 directory TPS activity 2: Discuss questions 1 – 4 with your TPS partners in your assigned group (10 minutes) and record your answers in tpsAnswers.txt under a section labelled “TPS 2”: 1. How can you open a terminal from your Linux computer? a. Can you open more than 1 terminal at the same time? b. Why do you think you want to open more than 1 terminal at the same time? 2. In the terminal, how can you tell what are contents inside the current directory (i.e., what is the command)? 3. From your current directory, how can you navigate to Desktop directory? 4. While you are in Desktop, create a new directory called CSE31. How do you do this?Your TA will “invite” one of you randomly after the activity to share what you have discussed. Now navigate to the directory you have just created (CSE31), create another new directory called Lab_1 here (Lab_1 is inside CSE31). You will be saving all the programs you create today in this directory.Coding 1: Create main.c Make sure you are in your Lab_1 directory, type gedit main.c and press enter (if you get an error, you may need to install gedit by typing sudo apt install gedit on the terminal before using it). The gedit text editor will be displayed. Note that gedit is only available in a Linux system with graphic interface. You may want to use other text editors (vi, nano, sublime, etc.) if terminal is the only interface to access a Linux system, or if you are using Windows or a Mac. Ask your TA if you are not sure about this. Copy the following code to your file: #include int main() { printf(“Welcome to CSE 31! ”); return 0; } Save your file and exit gedit. Congratulations, you have just written your first C program! The first line, #include< stdio.h>, includes a library that allows you perform simple Input/Output (I/O) operations. In this program, the library allows you to use the printf statement. In the next line, int main(), we start the main function, which is a mandatory function for any C program. This is the function that first executes when the program is launched. The contents of the function’s code need to be surrounded by curly braces (lines 3 and 6). In line 4, we are printing the text Welcome to CSE031! to the screen, ending with a new line ( ). Finally, the last line returns from the main function, which will stop execution of the program.Once you have created this file and understood its content, you want to compile the source file (main.c) into an executable so that you can run it on your computer. To compile, we will use GCC compiler (not G++ – it is used for C++).TPS activity 3: Discuss questions 1 – 9 with your TPS partners in your assigned group (15 minutes) and record your answers in tpsAnswers.txt under a section labelled “TPS 3”: 1. Independently find 2 online references on how to use GCC in a Linux terminal. 2. Share what you have found with your partners and save your results in the bookmark of your browser.You will refer to these references to answer the following questions. 3. What command do you type in the terminal to compile your main.c? 4. How do you know if your program has compiled successfully? 5. What does the –c flag do in gcc? 6. What does the –g flag do in gcc? 7. How do you change the executable name from main to cselab1? 8. What happens when you compile your code by typing gcc main.c only? 9. Now, let us run the program you have just compiled. What command do you use?Your TA will “invite” one of you randomly after the activity to share what you have discussed. Coding 2: Create punishment.c A common punishment for school children is to write out the same sentence multiple times. Individually create a C program (punishment.c) that will write out the following sentence the number of times specified by the user (without the quotes, unless explicitly mentioned): “Programming in C is fun!”.Your program will ask the user for the number of times to output the punishment phrase using the following prompt (notice the space at the end of the prompt): “Enter the number of times to repeat the punishment phrase: ”. If an invalid value is entered (think about what would constitute an invalid value), your program should output You entered an invalid value for the number of repetitions! and continue asking the user for an input till a valid one is entered. To make this program “realistic”, it will introduce a typo during a certain repetition. It will ask for the repetition during which to introduce a typo using the following prompt: “Enter the repetition line where you want to introduce the typo: ”.Once again, you should check that the value entered by the user is valid (think about what would constitute an invalid value). If the value is invalid, display You entered an invalid value for the typo placement! and continue asking the user for an input till a valid one is entered. When both inputs are correct, you should display the punishment phrase the correct number of times (Programming in C is fun!), making sure to change it to Progranming in c is phun! (the typo) during the repetition count defined/input by the user. You will need to use scanf to process user inputs. Look it up online to find out how to use it. Please see the sample runs below. Your program must produce an output that exactly resembles the Sample Runs, including identical wording of prompts, spacing, input locations, etc. Sample Runs (user input shown in blue, with each run separated by a dashed line): ——————————————————————————-SAMPLE RUN 1 Enter the number of times to repeat the punishment phrase: 4 Enter the repetition line where you want to introduce the typo: 1 Progranming in c is phun! Programming in C is fun! Programming in C is fun! Programming in C is fun! ——————————————————————————-SAMPLE RUN 2 Enter the number of times to repeat the punishment phrase: 6 Enter the repetition line where you want to introduce the typo: 3 Programming in C is fun! Programming in C is fun! Progranming in c is phun! Programming in C is fun! Programming in C is fun! Programming in C is fun! ——————————————————————————-SAMPLE RUN 3 Enter the number of times to repeat the punishment phrase: -8 You entered an invalid value for the number of repetitions! Enter the number of times to repeat the punishment phrase again: 0 You entered an invalid value for the number of repetitions! Enter the number of times to repeat the punishment phrase again: 2 Enter the repetition line where you want to introduce the typo: 0 You entered an invalid value for the typo placement! Enter the repetition line where you want to introduce the typo again: 3 You entered an invalid value for the typo placement! Enter the repetition line where you want to introduce the typo again: 2 Programming in C is fun! Progranming in c is phun! Coding 3: Create averages.c Create a new program that will ask a user to enter a number repeatedly. This program will calculate 2 averages based on whether the sum of digits in the inputted numbers are odd or even: avg_even (average of all inputs whose digits sum up to an even number) and avg_odd (average of all inputs whose digits sum up to an odd number). The program will stop when the user enters a ‘0’. For example, the numbers 2, 26 and 123 are those whose digits sum up to an even number (2, 2+6=8 and 1+2+3=6, respectively). Before writing the program in C code, perform the TPS activity below to write a pseudocode to describe your approach to this problem. TPS activity 4: Work with your TPS partners in your assigned group to write the pseudocode together (20 minutes) in a text file named pseudoAverages.txt. Make sure to only discuss the pseudocode. You must write the C code individually. Your TA will “invite” one of you randomly after the activity to share your pseudocode. Your program must produce an output that exactly resembles the Sample Runs, including identical wording of prompts, spacing, input locations, etc. Notice that the text in the input prompts, where the user enters an integer, changes each time — stating “1st integer”, “2nd integer”, “3rd integer”, “4 th integer”, etc. You will need to code this behavior into your program. Sample Runs (user input shown in blue, with each run separated by a dashed line): ——————————————————————————-SAMPLE RUN 1 Please enter the 1st integer: 2 Please enter the 2nd integer: 26 Please enter the 3rd integer: 123 Please enter the 4th integer: 3 Please enter the 5th integer: -14 Please enter the 6th integer: 111 Please enter the 7th integer: 0 Average of inputs whose digits sum up to an even number: 50.33 Average of inputs whose digits sum up to an odd number: 33.33 ——————————————————————————-SAMPLE RUN 2 Please enter the 1st integer: 92 Please enter the 2nd integer: -142 Please enter the 3rd integer: 7 Please enter the 4th integer: 36 Please enter the 5th integer: 0 Average of inputs whose digits sum up to an odd number: -1.75 ——————————————————————————-SAMPLE RUN 3 Please enter the 1st integer: 0 There is no average to compute. Collaboration You must credit anyone you worked with in any of the following three different ways: 1. Given help to 2. Gotten help from 3. Collaborated with and worked together What to hand in When you are done with this lab assignment, submit all your work through CatCourses. Before you submit, make sure you have done the following: • Your code compiles and runs on a Linux machine (without the need for special libraries). • Attached punishment.c, pseudoAverages.txt, averages.c, and tpsAnswers.txt. • Filled in your collaborator’s name (if any) in the “Comments…” text-box at the submission page. Also, remember to demonstrate your code to the TA or instructor before the end of the grace period.
In this lab, we will explore a new useful data structure: Binary Trees. A binary tree is a very efficient data structure to store and retrieve sorted data. They are frequently used to implement maps and dictionaries (multimaps). In this lab, you will implement a simple form of binary trees. Getting started Create a new directory in your main development directory (probably on Desktop/CSE30) called Lab_11. Try to use the terminal on your own, without getting help from the TA to setup the new directories (try to learn/remember the terminal commands). The g++ syntax to compile classes is slightly different than for a single program comprised of a main (and potential functions): g++ class1.h class1.cpp class2.h class2.cpp mainSource.cpp -o executable where: g++ is the compiler (installed on your Linux system) of C++ source files, mainSource.cpp is the source file for your main program (main function), class1.h is the class declaration for your 1st class, class1.cpp is your 1st class definition, class2.h is the class declaration for your 2nd class, class2.cpp is your 2nd class definition (and so on…), -o tells the compiler that you want to give the executable its own name, and executable is the name you want to give your program. As an example, if we have a main source file called Exercise1.cpp, the class declaration called LinkedList.h, the class definition called LinkedList.cpp, and want to create an executable called aTestProgram, you would type: g++ LinkedList.h LinkedList.cpp Exercise1.cpp -o aTestProgram Assuming that your program compiled successfully (i.e. no errors were found), you can run your program as you normally would by typing “./aTestProgram” in the terminal/console. Good coding practices (worth 2 points!) Writing code that is understandable by humans is as important as being correct for compilers. Writing good code will help you complete the code, debug it and … get good grades. It is very important to learn as soon as possible, because bad habits are hard to get rid of and good habits become effortless. Someone (guess who) reads your code will be in a better mood if it is easy to understand … leading to better grades! This lab will include 2 points (10% for code quality): Explanations with comments Meaningful names Indenting of blocks { } and nesting … Proper use of spaces, parentheses, etc. to Visible, clear logic One / simple statements per line Anything that keeps your style consistent (Exercise) In this part of the lab, you will be implementing the basic functions for a Binary Tree, which are provided in the class declaration BTree.h (on CatCourses). In other words, you have to create and implement the class implementation in a file called BTree.cpp. The main file you have to use for this lab is also provided on CatCourses (Exercise.cpp). DO NOT modify the class declaration (BTree.h) or main file (Exercise.cpp). Looking at the class declaration, you will find that a Node is defined as a structure comprised of a key value (key_value, of type int) and two pointers to the child nodes (left and right, of type Node pointer). You will also notice (under private) that you will be keeping track of your Binary Tree using a Node pointer, root. This root pointer should always point to the root element of your Binary Tree. If the Binary Tree is empty, the root pointer should point to NULL. In this part of the lab, you will need to implement the following functions for the BTree class: Default Constructor: initializes the root, the binary tree is empty. Destructor: deletes the entire Binary Tree by calling destroy_tree(). BTree_root(): returns a pointer pointing to the root of the Binary Tree. destroy_tree(node *leaf): a recursive function that destroys a subtree with the input argument (leaf) as root. This function will check if leaf exists, then recursively destroy its left and right child nodes. insert(int key, node *leaf): a recursive function that compares the input argument key with the key_value of the other input argument leaf. If key is less than key_value, the same function is called with the left child node of leaf as the new input argument; otherwise, the right child node of leaf will be used as the new input argument. When the leaf node is empty (NULL), a new node is created and its key_value is set to key (remember to set its left and right child nodes to NULL). search(int key, node *leaf): a recursive function that compares the input argument key with the key_value of the other input argument leaf. It returns the pointer to leaf if key = key_value. If key < key_value, the same function is called with the left child node of leaf as the new input argument; otherwise, the right child node of leaf will be used as the new input argument. It returns NULL if leaf is NULL (it reaches the end of the tree but the key is not found). insert(int key): a public function that inserts a key into the tree. It creates a new node as root with key_value equals to key if the tree is empty, otherwise it calls insert(key, root) to insert the key at the correct location. search(int key): a public function that starts the search of the input argument key from the root node. It returns the pointer to the node that has the same key_value as key (you do not need to perform any comparison in this function, only need to call search(int key, node *leaf) with the correct input arguments to start the search). destroy_tree(): a public function that calls destroy_tree(node *leaf) with the correct input argument to destroy the whole tree. Note: a pointer does not point to anything unless you 1) use the reference operator (&) in front of a variable, 2) you dynamically allocate memory for it (using the new operator), or 3) you assign it (set its value to) to another pointer every time you want to create a node, you will have to use the new operator every time you allocate memory dynamically for a pointer using the new keyword, you have to make sure that you de-allocate the memory once you do not need the data anymore. This can be done using delete (in the destructor, clear and remove functions). Sample output from Exercise.cpp: Root has key: 10 Left child of root has key: 6 Right child of root has key: 14 Searching for key 14… Key 14 found! Its left child has key: 11 Its left child has key: 18 Searching for key 13… Key 13 not found! What to hand in When you are done with this lab assignment, you are ready to submit your work. Make sure you have included the following before you press Submit: A compressed file that includes BTree.h, BTree.cpp, Exercise.cpp, and a list of Collaborators. Documentation (in a text file) of code you used from the internet. You may want to cutand-paste the original code as well.
In this lab, we will explore a new useful data structure: Queues. Queues are usually referred to as a FIFO (First In First Out) structure, where the first element inserted into the data structure is the first one to be removed from it. Queues can be implemented with any type of container (e.g. arrays, linked lists, etc.). In this lab, you will implement the Queues with your implementation of the Linked Lists in Lab#8. In fact, you can think of Queues as Linked Lists, with the FIFO constraints: you will implement them using inheritance, by inheriting from a Linked List class. Getting started Create a new directory in your main development directory (probably on Desktop/CSE30) called Lab_10. Try to use the terminal on your own, without getting help from the TA to setup the new directories (try to learn/remember the terminal commands). The g++ syntax to compile classes is slightly different than for a single program comprised of a main (and potential functions): g++ class1.h class1.cpp class2.h class2.cpp mainSource.cpp -o executable where: g++ is the compiler (installed on your Linux system) of C++ source files, mainSource.cpp is the source file for your main program (main function), class1.h is the class declaration for your 1st class, class1.cpp is your 1st class definition, class2.h is the class declaration for your 2nd class, class2.cpp is your 2nd class definition (and so on…), -o tells the compiler that you want to give the executable its own name, and executable is the name you want to give your program. As an example, if we have a main source file called Exercise1.cpp, the class declaration called LinkedList.h, the class definition called LinkedList.cpp, and want to create an executable called aTestProgram, you would type: g++ LinkedList.h LinkedList.cpp Exercise1.cpp -o aTestProgram Assuming that your program compiled successfully (i.e. no errors were found), you can run your program as you normally would by typing “./aTestProgram” in the terminal/console. Good coding practices (worth 2 points!) Writing code that is understandable by humans is as important as being correct for compilers. Writing good code will help you complete the code, debug it and … get good grades. It is very important to learn as soon as possible, because bad habits are hard to get rid of and good habits become effortless. Someone (guess who) reads your code will be in a better mood if it is easy to understand … leading to better grades! This lab will include 2 points (10% for code quality): Explanations with comments Meaningful names Indenting of blocks { } and nesting … Proper use of spaces, parentheses, etc. to Visible, clear logic One / simple statements per line Anything that keeps your style consistent (Exercise 1) In this part of the lab, you will be implementing your own Queue class, comprised of a class declaration (Queue.h) and class definition (Queue.cpp). You will also create a simple main program to test your queue class (Exercise1.cpp). This part of the lab will use int as the type for elements in the Queue (Linked List nodes). Similar to your stack implementation in Lab#11, your Queue class will inherit the LinkedList class so that any functions available inside the LinkedList class can be used by the Queue class. Take a look at the Inheritance_example_files from lecture to see how to use inheritance. As you will see when you implement the Queue class, inheriting the LinkedList class will make this part of the lab very simple. Your Queue class will be comprised of the following functions, which you need to implement (note that the Queue class does not need any variables, since those from the inherited LinkedList are all you need): Default Constructor (Queue()): does nothing Destructor (~Queue()): does nothing void enqueue(int value): inserts a new element (value) at the back of the Queue, by calling the appropriate LinkedList function. int dequeue(): removes the first element of the Queue, by calling the appropriate LinkedList function. It also returns the value of the element that has been dequeued. int& front(): returns a reference to the front element of the Queue. You also need to create your own main program (Exercise1.cpp) to test the various Queue functions: Create a queue of at least 10 elements in your main program and call various member functions to manipulate the queue (as you have seen in your HW2 problem). Call enqueue to insert integer to the queue Call front to return to the front of the queue Call dequeue to remove elements from the queue Check the size of the queue by calling a function inherited from Linked List. Check if the queue is empty by calling a function inherited from Linked List. Print the content of the queue by calling a function inherited from Linked List and verify if the member functions work correctly. Note: Your Queue implementation should be very simple and short. It will be similar to your implementation of Stack in Lab#11. Remember that since you are inheriting the LinkedList class, you can call any functions/variables that were defined inside the LinkedList class. Unlike your Stack implementation in Lab#11, you must generate exceptions where appropriate: you should throw exceptions in both dequeue and front functions whenever these functions would fail. You will need to catch the exceptions and print the following error messages if an exception is generated: “Call to front() generated an exception, because the queue is empty” OR “Call to dequeue() generated an exception, because the queue is empty” o You should throw an exception (an integer value) inside the appropriate Queue’s functions. (i.e. in Queue.cpp) See the online tutorial in exceptions for examples on how to implement exceptions. All you need to do is to throw an integer value when an error arises. o http://www.cplusplus.com/doc/tutorial/exceptions/ o For each call to the dequeue and front functions, you should try to catch the exception (the integer value thrown from the functions) in the main file (Exercise.cpp) and print the appropriate error to the screen. (Exercise 2) In this part of the lab, you will make the following changes to the code developed in Exercise 1: Change your Queue and Linked List classes so that they use char type instead of int. Name them Queue_char.h/Queue_char.cpp and LinkedList_char.h/ LinkedList_char.cpp to avoid the confusion between the classes created in Exercise 1. Create a main program (Exercise2.cpp) to produce the following output similar to what was illustrated in the lecture. You do not need to produce the table lines, but need to use tabs in between columns and newlines for each row. Columns do not need to be aligned between rows. What to hand in When you are done with this lab assignment, you are ready to submit your work. Make sure you have included the following before you press Submit: Your LinkedList.h, LinkedList.cpp, LinkedList_char.h, LinkedList_char.cpp , Queue.h, Queue.cpp, Queue_char.h, Queue_char.cpp, Exercise1.cpp, Exercise2.cpp , and a list of Collaborators. Documentation (in a text file) of code you used from the internet. You may want to cutand-paste the original code as well.
In this lab, we will explore a new useful data structure: Stacks. Stacks are usually referred to as a LIFO (Last In First Out) structure, where the last element inserted into the data structure is the first one to be removed from it. Stacks can be implemented with any type of container (e.g. arrays, linked lists, etc.). In this lab, you will implement the Stacks with your implementation of the Linked Lists in Lab#8. In fact, you can think of Stacks as Linked Lists, with the LIFO constraints: you will implement them using inheritance, by inheriting from a Linked List class. Getting started Create a new directory in your main development directory (probably on Desktop/CSE30) called Lab_9. Try to use the terminal on your own, without getting help from the TA to setup the new directories (try to learn/remember the terminal commands). The g++ syntax to compile classes is slightly different than for a single program comprised of a main (and potential functions): g++ class1.h class1.cpp class2.h class2.cpp mainSource.cpp -o executable where: g++ is the compiler (installed on your Linux system) of C++ source files, mainSource.cpp is the source file for your main program (main function), class1.h is the class declaration for your 1st class, class1.cpp is your 1st class definition, class2.h is the class declaration for your 2nd class, class2.cpp is your 2nd class definition (and so on…), -o tells the compiler that you want to give the executable its own name, and executable is the name you want to give your program. As an example, if we have a main source file called Exercise1.cpp, the class declaration called LinkedList.h, the class definition called LinkedList.cpp, and want to create an executable called aTestProgram, you would type: g++ LinkedList.h LinkedList.cpp Exercise1.cpp -o aTestProgram Assuming that your program compiled successfully (i.e. no errors were found), you can run your program as you normally would by typing “./aTestProgram” in the terminal/console. Good coding practices (worth 2 points!) Writing code that is understandable by humans is as important as being correct for compilers. Writing good code will help you complete the code, debug it and … get good grades. It is very important to learn as soon as possible, because bad habits are hard to get rid of and good habits become effortless. Someone (guess who) reads your code will be in a better mood if it is easy to understand … leading to better grades! This lab will include 2 points (10% for code quality): Explanations with comments Meaningful names Indenting of blocks { } and nesting … Proper use of spaces, parentheses, etc. to Visible, clear logic One / simple statements per line Anything that keeps your style consistent (Exercise 1) In this part of the lab, you will be implementing your own Stack class, comprised of a class declaration (Stack.h) and class definition (Stack.cpp). You will also create a simple main program to test your stack class (Exercise1.cpp). This part of the Lab will use int as the type for elements in the Stack (Linked List nodes). In order to make the Stack implementation as easy as possible, your stack class will inherit the LinkedList class so that any functions available inside the LinkedList class can be used by the Stack class. Take a look at the Inheritance_example_files from lecture to see how to use inheritance. As you will see when you implement the Stack class, inheriting the LinkedList class will make this part of the lab very simple. Your Stack class will be comprised of the following functions, which you need to implement (note that the Stack class does not need any variables, since those from the inherited LinkedList are all you need): Default Constructor (Stack()): does nothing Destructor (~Stack()): does nothing void push(int value): inserts a new element (value) at the front of the stack, by calling the appropriate LinkedList function. int pop(): removes the first element of the Stack, by calling the appropriate LinkedList function. It also returns the value of the element that has been popped. int& top(): returns a reference to the top element of the Stack. You also need to create your own main program (Exercise1.cpp) to test the various Stack functions: Create a stack of at least 10 elements in your main program and call various member functions to manipulate the stack (as you have seen in your HW2 problem). Call push to insert integer to the stack Call top to return to the top of the stack Check the size of the stack by calling a function inherited from Linked List. Check if the stack is empty by calling a function inherited from Linked List. Print the content of the stack by calling a function inherited from Linked List and verify if the member functions work correctly. Note: You do not need to create exceptions, so create a main program that does not call top or pop when the stack is empty. Your Stack implementation should be very simple and short. Most, if not all, functions can be implemented using a single line of code. Remember that since you are inheriting the LinkedList class, you can call any functions/variables that were defined inside the LinkedList class. (Exercise 2) In this part of the lab, you will make the following changes to the code developed in Exercise 1: Change your Stack and Linked List classes so that they use char type instead of int. Name them Stack_char.h/Stack_char.cpp and LinkedList_char.h/ LinkedList_char.cpp to avoid the confusion between the classes created in Exercise 1. Create a main program (Exercise2.cpp) to produce the following output similar to what was illustrated in the lecture. You do not need to produce the table lines, but need to use tabs in between columns and newlines for each row. Columns do not need to be aligned between rows. What to hand in When you are done with this lab assignment, you are ready to submit your work. Make sure you have included the following before you press Submit: Your LinkedList.h, LinkedList.cpp, LinkedList_char.h, LinkedList_char.cpp , Stack.h, Stack.cpp, Stack_char.h, Stack_char.cpp, Exercise1.cpp, Exercise2.cpp , and a list of Collaborators. Documentation (in a text file) of code you used from the internet. You may want to cutand-paste the original code as well.