Introduction to C++ / Lab 0

Start | Variables | Input/Output | Branching | Looping | Functions | Arrays
Introduction to the introduction

At the end of this introduction I've included some strongly-recommended exercises, but this lab itself is ungraded and you cannot even turn it in. Please see me or a ninja if you want feedback on your work. The exercises are intended to be brief and simple, and the time you invest now will save you much time completing the first graded lab (01) due next week. If you struggle with many lab 00 issues while completing lab 01, the ninjas might ask you to go back and complete lab 00 before helping you with lab 01.

This week, you should become familiar with Linux, an editor, and the basics of C++. The online C++ tutorial is a very good review. By next week, you should be familiar with all the sections up to Character Sequences. There are some topics which you can safely ignore. We will probably not cover them soon, or perhaps not at all:

Topics covered in the tutorial are also covered in the text in sections 1.1-1.4. Please ignore the discussion on pointers for now. We will get to them soon enough.

Any references to ponies, unicorns, or other mythical beasts are incidental and are because these materials are adapted from Andy Danner's introduction to previous semesters of the course.

Recommended required exercises

  1. Type the Hello World program below into a file. Compile and run it.
  2. Spring 2011 CS21 Lab 1, exercise 2: Using C++ instead of Python, write a program that asks the user for an integer n and then prints all of the cubes between 1 and n inclusive. Compile and test your program.
  3. Write a program contatining a function bool isAnA(float avg) that determines if the function's argument (representing a student's average score) is an A (above 90%). Compile and test your program.
  4. Complete and test the function minimum in cs35/inclass/w01/array2.cc.



Getting started: Hello World
Below is a sample program:
#include <iostream>
using namespace std;

// This is a one line comment.
// The first C++ program, hello world

/* 
  Here is the format for
  multiple line
  comments.
*/

// Any executable program must have one function called main.
int main() {
  cout << "Hello world of CS35\n";

  return 0;
}
Note the following features of the basic program:

To run a program, we must first save the code using an editor, then compile and run our program. The syntax for compiling is

g++ <inputfile> -o <outputfile>
for example
g++ hello.cc -o hello
We run the program using ./hello. If we change the source (.cc file), we must recompile with g++ before running ./hello. If there are any errors, the ./hello file will not be created/recreated.



Variables

Variables are named containers for holding data. In C++ all variables must be declared before use. A variable can only have a single type within a particular scope (the part of the program where a given variable is . Valid basic types are int, float, double, char, bool and string. To use the string type, you must add #include <string> and (typically) using namespace std; to the top of your program.

Examples for declaring variables are shown below.

 int x;      // declaring x to be an int
 x = 7;      // assigning x an initial value
 x = x + 3;  // updating x

 float winpct = 0.352;   // You can assign a variable when you declare it
 double pi = 3.1415926;  // doubles are more precise than float

 int i, j, k;  // You can declare multiple variables on a single line
 
 float w, y, z=1.5;  // only z has the value 1.5, w and y are undefined
 
 char let='A';                            // use single quotes for chars
 string phrase = "unicorn corn holders";  // use double quotes for strings

 bool possible, probable; 
 possible=true;   // valid bool values are true/false (lowercase)
 probable=false;  
Note the semicolons galore. C++ expects them. You'll forget them. You'll learn. g++ almost never says "You missed a semicolon" even though that might be the only problem with your program.

On most variable types, you may use the following operators. Some may not apply depending on type.



Input/Output
C++ uses cout and cin to print output to the terminal and read input from the terminal, respectively. (These are called standard out and standard in.) Both are in the iostream library; you need to #include <iostream> and using namespace std; to use them.

Examples:

  int x = 5;
  cout << "Hello. x=" << x << endl;
  cout << "How many ";
  cout << "lines will this ";
  cout << "print on";
  cout << endl;

  cout  << "Enter a number: ";
  cin >> x;
  cout << "You entered " << x << endl;

endl is similar to the newline character ('\n'). You can also use the newline character either as a character alone or within a string.



Branches with if/else
The syntax for branching in C++ is shown below:
// one way branch
if ( <Boolean expression> ) {
  <true body>
}

// two way branch
if ( <Boolean expression> ) {
  <true body>
} else {
  <false body>
}

// multibranch
if ( <Boolean expression 1> ) {
  <true 1 body>
} else if ( <Boolean expression  2> ) {
  // if first expression is false, second is true
  <true 2 body>
} else {
  // if both expressions are false
  <false body>
}
You may use the following Boolean operators:

Loops

For loop syntax is substantially different than for loops in Python:

for ( <initialization>; <continue?>; <update> ) {
 <body>
}
The for loop declaration has three (optional) parts:

For example:

for (int i=0; i<10; i++) {
  cout << "i = " << i << endl;
}
will print ten lines, one for each value of i from 0 to 9.

While loop syntax is more familiar:

while ( <Boolean expression> ) {
  <true body>
}
The while loop checks the loop condition (the boolean expression) first and executes the body if true. C++ has a similar do-while loop that always executes the body once first, then checks the condition and re-runs the loop if the condition is true.
do {
  <body>
} while ( <Boolean expression> );

Inside a loop you can use break or continue statements. break immediately stops executing the loop and execution continues with the code below the loop block. continue immediately stops executing the loop but instead prepares to run the next execution of the loop. If the loop is a while loop it evaluates the boolean loop condition and either re-runs or exits the loop; for a for loop the update expression is run and then the loop condition is evaluated, with the for loop re-running or exiting based on whether the loop condition is true or false.

See forLoop1.cc, forLoop2.cc, whileLoop1.cc and whileLoop2.cc for examples.



Functions

Functions may take parameters as input and return a single value of a specific type. A function declaration specifies the function's name, return type, and the number and type of all parameters. A function definition includes the code to be executed when the function is called. Functions must be declared before they are called.

Arguments are typically passed to C++ functions by value. This means a copy of each variable's value is made before the body of the function executes. Any modifications to the parameters in the function are not visible to the callee. It is also possible to pass arguments in C++ by reference (in which case modifications are visible to the callee) but we will not use this feature much in CS35.

See function1.cc for an example.



Arrays
C++ arrays are a sequential collection of other data in memory -- much like a poor man's list -- storing multiple items of the same type. For now, we will use only statically-sized arrays, meaning you must know the size of the array when you declare the array and compile the program. (We will discuss dynamically-sized arrays in future weeks.)

To declare an array you must specify its type, name and size, e.g.:

  int a[10];
Individual elements can be accessed by indexing:
  cout << "first item = " << a[0] << endl; 
  a[9] = 25;  // sets the last item
Sorry Python users, there is no array/list slicing or negative indexing.

It is also possible to declare multi-dimensional arrays:

  int b[10][100][42];  // a 3-d array containing 42000 ints
Using multi-dimensional arrays you can efficiently write hard-to-understand code, because it is easy to confuse the meaning of the different array dimensions.

If you don't know the size of an array at compile-time but will know at run-time, there is a non-standard way to declare an array that acts like a statically-sized array. For example:

  int size;
  cout << "Enter the size of the array:  ";
  cin >> size;

  int a[size];
For most C++ compilers this creates an array of size items (for whatever size the user enters) but is non-standard and is discouraged. You might want to use this trick for lab 01, but it's better to use dynamically-sized arrays once we discuss them.

To declare a one-dimensional array as a parameter to a function you declare its name and type but do not need to declare its size, e.g.: int a[]. Arrays do not store their size, so if you want the function to know an array's size you need to pass the size as a second argument:

  void printArray(int a[], int size) {
    // ...
  }
To call a function that takes an array as an argument, pass only the name of the array:
  printArray(myItems, 42);

To declare a multi-dimensional array as a parameter to a function, you need to declare at least some of the sizes of the dimensions (all but the first dimension). For example, you could declare a function that accepts the array b above as:

  void printArray(int b[][100][42], int size1, int size2, int size3);

See array1.cc and array2.cc for some example uses of arrays.