C++ Programming
I hope you guys enjoy this tutorial. If you have any questions, feel free to ask. I will probably add one part a week so that there is plenty of time to learn everything in the available part(s) before moving onto the next one. If you like it, show that you do.
Free C++ Compiler: Bloodshed Dev-C++
Part 1: The Basics
We will start off with the very basics.
The overall structure of a C++ program contains one function named main(), called the driver function. All other functions are invoked from main().
Every statement inside the function must be ended with a semicolon, ;.
A keyword causing the appropriate value to be returned from the function is return. The statement return 0 in the main() function causes the program to end.
When writing code you want to make sure there is a structure so that it is easy to read and follow. This will make it easier for you or anyone else to understand what the code will do.
cout << "insert text here" is used to display text to the person using your program. This is easily used to ask the user for input.
cin >> "insert variable here" is used to store the user's input as a variable.
Comments are explanatory remarks in the source code added by you, the programmer. They begin with // and continue to the end of the line. Block comments span across two or more lines. These begin with /* and end with */. These are useful for sections with many comments, such as problem background of logos. This can also be used to temporarily "comment out" a section of a program while you debug it. They can also be used for your headings. Here is an example of how I usually use comments:
A variable name is referred to as an identifier. All variable names must be declared. This means you need to list the name and type. Data types include int, float, double, char,....(there are more but these will be sufficient for now). Variables of the same type may be declared in the same statement separated by a comma. To name identifiers there are a few rules you must follow:
To give numeric values to variables you need to use the assignment operator (=) which is what you know as the equal sign.
Also, you can use constant qualified variables. For example you can use const double PI = 3.14159 to declare the variable PI as that constant. It cannot be modified later in the program. To use it simply insert "PI" anywhere that it is needed in the program. I recommend using all uppercase characters to name constants as it makes them easier to identify. You could also use what I use:
I want to make sure that you guys understand that = does NOT mean equal. For example:
C++ Data Types
I will go into more detail about the data types now.
Integers are numbers without decimal points. Each one has a different amount of memory, a different range of numbers so to speak.
Real numbers are numbers with decimal points. They may be in scientific notation or in fixed-point notation. If you exceed the range there can be overflow or underflow errors.
A character consists of any single symbol enclosed in single quotes. Escape sequences such as \t, \n, \r, \v are regarded as a single character. You can think of a character as essentially acting like an integer. Based on the table below you can see that these two commands would have the same effect:
char c1 = 'A';
char c1 = 65;
Let's go into more detail about using cout and cin.
cout << [variable, expression, or text (in double quotes)]
cin >> value
<< is referred to as the extraction operator. >> is referred to as the insertion operator.
If there is text inside the double quotes, it is referred to as a string. A string is any combination of letters, numbers, and special characters enclosed in double quotes (delimiter). A delimiter is a symbol that marks the beginning and ending of a string, but is not part of the string.
The backslash (\) can be used at an end of a line to indicate that the string constant will be continued on the next line. The following two statements are equivalent:
C++ does not automatically advance the display to the next line after using cout. To do this you need to use endl (endline) or \n (\ is used to start an escape sequence and n is for "newline").
Here are some more escape sequences:
To use C++ for programs related with math you need to use arithmetic operations. These look like algebraic expressions and consist of sequences of operands and operators. An operand is a variable, constant, or any value. Most common operators are +, -, *, /, and %.
Try to avoid mixed-type operations unless they are necessary and intentional. If a real result is converted to an integer it is chopped off after the decimal point, not rounded off. If a real value is assigned to an integer variable the same thing happens. If an integer value is assigned to a real variable, it is promoted to a real (decimal point added).
Here is the order of operator precedence:
++ is the increment operator. -- is the decrement operator.
For example:
x++ means x=x+1
x-- means x=x-1
When these are placed in front, incrementing or decrementing occurs BEFORE value assigned. When placed in back, occurs AFTER value assigned.
You can also use compound assignment operators as a "shortcut".
For example:
A += B; is the same thing as A = A + B;
A -= B; is the same thing as A = A - B;
A *= B; is the same thing as A = A * B;
A /= B; is the same thing as A = A / B;
A %= B; is the same thing as A = A % B;
To use certain math functions you must use the cmath or cstlib headers: #include <cmath> or #include <cstlib>
It is important to remember that all trig functions in C++ use radians not degrees. Also, the "log" function calculates the natural logarithm. To calculate the base 10 logarithm use the "log10" function.
Here are some of the math functions:
Alright, I think it is time for you to make a simple program to calculate the area of a circle. Try to do this yourself given what you have read and learned so far. Remember the area of a circle is PI*r^2. You will need #include <cmath>. Below is an example of how it could look:
This would be the output if the user entered 20 for the radius:
I think this is a good place to stop the tutorial for now. One of the things I will cover in the next part is formatting.
The overall structure of a C++ program contains one function named main(), called the driver function. All other functions are invoked from main().
Every statement inside the function must be ended with a semicolon, ;.
A keyword causing the appropriate value to be returned from the function is return. The statement return 0 in the main() function causes the program to end.
When writing code you want to make sure there is a structure so that it is easy to read and follow. This will make it easier for you or anyone else to understand what the code will do.
cout << "insert text here" is used to display text to the person using your program. This is easily used to ask the user for input.
cin >> "insert variable here" is used to store the user's input as a variable.
Comments are explanatory remarks in the source code added by you, the programmer. They begin with // and continue to the end of the line. Block comments span across two or more lines. These begin with /* and end with */. These are useful for sections with many comments, such as problem background of logos. This can also be used to temporarily "comment out" a section of a program while you debug it. They can also be used for your headings. Here is an example of how I usually use comments:
A variable name is referred to as an identifier. All variable names must be declared. This means you need to list the name and type. Data types include int, float, double, char,....(there are more but these will be sufficient for now). Variables of the same type may be declared in the same statement separated by a comma. To name identifiers there are a few rules you must follow:
- First character must be a letter.
- Other characters may be letters (a-z, A-Z, _ ) or digits 0-9.
- Cannot use C++ keywords (reserved words - see next image).
- Cannot have blanks within identifiers (spaces).
- Use descriptive names (Not necessary, but very helpful).
To give numeric values to variables you need to use the assignment operator (=) which is what you know as the equal sign.
Also, you can use constant qualified variables. For example you can use const double PI = 3.14159 to declare the variable PI as that constant. It cannot be modified later in the program. To use it simply insert "PI" anywhere that it is needed in the program. I recommend using all uppercase characters to name constants as it makes them easier to identify. You could also use what I use:
I want to make sure that you guys understand that = does NOT mean equal. For example:
C++ Data Types
I will go into more detail about the data types now.
- Integers - int, short int, long int, unsigned int, etc.
- Real numbers - float, double, and long double.
- Characters - char.
- Boolean - bool.
- Strings - string. (using string class, string.h)
Integers are numbers without decimal points. Each one has a different amount of memory, a different range of numbers so to speak.
Real numbers are numbers with decimal points. They may be in scientific notation or in fixed-point notation. If you exceed the range there can be overflow or underflow errors.
A character consists of any single symbol enclosed in single quotes. Escape sequences such as \t, \n, \r, \v are regarded as a single character. You can think of a character as essentially acting like an integer. Based on the table below you can see that these two commands would have the same effect:
char c1 = 'A';
char c1 = 65;
Let's go into more detail about using cout and cin.
cout << [variable, expression, or text (in double quotes)]
cin >> value
<< is referred to as the extraction operator. >> is referred to as the insertion operator.
If there is text inside the double quotes, it is referred to as a string. A string is any combination of letters, numbers, and special characters enclosed in double quotes (delimiter). A delimiter is a symbol that marks the beginning and ending of a string, but is not part of the string.
The backslash (\) can be used at an end of a line to indicate that the string constant will be continued on the next line. The following two statements are equivalent:
C++ does not automatically advance the display to the next line after using cout. To do this you need to use endl (endline) or \n (\ is used to start an escape sequence and n is for "newline").
Here are some more escape sequences:
To use C++ for programs related with math you need to use arithmetic operations. These look like algebraic expressions and consist of sequences of operands and operators. An operand is a variable, constant, or any value. Most common operators are +, -, *, /, and %.
Try to avoid mixed-type operations unless they are necessary and intentional. If a real result is converted to an integer it is chopped off after the decimal point, not rounded off. If a real value is assigned to an integer variable the same thing happens. If an integer value is assigned to a real variable, it is promoted to a real (decimal point added).
Here is the order of operator precedence:
++ is the increment operator. -- is the decrement operator.
For example:
x++ means x=x+1
x-- means x=x-1
When these are placed in front, incrementing or decrementing occurs BEFORE value assigned. When placed in back, occurs AFTER value assigned.
You can also use compound assignment operators as a "shortcut".
For example:
A += B; is the same thing as A = A + B;
A -= B; is the same thing as A = A - B;
A *= B; is the same thing as A = A * B;
A /= B; is the same thing as A = A / B;
A %= B; is the same thing as A = A % B;
To use certain math functions you must use the cmath or cstlib headers: #include <cmath> or #include <cstlib>
It is important to remember that all trig functions in C++ use radians not degrees. Also, the "log" function calculates the natural logarithm. To calculate the base 10 logarithm use the "log10" function.
Here are some of the math functions:
Alright, I think it is time for you to make a simple program to calculate the area of a circle. Try to do this yourself given what you have read and learned so far. Remember the area of a circle is PI*r^2. You will need #include <cmath>. Below is an example of how it could look:
This would be the output if the user entered 20 for the radius:
I think this is a good place to stop the tutorial for now. One of the things I will cover in the next part is formatting.
Video:
Courtesy of @"Mr.Anderson"
[video=youtube]http://www.youtube.com/watch?v=_3RV_ImD6GE&feature=youtu.be[/video]
Part 2: Formatting
In C++ there are ways to format your output, the things that the uesr of your program will see.
Output values are formatted in C++ by inserting I/O manipulators (parameterized) into cout statements for printing.
An example is cout<<setprecision(6)<<x<<y; where "setprecision(6)" is the I/O Manipulator.
These usually affect all outputs from that point on so there is no need to include the one your previously used in every cout statement after, but this might be compiler dependent.
In order to use I/O manipulators to format output you must have the header#include <iomanip>. The basic form for using I/O manipulators is: cout<<manipulator(parameter);.
Here is a list of several common I/O manipulators:
Here are some examples of how you can use these.
For printing monetary values it is necessary to use I/O manipulators.
For example:
double income = 7842;
cout<<setprecision(2)<<setiosflags(ios::fixed|ios::showpoint)
<<"Income = $" <income;
Output:
Income = $7842.00
Here is the code, input, and output of an example showing how these manipulators work:
Output values are formatted in C++ by inserting I/O manipulators (parameterized) into cout statements for printing.
An example is cout<<setprecision(6)<<x<<y; where "setprecision(6)" is the I/O Manipulator.
These usually affect all outputs from that point on so there is no need to include the one your previously used in every cout statement after, but this might be compiler dependent.
In order to use I/O manipulators to format output you must have the header#include <iomanip>. The basic form for using I/O manipulators is: cout<<manipulator(parameter);.
Here is a list of several common I/O manipulators:
- setfill (int f) - This sets the fill character to f.
- setprecision(int p) - This sets the precision of a floating-point number to p.
- setw(int w) - This sets the field width to w.
- Setiosflags(long f) - This sets the format flag specified by f.
- resetiosflags(long f) - This returns to default for the flag specified by f.
- setbase(int b) - This sets the base of numbers output to be b (must be 8, 10, or 16).
- showpoint - Directs the output to include trailing zeros.
Here are some examples of how you can use these.
setw():
setprecision():
showpoint:
Two forms - cout<<setiosflags(ios::showpoint) and cout<<showpoint
setfill():
setiosflags(ios:: ):
cout<<setiosflags(ios::flag)
cout<<setiosflags(ios::flag1|ios::flag2|......)
Flags include:
setprecision():
showpoint:
Two forms - cout<<setiosflags(ios::showpoint) and cout<<showpoint
setfill():
setiosflags(ios:: ):
cout<<setiosflags(ios::flag)
cout<<setiosflags(ios::flag1|ios::flag2|......)
Flags include:
- left - left justify the output
- right - right justify the output
- fixed - use fixed-point notation (not scientific notation)
- scientific - use scientific notation
- showpoint - include trailing zeros
For printing monetary values it is necessary to use I/O manipulators.
For example:
double income = 7842;
cout<<setprecision(2)<<setiosflags(ios::fixed|ios::showpoint)
<<"Income = $" <income;
Output:
Income = $7842.00
Here is the code, input, and output of an example showing how these manipulators work:
Part 3: Selection Structures
It is often necessary in programming to make decisions, where the program will perform different tasks based on the results of some test.
The flowchart below shows the difference between straight line control structures and selection control structures.
if control structures are used to make decisions. Relational expressions are evaluated as true or false. The block of statements are only executed if true.
if control structures follow this form:
if (relational expression)
{
statement(s);
}
To use these kinds of structures you must use relational expressions. This is what produces the result of true or false. It compares values of two arithmetic expressions.
Sometimes you will need to compare characters and strings. This is essential in alphabetizing names or in using characters to make decisions in selection structures. Single characters are treated as integers and are compared based on their ASCII value. ('A' is valued at 65 and 'a' is valued at 97 therefore A < a)
Strings of characters are compared one character at a time. If the first character in each string is the same, then move on and compare the second character, etc. They are essentially ordered as they might be in a dictionary, so
"sent"<"sentence"<"sentences"
Sometimes logical operators are used for more complicated logical tests for branching. For example, instead of executing a block of statements if x>2, we might want to execute them if x>2 and if x<7.
The logical operators that are commonly used:
The symbol && represents the logical function AND. It combines two relation expressions. The combined expression is true only if BOTH expressions are true.
The symbol || represents the logical function OR. It combines two relational expressions. This combined expression is false only if BOTH expressions are false.
The symbol ! represents the logical NOT function. It reverses the result of a relational expression.
Here is the precedence of operators:
Simple if/else control structures:
Examples:
if (x<12)
----cout << "smaller than twelve";
else
----cout << "twelve or larger";
Note: No braces are needed since each block contains only one statement.
if (Hours > 40)
----{
----cout << "You worked overtime";
----Pay = 40*Base_Rate + (Hours - 40)*Overtime_Rate;
----}
else
----{
----cout << "No overtime worked";
----Pay = Hours*Base_Rate;
----}
Nested if statements are very common in programming. A nested if statement is an if statement that is the target of another if or else statement. Proper indentation helps us to understand the structure (although the compiler doesn't care).
Try to figure out the results from below and then check to see if you were right by compiling it.
if-else-if structures:
Try this one below:
You can check the answers from above by simply compiling the code on the left side of the picture.
Note: The indentation used in that code is extremely important. Without that indentation it would be much harder to read and understand the code. (even though it doesn't matter to the computer)
Below is an example of using "switch" structure.
The next image is the same program but allows for character input instead of numerical input. (for the choice)
- So far, all of our C++ programs have consisted of straight line control, or a series of commands executed in order with no branches.
- Now we will talk about selection structures (also called decision structures or branching structures).
- Two types of selection structures will be introduced: if structures and switch structures.
The flowchart below shows the difference between straight line control structures and selection control structures.
if control structures are used to make decisions. Relational expressions are evaluated as true or false. The block of statements are only executed if true.
if control structures follow this form:
if (relational expression)
{
statement(s);
}
To use these kinds of structures you must use relational expressions. This is what produces the result of true or false. It compares values of two arithmetic expressions.
Sometimes you will need to compare characters and strings. This is essential in alphabetizing names or in using characters to make decisions in selection structures. Single characters are treated as integers and are compared based on their ASCII value. ('A' is valued at 65 and 'a' is valued at 97 therefore A < a)
Strings of characters are compared one character at a time. If the first character in each string is the same, then move on and compare the second character, etc. They are essentially ordered as they might be in a dictionary, so
"sent"<"sentence"<"sentences"
Sometimes logical operators are used for more complicated logical tests for branching. For example, instead of executing a block of statements if x>2, we might want to execute them if x>2 and if x<7.
The logical operators that are commonly used:
- AND (&&)
- OR (||)
- NOT (!)
The symbol && represents the logical function AND. It combines two relation expressions. The combined expression is true only if BOTH expressions are true.
The symbol || represents the logical function OR. It combines two relational expressions. This combined expression is false only if BOTH expressions are false.
The symbol ! represents the logical NOT function. It reverses the result of a relational expression.
Here is the precedence of operators:
Simple if/else control structures:
- One block of statements is executed if the expression is true and another block if the expression is false.
- Braces are optional if there is only one statement in the block.
Examples:
if (x<12)
----cout << "smaller than twelve";
else
----cout << "twelve or larger";
Note: No braces are needed since each block contains only one statement.
if (Hours > 40)
----{
----cout << "You worked overtime";
----Pay = 40*Base_Rate + (Hours - 40)*Overtime_Rate;
----}
else
----{
----cout << "No overtime worked";
----Pay = Hours*Base_Rate;
----}
Nested if statements are very common in programming. A nested if statement is an if statement that is the target of another if or else statement. Proper indentation helps us to understand the structure (although the compiler doesn't care).
Try to figure out the results from below and then check to see if you were right by compiling it.
if-else-if structures:
- Shifts program control, step by step, through series of statement blocks
- Control stops at relational expression that tests true
- Some programming languages have an "elseif" command. In C++, using else if(relational expression) simply implies that the if statement represents that block of instructions to be represented when the else condition is true.
- Proper indentation is important for readability.
- In general, an else statement always refers to the nearest if statement that is within the same block as the else and not already associated with another else.[/b]
Try this one below:
You can check the answers from above by simply compiling the code on the left side of the picture.
Note: The indentation used in that code is extremely important. Without that indentation it would be much harder to read and understand the code. (even though it doesn't matter to the computer)
Below is an example of using "switch" structure.
The next image is the same program but allows for character input instead of numerical input. (for the choice)