Learning C++ Part One Example
C++ Syntax
Example
- #include <iostream>
- using namespace std;
- int main() {
- cout << "Hello World!";
- return 0;
- }
Example explained
- Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such as cout (used in line 5). Header files add functionality to C++ programs.
- Line 2: using namespace std means that we can use names for objects and variables from the standard library.
- Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.
- Line 4: Another thing that always appear in a C++ program, is int main(). This is called a function. Any code inside its curly brackets {} will be executed.
- Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to output/print text. In our example it will output "Hello World!".
- Note: Every C++ statement ends with a semicolon;.
- Note: The body of int main() could also been written as:
- int main () { cout << "Hello World! "; return 0; }
- Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.
- Line 6: return 0 ends the main function.
- Line 7: Do not forget to add the closing curly bracket } to actually end the main function.
Omitting Namespace
You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omitted and replaced with the std keyword, followed by the:: operator for some objects:
Example
- #include <iostream>
- int main() {
- std::cout << "Hello World!";
- return 0;
- }
C++ Output (Print Text)
- #include <iostream>
- using namespace std;
- int main() {
- cout << "Hello World!";
- return 0;
- }
- #include <iostream>
- using namespace std;
- int main() {
- cout << "Hello World!";
- cout << "I am learning C++";
- return 0;
- }
- #include <iostream>
- using namespace std;
- int main() {
- cout << "Hello World! \n";
- cout << "I am learning C++";
- return 0;
- }
- #include <iostream>
- using namespace std;
- int main() {
- cout << "Hello World! \n\n";
- cout << "I am learning C++";
- return 0;
- }
- #include <iostream>
- using namespace std;
- int main() {
- cout << "Hello World!" << endl;
- cout << "I am learning C++";
- return 0;
- }
|
Escape Sequence |
Description |
|
\t |
Creates a horizontal tab |
|
\\ |
Inserts a backslash character (\) |
|
\" |
Inserts a double quote character |
- // This is a comment
- cout << "Hello World!";
- cout << "Hello World!"; // This is a comment
- /* The code below will print the words Hello World!
- to the screen, and it is amazing */
- cout << "Hello World!";
C++ Variables
- int - stores integers (whole numbers), without decimals, such as 123 or -123
- double - stores floating point numbers, with decimals, such as 19.99 or -19.99
- char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
- string - stores text, such as "Hello World". String values are surrounded by double quotes
- bool - stores values with two states: true or false
Declaring (Creating) Variables
- type variableName = value;
- int myNum = 15;
- cout << myNum;
- int myNum;
- myNum = 15;
- cout << myNum;
- int myNum = 15; // myNum is 15
- myNum = 10; // Now myNum is 10
- cout << myNum; // Outputs 10
Other Types
- int myNum = 5; // Integer (whole number without decimals)
- double myFloatNum = 5.99; // Floating point number (with decimals)
- char myLetter = 'D'; // Character
- string myText = "Hello"; // String (text)
- bool myBoolean = true; // Boolean (true or false)
Display Variables
- int myAge = 35;
- cout << "I am " << myAge << " years old.";
Add Variables Together
- int x = 5;
- int y = 6;
- int sum = x + y;
- cout << sum;
Declare Many Variables
- int x = 5, y = 6, z = 50;
- cout << x + y + z;
- int x, y, z;
- x = y = z = 50;
- cout << x + y + z;
C++ Identifiers
- // Good
- int minutesPerHour = 60;
- // OK, but not so easy to understand what m actually is
- int m = 60;
- Names can contain letters, digits and underscores
- Names must begin with a letter or an underscore (_)
- Names are case sensitive (myVar and myvar are different variables)
- Names cannot contain whitespaces or special characters like !, #, %, etc.
- Reserved words (like C++ keywords, such as int) cannot be used as names
Constants
- const int myNum = 15; // myNum will always be 15
- myNum = 10; // error: assignment of read-only variable 'myNum'
- const int minutesPerHour = 60;
- const float PI = 3.14;
C++ User Input
- int x;
- cout << "Type a number: "; // Type a number and press enter
- cin >> x; // Get user input from the keyboard
- cout << "Your number is: " << x; // Display the input value
- cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)
- cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)
Creating a Simple Calculator
- int x, y;
- int sum;
- cout << "Type a number: ";
- cin >> x;
- cout << "Type another number: ";
- cin >> y;
- sum = x + y;
- cout << "Sum is: " << sum;
- int x;
- cout << "Type a number: ";
- ___>> _____
- ;
C++ Data Types
- int myNum = 5; // Integer (whole number)
- float myFloatNum = 5.99; // Floating point number
- double myDoubleNum = 9.98; // Floating point number
- char myLetter = 'D'; // Character
- bool myBoolean = true; // Boolean
- string myText = "Hello"; // String
Basic Data Types
|
Data
Type |
Size |
Description |
|
Boolean |
1
byte |
Stores true or
false values |
|
char |
1
byte |
Stores a single
character/letter/number, or ASCII values |
|
int |
2
or 4 bytes |
Stores whole
numbers, without decimals |
|
float |
4
bytes |
Stores
fractional numbers, containing one or more decimals. Sufficient for storing
6-7 decimal digits |
|
double |
8
bytes |
Stores
fractional numbers, containing one or more decimals. Sufficient for storing
15 decimal digits |
- ______ myNum = 9;
- ______ myDoubleNum = 8.99;
- ______ myLetter = 'A';
- _______ myBool = false;
- _______ myText = "Hello World";
Numeric Types
- int myNum = 1000;
- cout << myNum;
- float myNum = 5.75;
- cout << myNum;
- double myNum = 19.99;
- cout << myNum;
float vs. double
- float f1 = 35e3;
- double d1 = 12E4;
- cout << f1;
- cout << d1;
Boolean Types
- bool isCodingFun = true;
- bool isFishTasty = false;
- cout << isCodingFun; // Outputs 1 (true)
- cout << isFishTasty; // Outputs 0 (false)
Character Types
- char myGrade = 'B';
- cout << myGrade;
- char a = 65, b = 66, c = 67;
- cout << a;
- cout << b;
- cout << c;
String Types
- string greeting = "Hello";
- cout << greeting;
- // Include the string library
- #include <string>
- // Create a string variable
- string greeting = "Hello";
- // Output string value
- cout << greeting;
C++ Operators
- int x = 100 + 50;
- int sum1 = 100 + 50; // 150 (100 + 50)
- int sum2 = sum1 + 250; // 400 (150 + 250)
- int sum3 = sum2 + sum2; // 800 (400 + 400)
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
Arithmetic Operators
|
Operator |
Name |
Description |
Example |
|
+ |
Addition |
Adds together
two values |
x
+ y |
|
- |
Subtraction |
Subtracts one
value from another |
x
- y |
|
* |
Multiplication |
Multiplies two
values |
x
* y |
|
/ |
Division |
Divides one
value by another |
x
/ y |
|
% |
Modulus |
Returns the
division remainder |
x
% y |
|
++ |
Increment |
Increases the
value of a variable by 1 |
++x |
|
-- |
Decrement |
Decreases the
value of a variable by 1 |
--x |
- cout << 10 _____ 5;
Assignment Operators
- int x = 10;
- int x = 10;
- x += 5;
|
Operator |
Example |
Same
As |
|
= |
x
= 5 |
x
= 5 |
|
+= |
x
+= 3 |
x
= x + 3 |
|
-= |
x
-= 3 |
x
= x - 3 |
|
*= |
x
*= 3 |
x
= x * 3 |
|
/= |
x
/= 3 |
x
= x / 3 |
|
%= |
x
%= 3 |
x
= x % 3 |
|
&= |
x
&= 3 |
x
= x & 3 |
|
|= |
x
|= 3 |
x
= x | 3 |
|
^= |
x
^= 3 |
x
= x ^ 3 |
|
>>= |
x
>>= 3 |
x
= x >> 3 |
|
<<= |
x
<<= 3 |
x
= x << 3 |
Comparison Operators
- int x = 5;
- int y = 3;
- cout << (x > y); // returns 1 (true) because 5 is greater than 3
|
Operator |
Name |
Example |
|
== |
Equal
to |
x
== y |
|
!= |
Not
equal |
x!
= y |
|
> |
Greater
than |
x
> y |
|
< |
Less
than |
x
< y |
|
>= |
Greater
than or equal to |
x
>= y |
|
<= |
Less
than or equal to |
x
<= y |
Logical Operators
|
Operator |
Name |
Description |
Example |
|
&& |
Logical
and |
Returns true if
both statements are true |
x
< 5 && x < 10 |
|
|| |
Logical
or |
Returns true if
one of the statements is true |
x
< 5 || x < 4 |
|
! |
Logical
not |
Reverse the
result, returns false if the result is true |
!(x
< 5 && x < 10) |
C++ Strings
- string greeting = "Hello";
- // Include the string library
- #include <string>
- // Create a string variable
- string greeting = "Hello";
- ______ _______ = _______ ;
String Concatenation
- string firstName = "John ";
- string lastName = "Doe";
- string fullName = firstName + lastName;
- cout << fullName;
- string firstName = "John";
- string lastName = "Doe";
- string fullName = firstName + " " + lastName;
- cout << fullName;
- string firstName = "John ";
- string lastName = "Doe";
- string fullName = firstName.append(lastName);
- cout << fullName;
Adding Numbers and Strings
- int x = 10;
- int y = 20;
- int z = x + y; // z will be 30 (an integer)
- string x = "10";
- string y = "20";
- string z = x + y; // z will be 1020 (a string)
- string x = "10";
- int y = 20;
- string z = x + y;
String Length
- string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- cout << "The length of the txt string is: " << txt.length();
- string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- cout << "The length of the txt string is: " << txt.size();
Access Strings
- string myString = "Hello";
- cout << myString[0];
- // Outputs H
- string myString = "Hello";
- cout << myString[1];
- // Outputs e
- string myString = "Hello";
- myString[0] = 'J';
- cout << myString;
- // Outputs Jello instead of Hello
Strings - Special Characters
- string txt = "We are the so-called "Vikings" from the north.";
|
Escape
character |
Result |
Description |
|
\' |
' |
Single quote |
|
\" |
" |
Double quote |
|
\\ |
\ |
Backslash |
- string txt = "We are the so-called \"Vikings\" from the north.";
- string txt = "It\'s alright.";
- string txt = "The character \\ is called backslash.";
|
Escape Character |
Result |
|
\n |
New Line |
|
\t |
Tab |
User Input Strings
- string firstName;
- cout << "Type your first name: ";
- cin >> firstName; // get user input from the keyboard
- cout << "Your name is: " << firstName;
- // Type your first name: John
- // Your name is: John
- string fullName;
- cout << "Type your full name: ";
- cin >> fullName;
- cout << "Your name is: " << fullName;
- // Type your full name: John Doe
- // Your name is: John
- string fullName;
- cout << "Type your full name: ";
- getline (cin, fullName);
- cout << "Your name is: " << fullName;
- // Type your full name: John Doe
- // Your name is: John Doe
Omitting Namespace
- #include <iostream>
- #include <string>
- int main() {
- std::string greeting = "Hello";
- std::cout << greeting;
- return 0;
- }
C++ Math
- cout << max(5, 10);
- cout << min(5, 10);
- // Include the cmath library
- #include <cmath>
- cout << sqrt(64);
- cout << round(2.6);
- cout << log(2);
Other Math Functions
|
Function |
Description |
|
abs(x) |
Returns the
absolute value of x |
|
acos(x) |
Returns the
arccosine of x |
|
asin(x) |
Returns the arcsine
of x |
|
atan(x) |
Returns the
arctangent of x |
|
cbrt(x) |
Returns the cube
root of x |
|
ceil(x) |
Returns the value
of x rounded up to its nearest integer |
|
cos(x) |
Returns the cosine
of x |
|
cosh(x) |
Returns the
hyperbolic cosine of x |
|
exp(x) |
Returns the value
of Ex |
|
expm1(x) |
Returns ex -1 |
|
fabs(x) |
Returns the
absolute value of a floating x |
|
fdim(x, y) |
Returns the
positive difference between x and y |
|
floor(x) |
Returns the value
of x rounded down to its nearest integer |
|
hypot(x, y) |
Returns sqrt(x2 +y2)
without intermediate overflow or underflow |
|
fma(x, y, z) |
Returns x*y+z
without losing precision |
|
fmax(x, y) |
Returns the highest
value of a floating x and y |
|
fmin(x, y) |
Returns the lowest
value of a floating x and y |
|
fmod(x, y) |
Returns the
floating point remainder of x/y |
|
pow(x, y) |
Returns the value
of x to the power of y |
|
sin(x) |
Returns the sine of
x (x is in radians) |
|
sinh(x) |
Returns the
hyperbolic sine of a double value |
|
tan(x) |
Returns the tangent
of an angle |
|
tanh(x) |
Returns the
hyperbolic tangent of a double value |
- int x = 5;
- int y = 10;
- cout << ______ (x, y);
C++ Booleans
- YES / NO
- ON / OFF
- TRUE / FALSE
Boolean Values
- bool isCodingFun = true;
- bool isFishTasty = false;
- cout << isCodingFun; // Outputs 1 (true)
- cout << isFishTasty; // Outputs 0 (false)
Boolean Expression
- int x = 10;
- int y = 9;
- cout << (x > y); // returns 1 (true), because 10 is higher than 9
- cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
- int x = 10;
- cout << (x == 10); // returns 1 (true), because the value of x is equal to 10
- cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15
- int myAge = 25;
- int votingAge = 18;
- cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds are allowed to vote!
- int myAge = 25;
- int votingAge = 18;
- if (myAge >= votingAge) {
- cout << "Old enough to vote!";
- } else {
- cout << "Not old enough to vote.";
- }
- // Outputs: Old enough to vote!
- ____ isCodingFun = true;
- _____ isFishTasty = false;
- cout << ______ ;
- cout << _____ ;
C++ Conditions and If Statements
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to a == b
- Not Equal to: a != b
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to specify many alternative blocks of code to be executed
The if Statement
- if (condition) {
- // block of code to be executed if the condition is true
- }
- if (20 > 18) {
- cout << "20 is greater than 18";
- }
- int x = 20;
- int y = 18;
- if (x > y) {
- cout << "x is greater than y";
- }
- int x = 50;
- int y = 10;
- ______ (x ______ y) {
- cout << "Hello World";
- }
The else Statement
- if (condition) {
- // block of code to be executed if the condition is true
- } else {
- // block of code to be executed if the condition is false
- }
- int time = 20;
- if (time < 18) {
- cout << "Good day.";
- } else {
- cout << "Good evening.";
- }
- // Outputs "Good evening."
The else-if Statement
- if (condition1) {
- // block of code to be executed if condition1 is true
- } else if (condition2) {
- // block of code to be executed if the condition1 is false and condition2 is true
- } else {
- // block of code to be executed if the condition1 is false and condition2 is false
- }
- int time = 22;
- if (time < 10) {
- cout << "Good morning.";
- } else if (time < 20) {
- cout << "Good day.";
- } else {
- cout << "Good evening.";
- }
- // Outputs "Good evening."
Short Hand If...Else (Ternary Operator)
- variable = (condition) ? expressionTrue : expressionFalse;
- int time = 20;
- if (time < 18) {
- cout << "Good day.";
- } else {
- cout << "Good evening.";
- }
- int time = 20;
- string result = (time < 18) ? "Good day." : "Good evening.";
- cout << result;
C++ Switch Statements
- switch(expression) {
- case x:
- // code block
- break;
- case y:
- // code block
- break;
- default:
- // code block
- }
- The switch expression is evaluated once
- The value of the expression is compared with the values of each case
- If there is a match, the associated block of code is executed
- The break and default keywords are optional, and will be described later in this chapter
- int day = 4;
- switch (day) {
- case 1:
- cout << "Monday";
- break;
- case 2:
- cout << "Tuesday";
- break;
- case 3:
- cout << "Wednesday";
- break;
- case 4:
- cout << "Thursday";
- break;
- case 5:
- cout << "Friday";
- break;
- case 6:
- cout << "Saturday";
- break;
- case 7:
- cout << "Sunday";
- break;
- }
- // Outputs "Thursday" (day 4)
The default Keyword
- int day = 4;
- switch (day) {
- case 6:
- cout << "Today is Saturday";
- break;
- case 7:
- cout << "Today is Sunday";
- break;
- default:
- cout << "Looking forward to the Weekend";
- }
- // Outputs "Looking forward to the Weekend"
- int day = 2;
- switch ( ______ ) {
- _____ 1:
- cout << "Saturday";
- break;
- _______ 2:
- cout << "Sunday";
- _________ ;
- }
C++ Loops
C++ While Loop
- while (condition) {
- // code block to be executed
- }
- int i = 0;
- while (i < 5) {
- cout << i << "\n";
- i++;
- }
- int i = 1;
- ______ (i < 6) {
- cout << i << "\n";
- _______ ;
- }
The Do/While Loop
- do {
- // code block to be executed
- }
- while (condition);
- int i = 0;
- do {
- cout << i << "\n";
- i++;
- }
- while (i < 5);
C++ For Loop
- for (statement 1; statement 2; statement 3) {
- // code block to be executed
- }
- Statement 1 is executed (one time) before the execution of the code block.
- Statement 2 defines the condition for executing the code block.
- Statement 3 is executed (every time) after the code block has been executed.
- for (int i = 0; i < 5; i++) {
- cout << i << "\n";
- }
- Statement 1 sets a variable before the loop starts (int i = 0).
- Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.
- Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Another Example
- for (int i = 0; i <= 10; i = i + 2) {
- cout << i << "\n";
- }
Nested Loops
- // Outer loop
- for (int i = 1; i <= 2; ++i) {
- cout << "Outer: " << i << "\n"; // Executes 2 times
- // Inner loop
- for (int j = 1; j <= 3; ++j) {
- cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
- }
- }
The foreach Loop
- for (type variableName : arrayName) {
- // code block to be executed
- }
- int myNumbers[5] = {10, 20, 30, 40, 50};
- for (int i : myNumbers) {
- cout << i << "\n";
- }
- _______ (int i = 0; i < 5; ______ ) {
- cout << _______ << "\n";
- }
C++ Break
- for (int i = 0; i < 10; i++) {
- if (i == 4) {
- break;
- }
- cout << i << "\n";
- }
C++ Continue
- for (int i = 0; i < 10; i++) {
- if (i == 4) {
- continue;
- }
- cout << i << "\n";
- }
Break and Continue in While Loop
- int i = 0;
- while (i < 10) {
- cout << i << "\n";
- i++;
- if (i == 4) {
- break;
- }
- }
- int i = 0;
- while (i < 10) {
- if (i == 4) {
- i++;
- continue;
- }
- cout << i << "\n";
- i++;
- }
- for (int i = 0; i < 10; i++) {
- if (i == 5) {
- _______
- ;
- }
- cout << i << "\n";
- }
C++ Arrays
- string cars[4];
- string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
- int myNum[3] = {10, 20, 30};
Access the Elements of an Array
- string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
- cout << cars[0];
- // Outputs Volvo
Change an Array Element
- cars[0] = "Opel";
- string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
- cars[0] = "Opel";
- cout << cars[0];
- // Now outputs Opel instead of Volvo
- ____ _____[4] = {"Volvo", "BMW", "Ford", "Mazda"};
Loop Through an Array
- string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
- for (int i = 0; i < 5; i++) {
- cout << cars[i] << "\n";
- }
- string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
- for (int i = 0; i < 5; i++) {
- cout << i << " = " << cars[i] << "\n";
- }
- int myNumbers[5] = {10, 20, 30, 40, 50};
- for (int i = 0; i < 5; i++) {
- cout << myNumbers[i] << "\n";
- }
The foreach Loop
- for (type variableName : arrayName) {
- // code block to be executed
- }
- int myNumbers[5] = {10, 20, 30, 40, 50};
- for (int i : myNumbers) {
- cout << i << "\n";
- }
Omit Array Size
- string cars[] = {"Volvo", "BMW", "Ford"}; // Three arrays
- string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three arrays
Omit Elements on Declaration
- string cars[5];
- cars[0] = "Volvo";
- cars[1] = "BMW";
- ...
Get the Size of an Array
- int myNumbers[5] = {10, 20, 30, 40, 50};
- cout << sizeof(myNumbers);
- int myNumbers[5] = {10, 20, 30, 40, 50};
- int getArrayLength = sizeof(myNumbers) / sizeof(int);
- cout << getArrayLength;
Loop Through an Array with sizeof()
- int myNumbers[5] = {10, 20, 30, 40, 50};
- for (int i = 0; i < 5; i++) {
- cout << myNumbers[i] << "\n";
- }
- int myNumbers[5] = {10, 20, 30, 40, 50};
- for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
- cout << myNumbers[i] << "\n";
- }
- int myNumbers[5] = {10, 20, 30, 40, 50};
- for (int i : myNumbers) {
- cout << i << "\n";
- }
Multi-Dimensional Arrays
- string letters[2][4];
- string letters[2][4] = {
- { "A", "B", "C", "D" },
- { "E", "F", "G", "H" }
- };
- string letters[2][2][2] = {
- {
- { "A", "B" },
- { "C", "D" }
- },
- {
- { "E", "F" },
- { "G", "H" }
- }
- };
Access the Elements of a Multi-Dimensional Array
- string letters[2][4] = {
- { "A", "B", "C", "D" },
- { "E", "F", "G", "H" }
- };
- cout << letters[0][2]; // Outputs "C"
Change Elements in a Multi-Dimensional Array
- string letters[2][4] = {
- { "A", "B", "C", "D" },
- { "E", "F", "G", "H" }
- };
- letters[0][0] = "Z";
- cout << letters[0][0]; // Now outputs "Z" instead of "A"
Loop Through a Multi-Dimensional Array
- string letters[2][4] = {
- { "A", "B", "C", "D" },
- { "E", "F", "G", "H" }
- };
- for (int i = 0; i < 2; i++) {
- for (int j = 0; j < 4; j++) {
- cout << letters[i][j] << "\n";
- }
- }
- string letters[2][2][2] = {
- {
- { "A", "B" },
- { "C", "D" }
- },
- {
- { "E", "F" },
- { "G", "H" }
- }
- };
- for (int i = 0; i < 2; i++) {
- for (int j = 0; j < 2; j++) {
- for (int k = 0; k < 2; k++) {
- cout << letters[i][j][k] << "\n";
- }
- }
- }
Why Multi-Dimensional Arrays?
- // We put "1" to indicate there is a ship.
- bool ships[4][4] = {
- { 0, 1, 1, 0 },
- { 0, 0, 0, 0 },
- { 0, 0, 1, 0 },
- { 0, 0, 1, 0 }
- };
- // Keep track of how many hits the player has and how many turns they have played in these variables
- int hits = 0;
- int numberOfTurns = 0;
- // Allow the player to keep going until they have hit all four ships
- while (hits < 4) {
- int row, column;
- cout << "Selecting coordinates\n";
- // Ask the player for a row
- cout << "Choose a row number between 0 and 3: ";
- cin >> row;
- // Ask the player for a column
- cout << "Choose a column number between 0 and 3: ";
- cin >> column;
- // Check if a ship exists in those coordinates
- if (ships[row][column]) {
- // If the player hit a ship, remove it by setting the value to zero.
- ships[row][column] = 0;
- // Increase the hit counter
- hits++;
- // Tell the player that they have hit a ship and how many ships are left
- cout << "Hit! " << (4-hits) << " left.\n\n";
- } else {
- // Tell the player that they missed
- cout << "Miss\n\n";
- }
- // Count how many turns the player has taken
- numberOfTurns++;
- }
- cout << "Victory!\n";
- cout << "You won in " << numberOfTurns << " turns";
C++ Structures
Create a Structure
- struct { // Structure declaration
- int myNum; // Member (int variable)
- string myString; // Member (string variable)
- } myStructure; // Structure variable
Access Structure Members
- // Create a structure variable called myStructure
- struct {
- int myNum;
- string myString;
- } myStructure;
- // Assign values to members of myStructure
- myStructure.myNum = 1;
- myStructure.myString = "Hello World!";
- // Print members of myStructure
- cout << myStructure.myNum << "\n";
- cout << myStructure.myString << "\n";
- struct {
- int myNum;
- string myString;
- } myStruct1, myStruct2, myStruct3; // Multiple structure variables separated with commas
- struct {
- string brand;
- string model;
- int year;
- } myCar1, myCar2; // We can add variables by separating them with a comma here
- // Put data into the first structure
- myCar1.brand = "BMW";
- myCar1.model = "X5";
- myCar1.year = 1999;
- // Put data into the second structure
- myCar2.brand = "Ford";
- myCar2.model = "Mustang";
- myCar2.year = 1969;
- // Print the structure members
- cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
- cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
Named Structures
- struct myDataType { // This structure is named "myDataType"
- int myNum;
- string myString;
- };
- myDataType myVar;
- // Declare a structure named "car"
- struct car {
- string brand;
- string model;
- int year;
- };
- int main() {
- // Create a car structure and store it in myCar1;
- car myCar1;
- myCar1.brand = "BMW";
- myCar1.model = "X5";
- myCar1.year = 1999;
- // Create another car structure and store it in myCar2;
- car myCar2;
- myCar2.brand = "Ford";
- myCar2.model = "Mustang";
- myCar2.year = 1969;
- // Print the structure members
- cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
- cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
- return 0;
- }
Creating References
- string food = "Pizza"; // food variable
- string &meal = food; // reference to food
- string food = "Pizza";
- string &meal = food;
- cout << food << "\n"; // Outputs Pizza
- cout << meal << "\n"; // Outputs Pizza
Memory Address
- string food = "Pizza";
- cout << &food; // Outputs 0x6dfed4
Creating Pointers
- string food = "Pizza"; // A food variable of type string
- cout << food; // Outputs the value of food (Pizza)
- cout << &food; // Outputs the memory address of food (0x6dfed4)
- string food = "Pizza"; // A food variable of type string
- string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food
- // Output the value of food (Pizza)
- cout << food << "\n";
- // Output the memory address of food (0x6dfed4)
- cout << &food << "\n";
- // Output the memory address of food with the pointer (0x6dfed4)
- cout << ptr << "\n";
- string* mystring; // Preferred
- string *mystring;
- string * mystring;
- string food = "Pizza";
- ______ _____ = & ______ ;
Get Memory Address and Value
- string food = "Pizza"; // Variable declaration
- string* ptr = &food; // Pointer declaration
- // Reference: Output the memory address of food with the pointer (0x6dfed4)
- cout << ptr << "\n";
- // Dereference: Output the value of food with the pointer (Pizza)
- cout << *ptr << "\n";
- When used in declaration (string* ptr), it creates a pointer variable.
- When not used in declaration, it act as a dereference operator.
Modify the Pointer Value
- string food = "Pizza";
- string* ptr = &food;
- // Output the value of food (Pizza)
- cout << food << "\n";
- // Output the memory address of food (0x6dfed4)
- cout << &food << "\n";
- // Access the memory address of food and output its value (Pizza)
- cout << *ptr << "\n";
- // Change the value of the pointer
- *ptr = "Hamburger";
- // Output the new value of the pointer (Hamburger)
- cout << *ptr << "\n";
- // Output the new value of the food variable (Hamburger)
- cout << food << "\n";

Comments
Post a Comment