file comment header (right click and "Save Target As...")
function comment header (right click and "Save Target As...")
Consider the two programs:
| Code #1 | Code #2 |
|
/**************************************************************************
PROGRAM.CPP I declare that I am the sole author of
this code and that I did not I am fully aware that if I did receive
any help from anyone that this Author Adrian Chan The program accepts
a user input for an integer and determines if it is Modifications 06/05/18 AC First created. #include <iostream> #include <conio>
using namespace std;
int main () { int number, divisor; bool still_looking;
cout << "Please enter a number (-1 to terminate): "; cin >> number;
while (number > 0 ) { // stop on -1 or junk input // we have a valid number. to determine whether we've a // prime number, try all possible divisors starting with 2. divisor = 2; do { if ((divisor * divisor) > number) { // our divisor has reached the square root of the number. // the number must be prime. cout << number << " is a prime number" << endl; still_looking = false; // time to stop loopin } else if ((number % divisor) == 0) { // we've found something that divides the number. // the number is not prime. cout << number << " is a not prime number" << " (divisible by " << divisor << ")" << endl; still_looking = false; // time to stop looping } else { // nothing definite yet - must try the next divisor divisor = divisor + 1; still_looking = true; } } while (still_looking);
// obtain the next number to be processed cout << "Please enter a number (-1 to terminate): "; cin >> number; }
system("pause"); return 0; }
|
#include <iostream> #include <conio> using namespace std; int main () { int n, x, bool l; cout << "Please enter a number (-1 to terminate): "; cin >> n; while (n > 0) { x = 2; do { if ((x * x) > n) { cout << n << " is a prime number" << endl; l = false; } else if ((n % x) == 0) {cout << n << " is a not prime number" << " (divisible by " << x << ")" << endl; l = false; } else { x = x + 1; l = true; } } while (l); cout << "Please enter a number (-1 to terminate): "; cin >> number; system("pause"); return 0; }}
|
The two blocks of code are equivalent from a compiler's point of view and this programs will execute exactly identically. From a human point of view, there is an obvious difference. The first program (Code #1) is much easier to read than the second (Code #2). The readability of the code is much more readable for a number of reasons including formatting/layout (tabbing, and line spacing) and commenting. While the second code is much shorter, it is much more difficult to debug (find errors) and modify; especially, if these tasks were to be done by a different programmer.
Students must use comment blocks for each .cpp file submitted. The comment block should the student name, student ID, the course number, a brief description of the code, and a modification list. See the example in Code #1 above.
Functions should also have a comment block and should be formatted as shown below. The function comment block should include a copy of the function prototype, a brief description of the code, a list and description of the function inputs, a description of the function output, and a modification list.
These comment blocks are good to use in this course as it will instill good programming practices and as you progress to more complex programs will make things easier to debug. If you ever have to write code for a job etc. this type of commenting is generally a must!
/*----------------------------------------------------------
float bmi(float height, float weight)
This function computes the body mass index (BMI)
using the formula weight/(height^2).
Input
height: this is the person's height specified in meters
weight: this is the person's weight specified in kg
Output
the person's BMI
Modification list
03-02-05 AC First created.
----------------------------------------------------------*/
There are a number of different styles for indentation, each with their advantages and disadvantages. Style 1 is my preference but other styles are acceptable as well.
|
if (<condition>) { <statements> } else { <statements> } |
while (<condition>) { <statements> } |
do { <statements> } while (<condition>); |
|
if (<condition>) { <statements> } else { <statements> } |
while (<condition>) { <statements> } |
do { <statements> } while (<condition>); |
|
if (<condition>) { <statements> } else { <statements> } |
while (<condition>) { <statements> } |
do { <statements> } while (<condition>); |
Use the indentations to make blocks of code. This helps make the code readable as it makes obvious that a particular block of code belongs to a loop or conditional statement. You will find this makes the code easier to debug (find missing braces, and logical errors).
In the code below it is easy to what code belongs to the if and which part belongs to the else. The portions of the code that belong to the while loop are further indented and the code that belongs to the for loop further intended again.
if (x > 0 ) {
while (y > 5) {
for (z = 0; z < 5; z++) {
y = y/z;
x++;
}
x = x + z;
}
cout << "x = " << x << endl;;
cout << "y = " << y << endl;;
cout << "z = " << z << endl;;
}
else {
cout << "x is not greater than zero";
}
Compare that code with the code below and it is easy to see how a brace could be missing or how programming errors are hard to detect.
if (x > 0 ) {
while (y > 5) {
for (z = 0; z < 5; z++) {
y = y/z;
x++;
}
x = x + z;
}
cout << "x = " << x << endl;;
cout << "y = " << y << endl;;
cout << "z = " << z << endl;;
}
else {
cout << "x is not greater than zero";
}
The C++ "goto" statement will not be taught. Although, it may be useful under certain circumstances, in this course it will unacceptable to use.
Global variables, when properly documented, can be a useful programming tool. They are, however, really only necessary in the case of programs much larger than anything we'll see in ECOR 1606, and, were they allowed, experience suggests that students would use them mostly as a way of avoiding of having to really understand how functions work. For this reason, global variables are prohibited.
Note that this prohibition does not apply to global constants, which are fine. For example, the global variable for p is used frequently:
const double M_PI = 2.0*asin(1.0);
There are cases in which terse, single character variable names are in fact appropriate. Consider, for example, the following code segment, which prints out a message ten times.
for (i = 0; i < 10; i++) {
cout << "Hello world!" << endl;
}
In this case absolutely nothing would be gained by replacing "i" with a more "meaningful" name. Indeed using a longer name would probably make the code segment harder rather than easier to understand. Other examples could be offered. If the function of a piece of code is to determine the value of "x", "x" may be a quite reasonable variable name, and "n" is commonly used to represent the size of an array.
In general, however, variable names should be descriptive. Thus "speed" is much better than "s", and "population" is superior to "p". It is often a good idea to use multiple words (separated by underscrores) in naming variables. Thus, for example, one might have "initial_population", or "size_of_room". Alternatively, capitalizing the first letter of the words (except the first) can be used (initialPopulation, sizeOfRoom).
The test of a good variable name is whether or not it conveys the role of the variable to the reader. While sometimes single character names will pass this test, this can be expected to be the exception rather than the rule. If all (or most) of your variables have single character names, you can be pretty sure that your program will not be acceptable.
A "magic number" is a constant which leaves the reader wondering just what is represents, and where on earth it came from. Consider, for example, the following statement:
angular_position = 57.29578 * (omega / i);
While some might recognize the value, it is far from clear just what is going on here, and in particular what the value represents. The value 57.29578 is a "majic value". Magic values are not good style and should be avoided by using named constants as shown below.
const double degrees_per_radian = 57.29578;
....
angular_position = degrees_per_radian * (omega / i);
Not only is the assignment statement now much more self-explanatory, but, if the constant were used in a number of places, there would much less chance of a typing error leading to the use of an incorrect value.
While all magic numbers are constants, not all constants are magic numbers. In the case below, the zero is just that . The reader knows what it represents, and does not wonder where it came from. Replacing the "0" with a named constant called "zero" would contribute nothing to the clarity of the program, and would instead just make it wordy.
if (speed < 0) { // speed is negative
cout << "We're going backwards." << endl;
}
In C++ it is permissible to intermingle "declarative" statements (the declaration of variables and constants) with what might be called "executable" statements (cin's, cout's, assignments, and so on). Indeed this approach was extensively employed in a previous text (and is one of the reasons we dropped it).
We strongly recommend, however, that students not mix things up, and instead declare first and execute afterwards If all declarations are kept together you'll always know where to look for them, and, more importantly, you'll avoid playing with fire. Declaring variables "on the fly" raises a number of issues which can get a bit tricky and which we won't be covering in this course. Consider, for example, the following code segment:
int b;
...
if (b < 0) {
int a = 7;
} else {
int a = 9;
}
cout << a << endl;
If you can understand why it will result in an error message to the effect that "a" is undefined, you are well ahead of the game and are not the kind of student we're worried about. If this makes no sense, on the other hand, you're well advised to avoid getting in over your head. Just put all your declarations first and this kind of thing won't crop up.
One somewhat special case is that of declaring a variable within a "for" loop as shown below.
for (int i = 0; i < 10; i++) {
<statements>
}
While some would argue that this represents much better style than declaring "i" at the beginning of the function, it also has the potential to leave beginners very confused. If one breaks out of the loop, for example, "i" cannot be examined to determine when the break occurred. This is because, if declared in this fashion, "i" only exists for a long as the loop is being executing. In this course students are discouraged to use this feature. Instead, always declare "i" at the beginning, write the loop as "for (i = 0; ...".
Last Modified 08-08-01