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

Дата изменения: 7 сентября 2020

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) // или short
  • unsigned int (4) // или unsigned
  • unsigned char (1) // это 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 #include’d 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
Arithmetic operations
a += 2; // a = a+2;
b = a++; // t = a; a++; b = t;
b = ++a; // a++; b = a;
7 / 3 // 7 div 3
7 % 3 // 7 mod 3
(i < 0 || i > 2) // OR
(i >= 2 && i <= 3) // AND
!(i>2) // не
& | ^ ~ // bitwise and, or, xor, not
a = b = c; // multiple assignment

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>
int main() {
  int x = 2;
  std::cout << "Outer scope value of x (should be 2): " << x << std::endl;
 
  if (true) {
    int x = 3;
    std::cout << "Inner scope vaue of x (should be 3): " << x << std::endl;
  }
 
  std::cout << "Outer scope value of x (should be 2): " << x << std::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>
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++) {
    std::cout << "[Inside the loop] x is now: " << x << std::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++) {
    std::cout << "[Inside the loop] x is now: " << x << std::endl;
  }
 
  return 0;
}

while loops
syntax:

while ( condition ) { loop body }

We’ll talk about other loops in a later lesson.

Labs and tasks

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.

The resulting example:

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;
    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.
  
The resulting example:

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.

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 (condition 1) {}
	else if (condition 2) {}
	else if (condition 3)
	{}
	else
	{}

The resulting example:

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.

The resulting example:

What’s your mark?
2
The characteristic is bad

[Solution and Project name: Lesson_1Task3, file name L1Task3.cpp]

Task 4:

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.

The resulting examples:

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:

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.

The resulting examples:

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’ll have the variable counter +=3

The resulting example:

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 . . . 3 2 1 (with a step i— as a counter for the second loop).

The resulting example:

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 input. 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 counters to find the quantity.

The resulting example:

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. Start with product = 1.

The resulting example:

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).

The resulting example:

15 12 9 6 3 0

[Solution and Project name: Lesson_1Task10, file name L1Task10.cs]

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

*
*


Вставить формулу как
Блок
Строка
Дополнительные настройки
Цвет формулы
Цвет текста
#333333
Используйте LaTeX для набора формулы
Предпросмотр
\({}\)
Формула не набрана
Вставить