lab01 : Getting started with C++

num ready? description assigned due
lab01 true Getting started with C++ Wed 04/04 08:00AM Mon 04/09 12:00PM

Introduction

Your first lab for this week is an introduction to programming on CSIL and in the Computer Science lab. You will write your first 2 C++ programs.

THE DEADLINE TO SUBMIT THIS LAB IS MONDAY, 2/9 BY NOON. Details on how to submit are further down in this document.


For this first lab, you will do the following:

  1. Create a College of Engineering online computer account, if you do not have one already.
  2. Learn how to open a terminal on a lab or personal computer.
  3. Learn how to edit a text file used for writing programming code.
  4. Write actual programs in C++.
  5. Compile your programs and see if they run.
  6. Learn how to submit your programs for grading.

Step 1: Create an Engineering Account

To log in to the machines in the Computer Science labs, or to connect remotely, you will need a College of Engineering account.

At this point, please go to THIS LINK and view the important presentation from Engineering Computing Infrastructure on the College of Engineering accounts and computer labs.

You can create an account online at https://accounts.engr.ucsb.edu/create.

If you are enrolled in any CoE course this quarter (including CS16), you can create your account immediately. If you are not, you will need to contact the ECI Help Desk at help@engineering.ucsb.edu.


Step 2: Open a Terminal

The first step in every assignment will be to open a terminal window, which will be the environment you use to write, compile, and run your programs.

If you are working on your laptop, whether Windows, Mac or Linux, the instructions below will tell you how to connect to a CSIL computer, like:

You will get much better performance on those individual machines, because they are much less heavily loaded and have newer hardware, as compared to csil.cs.ucsb.edu.

    Step 2a: Opening a Terminal on a Phelps Lab Machine

  1. Log in to the machine using your account credentials (i.e. your username and password) created in Step 1.
  2. Find the Activities menu, which is in the top-left corner of the screen. Click on it to open the menu.
  3. Next, type "shell" in the search box. Then click the "Terminal" application which appears.
  4. You should now see a terminal window open. You can open more tabs or windows from the Terminal applications menu.

    Step 2b: Connecting to CSIL via SSH on Mac OS X or Linux

    To get started on Mac OS X or Linux, you first need to open a terminal program. This involves slightly different steps on either OS.

    On Ubuntu (an example of a Linux OS):

  1. You will first want to find the search menu. It appears at the top of the Unity bar:
  2. Ubuntu Search Menu
  3. Click on that icon to open the search menu. Then type "terminal" and click on the "Terminal" application which appears:
  4. Ubuntu Terminal Application

    On Mac OS X:

  5. Open the "Terminal" application. It is found inside the Applications folder of your main drive, inside the Utilities subfolder. The icon looks like this:
  6. Mac OS X Terminal Icon You can also find it using Spotlight by typing "terminal" and pressing ENTER.

    Once you have a terminal window open on your machine, you next need to connect to the CSIL server remotely.
    You will do this using a UNIX command (an internet protocol, really) called SSH (short for Secure Shell).

    Type the following command in your terminal, replacing USERNAME with your CSIL username:

    $ ssh USERNAME@csil-10.cs.ucsb.edu

    SSH will first ask you a question which looks like this:

    The authenticity of host 'csil.cs.ucsb.edu (128.111.43.14)' can't be established.
    RSA key fingerprint is 90:ab:6a:31:0b:81:62:25:9b:11:50:05:18:d3:1a:b5.
    Are you sure you want to continue connecting (yes/no)? 

    Type yes and then ENTER to continue. It will next ask for your CSIL account password. When you type it in, nothing will show on the screen (not even dots). However what you type is still being sent and once you are finished with your password, you can press ENTER to login.

    You should now be remotely connected to CSIL! You can make sure by typing the following command (which will tell you what machine you are currently issuing commands to):

    $ hostname

    This should show csil-10.cs.ucsb.edu. You can now do anything you could normally do in a terminal window in CSIL or the Phelps lab (except run graphical programs).

    Extra Note: Graphical Forwarding

    This is not required or necessary to use CSIL remotely, so if you are not interested, go ahead and skip this part.

    If you have an X windows system installed you can get graphical applications running by forwarding X from CSIL to your machine. To do this, add the -X option to the SSH command like this:

    $ ssh -X USERNAME@csil-10.cs.ucsb.edu

    X windows is almost always installed on graphical Linux, and can be installed on Mac OS X as XQuartz (which can be found at http://xquartz.macosforge.org/landing/).

Step 2c: Connecting to CSIL via SSH with PuTTY

To connect remotely on Windows machines, we recommend using a program called PuTTY. This program is a well-known and widely-used SSH client for the Windows OS.

First, download the program from http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html. You only need the executable file putty.exe, but feel free to download any other programs that you want. The page includes portable versions and a version with an installer. Always make sure to download PuTTY from this site, so that you can make sure it is the correct program.

Once downloaded, run PuTTY like you would open other programs. If you just download the putty.exe file, you can open it from your downloads folder directly. You can also move it to any other location on your machine and open it from there. If you used the installer, open PuTTY from the Start Menu.

When PuTTY opens, you should see a window that looks like this:

Empty PuTTY window

Type csil.cs.ucsb.edu into the box labeled “Host Name (or IP address)”. Leave the “Port” setting at 22 and leave the “SSH” button checked. The window should now look like this:

Completed PuTTY window

Then click on the “Open” button to connect. PuTTY will then show a prompt which looks like this:

PuTTY Host Key Prompt

Click “Yes” to accept and have PuTTY remember the CSIL key.

Once a connection is made, CSIL will ask for both your username and then your password. Type in your CSIL username and password. The password will not be shown on the screen, but the characters you type are being used. This step will look something like this (with your username instead of “username”):

PuTTY Login Prompt

Once you have logged in successfully, you should be connected remotely to the CSIL server. Run the following command to make sure (this command shows the full host name of the machine you are logged in to):

$ hostname

This command should output csil.cs.ucsb.edu. You can now do anything in this terminal window that you could do on a CSIL machine or a Phelps lab machine, except run graphical applications.

If you want to run graphical applications, instead of using puTTY, you can use other programs, such as MobaXterm.


Step 3: Create CS16 and Programming Assignment 01 Directories

Now that your environment is set up, you next will need to create a directory (a folder is also called directory in Linux) that will contain all your work for the course. Then, inside that directory, you will need to create another directory to contain your work for this assignment.

To create your CS16 directory, use the mkdir command. Type the following in the terminal and press enter:

$ mkdir cs16

The $ represents the terminal prompt; you will not type this character. Whenever you see it, that means that the following command is intended to be typed into the terminal window and run by pressing enter.

You can see list of files and directories in the current directory with ls command. Type the following in the terminal and press enter:

$ ls

You should be able to see the directory you just created i.e. cs16

Now move into that new CS16 directory with the cd command as follows:

$ cd cs16

And create and move into a LAB 01 directory:

$ mkdir lab01
$ cd lab01   

At any time, you can check what directory you are current in with the command pwd. It will output the full path of the current directory. For example, if you are inside your lab01 directory, you might see:

/cs/student/yourcsilname/cs16/lab01

Knowing how to navigate a UNIX environment and issue UNIX commands is VERY valuable to computer scientists and engineers. To learn more UNIX commands, there are lot of cool Web resources and books on the topic. This is one website I found that has a good introductory page: https://www.tjhsst.edu/~dhyatt/superap/unixcmd.html.


Step 3: Editing text files for programming

Let us take a little detour on how to best create and modify text files. These will carry all the code (regardless of computer language) that we want to assemble, compile, and execute.

You are surely all familiar with Microsoft Word as a widely-used “word processor”, but please DO NOT USE MS WORD TO WRITE PROGRAMS!!! :)
Instead, for programming, you have access to a very large number of excellent text editors - most of them are free to use! I will introduce you to just 4 of them below. If you already have a favorite editor and know how to use it well, then you do not have to change and use something else, just for this class.

In fact, AND PLEASE NOTE THIS, no one editor is necessarily “better” than another. It is a matter of your preference. This is a great time for you to explore multiple options and then pick one. Once you pick an editor of choice, STICK WITH IT!
As you progress in your Computer Science education and, subsequently, your careers in CS, make sure you end up learning how to use more than one editor. You can still have a “favorite” that you excel at using, but at least have a working familiarity with others.

  1. emacs for UNIX-based OS
    1. emacs is a very popular editor that's available on just about every UNIX machine (including the ones that you're using in the CS labs) and UNIX-based machines (like MacOS computers).

      To run emacs on a UNIX machine or a MacOS machine, open up a terminal (see above for how to do that on Macs) and type:

      $ emacs

      To edit a file (let's say it's called "filename"), you'd type:

      $ emacs filename
      </p>

      To learn how to use emacs, there is no substitute for PRACTICE!!! Of course, there are multiple online resources that you can look at (especially given emacs' popularity) and here are some of them:

    2. emacs tour from the GNU organization (makers of emacs)

    3. emacs commands - a handy reference card

    4. a beginner's guide to emacs
  2. vim for UNIX-based OS
    1. vim (or sometimes called vi) is another popular editor that's also available on just about every UNIX machine (including the ones that you're using in the CS labs) and UNIX-based machines (like MacOS computers).

      To run vim on a UNIX machine or a MacOS machine, open up a terminal (see above for how to do that on Macs) and type:

      $ vim

      To edit a file (let's say it's called "filename"), you'd type:

      $ vim filename
      </p>

      Again, to learn how to use vim, there is no substitute for PRACTICE!!! Again, there are multiple online resources that you can look at and here are some of them:

    2. About vim

    3. vim commands - a handy reference card

    4. another reference cheat sheet for vim
  3. Sublime Text 2 for Windows OS and MacOS X --- see the product website (it's a program that you'd have to download)
  4. Notepad++ for Windows OS --- see the product website (it's a program that you'd have to download)

Step 4: Create and edit a file containing a C++ program

Now it’s time to write the program! If you’re comfortable with one of the reviewed text editors, then go ahead and use one. Otherwise, here are some emacs hints and some vim hints.

This assignment only needs you to write a program that prints out two lines on the display, and nothing else. The output should look exactly as follows (no space before or after each line, except the 2 newlines):

Hello, world!
CS16 Spring 2018.

Start with a “skeleton program” (or template) that contains the necessary structure but that does not do anything:

#include <iostream>

using namespace std;

int main() {
    // Your printing code should go here
    // By the way, when a line in C++ starts with //, it's a comment

    return 0;
}

Go ahead and type this in to the hello.cpp file. Alternatively, you can copy and paste it directly from this page.

Next, you will need to replace the comment with code to print out the expected output. Comments in C++ are lines that start with // or text between /* and */. The second type can span multiple lines.

Important note: For students familiar with Python, remember that lines starting with the # character are not comments in C++. Rather, they are important include lines that allow your program to use the input and output functionality. Make sure to copy those lines in your program as well. Only // or /* create comments in C++.

To print out text to the terminal, you can use the cout stream. To output something use the << operator as shown below:

cout << "This will be printed out to the terminal" << endl;

The endl command will cause a newline (i.e. a carriage return) to be printed and the next print to go on the next line.

You can adapt this line to achieve the objective of the assignment. Remember that we need to print two lines, each with a newline at the end. You can do this with one or two statements.


Step 5: Compile the Code

Now that the code is written, we need to compile it. This will be done using a special program called a compiler.

Before moving on, make sure you save your code and close the text editor. The following step will be done in the terminal.

For C++ code we will use the g++ compiler that’s built-into many UNIX machines (it even works on most MacOS terminal programs). You can compile the hello.cpp file into an executable called hello with the following command:

$ g++ -o hello hello.cpp

This will compile your code and make an executable version of it. Specifically, it will tell the compiler to take the source code file hello.cpp and compile and link it to an executable called hello.

If the compilation is successful, you won’t see any output from the compiler, but if you issue a UNIX ls command, you should see a new file has appeared: one called hello. You can then use the following command to run your program:

$ ./hello

Which means “in the current directory, as represented by the . character, run the program hello”. You should then see the program output the two expected lines.

The other possibility is that the program may not compile successfully. What to do then?
If you run the g++ command and are unsuccesful with your compilation, then you might see an output that looks like this:

hello.cpp: In function ‘int main()’:
hello.cpp:10:1: error: expected ‘;’ before ‘}’ token
 }
 ^

The compiler will try to give you hints on the line (in this case, it is complaining about line 10) where the error occurs, and also about what the error is (in this case a missing semicolon). You will also note that, in this case, an output executable file is not produced.

If you encounter an error, use the compiler hints and examine the line in question. If the compiler messsage is not sufficient to identify the error (which happens more than sometimes), you can search online to see when the error occurs in general. Once you have fixed the error, run the compilation command again. De-bugging a program code is a necessary ritual in almost all programs written (even those written by expert coders). More on that in a later class.


Step 6: Write your second C++ program: COINS.CPP!

Write a program, called coins.cpp that allows the user to enter a number of quarters, dimes, and nickels and then outputs the monetary value of the coins in cents. For example, if the user enters 2 for the number of quarters, 3 for the number of dimes, and 1 for the number of nickels, then the program should output that the coins are worth 85 cents.

Start off, like with the previous program, by starting up your favorite text editor (emacs, vim, or something else that can create simple text files – AGAIN, NOT MS Word). Call your new file coins.cpp.

Before you write the program, think about what it would entail to get this code to work. In other words, come up with the step-by-step algorithm.

The program should print a string of text to the terminal (that is, the computer display, also known as the ‘standard output’ device) before getting each piece of input from the user. A session should look exactly like the following example (including whitespace and formatting), with possibly different numbers for inputs and the output (so the following is just ONE example of how the program might run, but the FORMATTING has to be exactly the same in order for you to get full credit):

Enter number of quarters:
3
Enter number of dimes:
2
Enter number of nickels:
4
The coins are worth 115 cents.

Each string printed by the program should include a newline at the end, but no other trailing whitespace (i.e. do not have extra space characters at the end of the line).

HINT: Start with this template that contains the necessary structure but that does not do anything:

#include <iostream>

using namespace std;

int main() {
    // 1. Declare your variables -- HINT: They are all integers
    // 2. Put a cout statement to print something to the display (a.k.a standard output)
    // 3. Put a cin statement to get something from the keyboard (a.k.a standard input)
    // 4. Repeat parts (2) and (3) twice more
    // 5. Calculate the total value of all the coins based on the 3 inputs you got in prior steps
    // 6. Put a cout statement to print that total value

    return 0;
}

The program example that I showed you in the 1st lecture should contain several clues as to how to complete this program.

Step 7: Compile your second C++ program

Before moving on, make sure you save your code and close the text editor. The following step will be done in the terminal.

Again, we will use the g++ compiler to create an executable called coins with the following command:

$ g++ -o coins coins.cpp

This will compile your code and make an executable version of it. Specifically, it will tell the compiler to take the source code file coins.cpp and compile and link it to an executable called coins.

If the compilation is successful, you will not see any output from the compiler, but if you issue a UNIX ls command, you should see a new file has appeared: one called coins. You can then use the following command to run your program:

$ ./coins

Step 8: Submit your program for grading

Once you are satisfied that your programs are correct, then it is time to submit them.

Please remember that you must submit the programs to obtain any credit for the assignment; just completing the programs is not enough.

For this example, let us assume that you only had to submit 1 program (hello.cpp). This applies to ANY C++ program you submit via this system:


In this course we will use the submit.cs.ucsb.edu system. You can make a submission from either the command line on any CS machine, or from a Web browser.

If you do not have a submit.cs account, you will first need to create one. This can be done at https://submit.cs.ucsb.edu/form/user.

Once you have an account created, login at https://submit.cs.ucsb.edu/session.

Next, you need to join the CS16 course. Look for the “Join Class” link at the top of the page. It is in the top bar, as seen below:

submit.cs Top Bar

Once you see the list of all courses, click on the “Join CS16_s18_matni” button.

You should then see CS16 appear on your homepage when logging in to the submit.cs system. Click on the course now.

Now find “lab01” and click on the “Make Submission” button. It looks like this:

Make Submission Button

This is the Web interface for submitting your code for the assignment. You can now upload your source file directly on this page. The browser will open a dialog box and you will need to navigate to the directory containing your hello.cpp file and select it.

Once your file is uploaded, click “Submit 1 File”:

Submit 1 File Button

Once you submit, you should see a page detailing your submission. The system will automatically grade your program and will show you the results on this page after about a 1 minute delay.

You can alternatively submit your code from the command line (i.e. in the terminal) on any CS machine, including the Phelps lab machines or the CSIL server. You can also use this method when logged in remotely. To submit the the hello.cpp file to this assignment by running the command:

$ ~submit/submit -p 979 hello.cpp coins.cpp

The program will ask you to login with your submit.cs username and password. The password will not be printed to the terminal, but what you type will be used. It will also offer the option to save your credentials, so that you do not have login next time you submit. You may choose to do this or not. After the submission succeeds, you should see the program output something like:

Results will be available at: https://submit.cs.ucsb.edu/submission/xxxxx

You can copy this URL and paste into a Web browser to reach the same submission result page as described above.


Step 9: Check Submission Results

After the 1 minute delay, the submit system will show your score and give you feedback on your submission. Refresh the webpage after a minute to see this information. This usually takes one of three forms:

A correct submission with a score of 100. This means that your program passed all the tests for this assignment. Once you get to this point, you are finished with the assignment and will receive full credit. This case will look like this:

Correct Submission.

An incorrect submission with a score of 0 to 99. This means that your program failed 1 or more of the tests. For this assignment, the system will show both the expected output and the output your program generated side-by-side so that you can see what went wrong. You will need to fix your program, and then do Step 8 again to re-submit. This case will look like this:

Incorrect Submission.

Or a submission for which compilation failed. This means that your program caused compilation errors when the system tried to compile it. You will need to interpret the compiler output and fix the errors. The system will show you the compilation command that failed along with the full error message. This case will look like this:

Compilation Failure.

You may submit your program multiple times before the deadline. You should really only submit after local compilation does not produce any errors and runs as expected - that is the most efficient and preferred way to do things. The score of the last submission uploaded before the deadline will be used as your assignment grade.


Step 10: Done!

Once your submission receives a score of 100/100, you are done with this assignment. Congratulations on completing your first C++ programs!

If you are in the Phelps lab or in CSIL, make sure to log out of the machine before you leave. Also, make sure to close all open programs before you log out. Some programs will not work next time if they are not closed. Remember to save all your open files before you close your text editor.

If you are logged in remotely, you can log out using the exit command in UNIX:

$ exit