Theory
Types
- C++ is a strongly typed programming language where every variable has a type, name, value, and location in memory.
- In C++, there are only two types of variables that we can have. Every variable is either a primitive variable or it is a user-defined variable.
- Primitive
- User-defined
int
, (4) stores integerschar
, (1)stores single characters/single bytebool
, (1) stores a Boolean (true or false)float
, (4) stores a floating point numberdouble
, (8)stores a double-precision floating point numbervoid
, denotes the absence of a valueshort int
(2) // or shortunsigned int
(4) // or unsignedunsigned char
(1) // is bytestd::string
, a string (sequence of characters)std::vector
, a dynamically-growing array
The type of a variable defines the contents of the variable. Every type is either:
Primitive Types
There are just 6 common primitive types in C++:
and some more:
User-Defined Types
An unbounded number of user-defined types can exist
Two very common user-defined types:
C++ Programs
Every C++ program must contain a starting point. By the C++ standard, the starting point is a function: int main()
By convention, the return value of main is 0 (zero) if the program was successful and non-zero on errors.
Sample:
int main() { int i= 4; i = i+ 2; char c = 'a'; std::cout << i << " " << c << std::endl; // output return 0; } |
C++’s Standard Library (std)
The C++ standard library (std
) provides a set of commonly used functionality and data structures.
The C++ standard library is organized into many separate sub-libraries that can be #included in any C++ program.
The iostream
header includes operations for reading/writing to files and the console itself, including std::cout
.
#include <iostream> int main() { std::cout << "Hello, world!" << std::endl; system("pause"); return 0; } |
All functionality used from the standard library will be part of the std
namespace. Namespaces allow us to avoid name conflicts for commonly used names. If a feature from a namespace is used often, it can be imported into the global space with using
statement:
#include <iostream> using std::cout; using std::endl; int main() { cout << "Hello, world!" << endl; system("pause"); return 0; } |
or importing the namespace std
itself:
#include <iostream> using namespace std; int main() { cout << "Hello, world!" << endl; system("pause"); return 0; } |
C++ SYNTAX
double d { 3.14 }; auto s { "C++" }; int i { 3.7 }; // error! char c { 128 }; // error! bool b { -1 }; // error! int j { true }; // OK, j == 1 |
When trying to assign a floating point value to an integer variable, the fractional part will be discarded
int i = 3.14; // i == 3 |
char c = 128; // warning: constant value truncation |
bool b = -1; // true – warning: truncation from "int" to "bool" |
C++
|
PascalABC.NET
|
Block Scope
The idea is that certain blocks of code, signified by { }
, create an inner stack on top of the previous stack memory, which can hide the pre-existing values. The lifetime of stack variables inside a block is called the variable’s scope. Variables created on the stack inside the inner block are only in existence for the duration of the block. When the block ends, the inner stack is removed, and the pre-existing values in the outer scope are available again.
#include <iostream> int main() { // In the initial, outer scope: int x = 2; std::cout << "Outer scope value of x (should be 2): " << x << std::endl; // Create an inner scope and make a new variable with the name "x". // We can redeclare x because of the inner scope. { int x = 3; int y = 4; std::cout << "Inner scope vaue of x (should be 3): " << x << std::endl; std::cout << "Inner scope vaue of y (should be 4): " << y << std::endl; } // Now that the inner block has closed, the inner x and y are gone. // The original x variable is still on the stack (memory), and it has its old value: std::cout << "Outer scope value of x (should be 2): " << x << std::endl; // We can't refer to y here, because it doesn't exist in this scope at all! // If you un-comment this line, there will be a compile error. // std::cout << "This line causes an error because y doesn't exist: " << y << std::endl; return 0; } |
Condition statements
Some keywords like if can have a block in { }
afterwards, which does create an inner block scope for the duration of the conditional block:
#include <iostream> using namespace std; int main() { int x = 2; cout << "Outer scope value of x (should be 2): " << x << endl; if (true) { int x = 3; cout << "Inner scope vaue of x (should be 3): " << x << endl; } cout << "Outer scope value of x (should be 2): " << x << endl; return 0; } |
if (condition) { // true case } else { // false case } |
or multiple cases:
if (condition1) { } else if (condition2) { } else if (condition3) { } else { // If none of the other conditions were met... } |
Syntax:
[Boolean-valued condition] ? [expression to evaluate if true] : [expression to evaluate if false]
// Since (5<10) is true, the expression before the colon will be selected, which is 1. int x = 5 < 10 ? 1 : 2; // Now x is equal to 1 |
Syntax:
switch (variable to check) { case value1: // to do something break; case value2: // to do something break; case value3: // to do something break; … default: // to do something if nothing matches } |
Loops
There are several kinds of loops in C++ that allow you to process data iteratively.
for loops
The for loop
is a common loop type that lets you specify an iteration variable (counter), a range for that variable, and an increment instruction. The syntax is:
for ( declaration ; condition ; increment operation ) { loop body }
#include <iostream> using namespace std; int main() { // outer scope version of "x" int x = -1; // The for loop lets us declare a variable in the first part of the // loop statement, which will belong to the inner block scope: for (int x = 0; x <= 2; x++) { cout << "[Inside the loop] x is now: " << x << endl; // 0 .. 1 .. 2 } // This version doesn't redeclare x, so it just inherits access to the // same x variable from the outer scope. This modifies the outer x directly for (x = 0; x <= 2; x++) { cout << "[Inside the loop] x is now: " << x << endl; } return 0; } |
while loops
syntax:
while (condition) { loop body } |
do-while loops
syntax:
do { loop body } while (condition) |
Labs and tasks
To do: Create a simple console application that allows you to enter an integer, increase it by one, and print the result out to the console.
Expected output:
Please enter an integer: 4 Result: 5
[Solution and Project name: Lesson_1
, file name main.cpp
]
✍ How to do:
- Open Microsoft Visual Studio. Select menu item File -> New project. In the Template region find C++ and then, Win32 Console Application.
- Create a new console project, name your project
Lesson_1
. Among the Additional options mark Empty project and nothing more. Click Finish button. - In the Solution Explorer window find a Source files folder, click the right mouse button on it and select Add -> New Item. We’re going to create
.cpp
file. Call itMain.cpp
. - Make sure that the file
Main.cpp
is active in the Solution Explorer window. - Place your cursor on the first line of the code editor window.
- Add a header code:
- After, type the code of the Main function:
- Place your cursor after the opening curly brace of the main function and make a new line. Add a declaration of the
x
variable. It must be integer: - Ask the user to input a number:
- Use std library again to input a value to store it in
x
variable: - Enter the code to increase x by 1:
- Print the result out to the console:
- The main function commonly must return 0. Add the code line right before the closing curly brace of the main function:
- Run the application. The console window has disappeared too fast. We can’t see the result.
- Add the pause to stay the window opened:
- Run the application again.
- In order not always to print
std
namespace, we can import some it’s functions to our project. Type the following code at the top of your code, in the header region: - Now, you can change the code with
cout
andcin
methods by clearing up thestd
: - Run the application again.
- But instead of importing some features of
std
library we can import thestd
namespace itself. Clear the using lines we’ve added. Place the following code instead of them: - Run the project and see the same results.
#include <iostream> |
int main() { // … }
int x; |
std::cout << "Please enter an integer: ";
std
) provides a set of commonly used functionality and data structures to build upon....
std::cin >> x;
...
x++; |
std::cout << "Result: " << x << std::endl;
endl
makes a new line after your code.… system("pause"); return 0; }
Importing some features from the std library:
using std::cout; using std::cin; using std::endl;
std
namespace.If a feature from a namespace is used often, it can be imported into the global space
cout << "Please enter an integer: "; … cin >> x; … cout << "Result: " << x << endl;
Importing std namespace:
using namespace std;
To do: Create a simple console application that prints a welcome phrase (“Hello world!”) out to the console. Give Lesson_1Task1
name to your application and L1Task1.cpp
name to your .cpp file. Use the lab 1 to create a console application and give it a name.
Expected output:
Hello world!
[Solution and Project name: Lesson_1Task1
, file name L1Task1.cpp
]
To do: Ask the user to input a number — a grade mark (1, 2, 3, 4, 5). Check the input and print out the characteristic of the mark to the console window (very_bad — 1, bad — 2, satisfactory — 3, good — 4, excellent — 5). The characteristic should be stored in a string variable (it is better to have the same name for this variable — characteristic
).
Note 1: To use string variable you should include the library:
#include <string> … std::string characteristic; |
Note 2: Use the syntax of multiple if statement:
if (mark == 1) { … } else if (...) // condition 2 { … } else if (...) // condition 3 { … } else { … } |
Expected output:
What’s your mark? 2 The characteristic is bad
[Solution and Project name: Lesson_1Task2
, file name L1Task2.cpp
]
To do: Make the previous task using switch statement.
Expected output:
What’s your mark? 2 The characteristic is bad
[Solution and Project name: Lesson_1Task3
, file name L1Task3.cpp
]
To do: Ask the user to enter a number — coffee size (1=small, 2=medium, 3=large). Output the price (1 — 25 cents, 2 — 50 cents, 3 — 75 cents). Use if statement.
Expected output:
Coffee sizes: 1=small 2=medium 3=large Please enter your selection: 2 The result: Please insert 25 cents
Coffee sizes: 1=small 2=medium 3=large Please enter your selection: 5 The result: Invalid selection. Please select 1, 2, or 3.
[Solution and Project name: Lesson_1Task4
, file name L1Task4.cpp
]
To do: Ask the user to enter a number — coffee size (1=small, 2=medium, 3=large). Output the price (1 — 25 cents, 2 — 50 cents, 3 — 75 cents). Use switch statement.
Expected output:
Coffee sizes: 1=small 2=medium 3=large Please enter your selection: 2 The result: Please insert 25 cents
Coffee sizes: 1=small 2=medium 3=large Please enter your selection: 5 The result: Invalid selection. Please select 1, 2, or 3.
[Solution and Project name: Lesson_1Task4
, file name L1Task4.cpp
]
To do: Output the sequence: -3 0 3 6 9 12 15 18 21 24
. Make the task with FOR
loop. An iterator of the loop has a step equaled 3.
Note: To make a step equal to 3 see syntax:
for ([initializers]; [condition]; [iterator])
instead of the iterator you have to use variable counter +=3
Expected output:
The sequence: -3 0 3 6 9 12 15 18 21 24
[Solution and Project name: Lesson_1Task6
, file name L1Task6.cpp
]
To do: Output the sequence: 1 2 3 4 . . . 99 100 99 . . . 3 2 1
.
Note 1: Create two for
loops: the first loop 1 2 3 4 . . . 99 100
, the second loop 99 98 . . . 3 2 1
(with a step i— as a counter for the second loop).
Expected output:
The sequence: 1 2 3 4 5 . . . 99 100 99 . . . 4 3 2 1
[Solution and Project name: Lesson_1Task7
, file name L1Task7.cs
]
To do: 10 integers are entered. Output the quantity of positive and negative among them.
Note 1: Create for
loop to input the numbers. Within the loop, check each number whether it is positive or negative. Use two counter variables for calculations.
Expected output:
1 -5 -12 2 3 9 -1 9 5 -8 => counter_positive = 6, counter_negative = 4
[Solution and Project name: Lesson_1Task8
, file name L1Task8.cs
]
To do: Calculate a multiplication of 2-digit even integers in the interval [10;20] (10 * 12 * 14 * 16 * 18 * 20
). Make the task using a while
loop.
Note: To calculate a multiplication you should use a variable with the name product
. The initial value of the product
must be product = 1
.
Expected output:
10 * 12 * 14 * 16 * 18 * 20 = 9676800
[Solution and Project name: Lesson_1Task9
, file name L1Task9.cs
]
To do: Output the sequence 15 12 9 6 3 0
(from 15 down to 0 with a step = -3).
Note: Inside one project, create two loops — while
and do..while
loops, with different counters (counter1
, counter2
).
Expected output:
while: 15 12 9 6 3 0 do-while: 15 12 9 6 3 0
[Solution and Project name: Lesson_1Task10
, file name L1Task10.cs
]
Note: tasks should be saved in a file with the name of the task, and be sure to insert a comment with the statement of the task in the code.
BEGIN
- Begin12. The legs
a
andb
of a right triangle are given. Find the hypotenusec
and the perimeterP
of the triangle:c = (a2 + b2)1/2, P = a + b + c.
Expected output: << a=4.90 << b=9.90 results: c=11.05 P=25.85
- Begin17. Three points A, B, C are given on the real axis. Find the length of AC, the length of BC, and the sum of these lengths.
Expected output: << A=-3.80 << B=3.40 << C=0.50 results: AC=4.30 BC=2.90 AC+BC=7.20
- Begin23. Variables A, B, C are given. Change values of the variables by moving the given value of A into the variable B, the given value of B into the variable C, and the given value of C into the variable A. Output the new values of A, B, C.
Expected output: << A=2.47 << B=1.41 << C=9.50 results: A=9.50 B=2.47 C=1.41
- Begin27. Given a number A, compute a power A8 using three multiplying operators for computing A2, A4, A8 sequentially. Output all obtained powers of the number A.
Expected output: << A=3.20 results: A2=10.24 A4=104.86 A8=1095.12
- Begin28. Given a number A, compute a power A15 using five multiplying operators for computing A2, A3, A5, A10, A15 sequentially. Output all obtained powers of the number A.
Expected output: << A=1.57 results: A2=2.46 A3=3.87 A5=9.54 A10=90.99 A15=867.95
- Begin40. Solve a system of linear equations
A1·x + B1·y = C1, A2·x + B2·y = C2
with given coefficients A1, B1, C1, A2, B2, C2 provided that the system has the only solution. Use the following formulas:
x = (C1·B2 − C2·B1)/D, y = (A1·C2 − A2·C1)/D, where D = A1·B2 − A2·B1.
Expected output: << A1=-3.00 << B1=-2.00 << C1=4.00 << A2=-1.00 << B2=-4.00 << C2=-2.00 results: x = -2.00 y = 1.00
INTEGER
- Integer7. A two-digit integer is given. Find the sum and the product of its digits.
Expected output: << 47 results: sum = 11 product = 28
- Integer9. A three-digit integer is given. Using one operator of integer division find first digit of the given integer (a hundreds digit).
Expected output: << 188 results: 1
- Integer10. A three-digit integer is given. Output its last digit (a ones digit) and then its middle digit (a tens digit).
Expected output: << 916 results: ones 6, tens 1
- Integer11. A three-digit integer is given. Find the sum and the product of its digits.
Expected output: << 363 results: sum 12, product 54
- Integer12. A three-digit integer is given. Output an integer obtained from the given one by reading it from right to left.
Expected output: << 263 results: 362
- Integer13. A three-digit integer is given. Output an integer obtained from the given one by moving its left digit to the right side.
Expected output: << 124 results: 241
BOOLEAN
- Boolean4. Given two integers A and B, verify the following proposition: "The inequalities A > 2 and B ≤ 3 both are fulfilled".
Expected output: << A = 1 B = 2 results: false
- Boolean5. Given two integers A and B, verify the following proposition: "The inequality A ≥ 0 is fulfilled or the inequality B < −2 is fulfilled".
Expected output: << A = 0 B = -3 results: true
- Boolean6. Given three integers A, B, C, verify the following proposition: "The double inequality A < B < C is fulfilled".
Expected output: << A = 50 B = 66 c = 73 results: true
- Boolean7. Given three integers A, B, C, verify the following proposition: "The number B is between A and C".
- Boolean17. Given a positive integer, verify the following proposition: "The integer is a three-digit odd number".
- Boolean18. Verify the following proposition: "Among three given integers there is at least one pair of equal ones".
Expected output: << -1 -5 3 results: false
IF
- If4. Three integers are given. Find the amount of positive integers in the input data.
Expected output: << -10 -7 -11 results: 0
- If6. Given two real numbers, output the larger value of them.
- If13. Given three real numbers, output the value between the minimum and the maximum.
- If15. Given three real numbers, output the sum of two largest values.
- If24. Given a real independent variable x, find the value of a real function f defined as:
f(x) = 2·sin(x), if x > 0, 6 − x, if x ≤ 0.
Expected output: << x = 6.05 results: -0.46
- If26. Given a real independent variable x, find the value of a real function f defined as:
−x, if x ≤ 0, f(x) = x2, if 0 < x < 2, 4, if x ≥ 2.
Expected output: << x = 1.05 results: 1.10
CASE
- Case6. The units of length are numbered as: 1 — decimeter, 2 — kilometer, 3 — meter, 4 — millimeter, 5 — centimeter. The order number N of a unit of length and also the length L of a segment are given (N is an integer in the range 1 to 5, L is a real number). Output the length of the segment in meters.
Expected output: << dm =3.15 results: m = 0.315
- Case12. Elements of a circle are numbered as: 1 — radius R, 2 — diameter D = 2·R, 3 — length L = 2·π·R of the circumference, 4 — area S = π·R2. The order number of one element and its value (as a real number) are given. Output values of other elements in the same order. Use 3.14 for a value of π.
Expected output: << 2 D = 0.79 results: R = 0.40 L = 2.48 S = 0.49
- Case15. The suits of playing cards are numbered as: 1 — spades, 2 — clubs, 3 — diamonds, 4 — hearts. Card values "Jack", "Queen", "King", "Ace" are numbered as 11, 12, 13, 14 respectively. A card value N (as an integer in the range 6 to 14) and a suit M (as an integer in the range 1 to 4) are given. Output the card description as: "six of diamonds", "queen of spades", etc.
Expected output: << Card number N = 9, Card value M = 3 results: "diamonds nine"
FOR
- For10. Given an integer N (> 0), find the value of a following sum (as a real number):
1 + 1/2 + 1/3 + … + 1/N.
Expected output: << N = 11 results: 3.019877
- For12. Given an integer N (> 0), find the value of a following product of N factors:
1.1 · 1.2 · 1.3 · … .
Expected output: << N = 6 results: 5.765760
- For13. Given an integer N (> 0), find the value of the following expression of N terms with alternating signs:
1.1 − 1.2 + 1.3 − … .
Do not use conditional statements.
Expected output: << N = 8 results: -0.40
- For22. A real number X and an integer N (> 0) are given. Compute the expression
1 + X + X2/(2!) + … + XN/(N!)
(N! = 1·2·…·N). The result is an approximate value of exp(X).
Expected output: << X = -1.10767556 N = 5 results: 0.32811651
- For35. An integer N (> 2) is given. A sequence of integers AK is defined as:
A1 = 1, A2 = 2, A3 = 3, AK = AK−1 + AK−2 − 2·AK−3, K = 4, 5, … .
Output terms A1, A2, …, AN of the sequence.
Expected output: << N = 11 results: 1 2 3 3 2 -1 -5 -10 -13 -13 -6
WHILE
- While4. An integer N (> 0) is given. If it equals 3 raised to some integer power then output True, otherwise output False.
Expected output: << N = 86 results: false
- While7. Given an integer N (> 0), find the smallest positive integer K such that its square is greater than N: K2 > N. Do not use the operation of extracting a root.
Expected output: << N = 81 results: K = 10
- While10. Given an integer N (> 1), find the largest integer K such that the inequality 3K < N is fulfilled.
Expected output: << N = 729 results: K = 5
- While17. Given an integer N (> 0), output all digits of the number N starting from the right digit (a ones digit). Use the operators of integer division and taking the remainder after integer division.
Expected output: << N = 6772 results: 2 7 7 6
- While18. Given an integer N (> 0), find the amount and the sum of its digits. Use the operators of integer division and taking the remainder after integer division.
Expected output: << N = 2325 results: 4 sum=12
- While21. An integer N (> 0) is given. Determine whether its decimal representation contains odd digits or not, and output True or False respectively. Use the operators of integer division and taking the remainder after integer division.
Expected output: << N = 10101 results: true