Introduction to C++

Start | Variables | Input/Output | Branching | Looping | Functions | Arrays
Getting started with the basics

As you may have noticed there are very few computers in this classroom. You may bring a laptop to work on in class exercise provided (1) you are willing to share with other students so that everyone has an opportunity to look at live code during class (2) you are using the laptop for class related purposes (no facebook, amazon, twitter, WOW, Pittsburgh sports and mini ponies blog, etc.) (3) you can remotely connect to the CS network through SSH. In general, you should attempt the example exercises on your own outside of class and prior to lab on Friday.

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 not be covering them anytime soon (or maybe 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.

Below I will quickly cover the basics of C++, but you should follow up with the tutorial and practice writing your own programs.

Getting started
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.cpp -o hello
We run the program using ./hello. If we change the source (.cpp 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. Valid basic types are int, float, double, char, bool and string (to use the string type, you must add #include <string> to the top of your program. Examples for declaring variables are shown below. For anyone coming from C, variables can be declared at any point in C++, not just the top of the block (though many people still prefer to keep this convention).


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

 //you can assign a value to a variable when you declare it
 float winpct=0.352;     //way to go Pittsburgh Pirates
 double pi = 3.1415926;  //more precise than float, less precise than pi itself

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

 bool possible, probable; 
 possible=true;    //no quotes here. valid bool values are true/false (lowercase)
 probable=false;   //I don't think *that* donkey will be a good forklift operator
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 thing wrong with your program. Learn to translate g++ errors. 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. Both are in the iostream library (add #include <iostream> 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;
cout is sometimes annoying, especially if you want to format numbers to a particular precision or use fancy formatting. Suppose we want to print out an x,y pair as (4.5, 5.2). Here is the cout way, in its full glory.
#include <iostream>
#include <iomanip> //needed for setprecision
using namespace std;

// The first C++ program, hello world.

int main() {
  float x=4.50001;
  float y=5.199999;

  cout << "(" << setprecision(2) << x << ", " << y << ")" << endl;

  return 0;
}

Alternatively, we could use printf, a old C-style output function that is still very handy.
#include <iostream>
#include <iomanip> //needed for setprecision
#include <cstdio> //for printf
using namespace std;

// The first C++ program, hello world.

int main() {
  float x=4.50001;
  float y=5.199999;

  cout << "(" << setprecision(2) << x << ", " << y << ")" << endl;
  
  //Ah, much nicer.
  printf("(%.1f, %.1f)\n", x, y);
  
  return 0;
}

Branching 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 body>
}
else if( <Boolean expression  2>){
  //first expression is false, second is true
  <true 2 body>
}
else{
  //both expressions are false
  <false body>
}

You may use the following Boolean operators:
Looping
For loop syntax (see forLoop1.cpp and forLoop2.cpp for examples.)
for( <initialization>; <boolean expression> <update> ){
 <body>
}

for (int i=0; i<10; i++){
  cout << "i= " << i << endl;
}
While loop syntax (see whileLoop1.cpp and whileLoop2.cpp for examples.)
while ( <Boolean expression> ){
  <true body>
}
The while loop checks the Boolean expression first and executes the body if true. A similar do-while loop executes the body first, then checks a condition and runs the loop again if the condition is true.
do{
  <body>
} while ( <Boolean expression> );
Functions
Use functions to break code into manageable pieces and reduce code duplication. 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.

See function1.cpp for an example.

Arguments are passed to C++ functions by value. Thus a copy of the variables value is made before the body of the function executes. Any modifications to the parameters in the function are not visible to the callee.

Exercise: write a function bool isAnA(float avg) that determines if an average score is an A (above 90%).

Arrays
Arrays are a poor man's list. They can store multiple items of the same type. For now, we will use only statically sized arrays, meaning we must know the size of the array at compile time. We cannot shrink or grow the array at run time (at least not yet). The files array1.cpp and array2.cpp have some example uses of arrays.

To declare an array, specify its type, name and size, e.g., int a[10];. Individual elements may be accessed by indexing, e.g., cout << "first item= " << a[0] << endl; or a[9]=25; //last item. Sorry python users, there is no array/list slicing or negative indexing.

To declare an array as an argument to a function, we must use the crazy syntax int a[]. Note we do not specify the size in the parameter list (the function can accept array of any size). Arrays do not know their size, so if we want the function to know, we should pass the size as a second argument, e.g., void printArray(int a[], int size). To call a function that takes an array as an argument, pass only the name of the array and omit the brackets.

Exercise: complete and test the function minimum in array2.cpp.