Lab Experiments: High-Level Language Programming

Objectives

To investigate writing programs in a high-level language including the syntax and the process.

High-Level Language Programs

High-level programming languages are closer to the pseudocode that we write and therefore are closer to our needs when programming. This is in contrast to assembly languages that are closely tied to machine languages and therefore are closer to the needs of the hardware.

The process of programming using a high-level language is a sequence of steps that is repeated until we are satisfied that the program meets the specified requirements:

Editing The high-level language program is a text file we create using a text editor. Any text editor can be used as long as it can store the program as an ASCII file. The file is referred to as the source file and contains the source program.

Compiling The source program is translated into machine language by the compiler. The compiler outputs a file which contains the machine language program. This called an object file.

Linking The object file is combined with other needed object files by the linker. The resulting file is referred to as the executable file and contains the executable program.

This is an important step that beginning programmers are often unaware of. It often is done automatically by the tool or program that does the compiling, or right before the program executes.

Executing The executable program is loaded into the memory of the computer and the instructions in it are carried out. This is also called running the program.

 

Developing Programs

Even in a high-level language it is surprisingly difficult to develop programs that do exactly what they need to do and that are completed on time. That is one reason why that programmers (people who write programs) are in such high demand.

Good programmers develop good habits which give them more of a chance to successfully complete their programs.

In this lab we will mention some of these good habits as you go along. Keep track of them.

Good programming skills often translate to good skills in other project areas such as project management.

 

Programming Language and Compiler

The high-level programming language used in this lab is C++. In order to write programs in C++ we need a compiler.

Source files in C++ are named with a .cpp extension. Object files are named with a .o extension. The C++ compiler, g++ is used to compile the source file into the object file.

The "Hello World" Project

In pseudocode we were not very concerned about the initial setup of our algorithm. In a programming language there are usually certain standard items that must be there for the program to compile.

One of the best software development skills that you can learn is to start with a minimal program, get it to compile and run, and add to it in small, incremental steps with a new compile and run between each addition.

Our first program is not going to do much at all, except printing out Hello World! on the screen.

This is a good place to start because it is the simplest place to start. Here is our beginning program. You will not be able to copy and paste the programs in this lab since you will learn the C++ syntax while typing. Edit this program by using the Notepad and save it as helloworld.cpp. DO NOT EDIT THE TITLE OF THE FIGURE IN THE FILE (i.e. Example 1.helloworld.cpp should not be edited). Edit only the code (the part in gray and in Courier).
Example 1Example 1

Program Details

This is a C++ program that corresponds to the pseudocode algorithm .

Print "Hello World!"
Stop

Note that there is a lot more detail here than there is in the corresponding pseudocode program. These details must be corrected or the program cannot be compiled and executed. Since there are more details it is easier to make mistakes. Looking at the source program notice the following:

Comments There are two ways to comment a C++ program. 1) anything between /* and */ is a comment, and 2) anything after // until the end of the line is a comment

Header Comments Typically there are some comments at the top of the source file called the header comments. It is a good habit to put in meaningful header comments including the name of the file, a brief description of what it does, and the name of the person who wrote the program (so you can blame them when it doesn't work).

#include - C++ programs are built from a core programming language, combined with various add-on features. These features are specified in a special statement called a pre-processor directive. The #include <iostream> statement in our first program includes add-on features which allow us to do various input and output operations. This capability is not included in the core C++ language.

main Every C++ program must have a  main function. The main function  contains the statements that will be executed by the computer when the program is run. The body of the main function is between the { } braces.

std::cout << The first statement in the main function uses the  << function to output the message "Hello World!" to the cout output stream. This function is one of the add-on features we got from including  <iostream>. Output is displayed on the terminal window where you are running the program.

Getting Started

You will keep three different windows open together. Keep all of three windows open for the rest of this lab.
             a. the local editor (i.e. your Notepad)
             b. the SSH File Transfer Client window (this is the GUI terminal window for the file transfer)
             c. the SSH Secure Shell Client ( I will call this window from now on the terminal window. It is the CLI window for the commands)
You will use both the SSH File Transfer Client and the SSH Secure Shell Client to connect to the loki machine on Kent campus in the same way you have been instructed in your previous lab.

This is the description of the cycle of steps that you will perform for all the projects of this lab.

  1. Start the Notepad and use it as the local editor. Edit the c++ file (hellowordl.cpp) or make corrections to your file and save it on your local machine.
  2. Switch to the SSH File Transfer Client and connect (if necessary), then transfer your helloworld.cpp from your local machine to the loki machine.
  3. Switch to the SSH Client (the shell window) and connect to loki (if necessary), then compile your file.
  4. If the file does not compile repeat step 1 and make corrections, then continue with step 2 and 3 until your program is correct and runs properly.
In the future you will learn to use an editor direclty on the loki machine that will aliminate this continuous transfering of files between your local machine and the remote machine.

Organizing the Project

The parts of this section give the basic process that we are going to follow on every program that we write. The descriptions in each subsection are specific to the first example. Try to get a sense of the process as you go through this section. If you have any questions as you are going through the steps let us know now on this simple example instead of wasting your time on the more complicated examples.

cd ..

at the prompt. (If you want to check if you are in your home directory,  type pwd in the loki terminal window. If you get as a result a path whose last word is your username, you are in your home). See your lab instructor if you are still unsure of what to do.

Create the following directory in your home directory by typing

mkdir labInC

at the prompt.

Change to this directory with the change directory command cd labInC.

Start the cycle....

Type the source code for helloworld.cpp from this lab experiment into the local editor window (using Notepad) and save it as helloworld.cpp

Transfer it on the loki machine inside the folder labInC directory via the SSH File Tranfer Client window

Go to the SSH terminal window. Check that you are in the correct folder. If you are not sure type

pwd

you should get something similar to this (with your username instead of mine)

/users/cs/lowlevel/llaguer0/labInC

For simple programs we can compile the program in one step by using the command in the loki terminal window:

g++ helloworld.cpp

If the program compiles with no errors it will generate a file named a.out  If you wish to specify the name of the executable file use the -o option as below.

g++ helloworld.cpp -o hello

This will generate a file named hello

The file hello (or a.out) contains machine language that when executed will perform the instructions of the source file.

Do an ls command to make sure the file is there.

If compiling the program produces any errors (for now you can ignore the warnings) you will need to fix these before you go on. Of course, since we wrote the program for you, either it was not copied correctly or we made a mistake. So start the cycle by identifing the copying errors, saving the file, tranferring it, compiling it and linking it again. If you still have a problem, ask us.

Execute the program

To run the program use the command:

./hello

or (   ./a.out   ). The general form is   ./prog_name 

Note that there are no spaces in the command!

This program prints Hello World! on the terminal screen.

You can now run the program as many times as you want by using this command.

The "Name" Project

Now lets write a C++ program that outputs your name instead of Hello World!.

We can use the helloworld.cpp source code as a starting point to create a program name.cpp.

It is a good habit when working on a program to start with another program that you know works.

Organizing the Project

Follow the general process and create the executable program.

Use the helloworld.cpp file as a starting point. Copy the file to make a new  source file in the labInC directory , name.cpp. You can copy it by using the command in the terminal window:

cp helloworld.cpp name.cpp

To see the file name.cpp inside the SSH File Tranfer Client window, put your cursor on the loki side and right-click on your mouse. Select "Refresh". You will see the file name.cpp that you have just created. Transfer back the file name.cpp to your local machine and prepare to make changes in your local editor window.

There are a couple of small changes to make to this program to change it to a good program that prints out your name.

Make each change in the following list one change at a time. After each change in the local text editor save your results and transfer the file back to loki. Then go to the loki shell window and compile the file again. You must do this every single time you make a modification in the source file. Make sure to get the program to successfully compile and run. Do not make all the changes at once without getting the program to successfully compile and run.

Again, you can compile the source code program with the command

g++ name.cpp -o name
 

1) Change the comments in the header to reflect the new name of the file, the purpose of the program, and your name

2) Change the output from "Hello World!" to your name.

Successful Program Development

At this point you have successfully written at least your first C++ program. Of course, the program we have created was quite simple and you might be thinking that all you did was change one line, and you still might not understand the rest. That is fine.

When a programmer is trying something new the best thing to do is to take a short example, make small changes to it, and make sure that those small changes worked.

To make sure that it works we need to be able to compile and link the program without any errors. We also need to run the program and make sure that it produces the correct answer (at least for the part that we changed).

If you learn to do this in small steps, you can be successful at programming. If not, then you won't be.

This even applies to your lab instructors. Of course we usually try the example first. We know that a mistake could easily have been made when copying the file, or that the person who wrote the program could have made a mistake.

The "I/O"  Project

I/O is shorthand for input and output. In pseudocode algorithms we are not very concerned with input and output. For input we just expect that the data got there somehow, and for output we are not very concerned with the format of how it appears.

However, in writing programs we are very concerned about input and output. This includes both what the input and output are and how they appear.

Lets see how to do input and output and how to use variables in a C++ program:

 Example 2

Program Details

Looking at the source program notice the following:

Input You can see that we added three lines to this program in order to do input.

First we use cout<< to ask the user to enter an integer

Next we use the int num; statement. This sets aside space for an integer  variable called num.We must do this so there is a place to store the number entered by the user. We could have called it almost anything, but num works well since it reminds us that the variable is a number.

This sort of statement is called a declaration. It is made up of two parts a type (int) and a name (num) followed by a semicolon (;). We need to specify the type of variable because that tells the compiler how much space to allow for it, as well as some other properties. We will be working, at least initially with only two types, int and double. We use int if we want to declare an integer variable. We use double if we want to declare a variable that can hold a number with a fractional part, like 2.34.

Finally we use  cin >> to get the number entered by the user and store it in the variable called num.
cin >> is another add-on feature we get from <iostream>

Comments and spacing in the code Comments are used in the code to describe what the next paragraph of code is going to do.

It is a good habit to put a comment in for every paragraph of code telling what it is for. It is also a good habit to a blank line between the paragraphs of code so we can easily tell them apart.

Indentation Notice how all the statements inside of main are indented the same amount, in this case 4 spaces. It is a good habit to carefully and cleanly indent your code. This makes it easier to read and follow. For now all the statements will be indented the same amount.

Variables Any variables that we want to use are declared with a type. The type determines what kind of values the variable can handle, and what we can do with the variable.

In this case we are using the type int which is a negative or positive integer.

All variables must be declared before they are used.

Organizing the Project

Follow the general process and create a new executable program.

The program will prompt you for a number to enter (enter a number) and it will output a message and the number in the terminal window.

Make sure to successfully follow all of the steps that we used before going on.

The "Square" Project

Lets see how to do some calculations with the numbers that we read in:

 Example 3

Program Details

Looking at the source program notice the following:

double We are using another type in place of int called double. Variables of type double can have values and do arithmetic on numbers with a fractional part.

Multiple Variables We use variables to store the result of a calculation from one step to use it later on. We can declare and use as many variables as we need.

Expressions We can write mathematical expressions using symbols such as + for addition, - for subtraction, * for multiplication, and / for division.

Input Variables Notice that the variable num is only used to store the number read in. We use another variable, square, to store the result of the calculation.

It is a good habit not to change the value of input variables. They might be needed later on in the program with their original value. Use another variable instead.

Separation of Input, Calculation and Output Notice how there are three distinct paragraphs of code, input, calculation, and output.

It is a good habit to separate the input of values, calculations, and the output of values in any program. This allows use to change the way that we prompt, or the way that we do the calculation, or the way that we output the result without changing the other paragraphs.

Organizing the Project

Follow the general process (i.e. the same sequence of steps that you have used to create inout)and create the executable program square.  Keep in mind:

This program is in the file square.cpp

When executed it will prompt you for a number to enter that it then displays the square of.

The "Temperature Conversion Project - Part 1"

Write a program that will read in a temperature in degrees Fahrenheit and display it in degrees Celsius.

Organizing the Project

Follow the general process and create the executable program.

Use the source file square.cpp as a starting point. Make a copy of this file and name it  tempFtoC.cpp .

Use the command    cp square.cpp tempFtoC.cpp  on loki and then trasfer the file tempFtoC.cpp back on your local machine OR open square.cpp on your local machine and save it as tempFtoC.cpp

Make the changes to the source file tempFtoC.cpp as described below.

When executed the program will prompt for a temperature in Fahrenheit degrees and display it in Celsius degrees.

Make sure to successfully follow all of the steps before going on.

Implementing the Project

There are a lot of small changes to make to this program to change it to a good program that converts from Fahrenheit to Celsius degrees.

Make each change in the following list one change at a time. After each change make sure to get the program to successfully compile and run. Do not make all the changes at once without getting the program to successfully compile

1) Change the comments in the header to reflect the new name of the file, the purpose of the program, and your name

2) Change the comments to reflect that we are going to enter a temperature in Fahrenheit, convert it to Celsius, and display the temperature in Celsius degrees.

3) Change the prompt to ask for a Fahrenheit temperature.

4) Change the statement int num; to double num;

5) Change the name of the variable num to fahrenheit. You will have to change the variable name in all places that it is used before the program will compile.

6) Change the name of the variable square to celsius. You will have to change the variable name in all places that it is used before the program will compile.

It is a good habit to use variable names that are descriptive of the real world item that the variable represents. When programmers have trouble naming variables it is usually because they don't understand what their program is about or what it is supposed to do in the real world.

7) Change the displayed message after cout <<  so that it tells you that you are displaying the temperature in degrees Celsius.

8) Change the formula for converting from Fahrenheit to Celsius. The conversion formula from Fahrenheit to Celsius is:

    double celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
 

Save and compile the tempFtoC.cpp file. Test it to make sure it works correctly
 

The "Temperature Conversion Project - Part 2"

Write a program that will read in a temperature in degrees Celsius and display it in degrees Fahrenheit.

Organizing the Project

Follow the general process and create the executable program.

Use the source file tempFtoC.cpp  as a starting point. Make a copy named  tempCtoF.cpp

Use the command cp tempFtoC.cpp tempCtoF.cpp  

Make the changes to the source file tempCtoF.cpp as described below.

When executed the program will prompt for a temperature in Celsius degrees and display it in Fahrenheit degrees.

Make sure to successfully follow all of the steps before going on.

Implementing the Project

There are a lot of small changes to make to this program to change it to a good program that converts from Fahrenheit to Celsius degrees.

Make each change in the following list one change at a time. After each change make sure to get the program to successfully compile and run. Do not make all the changes at once without getting the program to successfully compile

1) Change the comments in the header to reflect the new name of the file, the purpose of the program, and your name

2) Change the comments to reflect that we are going to enter a temperature in Celsius, convert it to Fahrenheit, and display the temperature in degrees Fahrenheit .

3) Change the prompt to ask for a Celsius temperature.

4) Change the displayed message after cout <<  so that it tells you that you are displaying the temperature in degrees Fahrenheit.

5) Change the formula for converting from Fahrenheit to Celsius to the formula for converting Celsius to Fahrenheit. :

Change this formula:

    double celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
 

to this formula:

double fahrenheit = (celsius * 9.0 / 5.0) + 32;

Save and compile the tempCtoF.cpp file. Test it to make sure it works correctly.
 

Programming Good Habits


In your local editor create a file goodhabits.txt and type in it the good habits that a programmer must acquire. Transfer this file to loki in the same folder where you have transferred all the previous files generated in this lab.



Submitting the Directory Structure

We want to see the directories and files that you created. Go to loki terminal window and move to your home directory by entering the command cd. Then enter the command:

ls -lhR labInC

This will display a list of all your directories and files in directory labInC on the terminal window where you entered the command.

Look at the sizes of all the source files and executable files. Is the size of the executable file larger or smaller than the source file? What do you think is the reason for such difference? If do not know the answer you better find out by asking us.

 

Use the cat command to concatentate into one file all the six  files you have created/modified and the goodhabits.txt  file.
Before executing the cat command, make sure that all the files are in the same directory.

cat -n helloworld.cpp name.cpp inout.cpp square.cpp tempFtoC.cpp tempCtoF.cpp goodhabits.txt > labInCfiles.txt

Transfer back on your local machine labInCfiles.txt using the SSH File Transfer Client (if you do not see it, remember to Refresh the window (right click on the remote window and press "Refresh")).  Print the file labInCfiles.txt and turn it in to your lab instructor. If you prefer to submit the electronic version, the deliverable should be sent no later than noon on April 6th.

 

Congratulations! You have completed the Lab.