Introduction to C / C++ Programming
Basic Format
Basic Format:
- The basic form of a simple C/C++ program is as shown below. ( Line numbers have been added for future reference. )
1 /* Filename.cpp
2
3 This program was written by Ima Programmer on some date
4
5 This program does something useful . . .
6
7 */
8
9 #include <iostream> // For input and output functions
10
11 using namespace std; // For easy reference to cin, cout, and cerr
12
13 int main( void ) {
14
15 // Declare variables to be used
16
17 // Explain to the user what the program does
18
19 // Get user input ( and check it if possible )
20
11 // Perform necessary calculations
22
23 // Report results ( in a complete and well-formed format. )
24
25 system( "pause" ); // Only needed with certain environments, e.g. Dev C++
26
27 return 0;
28
29 } // main
Explanation of Specific Lines
- The symbols /* and */ enclose a block comment, which may extend over any number of lines, or which may enclose only part of a line.
- EVERY well-written program should begin with a large block comment specifying the name of the file, the author of the program, when it was written, and a brief description of what the program does and why. In large projects the opening comment may include reference to external documents ( software requirements documentation ), and may include a revision history of who modified the program when and for what purposes.
- The #include statement informs the compiler of what libraries are needed.
- In this case only the input-output library iostream is specified, which is required of every program that does input or output.
- ( Many programs will also include cstdlib, the standard C library, but since iostream automatically includes cstdlib, that is not necessary here. )
- More advanced programs may need to include other libraries, such as cmath for using trigonometric functions.
- The double slash symbol, //, indicates a comment that extends to the end of the current line.
- Namespaces are complicated issues beyond the scope of this simple introduction. For now just trust that it makes input and output easier to use, and always put it in.
- Line 13 says that we are starting a function named main, which is the starting point for all C/C++ programs.
- The keyword int says that main returns an integer value as its return type. ( See line 23. )
- The open brace indicates the beginning of a block of code, which must be matched by a closing brace ( on line 25. )
- The keyword void expressly states that main takes no arguments. In other programs you may see the following alternatives:
- int main ( ) { - Does not expressly say what arguments main takes.
- int main( int argc, char *argv[ ] ) { - Beyond the scope of this introduction.
- int main( int argc, char *argv[ ], char ** envp ) { - Beyond the scope of this introduction.
- Some IDEs ( Integrated Development Environments ) execute programs in a separate window, and then immediately close the window when the program is completed. In this case, the system( pause ) statement holds the window open so that the results can be seen, until the user presses a key to release it. ( Dev C++ is one of those IDEs. ) Note that CodeLab does not permit the use of system( pause ), so make sure to leave it out when submitting CodeLab solutions.
- Every function must have a return statement, which causes the function to end and return control to whoever called it.
- Because main was declared to have an integer return type in line 13, this function must return an integer.
- The return value from main is typically interpreted as an error code, with a value of zero indicating successful completion.
- Negative 1 is a commonly used return value used to indicate an unspecified error of some kind.
- It is good practice to comment the closing brace of every function, and any other closing brace that is more than a few lines away from its matching opening brace. This makes it much easier to read more complex programs, which may have MANY sets of nested and consecutive braced blocks.
A Simple Sample:
- This simple program adds two numbers and reports the total.
1 /* addTwoAndSine.cpp
2
3 This program was written by John Bell on August 2009 for CS 109
3A Modified August 2011 to include use of the math library to calculate a sine.
4
5 This program asks the user for two floating point numbers and reports their total.
6
7 */
8
9 #include <iostream> // For input and output functions
9A #include <cmath> // For use of the math library functions
10
11 using namespace std; // For easy reference to cin, cout, and cerr
12
13 int main( void ) {
14
15 // Declare variables to be used
16
17 double num1(0.0), num2(0.0), total = 0.0;
18
19 // Explain to the user what the program does
20
21 cout << "This program adds together two floating point numbers.\n";
21A cout << "Written August 2009 by John Bell for CS 109.\n\n";
22
23 // Get user input ( and check it if possible )
24
25 cout << "Please enter the first number > ";
26 cin >> num1;
27
28 cout << "Please enter the second number > ";
29 cin >> num2;
30
31 // Perform necessary calculations
32
33 total = num1 + num2;
34
35 // Report results ( in a complete and well-formed format. )
36
37 cout << "\nThe total of " << num1 << " and " << num2
38 << " is " << total << endl;
39
40 cout << "\nThe sine of " << total << " is " << sin( total ) << endl;
41
42 return 0;
43
44 } // main
Explanation of Specific Lines
- The keyword "double" indicates double-precision floating point numbers, the most commonly used type of real numbers in C/C++.
- All variables must be declared before they can be used, generally at the very beginning of a program.
- Line 17 declares three variables of type double.
- Note the semicolon at the end of the line, which is how C/C++ knows that a line has ended.
- These particular variables are given initial values of 0.0. The two different styles are equivalent and interchangeable.
- The keyword cout represents the screen, and is used for output.
- The << symbol can be viewed as an arrow pointing to the left, showing the flow of data out to the screen.
- The \n within the quoted string indicates a new line. ( Two together produce a blank line. )
- Every well-written program should begin by explaining to the user what the program does.
- The keyword cin represents the keyboard, and is used for reading in input.
- The >> symbol can be viewed as an arrow pointing to the right, showing flow of data from the keyboard.
- Note that the input was preceded by a complete sentence asking the user for specific information.
- If there were units involved, such as degrees Centigrade, that should be specified in the request to the user.
- The equals symbol, =, as used here is an assignment, which takes the value from the right side and stores it in the left side.
- The plus sign, +, peforms addition, and yields the sum of its two arguments.
- Note that the output of the results is a complete sentence, and includes an echoing back of the user's input.
- Note also that a line of code may span over multiple lines in the file. C/C++ only recognizes the semi-colon as the end of a line.
- It is not necessary to store all results in variables before reporting them.
Another Example
Exercises
- Write a complete C/C++ program to convert a temperature from degrees Centigrade to degrees Kelvin. The conversion is that temperatures in degrees Kelvin are exactly 273.15 higher than in degrees Centigrade.
- Now write another program to convert from Centigrade to Fahrenheit and/or vice-versa.
- Write a program to evaluate a quadratic or higher-order polynomial, such as Ax^2 + Bx + C. Your program will have to ask the user for each of the coefficients, as well as the value of X at which to evaluate the function.
- Try more complex calculations, involving square roots, logarithms, trig functions, etc. ( Requires the use of the cmath library. )