ENGG 233 - Computing for Engineers I
Lab Assignment
Fall 2012 Lab: 2
Title: Introduction Algorithm Development, the Microsoft Visual Studio, and Basic C++
Starts: Week of September 24, 2012
Due Dates: • Exercise 1 (pre-lab exercise) – at the start of your scheduled lab session.
• Exercise 2 (in-lab exercise) – by the end of your scheduled lab session.
• Exercises 3 and 4, Week of October 1, 2012
This lab consists of four exercises. The first one is a pre-lab exercise that the answer must be provided by you before going to your scheduled lab session, and MUST be handed in (paper copy), personally to the lab TA at the beginning of the lab. The second exercise is an in-lab exercise that MUST be implemented during the scheduled lab session, and must be handed in (paper copy), before the end of the lab to your TA. Other exercises must be handed in electronically, via email to your TA, anytime before the indicated due date for your lab section.
1BObjectives
The objectives of this lab are as follows:
• Learn how to use flowcharts as means of describing an algorithm
• Get familiar with creation of a simple Win32 console application with Visual Studio
• Get familiar with variable declaration and implementation of basic arithmetic operations
• Writing and testing basic C++ programs from scratch.
2BRelevant Course Material
This lab deals with basic C++ programs including variable declaration, use of built-in functions, mathematical expressions and strings.
In order to derive the maximum benefit from the lab, students are encouraged to read the following material prior to completing the exercises:
Lecture Notes Sections 1 and 2 (basic syntax)
Horstmann: Sections 1.1 to 1.9; 2.1 to 2.4
Exercise 1 Pre-lab Exercise: Algorithm Development (22 pts)
Note: This exercise must be completed prior to your scheduled lab period and a hardcopy must be submitted to your TA at the start of
the lab period.
Programming is as much about developing and describing algorithms as it is about actually writing source code. In fact, in many situations, the development of the algorithm is done separately from the writing of the source code (possibly by different people). It is therefore critical that your algorithms be well described. To this end, there are two options; pseudocode and flowcharts. The following tasks will get you to describe an algorithm using both of these methods.
Describing an Algorithm using Pseudocode
Pseudocode is a method of describing the steps associated with an algorithm in plain English. There is no “standard” for how to write pseudocode. However, please read the following sections of the textbook to get some good suggestions for how to address the problem (another example is also given Task 1.2 below)
• “How To 1.1” on page 20 (2nd edition) and page 24 (older edition) .
• “Worked Example 1.1” which is available at the following webpage:
http://higheredbcs.wiley.com/legacy/college/horstmann/0470927135/workedex/ch01_we1.pdf
In addition to the above, some key points to remember are
• Make sure you satisfy the three requirements of any algorithm; it must be unambiguous, executable and terminating.
• Do not use language-specific (e.g., C++-specific) terminology. In fact, the sign of good pseudocode is that it can be used to implement an algorithm in any language, not just C++!
With this in mind, please read the following problem statement and answer the question below.
Problem Statement
You have been given the problem of writing an algorithm to solve quadratic equations.
The input to the algorithm are the three coefficients, , and of the quadratic equation to be solved
Then, the solutions to the quadratic equations are given by
The algorithm should be able to output both real and complex results (i.e., those results
which require taking the square root of negative number; ). As an example of a complex result, consider the following equation
0122 xx
whose solutions are given by
Note, however, that a computer cannot compute the square root of a negative number. If this is required, your algorithm should compute the square root of the absolute value
of the number and prefix the output (scaled by the denominator) with an “ ”. Mathematically, this is equivalent to writing the solution to the quadratic equation as
Question
• Write pseudocode to describe an algorithm to solve the above problem.
Describing an Algorithm using Flowcharts
Flowcharts are often used to describe an algorithm visually. For the purpose of ENGG 233, we will only consider three flowcharts “components”, as described in Table 1 below.
With this in mind, read the following pseudocode to determine the level of discount a buyer receives based on the amount of products being purchased, and to output the discounted price
• Prompt the user for the total regular price of the purchase • Read in the total regular price of the purchase • If the total regular price is greater than $100, then discount = 0.2 (20 %),
otherwise, discount = 0.1 (10 %)
• Compute: discounted price = ( 1 - discount ) x total regular price • Output the discounted price
Table 1 - Flowchart Components and Descriptions
Component Description Example
This indicates the start and/or end of the algorithm. Every algorithm must have a start and end.
See component
Input/Output. This is used to indicate that information is being output or being read in. It should be clear as to whether the component refers to input or output.
Statement or process. This describes a specific instruction (or group of similar instructions). A statement will have one or more entry points but only a single exit point.
Decision. Used to select an execution path based on a decision. There are one or more entry points, and two exit points. The exit points correspond to when the decision is true (“yes”) or false (“no), and must be labelled appropriately.
Question
• Draw a flowchart to represent the above algorithm.
What to Hand In
For this exercise, submit the paper copy of the pseudocode from Task 1.1 and the paper copy of the flowchart for Task 1.2.
Exercise 2 In-Lab Exercise: Introduction to Microsoft Visual C++ (7 pts)
Note: This exercise must be completed during the lab period and a hardcopy must be submitted to your TA, by the end of the lab
session.
Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft.
It supports different programming languages such as Visual Basic, Visual C#, Visual
C++ etc. An IDE is a software application that provides comprehensive facilities to
computer programmers for software development. In this course, we will use MS Visual
C++ environment to study C or C++. We will learn how to use MS Visual C++ to develop
console applications. The development of graphical user interface applications is for
advanced users which is not included in this course. In the following, we will learn how
to create a simplest console application using MS Visual C++.
Creating a Console Application Using MS Visual C++
To launch Microsoft Visual C++, from the start menu select ProgramsMicrosoft Visual
Studio 2010Microsoft Visual Studio 2010. If this is the first time you are using this
software on the computer, it will ask you to choose your default environment
settings. You need to select Visual C++ Development Settings from the list, and then
click on Start Visual Studio. Visual Studio will configure the IDE in Visual C++
development settings. It may take a few minutes to configure. Be patient. The Start
Page should now appear.
Creating a new project
When MS Visual Studio 2010 opens, you will see a Start Page. This is just Microsoft
propaganda and should be ignored. There is also a window of recent projects and a
window of Getting Started. I would also suggest ignoring the Getting Started tutorials
as they are too complicated and are aimed at professional developers. Instead, create a
new project by selecting FileNewProject. A new project dialog box will pop up as
shown in Figure 1. As the IDE is set as Visual C++ development environment, by
default, Visual C++ and Win32 Console Application in the Templates panel are
highlighted. To develop different applications, select different modules such as MFC
Application and Win32 Project etc. For all labs in ENGG 233 select Visual C++ and
Win32 Console Application in the New Project dialog box.
Type a name for the application in the Name box, and in the Location box, type the
path to where you want the application to be created. The default location is somewhere
in your home drive, H:\My Documents\Visual Studio 2010\Projects, which is not
convenient to use. Change the location to the root directory of Home drive H and type
lab2 in the Name textbox. Unselect the Create directory for solution in the bottom-
right of the new project dialog box, and press OK. A dialog box called Found a suitable
location for browsing database and IntelliSense files will appear. This dialog
appears because we are creating a project on a network drive. If you create a project on
a local drive, the dialog won’t appear. You need to click OK, and the Win32
Application Wizard will appear. On the left of the box, select Application Settings. In
the Applications Settings Window, make sure that Console Application is selected
(the default). In the Additional options, select Empty Project instead of Precompiled
Header. Your selections here are very important so be very careful with this step.
Different selections will cause totally different results. Make sure your selections are the
same as those shown in Figure 2, and then click Finish. A folder lab2 will be created in
the H drive, which contains an empty Win32 console project that Visual Studio
generated for you.
Figure 1 New project dialog box
Figure 2 Application settings dialog box
Once you click on Finish, the Application settings dialog box will disappear and a new
window labeled Solution Explorer will appear in the top right corner of the IDE (or top
left on some versions). This window allows you to see what files are parts of your
Solution. A Solution in MS Visual Studio is allowed to contain multiple projects. In the
file tree displayed you will see your project with the name you gave it on the second
level, below it are four folders for External Dependencies, Header Files, Resource
Files, and Source Files. If you try to expand these folders you will see that they are
empty.
Adding a new file
You will now create a new source file. To do this, right click on the Source Files folder
and select AddNew Item. A dialog box will appear where you will tell the IDE what
kind of file you want to create and where you want it to be located. From the template
box select C++ File (.cpp), give your file a sensible name in the Name box, like
helloWorld (the .cpp extension will be added automatically). The default location is in
the lab2 folder that you just created. When you click add, a blank .cpp file will appear in
an editor window and will also appear in the file tree under source files. Now type the
source code below into this file and save the file. Make sure you also include comments
at the top of the file indicating your name, the course name, the date, and the purpose
of the file. Please note that this information should be included at the top of all your files
in this and all future labs! You can also select AddExisting Item to add an existing
.cpp file into the project, which you will use in the Exercise 3.
// ENGG 233 Lab 2
// File: helloWorld.cpp
// Author: Student Name, ID#
// Created: Date
// Last Modified: Date
// Topic: Using Create and Run a “Hello, World!” Program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
Compiling vs. building
Next compile your program by selecting Compile from the Build menu. Results of the
compilation will appear in an output box below the editor window. If your program
compiled successfully the output window will show Build succeeded. If not, errors and
warning will be listed along with their corresponding line numbers. If you click on the
error message, you will be taken to the corresponding line in the editor window. Note
that after you have compiled once, the editor window now contains boxes on the left
margin that allow you to hide code that you know is working. This is a useful feature for
very complicated projects, but you will not typically use this feature in this course.
Compiling only compiles the file you are working on into machine/object code. If you
want to compile and link (to create the executable) all the source files in your project,
you must select either Build Solution or Build <your project name> from the Build
menu. Alternatively, you can right-clock your project in the Solution Explorer and select
Build. Do one of these steps now. If you have changed a file since the last Build, the
file will be automatically saved and recompiled before the linker runs. Then it will be
linked and the executable will be created. In a one file project, if there are no
compilation errors there should be no linker errors. In later labs, you may encounter
linking errors if you are missing files, or you have called functions in one file that are not
defined where they are supposed to be in another file.
Executing the program inside and outside of the IDE
To run your program from within the IDE, select DebugStart without Debugging
(note: VS express edition doesn’t have this feature). A console with some texts “Hello,
World!” will appear as the project is created as a Win32 console application. Note that
the result is exactly the same as the one in the lab1 that we run an excitable file. In
other words, the lab2 is to illustrate how to create the executable file of the lab1 using
the Visual Studio. Run your program and copy the output from the Console window into
your lab report.
To run it from outside of the IDE, locate your executable using the windows explorer. It
should be in the debug sub-directory below the directory lab2 containing your project.
The file will have the name of your project and be described as an Application. The file
name is actually <projectname>.exe (lab2.exe in this case). Now try to execute the
program. You may do this using the methods that you learned from lab1. Run your
program and copy the output from the Console window into your lab report.
What to Hand In
For this exercise, please submit the following paper copies to your TA:
• The source code for the program (i.e., *.cpp files).
• The output of the program.
Exercise 3 Variables and Basic Arithmetic (10 pts)
Note: An electronic copy of this exercise must be submitted via email to your TA, by the due date indicate on the first page.
Recall that variables are used to store values in a program. However, before variables can be used, they must first be created (declared/defined). This exercise will get you exposed to variable creation as well as basic arithmetic.
Basic Arithmetic
To begin this task, go to Blackboard and download the file called lab2_3.cpp and put it in a new directory called lab23. Create an empty Win32 console application using Visual Studio, and add lab2_3 into the project. To add a file to a project, there two ways: One easy way is to locate the file in the folder lab23, then drag the file (lab2_3.cpp) and drop it into the Source Files folder on your Solution Explorer pane on your Visual Studio. Or, another way is to take the following steps: Right click on the Source Files folder and select the AddExisting Item. Locate the directory that you just created (lab23), select the .cpp file (lab2_3.cpp) and click on Add to add it to the project.
Now the process of adding file lab2_3.cpp to your project is completed and you start working on your code. This file contains most of a program to perform various numerical calculations.
• At the point labelled 1), write the code to add the values of num1 and num2 and to store the result in the variable sum.
• At the point labelled 2), write the code to compute the square of the sum of num1 and num2 and to store the result in the variable sumSquared. Use the value of the variable sum computed in the previous step.
• At the point labelled 3), double the value of the sumSquared variable and store the result in sumSquared.
• Compile your program.
• Run the program and record the output.
What to Hand In
Email an electronic copy of the following files to your TA. The TAs list and their email addresses are posted on the Blackboard.
• The source code for the above task
• The output of the programs
Exercise 4 Scratch Continued… (10 pts)
Note: An electronic copy of this exercise must be submitted to your TA via email by the due date indicated on the first page.
This will be our last Scratch exercise. Here we will introduce a new data type called “List”. The list blocks allow for storing and accessing a list of variables, for example, numbers and strings. This kind of data structure can be considered a “dynamic array” in C++, and we will introduce arrays later in ENGG233. However, we can forget about C++ arrays for now, and let’s just have some fun with the Scratch lists.
To create a list, go to the Variables blocks category and click . Once you make a list, several list blocks will appear. When you create a list, a list monitor will also appear on the stage. A list monitor shows all the items in a given list. At first the list will be empty with length zero. To add to the list, you can use the list blocks, for example,
. And the length will increase by one.
Let’s try to create a simple Scratch program that adds two different types of fruits (e.g., banana and kiwi) into a list called Fruits, and then let the sprite to tell us what fruits the list has.
Adding fruit items into the list is easy. We can use the following statements (Figure 2). And because we add banana first, banana will be the #1 item and kiwi will be the #2 in the list (Figure 3).
Figure 1
Figure 2
However, there is a problem. How to retrieve each item from the list?? Of course, we
can copy-and-paste multiple times, and change the item number by 1 for each statement. However, this is tedious, difficult to read, and resource-inefficient (e.g., imagine if the list had 1,000 elements!). Remember our goal is not just to write a computer program to accomplish a task, but to accomplish it elegantly and efficiently.
To that end, we can use loops and create a new variable called counter in order to retrieve each item from the list. Let’s look at the following statements (Figure 4). First, we declare a new variable called counter, and initialize it (i.e., set its value to 1). Then
we create a loop that repeats times. The first time through the loop we retrieve the first item of the list (because we set the counter to 1), and then ask the sprite to say it out. Then we change counter by 1 and repeat the loop. Therefore the second time through the loop we can retrieve the second item in the list (because the counter is now 2), and so on and so forth. By using loops and a counter, we don’t need to copy-and-paste multiple times. Isn’t it much more elegant?
Figure 3
Write a Scratch Programme to Find the Maximum and Minimum Value from a List
Create a new file in Scratch, and save the file as myscratchLab2.sb. Then create a program to accomplish the following tasks.
• Create a list called numbers.
• Add 10 random integers ranging from 1~100 into the list (Hint: Look in the Operators block.).
• Find the maximum value and the minimum value from the list.
• Output the maximum and minimum value in the following format:
• Think “The maximum value is “ for 2 seconds and then
• Say out the maximum value, and wait for 2 seconds.
• Think “The minimum value is “ for 2 seconds and then
• Say out the minimum value, and wait for 2 seconds.
• Tip #1: Don’t forget to initialize the variables with proper values.
• Tip #2: If you do not delete elements from your list, the number of elements in the list will grow each time you run your program. This is not desired.
• Tip #3: You can find the algorithm of how to find max and min value from an array on textbook page 250…but it’s in C++.
What to Hand In
Submit your myscratchLab2.sb file electronically to your TA via email (no hardcopy required).
Recommended