Recent site activity

Resources‎ > ‎Programming‎ > ‎C++‎ > ‎C++ Tutorial‎ > ‎

Lesson 1

There are two main tasks for this lesson:
  • Get yourself familiar with your lesson environment. This includes setting up your programming environment and a version control system.
  • Start with simple C++ programming

Programming Environment


The following will describe basic procedure to start up a programming project in each environment:
  • Microsoft Visual Studio : If you are using School of IT's lab machine, you have immediate access to Microsoft Visual Studio.  This link describe the basic step to start up an empty Win32 console project.
  • OS X Xcode
  • Linux

Version Control


Purpose:
  • For keeping a repository of your current codes on a server. So it won't go missing.
  • Synchronise your codes from any terminal. So you can have your work anywhere you want.
  • Synchronise group work.



Steps: Basic steps of using a version control system are:
  • Creating the main repository (database) on a server.
  • "Checking out" your project from that repository (database) onto your terminal.   Used as a private working copy.
  • Edit your code
  • "Commit" your changes back to the repository (database).
While you're working on your tutorial materials or assignments, you might primarily do your work on your own computer (home desktop or notebook).  When you're working on your computer, you might not be in the situation that you do not have access to the network to interact with a version control server (repository).
Despite the lack of network connection, you probably still want to use the versioning system.  Hence, we encourage you to use git, which is a distributed version control system, rather than subversion.

How to version control...

Template


In order to practice various features of C++ (or programing in general), you should have a small program, which you can use to try them out. Here are the two small templates: 1) main function without arguments and 2) main function with arguments.

#include <iostream> 
using namespace std; 

//main() function without args 
int main() { 
    cout << "This is a C++ main without args" << endl; 
    return 0; 
}

#include <iostream> 
using namespace std; 

//main() function with args 
int main(int argc, char *argv[]) { 
    cout << "This is a C++ main with args" << endl; 
    return 0; 
}
Note:
  • In C++, a function with an empty '()', is treated as a function that does not take arguments. Hence, main()would be declared as int main() instead of int main(void) (like in C).
  • C++ source file uses .cpp as its extension.
  • In C++, you need to include <iostream> for I/O. C++'s library header name does not have .h
  • C++'s standard libraries are defined in std namespace. C does not have the concept of namespace.
  • In C++, you use standard I/O stream for input/output processes. C++ has cin, cout, and cerr for the standard I/O.


Practice 0


Write a program to display "Hello Wold" on a computer screen.

When you write a program, you need to use a text editor (your favorit editor or one provided by your programming environment such as Visual Studio).

C++ is a programming language, which is readable and understandable by humans. This form of program is often called "source program". A text file containing this source program is called "source file". Once you created a source file and typed a source program, you save the source file with its name. A typical extension of C++ source files is .cpp. (such as helloworld.cpp)

Once you created a source file, you need to compile it to produce an executable file (such as helloworld.exe). Then you can execute this file.

Comment


A line starting with // is a comment line. This is for assisting people, who read the source program, to understand the code. Whatever written as a comment does not affect actual program code (executable code). You can also write a comments between /*....*/.

header and incude


A line starting with #include is substituted with the content of <iostream>. After this #include, you can use various variables and functions defined in <iostream>. There are many other useful variables and functions defined in<string><cstdlib>. These are often called "header".


Practice0-1 (without header)

Remove #include <iostream> from your helloworld.cpp and see what will happen.

Display output and output stream

In order to output something to a display (console) and files, you use stream. A stream is connected to the target output and you just need to throw things into the stream to output. cout is connected to the standard output (console) and is called "standard output stream". To output letters to cout you insert letters to it using << (inserter).

String

In C++, a set of letters like "Hello World." is called "string literal" (or string). You sometime see \n at the end of string and it represents "carriage return".

Practice 0-2

Write a code which does:

  • declare two integer variable x and y, who are initializd with 34 and 44 respectively,

  • display values of x and y on the console like

The value of x is 34.
The value of y is 44.
  • display the sum and average of x and y like

The sum of x and y is 78.
The average of x and y is 39.

Practice 0-3

Write a code which reads a number being typed from the keyboard and displays it.

Practice 0-4

Write a code which reads a number being typed from the keyboard and displays its absolute value.

Practice 1 (C++ and std)

Try the following code. If it does not work as you intended, discuss what's wrong and how you could fix it.

// compute an average of elements from two arrays
#include <iostream>

int main() {
    int narray1[]=(16,22,38,46,51,69,70,88,95,102);
    int narray2[]={13,29,33,45,57,62,75,84,91,105};
    int size = sizeof narray1 / sizeof(int);

    for (int i = 0; i < size; i++) {
        cout << "The average of ";
             << "narray1[" << i << "] and narray2[" << i << "]: ";
             << (narray1[i] + narray2[i]) / 2 << endl;
    }
    return 0;
}
  • namespace is a method to divide a single global scope area.
  • like any other OOPL, C++ supports the concept of namespace.
  • C++'s standard libraries are defined in std namespace.

  • To use C++ standard libraries, you need to resolve the std namespace.

Practice 2 (Scope Resolution Operator)

Try the following code. If it does not work as you intended, discuss what's wrong and how you could fix it.

/* find max and min value of three arrays */
#include <iostream>

int main() {
    double narray1[] = { 16.21, 22.50, 38.33, 46.00, 51.71,
        69.09, 70.89, 88.05, 95.77, 102.01 };
    double narray2[] = { 13.44, 29.78, 33.45, 45.03, 57.66,
        62.07, 75.66, 84.00, 91.82, 106.00 };
    double narray3[] = { 10.05, 29.44, 34.35, 43.56, 55.25,
        69.44, 72.00, 89.80, 97.45, 105.02 };
    int size = sizeof narray1 / sizeof(double), i;

    std::cout << std::showpoint;
    // find the max
    for (i = 0; i < size; i++) {
        std::cout
            << "The max value of "
            << narray1[i] << ',' << narray2[i] << ',' << narray3[i] << " : "
            << ((narray1[i] > narray2[i] ? narray1[i]:narray2[i]) >
                (narray2[i] > narray3[i] ? narray2[i]:narray3[i]) ?
                (narray1[i] > narray2[i] ? narray1[i]:narray2[i]):
                (narray2[i] > narray3[i] ? narray2[i]:narray3[i]))
            << std::endl;
    }

    std::cout << std::noshowpoint;
    // find the min
    for (i = 0; i < size; i++) {
        std::cout
            << "The min value of "
            << narray1[i] << ',' << narray2[i] << ',' << narray3[i] << " : "
            << ((narray1[i] < narray2[i] ? narray1[i]:narray2[i]) <
                (narray2[i] < narray3[i] ? narray2[i]:narray3[i]) ?
                (narray1[i] < narray2[i] ? narray1[i]:narray2[i]):
                (narray2[i] < narray3[i] ? narray2[i]:narray3[i]))
            << std::endl;
    }

    return 0;
}

You can do one of followings:

  1. Resoluve each namespace scope. (namespace_name::identifier)
  2. Resolve a scope of certain identifier. (using namespace_name::identifier)
  3. Resolve the scope of all identifiers. (using namespace namespace_name)
  4. There are three different ways to resolve namespace.
  5. if the number of identifiers and their use are low, you can use ::.

Practice 3 (static keyword)

Try the following code. If it does not work as you intended, discuss what's wrong and how you could fix it.

/* reverse pointers */
#include <iostream>

// declare a const visible only within this file
static const int size = 10;

int main() {
    int narray[] = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
    int *pnarray[size], i, j;

    for (i = 0, j = size - 1; i < size; i++, j--)
        pnarray[j] = &narray[i];

    for (j = 0; j < size; j++)
        std::cout << "pnarray[" << j << "] is : "
                  << *pnarray[j] << std::endl;

    return 0;
}

If you need to define something(s), which is(are) visible only within the source file, you should use anonymous name space.

namespace {
    //identifies only visibile with in the file
    ...
}

Practice 4 (printf())

Try the following code. If it does not work as you intended, discuss what's wrong and how you could fix it.

/* Simple division */
#include <iostream>
using namespace std;

// anonymous name space for "file scope"
namespace {
    // a function to handle error.
    void errorexit(char *pchar) {
        // display an error to the standard err.
        fprintf(stderr, pchar);
        fprintf(stderr, "\n");
        exit(1);
    }
}

int main() {
    int n1, n2;

    cout << " [Simple Division Program]\n"
         << "Type in the first integer: ";
    // get the first input.
    cin >> n1;
    cout << "Type in the second integer: ";
    // get the second input.
    cin >> n2;
    if (n2 == 0)
    {
      errorexit("Divided by zero.");
    }
    else
    {
    cout << n1 << " / " << n2 << " = "
         << n1 / n2 << endl;
    }

    return 0;
}


Comments