Lab 1. Introduction to Linux and C++

[Linux shell illustration]

Welcome to CSCI 135. This first lab has two jobs: get you comfortable working at a Unix terminal, and get
your first C++ programs compiling and running. Neither is hard, but both need to become automatic, because
every remaining lab this semester assumes them.


Working in the terminal

You already met the terminal in CSCI 127. You need only a handful of commands to work comfortably in one:
ls, cd, pwd, mkdir, cp, mv, rm.

A brief summary:

pwd print the current working directory
ls list files in the current directory
ls path/to/a/directory list files in that directory
cd path/to/a/directory change directory
cd .. go to the parent directory (one level up)
mkdir newdirectoryname create a new directory
cp file1 file2 copy file1 and call the copy file2
mv file1 file2 rename (move) file1 to file2
rmdir directoryname remove an empty directory
rm file remove file — there is no undo, and no trash can

These are some useful directory shortcuts:

.   the current directory
..   the parent directory of the current one
~   your home directory
Where you are, and what the shortcuts mean THE DIRECTORY TREE / home yourname csci135 lab1 smaller.cpp leap.cpp Downloads you are here pwd prints this path FROM lab1, THE SHORTCUTS MEAN . this directory — lab1 .. one level up — csci135 ~ your home — yourname cd .. moves up one level; cd ~ jumps home from anywhere.

And these additional commands:

touch newfilename create a new, empty file
chmod <options> file change file permissions (read +r, write +w, execute +x)
man command the manual page for command

Make yourself a directory for this course before you write anything, so your work does not end up scattered
across your home directory:

$ mkdir ~/csci135
$ mkdir ~/csci135/lab1
$ cd ~/csci135/lab1
$ pwd
/home/yourname/csci135/lab1

Do the same for every lab this semester.

For more practice, try this Unix tutorial.


Your editor, and how your code should look

You will be writing your programs in the gedit text editor. Open it and set the tab width first: click
Text Editor in the upper left corner of the screen, choose Preferences, click the Editor tab, and set
Tab width to 4.

Regarding coding style: it is of paramount importance that all of your code is correctly indented. Always
use tabs to indent lines of code — never spaces.
In addition to the automatic grading, we will spot check
your code by hand and will reduce your grade if the indentation is wrong or if spaces were used instead of
tabs.

With the tab width set to 4, one tab shows as four columns, which is how every code example in this course is
formatted.


Writing and compiling a C++ program

Consider the following program, which asks for your age and prints it back:

#include <iostream>
using namespace std;

int main()
{
    cout << "Enter your age: " << endl;
    int age = 0;
    cin >> age;
    cout << "Your age is " << age << "." << endl;
    return 0;
}

Type it into gedit and save it as age.cpp in your lab1 directory.

A .cpp file is just text — the computer cannot run it directly. The compiler g++ translates it into
an executable file that it can run. To compile age.cpp and call the executable age:

$ g++ -o age age.cpp

Then run it. The ./ in front is not optional: it tells the shell to look for the program in the current
directory
.

$ ./age
From source file to running program age.cpp what you typed — just text g++ translates age the executable — a new file ./age runs Enter your age: 19 Your age is 19. the terminal You compile once. After that you can run ./age as many times as you like — but every time you change the .cpp file, you must compile again.

If you compile without giving an output name, the executable is called a.out, which you run the same way:

$ g++ age.cpp
$ ./a.out

That works, but naming your programs is worth the extra typing — otherwise every program you write this
semester is called a.out, and each one overwrites the last.

When it does not compile

It will not compile the first time. That is normal, and reading the error is a skill worth building
immediately. Two rules that will save you a lot of time:

How to compile and run programs on your own computer

You need three things:

If your computer runs Linux or macOS, you already have all three, though on macOS you may be prompted to
install the command line developer tools the first time you type g++. Let it.

If you are on Windows, follow this tutorial to install the Windows Subsystem for Linux:
Linux on Windows Tutorial.


A little C++ to get started

The tasks below need only a few pieces of C++. You will have seen all of these ideas in CSCI 127; what is new
is the way C++ writes them.

Every variable has a declared type, and you must say what it is before you use it:

int count = 0;         // a whole number
double average = 0.0;  // a number with a fractional part

Input and output go through cin and cout:

int x;
cout << "Enter a number: ";
cin >> x;                        // reads a number the user types
cout << "You typed " << x << endl;

endl ends the line. You can chain as many << as you need in one statement.

Decisions use if, else if, and else. Note that the condition goes in parentheses, and that the test
for equality is ==, not =:

if (x < 0)
{
    cout << "negative" << endl;
}
else if (x == 0)
{
    cout << "zero" << endl;
}
else
{
    cout << "positive" << endl;
}

The modulo operator % computes the remainder of a division. 37 % 10 is 7, because 7 is what is left
over when 37 is divided by 10. It gives you a quick way to ask whether one number divides another evenly: if
year % 4 is 0, then year is divisible by 4. You will need this in Tasks C and D.


Task A. Find the smaller of two integers

[two cats illustration]

Write a program smaller.cpp that asks the user to input two integer numbers and prints out the smaller
of the two.

Example

$ ./smaller
Enter the first number: 15
Enter the second number: -24

The smaller of the two is -24

Test it with the two numbers in the other order, and with two numbers that are equal. Decide what your program
should print in that last case, and make sure it does.

Task B. Find the smallest of three integers

[three cats illustration]

Write a program smaller3.cpp that asks the user to input three integer numbers, and prints out the
smallest of the three.

(Hint: there are many possible solutions here. One strategy: given numbers x, y, and z, first compare
x and y, take whichever is smaller, and compare that with z.)

Example

$ ./smaller3
Enter the first number: 23
Enter the second number: 76
Enter the third number: 37

The smaller of the three is 23

Test it with the smallest number in each of the three positions. A program that works when the answer comes
first and fails when it comes last is a very common outcome here.

Task C. A leap year or a common year?

Write a program leap.cpp that asks the user to input an integer representing a year number (1999, 2016,
etc.). If the input year is a leap year according to the modern Gregorian calendar, it should print
Leap year, otherwise print Common year.

In the modern Gregorian calendar, a year is a leap year if it is divisible by 4, but century years are
not leap years unless they are divisible by 400. Here is the rule as pseudocode:

if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)

This means that 2012, 2016, 2020, and 2040 are all leap years.
However, the century years 1800, 1900, 2100, 2200, 2300 and 2500 are NOT.
Yet 2000, 2400, and 2800 still are.

Example 1

$ ./leap
Enter year: 2016

Leap year

Example 2

$ ./leap
Enter year: 2017

Common year

Test all four branches of that pseudocode. The century years are where this goes wrong: check 1900 (common)
and 2000 (leap) specifically, because a program that only handles “divisible by 4” gets both of them wrong
and still passes every other test you are likely to try.

Task D. Number of days in a given month

Write a program month.cpp that asks the user to input the year and the month (1–12) and prints the
number of days in that month, taking leap years into account.

You may not use switch case or arrays, even if you already know these language constructs.

Example

$ ./month
Enter year: 2017
Enter month: 5

31 days

Check February in both a leap year and a common year, and check month 12. If you find yourself writing twelve
nearly identical branches, stop and look at the list of month lengths again — there are only three distinct
answers.


How to submit your programs

Each program should be submitted through Gradescope

Write separate programs for each part of the assignment.
Submit only the source code .cpp files, not the compiled executables.
Each program should start with a comment that contains your name and a short program description, for example:

/*
Author: your name
Course: CSCI-135
Instructor: their name
Assignment: title, e.g., Lab1A

Here, briefly, at least in one or a few sentences
describe what the program does.
*/