Structure of a C++ Program


Cyganek section 2.4


We can represent algorithms using flowcharts. There are some standard symbols used in programming flowcharts that you should be familiar with.

Here’s an example of a flowchart of the thought process in debugging a broken lamp:


Fig. 4 (Booyabazooka/Wikipedia)

Flowcharts can also have loops, like this example for a code that appears as:

for (A; B; C)

Fig. 5 (Paweł Zdziarski (faxe)/Wikipedia)

An alternative to flowcharts is to write out the algorithm in pseudocode

Both of these concepts help you layout the organization of your program before you start writing the code.

Hello, World

Let’s look at a simple “Hello, World” program (your text has an example to computes the square root of an input number).


Every C++ program needs to have a main() function

#include <iostream>

// our Hello, World program

int main()
   std::cout << "Hello World!" << std::endl;

A nice breakdown of a “Hello, World” program is shown here: – let’s walk through that.

A few important bits:

  • A preprocessor is used to bring additional functionality into our code (the #include)

  • C++ comments start with //

  • Each C++ program needs to have a function called main() and that function is of type int.

  • { and } are used to denote blocks of code in C++

  • The C++ Standard Library provides a lot of useful functions and capabilities. Here we use std::cout from the standard library to output.

  • << is an operator in C++. Its meaning can depend on context. Here it is used to pass "Hello, World!" to cout

  • :: is the scope operator. This tells us that cout is part of a namespace called std, and the compiler should look there for its implementation.

  • Statements end with ;


C++ files can have a variety of extensions, including: .C, .cxx, .cc, and .cpp.

I’ll use .cpp throughout this course.