6A. Programs and the Main Function

A C++ program is a collection of functions, exactly one of which is called main. The program starts by running main, and stops when main returns. All of the other functions constitute a toolbox for accomplishing the desired task.

For now, the heading for main should be

  int main()
That is different from Java. This main function does not take any parameters and it returns an integer, which is a status value telling whether the program was able to complete its job without errors. A status value of 0 indicates that all went well. Any other status value indicates that there was an error. (The status value should be a number from −128 to 127. Typically, only 0 and 1 are used.) If you are sure that your program will work, just return 0:
  int main()
  {
    
    return 0;
  }
Here is a complete program that just writes Hello.
  #include <cstdio>
  using namespace std;

  int main()
  {
    printf("Hello\n");
    return 0;
  }

Later, we will see a more general version of main that takes some parameters, but the simple parameterless form will do for now.

Documenting a program

When someone looks at your program, he or she does not want to reverse engineer it to figure out what it does. Write a helpful comment near the beginning of a program that briefly explains what the program does.

The reader should not need to reverse engineer the program to figure out what the input needs to look like. Say what the input format is, and give an example. If the input is just a number, say that the program reads a number.

Giving things names makes your comment much clearer. If the program reads an integer, say that it reads an integer n. In the remainder of the comment, refer to that integer as n, not as "the integer" or "the number that was read."

Exercises

  1. Write a complete program that reads a real number from the user (after a prompt) and writes the square root of that real number. Answer