Lesson # 1. Creating a C ++ Console App in Microsoft Visual Studio

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.
  • The type of a variable defines the contents of the variable. Every type is either:

  • Primitive
  • User-defined
  • Primitive Types
    There are just 6 common primitive types in C++:

  • int, (4) stores integers
  • char, (1)stores single characters/single byte
  • bool, (1) stores a Boolean (true or false)
  • float, (4) stores a floating point number
  • double, (8)stores a double-precision floating point number
  • void, denotes the absence of a value
  • and some more:

  • short int (2) // or short
  • unsigned int (4) // or unsigned
  • unsigned char (1) // is byte
  • User-Defined Types
    An unbounded number of user-defined types can exist
    Two very common user-defined types:

  • std::string, a string (sequence of characters)
  • std::vector, a dynamically-growing array

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

Initialization in a style of C++11
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
Implicit type conversion

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"
Arithmetic operations
C++

a = 4;
a += 2; // a = a+2;
b = a++; 
b = ++a; 
7 / 3  
7 % 3 
(i < 0 || i > 2) 
(i >= 2 && i <= 3) 
!(i>2) 
==
!=
& | ^ ~  
a = b = c;
PascalABC.NET

a := 4;
a += 2;
t := a; a++; b := t;
a++; b := a;
7 div 3
7 mod 3
(i < 0) or (i > 2)
(i >= 2) and (i <= 3)
not(i>2)
=
<>
bitwise and, or, xor, not
b:=c; a:=c;

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

If statement

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-Else
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...
}
Ternary operator or conditional operator

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
Switch statement

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

All the tasks that you did not have time to complete in class automatically become your homework. The homework must be completed before the next lesson.
Lab 1: Console С++ app in Microsoft Visual studio
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:

  1. Open Microsoft Visual Studio. Select menu item File -> New project. In the Template region find C++ and then, Win32 Console Application.
  2. Create a new console project, name your project Lesson_1. Among the Additional options mark Empty project and nothing more. Click Finish button.
  3. 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 it Main.cpp.
  4. Make sure that the file Main.cpp is active in the Solution Explorer window.
  5. Place your cursor on the first line of the code editor window.
  6. Add a header code:
  7. #include <iostream>
    The iostream header includes operations for reading/writing to files and the console itself
  8. After, type the code of the Main function:
  9. int main() {
    		// …
    }
    
    The main function is a starting point of C++ program.
  10. 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:
  11. int x;
  12. Ask the user to input a number:
  13. std::cout << "Please enter an integer: ";
    The C++ standard library (std) provides a set of commonly used functionality and data structures to build upon.
  14. Use std library again to input a value to store it in x variable:
  15. ...
     std::cin >> x;
    ...
  16. Enter the code to increase x by 1:
  17. x++;
  18. Print the result out to the console:
  19. std::cout << "Result: " << x << std::endl;
    The endl makes a new line after your code.
  20. The main function commonly must return 0. Add the code line right before the closing curly brace of the main function:
  21. return 0;

  22. Run the application. The console window has disappeared too fast. We can’t see the result.
  23. Add the pause to stay the window opened:
  24. system("pause");
       return 0;
    }
  25. Run the application again.
  26.   
    Importing some features from the std library:

  27. 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:
  28. using std::cout;
    using std::cin;
    using std::endl;
    
    All functionality used from the standard library will be part of the std namespace.
    If a feature from a namespace is used often, it can be imported into the global space
  29. Now, you can change the code with cout and cin methods by clearing up the std:
  30. cout << "Please enter an integer: ";
    …
    cin >> x;
    …
    cout << "Result: " << x << endl;
  31. Run the application again.
  32.  
    Importing std namespace:

  33. But instead of importing some features of std library we can import the std namespace itself. Clear the using lines we’ve added. Place the following code instead of them:
  34.  using namespace std;
  35. Run the project and see the same results.
Task 1: Std and output

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]

Task 2: If statement

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]

Task 3: Switch statement

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]

Task 4: If statement

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]

Task 5: Switch statement

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]

Task 6: For loop

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]

Task 7

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]

Task 8

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]

Task 9: While loop

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]

Task 10

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]


Tasks for self-solving

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

  1. Begin12. The legs a and b of a right triangle are given. Find the hypotenuse c and the perimeter P 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
    
  2. 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
    
  3. 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
    
  4. 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
    
  5. 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
    
  6. 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

  1. Integer7. A two-digit integer is given. Find the sum and the product of its digits.
    Expected output:
    << 47
    results:
    sum = 11  product = 28
    
  2. 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
    
  3. 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
    
  4. Integer11. A three-digit integer is given. Find the sum and the product of its digits.
    Expected output:
    << 363
    results:
    sum 12, product 54
    
  5. 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
    
  6. 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

  1. 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
    
  2. 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
    
  3. 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
    
  4. Boolean7. Given three integers A, B, C, verify the following proposition: "The number B is between A and C".
  5. Boolean17. Given a positive integer, verify the following proposition: "The integer is a three-digit odd number".
  6. 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

  1. If4. Three integers are given. Find the amount of positive integers in the input data.
    Expected output:
    << -10   -7   -11
    results:
    0
    
  2. If6. Given two real numbers, output the larger value of them.
  3. If13. Given three real numbers, output the value between the minimum and the maximum.
  4. If15. Given three real numbers, output the sum of two largest values.
  5. 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
    
  6. 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

  1. 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
    
  2. 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
    
  3. 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

  1. 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
    
  2. 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
    
  3. 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
    
  4. 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
    
  5. 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

  1. 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
    
  2. 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
    
  3. 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
    
  4. 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
    
  5. 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
    
  6. 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
    
* The tasks are taken from M. E. Abramyan (Southern Federal University) Programming Taskbook