fix(guide): move guide to english directory
This commit is contained in:
committed by
mrugesh mohapatra
parent
3a270cab98
commit
73a97354e1
80
client/src/pages/guide/english/cplusplus/casting/index.md
Normal file
80
client/src/pages/guide/english/cplusplus/casting/index.md
Normal file
@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Casting
|
||||
---
|
||||
|
||||
## Casting
|
||||
|
||||
Casting in C++ differs somewhat to that of C. C++ makes use of distinct casting functions.
|
||||
|
||||
##static_cast
|
||||
Static cast is used for implicit conversions between primitives and type-overloads.
|
||||
|
||||
##const_cast
|
||||
Const cast can be used to cast away const-ness. This is useful when there is a desire to mutate a constant value. This should be used sparingly, instead, one should consider making parameters/functions non-const in cases where a const-cast is used.
|
||||
|
||||
Const cast can also result in undefined behaviour. The only application of const cast should ever be to remove const-ness from a value that was passed to a function and marked const. If the value is truly const, that is, it is marked const at compile time and assigned a value, const cast and mutation of the variable will result in undefined behaviour.
|
||||
|
||||
```
|
||||
const int y = 10; // y is set to 10.
|
||||
const_cast<int &>(y) = 20; // undefined behaviour.
|
||||
```
|
||||
##dynamic_cast
|
||||
Dynamic cast is used to cast an object within it's class hierarchy (to parent, from parent and to siblings). Dynamic cast can only be called on polymorphic classes. Thus, the original class in this case `MyClass` must have a virtual member, which is present in the form of the virtual destructor.
|
||||
|
||||
If dynamic cast fails, it will return a `nullptr`. Dynamic cast may be useful in determination of object types at runtime. However, it should be noted that dynamic cast is not free and in some cases other techniques may prove to be more efficient at determination of class type at runtime.
|
||||
|
||||
##reinterpret_cast
|
||||
Reinterpret cast is perhaps the most dangerous of all the C++ casts, but when used correctly it can be ideal. Reinterpret cast incurs no performance cost as it does not perform any conversions. It simply instructs the compiler to treat the casted object as if it were the type requested. This can also bring forth alignment issues, so it should be used sparingly and only when side effects are known and accounted for.
|
||||
|
||||
##A note on C-style casts
|
||||
C++ supports the use of C-style casts, although they are not recommended. Use of the C-style cast will instruct the compiler to first perform a static_cast, if the static_cast fails, reinterpret_cast is used in its place. For this reason, C-style casts may produce unpredictable results and bring forth unexpected issues.
|
||||
|
||||
## Examples
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
class MyClass {
|
||||
public:
|
||||
virtual ~MyClass() = default;
|
||||
|
||||
void greet() {
|
||||
std::cout << "Hello World!" << std::endl;
|
||||
}
|
||||
};
|
||||
|
||||
class MyClassChild : public MyClass {
|
||||
};
|
||||
|
||||
void reinterpretCastTest(void *objectPtr) {
|
||||
// Let's assume we know objectPtr is of type MyClass *
|
||||
auto myClassObj = reinterpret_cast<MyClassChild *>(objectPtr);
|
||||
myClassObj->greet();
|
||||
}
|
||||
|
||||
void constCastTest(const MyClassChild &myClassChild) {
|
||||
auto nonConst = const_cast<MyClassChild &>(myClassChild);
|
||||
nonConst.greet();
|
||||
}
|
||||
|
||||
void dynamicCastTest(MyClass *myClass) {
|
||||
auto *child = dynamic_cast<MyClassChild *>(myClass);
|
||||
child->greet();
|
||||
}
|
||||
|
||||
void staticCastTest(float floatVal) {
|
||||
// Convert the float into an int.
|
||||
auto intVal = static_cast<int>(floatVal);
|
||||
std::cout << intVal << std::endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
MyClassChild myClass;
|
||||
reinterpretCastTest(&myClass);
|
||||
constCastTest(myClass);
|
||||
dynamicCastTest(&myClass);
|
||||
staticCastTest(10.5);
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
@ -0,0 +1,113 @@
|
||||
---
|
||||
title: Clean Code Guidelines
|
||||
---
|
||||
|
||||
# Clean Code Guidelines
|
||||
|
||||
When coding, the coding style you follow can be really important. Specially when you are working with a team or you plan on sharing your
|
||||
code.
|
||||
Most of these guidelines are standard and can be applied to most of the programming languages, however, here you have applications and
|
||||
snippets with c++ code, so you can familiarize with it easier.
|
||||
Remember that these are only recommendations for achieving clarity, which can be a personal prefference, so take these pieces of advice
|
||||
into account but don't take them to the letter. Sometimes breaking some of these rules can lead to cleaner code.
|
||||
|
||||
## Use good variable names and make comments
|
||||
|
||||
Make sure you create good variable names, for example, if you are creating a game, avoid using the variable "a" use something like "p1" referring to player 1. The [hungarian notation](https://en.wikipedia.org/wiki/Hungarian_notation) is commonly spread and can give you some gidelines for declaring variables.
|
||||
|
||||
Also, PLEASE, use comments, I'm not even kidding, just try to read some old projects you did without comments... now imagine being someone else who didn't even code it.
|
||||
|
||||
## Global variables
|
||||
|
||||
Global variables can be easy to use, and with little code it might look like a great solution. But, when the code gets larger and larger, it becomes harder to know when are they being used.
|
||||
|
||||
Instead of using global variables you could use variables declared in functions which can help you telling what values are being passed
|
||||
and identifying errors faster.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
// Global variables are declared outside functions
|
||||
int cucumber; // global variable "cucumber"
|
||||
```
|
||||
|
||||
## Using goto, continue, etc.
|
||||
|
||||
This is an usual discussion among programmers, just like global variables, these types of statements are usually considered bad practice.
|
||||
They are considered bad because they lead to ["spaguetti code"](https://en.wikipedia.org/wiki/Spaghetti_code). When we program we want a
|
||||
linear flow, when using those statements the flow is modified and lead to a "twisted and tangled" flow.
|
||||
|
||||
Goto was used in the past when while, for, if functions, however, witht the introduction of those structured programming was created.
|
||||
In general avoid using goto unless you are sure it will make your code cleaner and easier to read. An example might be using it in nested loops.
|
||||
|
||||
The usage of break and continue are practically the same. Use them in switches and try to make functions with an only purpose so you only have one exit point.
|
||||
|
||||

|
||||
|
||||
## Avoid changing the control variable inside of a for loop
|
||||
|
||||
Usually there are works around this that look clearer and less confusing, eg. while loops.
|
||||
Do:
|
||||
```cpp
|
||||
int i=1;
|
||||
while (i <= 5)
|
||||
{
|
||||
if (i == 2)
|
||||
i = 4;
|
||||
|
||||
++i;
|
||||
}
|
||||
```
|
||||
|
||||
Instead of:
|
||||
```cpp
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
if( i == 2)
|
||||
{
|
||||
i = 4;
|
||||
}
|
||||
// Do work
|
||||
}
|
||||
```
|
||||
|
||||
## Declare constants and types at the top
|
||||
|
||||
They are usually declared after libraries, this makes them be toguether and easier to read.
|
||||
For local variables it happens the same, declare them at the top (Other people preffer it declaring them as later as possible in order to save memory see: [cplusplus.com](http://www.cplusplus.com/forum/general/33612/)
|
||||
|
||||
## Use only one return function at the end
|
||||
|
||||
Just like we said before, we tend to make only one entry and exit to make the flow clearer.
|
||||
|
||||
## Use curly braces even when writing one-liners
|
||||
|
||||
Making it systematically will help you doing it faster and in case you want to change the code in the future you will be able to do it without worries.
|
||||
|
||||
Instead of:
|
||||
```cpp
|
||||
for (int i = 1; i <= 5; i++)
|
||||
//CODE
|
||||
```
|
||||
|
||||
Do:
|
||||
```cpp
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
//CODE
|
||||
}
|
||||
```
|
||||
## Other recommendations
|
||||
|
||||
* #### Use for when you know the number of iterations, while and do while when you don't.
|
||||
|
||||
* #### Use const, pass by value/reference when suitable. This will help with saving memory.
|
||||
|
||||
* #### Write const in caps, datatypes starting with T and variables in lower case.
|
||||
|
||||
```cpp
|
||||
const int MAX= 100; //Constant
|
||||
typedef int TVector[MAX]; //Data type
|
||||
TVector vector; //Vector
|
||||
```
|
79
client/src/pages/guide/english/cplusplus/compilers/index.md
Normal file
79
client/src/pages/guide/english/cplusplus/compilers/index.md
Normal file
@ -0,0 +1,79 @@
|
||||
---
|
||||
title: C++ Compilers
|
||||
---
|
||||
|
||||
# Intro to C++ Compilers
|
||||
|
||||
In order to get started with C++, you will need to learn a little about compilers and how C++ runs on your computer.
|
||||
|
||||
When all is said and done, computers only understand one language, machine language. Machine language is entirely made up of
|
||||
binary bits, or 0s and 1s. While it would be possible to program in binary, it would be incredibly tedious and time consuming.
|
||||
So, we humans developed programming languages to make it easier to develop software. Assembly language is a direct 1 to 1 with machine
|
||||
language. Languages like C, C++, and COBOL are a little higher and need to be compiled down. It goes even higher. Languages
|
||||
like JavaScript and Python have components that get translated into C++ or other low level languages before they get compiled,
|
||||
effectively making them "higher" languages than C or C++.
|
||||
Because computer architecture is made up of electronic switches and cables that can only work with binary 1s and 0s,
|
||||
you need a compiler to translate your code from high level C++ to machine language that the CPU can understand.
|
||||
|
||||
Compilers are utility programs that take your code and transform it into executable machine code files. When you run a compiler
|
||||
on your code, first, the preprocessor reads the source code (the C++ file you just wrote). The preprocessor searches for any
|
||||
preprocessor directives (lines of code starting with a #). Preprocessor directives cause the
|
||||
preprocessor to change your code in some way (by usually adding some library or another C++ file).
|
||||
Next, the compiler works through the preprocessed code line by line translating
|
||||
each line into the appropriate machine language instruction. This will also uncover any syntax errors that are present in your
|
||||
source code and will throw an error to the command line. Finally, if no errors are present, the compiler creates an object
|
||||
file with the machine language binary necessary to run on your machine. While the object file that the compiler just created
|
||||
is likely enough to do something on your computer, it still isn't a working executable of your C++ program. There is a final
|
||||
important step to reach an executable program.
|
||||
|
||||
C++ contains a vast library to aid in performing difficult tasks like I/O and hardware manipulation. You can include these
|
||||
libraries with preprocessor directives, but the preprocessor doesn't automatically add them to your code. In order for you to have
|
||||
a final executable program, another utility known as the linker must combine your object files with the library functions
|
||||
necessary to run the code. Think of it as having all the necessary blocks
|
||||
to build a house. The compiler made all the blocks but the linker is the one that sticks them all together to finally create a house.
|
||||
Once this is done, you now have a functioning executable file!
|
||||
|
||||
|
||||
## How to Compile a file
|
||||
Let's say you have a C++ file called `helloWorld.cpp` ...
|
||||
|
||||
### If you are on Windows --
|
||||
|
||||
#### Using and IDE like CodeBlocks
|
||||
|
||||
It is as simple as clicking the build and run buttons, they will create a file in the project folder.
|
||||

|
||||
|
||||
#### Using Command Prompt
|
||||
1. Open a Developer Command Prompt - For this step, you will need to have Microsoft Visual Studio or some other IDE that
|
||||
enables you to compile your program from the command line. You can also search online for C++ compilers.
|
||||
|
||||
2. Navigate to the source code directly
|
||||
|
||||
3. Run the Compiler on your source code (assuming you are using the Microsoft Visual Studio compiler)
|
||||
`cl /EHsc helloWorld.cpp`
|
||||
|
||||
This will now create an object file and automatically link it for you. If you look in that same folder, you will see a
|
||||
hellWorld.exe executable file (note the exe extension) is now present.
|
||||
|
||||
4. Type `helloWorld` into the prompt to run the executable
|
||||
|
||||
Alternatively, many IDEs allow for quick building and viewing of your program. This may be easier since your version of
|
||||
windows may not come pre packaged with a compiler utility.
|
||||
|
||||
### If you are on Linux or OSX --
|
||||
1. Open up a terminal window and navigate to the source code directory
|
||||
2. Run the Compiler on your source code
|
||||
`g++ helloWorld.cpp -o helloWorld`
|
||||
|
||||
This will create an object file and automatically link it for you. Look in the folder and you will see a helloWorld.exe
|
||||
executable file (note the exe extension).
|
||||
|
||||
3. Type `./helloWorld` in the terminal window to run the executable file
|
||||
|
||||
g++ is the standard Linux compiler and is a great utility. It comes packaged with the operating system.
|
||||
|
||||
____________
|
||||
|
||||
There are a number of different types of compilers. The two listed are the two that are usually packaged with the Windows
|
||||
or Linux/OSX.
|
@ -0,0 +1,42 @@
|
||||
---
|
||||
title: Conditional Operator
|
||||
---
|
||||
|
||||
## Conditional Operator
|
||||
|
||||
Conditional operator is a ternary operator, that is it needs 3 operands.
|
||||
Conditional operator is used to replace a simple if-else statements.
|
||||
|
||||
Syntax :
|
||||
```cpp
|
||||
(condition)?(expression-1):(expression-2);
|
||||
```
|
||||
Here, expression-1 is evaluated when condition is true and expression-2 is evaluated when condtion is false.
|
||||
Similar if-else statement would be :
|
||||
```cpp
|
||||
if(condition)
|
||||
{
|
||||
expression-1;
|
||||
}
|
||||
else
|
||||
{
|
||||
expression-2;
|
||||
}
|
||||
```
|
||||
Hence conditional operator is very handy when you need to write simple if-else statement. It can also be used in #define
|
||||
preprocessor when similar condition is to be used in multiple places.
|
||||
|
||||
For example, to find maximum of two number conditional operator can be used as follows :
|
||||
|
||||
```cpp
|
||||
#define big(a,b) (a>=b)?a:b
|
||||
|
||||
int maximum,x=5,y=6; // variable to store maximum of two numbers
|
||||
maximum=(x>y)?x:y; // directly using conditional operator
|
||||
maximum=big(x,y); // using the #define preprocessor defined above as big
|
||||
```
|
||||
**Good Luck to all of you**
|
||||
|
||||
**Happy Coding ! :)**
|
||||
|
||||
**Feel free to ask any queries on FreeCodeCamp's GitHub page or [FreeCodeCamp's Forum .](https://forum.freecodecamp.org/)**
|
@ -0,0 +1,33 @@
|
||||
---
|
||||
title: do while loop
|
||||
---
|
||||
## Do While Loop
|
||||
|
||||
The `do while loop` is almost the same as the while loop. The `do while loop` has the following form:
|
||||
```cpp
|
||||
do
|
||||
{
|
||||
do something;
|
||||
}
|
||||
while (expression);
|
||||
```
|
||||
Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the expression test comes afterward). Take a look at an example:
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int counter, howmuch;
|
||||
|
||||
cin >> howmuch;
|
||||
counter = 0;
|
||||
do
|
||||
{
|
||||
counter++;
|
||||
cout << counter << '\n';
|
||||
}
|
||||
while ( counter < howmuch);
|
||||
return 0;
|
||||
}
|
||||
```
|
@ -0,0 +1,31 @@
|
||||
---
|
||||
title: Dynamic Memory Allocation
|
||||
---
|
||||
## Dynamic Memory Allocation in C++
|
||||
|
||||
### What is Dynamic Memory Allocation in C++?
|
||||
* **Memory Allocation** in C++ refers to the memory alloted to the variables you use throughout your program.
|
||||
* **Dynamic Memory Allocation** is the memory which is alloted to the variables at the run-time and the amount of memory required is also decided at the run-time.
|
||||
* This memory comes from **heap**, whereas _non-static_ variables and _local_ variables get memory from **stack**.
|
||||
* In C++, the programmer can perform memory allocations manually, and is called as **_dynamic memory allocation_**.
|
||||
* It was possible in C to do dynamic memory allocation, by using _calloc_ and _malloc_ functions to allocate memory and using _free_ function to de-allocate the dynamic memory.
|
||||
* In C++, in addition to above, there are two functions, _new_ and _delete_ for performing dynamic memory allocation and de-allocation.
|
||||
|
||||
### NEW operator
|
||||
* `new` operator can grant the programmer memory from the heap (if available). If the memory which the programmer asks is available, then the `new` operator initializes the memory and then returns the address (reference) of the memory allocated.
|
||||
* **Syntax**
|
||||
`pointer-variable-type` = **new** `data-type;`
|
||||
Example 1: `int *ptr` = **new** `int;`
|
||||
Example 2: `int *ptr2` = **new** `int[10];`
|
||||
Here, `pointer-variable-type` is a **pointer** of `data type`. The `data-type` can be int, char, etc. or user-defined data-type.
|
||||
|
||||
### DELETE operator
|
||||
* It is programmer's responsibility to de-allocate the dynamically allocated memory otherwise the memory would not be available to be re-allocated until the end of the program.
|
||||
* To deallocate the memory, `delete` operator is available and can be used by the programmer.
|
||||
* **Syntax**
|
||||
**delete** `pointer-type-variable;`
|
||||
For example to free the memory allocated in example 1 above, we type:
|
||||
`delete ptr;`
|
||||
Similarly, for example 2, the memory can be freed by:
|
||||
`delete ptr2`;
|
||||
|
@ -0,0 +1,86 @@
|
||||
---
|
||||
title: Erase–remove idiom
|
||||
---
|
||||
|
||||
## Desctiprion
|
||||
How to remove elements from container is a common C++ interview question, so you can earn some brownie points, if you read this page carefully. The erase–remove idiom is a C++ technique to eliminate elements that fulfill a certain criterion from a container. Howerever, it is possible to eliminate elements with traditional hand-written loop, but the erase–remove idiom has several advantages.
|
||||
|
||||
### Comparison
|
||||
|
||||
```cpp
|
||||
// Using a hand-written loop
|
||||
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
||||
for (auto iter = v.cbegin(); iter < v.cend(); /*iter++*/)
|
||||
{
|
||||
if (is_odd(*iter))
|
||||
{
|
||||
iter = v.erase(iter);
|
||||
}
|
||||
else
|
||||
{
|
||||
++iter;
|
||||
}
|
||||
}
|
||||
|
||||
// Using the erase–remove idiom
|
||||
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
||||
v.erase(std::remove_if(v.begin(), v.end(), is_odd), v.end());
|
||||
```
|
||||
|
||||
As you can see, the code with hand-written loop requires a bit more typing, but it also has a performance issue. Each `erase` call has to move forward all the elements after the deleted one, to avoid "gaps" in the collection. Calling `erase` multiple times on the same container generates lots of overhead of moving the elements.
|
||||
|
||||
On the other hand, the code with the erase–remove idiom is not only more expressive, but it also is more efficient. First, you use `remove_if/remove` to move all elements which don't fit the remove criteria to the front of the range, keeping the relative order of the elements. So after calling `remove_if/remove`, a single call of `erase` deletes all remaining elements at the end of the range.
|
||||
|
||||
### Example
|
||||
|
||||
```cpp
|
||||
#include <vector> // the general-purpose vector container
|
||||
#include <iostream> // cout
|
||||
#include <algorithm> // remove and remove_if
|
||||
|
||||
bool is_odd(int i)
|
||||
{
|
||||
return (i % 2) != 0;
|
||||
}
|
||||
|
||||
void print(const std::vector<int> &vec)
|
||||
{
|
||||
for (const auto& i : vec)
|
||||
std::cout << i << ' ';
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
// initializes a vector that holds the numbers from 1-10.
|
||||
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
||||
print(v);
|
||||
|
||||
// removes all elements with the value 5
|
||||
v.erase(std::remove(v.begin(), v.end(), 5), v.end());
|
||||
print(v);
|
||||
|
||||
// removes all odd numbers
|
||||
v.erase(std::remove_if(v.begin(), v.end(), is_odd), v.end());
|
||||
print(v);
|
||||
|
||||
// removes multiples of 4 using lambda
|
||||
v.erase(std::remove_if(v.begin(), v.end(), [](int n) { return (n % 4) == 0; }), v.end());
|
||||
print(v);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
Output:
|
||||
1 2 3 4 5 6 7 8 9 10
|
||||
1 2 3 4 6 7 8 9 10
|
||||
2 4 6 8 10
|
||||
2 6 10
|
||||
*/
|
||||
```
|
||||
|
||||
### Sources
|
||||
"Erase–remove idiom" Wikipedia: The Free Encyclopedia. Wikimedia Foundation, Inc. [en.wikipedia.org/wiki/Erase-remove_idiom](https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom)
|
||||
|
||||
Meyers, Scott (2001). Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library. Addison-Wesley.
|
45
client/src/pages/guide/english/cplusplus/for-loop/index.md
Normal file
45
client/src/pages/guide/english/cplusplus/for-loop/index.md
Normal file
@ -0,0 +1,45 @@
|
||||
---
|
||||
title: For Loop
|
||||
---
|
||||
|
||||
# For Loop
|
||||
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
|
||||
|
||||
## Syntax
|
||||
for ( init; condition; increment ) {
|
||||
statement(s);
|
||||
}
|
||||
### init
|
||||
This is execute once only.This step allows you to declare and initialize any loop control variables
|
||||
|
||||
### condition
|
||||
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
|
||||
|
||||
### increment
|
||||
After the body of the for loop executes, the flow of control jumps back up to the increment statement.This can be used to alter the counter variable by simple addition,subtraction,multiplication,division.
|
||||
|
||||
## Example
|
||||
```C++
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main () {
|
||||
// for loop execution
|
||||
for( int a = 10; a < 20; a = a + 1 ) {
|
||||
cout << "value of a: " << a << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}```
|
||||
|
||||
Output:
|
||||
value of a: 10
|
||||
value of a: 11
|
||||
value of a: 12
|
||||
value of a: 13
|
||||
value of a: 14
|
||||
value of a: 15
|
||||
value of a: 16
|
||||
value of a: 17
|
||||
value of a: 18
|
||||
value of a: 19
|
52
client/src/pages/guide/english/cplusplus/functions/index.md
Normal file
52
client/src/pages/guide/english/cplusplus/functions/index.md
Normal file
@ -0,0 +1,52 @@
|
||||
---
|
||||
title: Functions in C++
|
||||
---
|
||||
## Definition:
|
||||
|
||||
A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main().
|
||||
|
||||
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
|
||||
|
||||
## The general form of a C++ function definition:
|
||||
|
||||
```cpp
|
||||
return_type function_name( parameter list )
|
||||
{
|
||||
body of the function
|
||||
}
|
||||
```
|
||||
|
||||
### Return type:
|
||||
A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
|
||||
|
||||
### Function name:
|
||||
This is the actual name of the function. The function name and the parameter list together constitute the function signature.
|
||||
|
||||
### Parameters:
|
||||
A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
|
||||
|
||||
### Function body:
|
||||
The function body contains a collection of statements that define what the function does.
|
||||
|
||||
##Example:
|
||||
|
||||
```cpp
|
||||
int max(int num1, int num2)
|
||||
{
|
||||
// local variable declaration
|
||||
int result;
|
||||
|
||||
if (num1 > num2)
|
||||
result = num1;
|
||||
else
|
||||
result = num2;
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
## More Information
|
||||
|
||||
* [TutorialsPoint](https://www.tutorialspoint.com/cplusplus/cpp_functions.htm)
|
||||
|
||||
|
@ -0,0 +1,192 @@
|
||||
---
|
||||
title: If-Else Statement
|
||||
---
|
||||
|
||||
## What does an If-Else Statement do?
|
||||
|
||||
* The If-Else statement is an extension of the simple If statement.
|
||||
* In the simple If statement, if the value of the test expression is false, then we skip the code of block and continue with our next statement.
|
||||
* But many times, we want to execute certain steps if the value of test expression is false.
|
||||
* In such cases, we use the if-else statement.
|
||||
|
||||
### General Form of If-Else Statement
|
||||
|
||||
```cpp
|
||||
|
||||
if (test expression)
|
||||
{
|
||||
//statements that run if the test expression is true
|
||||
}
|
||||
else
|
||||
{
|
||||
//statements that run if the test expression is false
|
||||
}
|
||||
```
|
||||
|
||||
### Example of If-Else Statement
|
||||
|
||||
If test expression is true :
|
||||
|
||||
```cpp
|
||||
|
||||
int a=10;
|
||||
if (a < 20) // This expression is true, so...
|
||||
{
|
||||
//...the code in this block gets executed, and...
|
||||
}
|
||||
else
|
||||
{
|
||||
//...the code in this block gets skipped.
|
||||
}
|
||||
//program continues
|
||||
```
|
||||
|
||||
If test expression is false :
|
||||
|
||||
```cpp
|
||||
int a=10;
|
||||
if (a>20) // This expression is false, so this time...
|
||||
{
|
||||
//...this code gets skipped...
|
||||
}
|
||||
else
|
||||
{
|
||||
//...and this code executes instead.
|
||||
}
|
||||
//program continues
|
||||
```
|
||||
|
||||
### Example in C++:
|
||||
|
||||
```cpp
|
||||
//Program to check whether number entered by user is positive or negative
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
int no;
|
||||
cout << "Enter a number: " << endl;
|
||||
|
||||
cin >> no;
|
||||
|
||||
// condition to check if number is positive or negative
|
||||
if (no >= 0) // positive
|
||||
{
|
||||
// block if value is true
|
||||
cout << "You entered a positive number: " << no << endl;
|
||||
}
|
||||
else // negative
|
||||
{
|
||||
// block if value is false
|
||||
cout << "You entered a negative number: " << no << endl;
|
||||
}
|
||||
|
||||
// program continues
|
||||
cout << "This step is always printed" << endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
#### Output
|
||||
|
||||
* When a positive number is entered :
|
||||
```
|
||||
Enter a number:
|
||||
4
|
||||
You entered a positive number: 4
|
||||
This step is always printed
|
||||
```
|
||||
|
||||
* When a negative number is entered :
|
||||
```
|
||||
Enter a number:
|
||||
-200
|
||||
You entered a negative number: -200
|
||||
This step is always printed
|
||||
```
|
||||
|
||||
<a href='https://repl.it/MzBq' target='_blank' rel='nofollow'>Try the code yourself</a>
|
||||
|
||||
**Feel free to ask any queries on FreeCodeCamp's GitHub page or [FreeCodeCamp's Forum .](https://forum.freecodecamp.org/)**
|
||||
=======
|
||||
[Try the code yourself](https://repl.it/MzBq)
|
||||
|
||||
|
||||
### Use of if...else if...else ladder
|
||||
If we have to make decisions based on more than one conditions using if else. We use else if condition as follows -
|
||||
```cpp
|
||||
#include<iostream>
|
||||
int main()
|
||||
{
|
||||
int score;
|
||||
std::cout<<"Enter your score: \n";
|
||||
std::cin>>score;
|
||||
if(score>=90)
|
||||
std::cout<<"Top performance.";
|
||||
else if(score<90 && score>=70)
|
||||
std::cout<<"Good performance";
|
||||
else if(score<70 && score>=45)
|
||||
std::cout<<"Average performance";
|
||||
else if(score<45 && score>=30)
|
||||
std::cout<<"You can improve it.";
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
#### Output
|
||||
```
|
||||
Enter your score:
|
||||
85
|
||||
Good performance
|
||||
```
|
||||
### Another example of if...else if...else ladder
|
||||
Suppose we have the user input two numbers and we are going to display if either number is greater than the other. And if neither is greater than the other, then we print the statement "Both are equal".
|
||||
|
||||
In this scinerio we will need an if...else if...else ladder statement. The program will look like this :
|
||||
|
||||
```
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
int number1,number2;
|
||||
cout << "Enter first number: \n";
|
||||
cin >> number1;
|
||||
cout << "Enter second number: \n";
|
||||
cin >> number2;
|
||||
|
||||
if(number1 > number2) // Checks if the first number is greater than the second number
|
||||
{
|
||||
cout << "Number 1 is greater.";
|
||||
}
|
||||
else if(number2 > number1) // Checks if the second number is greater than the first number
|
||||
{
|
||||
cout << "Number 2 is greater.";
|
||||
}
|
||||
else // If both of the above cases return false, then both numbers are equal
|
||||
{
|
||||
cout << "Both the numbers are equal.";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
#### Output
|
||||
```
|
||||
Enter first number:
|
||||
85
|
||||
Enter second number:
|
||||
86
|
||||
Number 2 is greater.
|
||||
```
|
||||
|
||||
* Note that the program will only check the 'else if' condition when the initial 'if' condition is not satisfied. And if neither of these conditions are satisfied, the last 'else' block gets executed which prints the statement: "Both the numbers are equal.".
|
||||
|
||||
* The size of the if...else if...else ladder may vary depending on the problem the program is trying to solve and the number of conditions that need to be checked.
|
||||
|
||||
**Good Luck to all of you**
|
||||
|
||||
**Happy Coding ! :)**
|
||||
|
||||
**Feel free to ask any queries on freeCodeCamp.org's GitHub page or [the freeCodeCamp.org Forum](https://forum.freecodecamp.org/)**.
|
105
client/src/pages/guide/english/cplusplus/index.md
Normal file
105
client/src/pages/guide/english/cplusplus/index.md
Normal file
@ -0,0 +1,105 @@
|
||||
---
|
||||
title: C++
|
||||
---
|
||||
# Hello World! - Your First C++ Program
|
||||
|
||||
## What is C++ ?
|
||||
|
||||
* C++ is a general purpose programming language which has been used since the 1990's
|
||||
* It was designed by Bjarne Stroustrup under with the name "C with classes".
|
||||
* It is a version of C that includes Object-Oriented elements, including classes and functions.
|
||||
|
||||
* It is considered one of the biggest programming languages, as you can see in the following image:
|
||||

|
||||
_source: Github_
|
||||
|
||||
### Your First Program in C++
|
||||
|
||||
```cpp
|
||||
#include<iostream>
|
||||
using namespace std ;
|
||||
int main()
|
||||
{
|
||||
cout << "Hello World" << endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
#### The Output of this program will simply be :
|
||||
|
||||
```
|
||||
Hello World!
|
||||
```
|
||||
|
||||
Now, let's break down the code:
|
||||
|
||||
|
||||
#### Lines 1 and 2
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
```
|
||||
|
||||
* The first line tells the computer to use the "iostream" header file for this specific program . A header file is a seperate file with prewritten C++ code. There are many other header files which are requireed for a specific program to run properly. Some of them are : math , vector and string. Header files are generally represented by a ".h" extension (you don't need to add .h when including C++ standard library files)
|
||||
* `iostream` stands for input-output stream . The "iostream" file contains code for allowing the computer to take input and generate an output, using the C++ language.
|
||||
* The second line tells the computer to use the standard namespace which includes features of standard C++. You could write this program without this line, but you'd have to use `std::cout` instead of `cout` on line 4. It makes the code more readable and our lives as programmers easier.
|
||||
|
||||
#### Line 3 and 4
|
||||
|
||||
```cpp
|
||||
int main()
|
||||
{
|
||||
```
|
||||
|
||||
* C++ starts execution of a program from the -main function- `int main()` . During execution , the computer starts running the code from every line from `{`(opening bracket) till `}`(closing bracket)
|
||||
**NOTE : Every function starts with an opening curly brace "{" and ends with a closing curly brace "}".**
|
||||
* Line 4 indicates the start of the main() function.
|
||||
|
||||
#### Lines 4,5 & 6
|
||||
|
||||
```cpp
|
||||
cout << "Hello World" << endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
* The word `cout` in C++ is used to output.
|
||||
* It is followed by `<<` , the _insertion operator_ .
|
||||
* Whatever is in the double quotes `""` is printed . Certain special characters have a different syntax for print statements
|
||||
* Now to print any other kind of data , you have to add `<<` .
|
||||
|
||||
***Challenge: Try to change Hello World to any other sentence or word(s). What will be the output ?***
|
||||
|
||||
* `endl` is a reserved word when using the C++ language to **end this line and go to the next line during output** . - _cout stands for "console output"_
|
||||
* Finally, finish the command with a semicolon `;`.
|
||||
|
||||
**NOTE : Every command except the main function definition and the #include directive needs to be ended by the semicolon. Without a ";" , you may encounter an error.**
|
||||
|
||||
* `return 0;` safely terminates the current function i.e. 'main()' in this case and since no function follows after 'main()' the program is terminated.
|
||||
* Don't forget to tell the computer that this is end of the main() function. To do this , you add the closing curly brace "}". You will encounter an error before program execution if you do not include the **}** .
|
||||
|
||||
### The code should look something like this:
|
||||
|
||||

|
||||
|
||||
Programmers use a Hello World program (like this one) as a ritual on using a new programming language. It is a symbol of good luck.
|
||||
_You have finished coding your first C++ program and have understood most of the code you have written/typed. CONGRATULATIONS!_
|
||||
|
||||
**Good Luck to all of you and happy coding! :)**
|
||||
|
||||
**Happy Coding ! :)**
|
||||
|
||||
**Feel free to ask any questions on FreeCodeCamp's GitHub page or [FreeCodeCamp's Forum.](https://forum.freecodecamp.org/)**
|
||||
|
||||
<a href='https://repl.it/L4k3' target='_blank' rel='nofollow'>Try it yourself ! :) </a>
|
||||
|
||||
**You may need some software to write and execute C++ code. I recommend using CodeBlocks. There's a download link below :**
|
||||
|
||||
Download Link : <a href='http://www.codeblocks.org/downloads/26' target='_blank' rel='nofollow'>Download Here</a>
|
||||
|
||||
* Click the link with the GNU/GCC compiler for windows. This will not require an additional installation
|
||||
|
||||
Other alternatives could be visual studio, using a compiler or an online IDE such as Cloud9 or repl.it
|
||||
|
||||
Link #2 for Mac : [Download for Mac #2 here](https://developer.apple.com/xcode/)
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Inline Function
|
||||
---
|
||||
|
||||
# Inline Function
|
||||
|
||||
## Introduction
|
||||
Inline function is a special function defined in C++ and is expanded inline when it is called.
|
||||
|
||||
Now, what does that exactly mean?
|
||||
|
||||
Whenever a function is called it takes a lot of extra time for performing series of activities such as jumping to the function, saving registers, pushing arguments into stack and returning to the calling function. So it takes a lot of time. But an inline function is a function in which the compiler has been requested to perform inline expansion. Where the function requests the compiler to insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined.
|
||||
|
||||
However, we cannot guarantee that every function declared inline will be inline. Because when we declare a function as `inline`, it is a request, not a command. Compiler may ignore the request of inlining in the following situations:-
|
||||
1) If the function contains loop e.g `for` loop, `while` loop, `do-while` loop etc.
|
||||
2) If the function contains a `switch` or `goto` statement.
|
||||
3) If the function doesn't return anything even if return type (other than `void` of course) is mentioned.
|
||||
4) If the function contains a static variable.
|
||||
5) If the function contains a recursive call.
|
||||
|
||||
``` c++
|
||||
syntax :-
|
||||
---------
|
||||
inline return_type function_name(argument_list){
|
||||
|
||||
// function body
|
||||
|
||||
}
|
||||
```
|
||||
## When to use Inline function
|
||||
|
||||
* When the function performs small tasks and is called very often.
|
||||
* When performance is important.
|
||||
* Instead of a macro.
|
||||
|
||||
``` c++
|
||||
#include<iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class MathOperation{
|
||||
|
||||
public:
|
||||
|
||||
inline int add(int x, int y){
|
||||
|
||||
return(x+y);
|
||||
}
|
||||
|
||||
inline float div(int n1, float n2){
|
||||
|
||||
return(n1/n2);
|
||||
}
|
||||
};
|
||||
|
||||
int main(){
|
||||
|
||||
MathOperation obj;
|
||||
|
||||
cout << "Addition is :" << obj.add(34,12) << <"\n";
|
||||
cout << "Division is :" << obj.div(12,3.4) << "\n";
|
||||
|
||||
return 0;
|
||||
|
||||
}
|
||||
```
|
||||
## Advantages of Inline function
|
||||
* It saves the overhead of return call from a function.
|
||||
* It increases locality of reference by utilizing instruction cache.
|
||||
* It speeds up your program by avoiding function call overheads.
|
||||
* It saves overhead of variables push/pop operations on the stack, when function calls happen.
|
||||
* It is possible to put a function definition in a header file, i.e. it can be included in multiple compilation unit, without the linker complaining.
|
||||
|
||||
## Disadvantages of inline function
|
||||
* When used in a header, it makes your header file larger with information which users don’t care.
|
||||
* It increases the executable size due to code expansion.
|
||||
* C++ inlining is resolved at compile time. Which means if you change the code of the inlined function,
|
||||
you would need to recompile all the code using it to make sure it will be updated.
|
||||
* As mentioned above it increases the executable size, which may cause thrashing in memory.
|
||||
More number of page fault, bringing down your program performance.
|
@ -0,0 +1,113 @@
|
||||
---
|
||||
title: Inline Functions in C++
|
||||
---
|
||||
|
||||
## Inline Functions in C++
|
||||
|
||||
When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually execute the function’s code. This overhead occurs for small functions because execution time of small function is less than the switching time.
|
||||
|
||||
C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency if it is small.
|
||||
The syntax for defining the function inline is:
|
||||
```cpp
|
||||
inline return-type function-name(parameters)
|
||||
{
|
||||
// function code
|
||||
}
|
||||
```
|
||||
Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request for inlining. Compiler may not perform inlining in such circumstances like:
|
||||
* If a function contains a loop. (for, while, do-while)
|
||||
* If a function contains static variables.
|
||||
* If a function is recursive.
|
||||
* If a function return type is other than void, and the return statement doesn’t exist in function body.
|
||||
* If a function contains switch or goto statement.
|
||||
|
||||
### Inline functions provide following advantages:
|
||||
|
||||
* Function call overhead doesn’t occur.
|
||||
* It also saves the overhead of push/pop variables on the stack when function is called.
|
||||
* It also saves overhead of a return call from a function.
|
||||
* When you inline a function, you may enable compiler to perform context specific optimization on the body of function. Such optimizations are not possible for normal function calls. Other optimizations can be obtained by considering the flows of calling context and the called context.
|
||||
* Inline function may be useful (if it is small) for embedded systems because inline can yield less code than the function call preamble and return.
|
||||
|
||||
### Inline function disadvantages:
|
||||
|
||||
* The added variables from the inlined function consumes additional registers, After in-lining function if variables number which are going to use register increases than they may create overhead on register variable resource utilization. This means that when inline function body is substituted at the point of function call, total number of variables used by the function also gets inserted. So the number of register going to be used for the variables will also get increased. So if after function inlining variable numbers increase drastically then it would surely cause an overhead on register utilization.
|
||||
|
||||
* If you use too many inline functions then the size of the binary executable file will be large, because of the duplication of same code.
|
||||
|
||||
* Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of instruction fetch from that of cache memory to that of primary memory.
|
||||
|
||||
* Inline function may increase compile time overhead if someone changes the code inside the inline function then all the calling location has to be recompiled because compiler would require to replace all the code once again to reflect the changes, otherwise it will continue with old functionality.
|
||||
|
||||
* Inline functions may not be useful for many embedded systems. Because in embedded systems code size is more important than speed.
|
||||
|
||||
* Inline functions might cause thrashing because inlining might increase size of the binary executable file. Thrashing in memory causes performance of computer to degrade.
|
||||
|
||||
The following program demonstrates this concept:
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
class operation
|
||||
{
|
||||
int a,b,add,sub,mul;
|
||||
float div;
|
||||
public:
|
||||
void get();
|
||||
void sum();
|
||||
void difference();
|
||||
void product();
|
||||
void division();
|
||||
};
|
||||
inline void operation :: get()
|
||||
{
|
||||
cout << "Enter first value:";
|
||||
cin >> a;
|
||||
cout << "Enter second value:";
|
||||
cin >> b;
|
||||
}
|
||||
|
||||
inline void operation :: sum()
|
||||
{
|
||||
add = a+b;
|
||||
cout << "Addition of two numbers: " << a+b << "\n";
|
||||
}
|
||||
|
||||
inline void operation :: difference()
|
||||
{
|
||||
sub = a-b;
|
||||
cout << "Difference of two numbers: " << a-b << "\n";
|
||||
}
|
||||
|
||||
inline void operation :: product()
|
||||
{
|
||||
mul = a*b;
|
||||
cout << "Product of two numbers: " << a*b << "\n";
|
||||
}
|
||||
|
||||
inline void operation ::division()
|
||||
{
|
||||
div=a/b;
|
||||
cout<<"Division of two numbers: "<<a/b<<"\n" ;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
cout << "Program using inline function\n";
|
||||
operation s;
|
||||
s.get();
|
||||
s.sum();
|
||||
s.difference();
|
||||
s.product();
|
||||
s.division();
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
Output:
|
||||
```
|
||||
Enter first value: 45
|
||||
Enter second value: 15
|
||||
Addition of two numbers: 60
|
||||
Difference of two numbers: 30
|
||||
Product of two numbers: 675
|
||||
Division of two numbers: 3
|
||||
```
|
@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Input and Output
|
||||
---
|
||||
|
||||
## Input and Output
|
||||
|
||||
* Input stream objects in C++ use 'cin'. This is used to save input data into the program.
|
||||
|
||||
* Output stream objects use 'cout', as shown in the first introduction of C++, to print out statements to the console.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int x;
|
||||
|
||||
cout << "Enter a number: " << endl; // Ask user for input
|
||||
cin >> x; // Take user input
|
||||
cout << "The output value of int x: " << x << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
* The header file `<iostream>` is required for stream objects.
|
||||
* After declaring a variable, using the `cin` object, input data can be saved into the variable.
|
||||
* The `cout` object prints the data saved into the variable to the console.
|
||||
|
||||
|
||||
The operators `<<` and `>>` are used to point in the direction of the data.
|
||||
* For `cin`, the `>>` operator is used. You can visualize the input data flowing into the variable.
|
||||
* For `cout`, the `<<` operator is used. You can visualize data from a string or variable flowing into the `cout` object.
|
||||
|
||||
Try the code <a href="https://repl.it/ND8q/1" target='_blank' rel='nofollow'>here</a> .
|
||||
|
||||
**Happy Coding ! :)**
|
||||
|
||||
**Feel free to ask any queries on FreeCodeCamp's GitHub page or [FreeCodeCamp's Forum .](https://forum.freecodecamp.org/)**
|
114
client/src/pages/guide/english/cplusplus/loops/index.md
Normal file
114
client/src/pages/guide/english/cplusplus/loops/index.md
Normal file
@ -0,0 +1,114 @@
|
||||
---
|
||||
title: Loops
|
||||
---
|
||||
|
||||
# Loops
|
||||
|
||||
## Introduction
|
||||
|
||||
Now lets discuss something known as loop. Suppose you want to print the even numbers from 1 to 1000 on the screen. One way
|
||||
to do this is to write the following lines
|
||||
|
||||
``` c++
|
||||
cout << 0 << endl;
|
||||
cout << 2 << endl;
|
||||
cout << 4 << endl;
|
||||
....
|
||||
....
|
||||
....
|
||||
cout << 1000 << endl;
|
||||
|
||||
```
|
||||
But the problem with this approach is that you have to write the same line again and again. And if suppose you have to print
|
||||
prime numbers from 1 to 1000 then this will be more hectic.
|
||||
Therefore, in order to solve such problems loops are introduced.
|
||||
|
||||
There are different types of loop functions:
|
||||
### While and do while loops
|
||||
|
||||
While and do while loops allow you to make the loop until a condition finishes.
|
||||
The difference between While and Do while is that Do while always executes once.
|
||||
Here you can see an example:
|
||||
``` c++
|
||||
while (condition){
|
||||
// Code that will execute while condition is true
|
||||
}
|
||||
do {
|
||||
// Will execute once and until the condition is false
|
||||
} while (condition);
|
||||
```
|
||||
### For loops
|
||||
|
||||
For loops are usually used when you know how many times the code will execute.
|
||||
The flow can be seen in this [graph](https://www.tutorialspoint.com/cplusplus/images/cpp_for_loop.jpg).
|
||||
|
||||
They are declared this way:
|
||||
``` c++
|
||||
for ( initialize a variable; check a condition; increment the initialized variable ) {
|
||||
//Code to execute
|
||||
}
|
||||
```
|
||||
|
||||
Lets write a program which will print numbers from 0 to 1000 including 1000 on the screen using a for loop.
|
||||
|
||||
``` c++
|
||||
for (int i = 0;i<=1000;i++)
|
||||
{
|
||||
cout << i << endl;
|
||||
}
|
||||
```
|
||||
|
||||
When you execute this code in a c++ program numbers from 1 to 1000 will be printed.
|
||||
Now lets discuss how the for loop works.
|
||||
|
||||
* You start a for loop by typing the keyword 'for'. It means you are starting a for loop
|
||||
` for `
|
||||
* Next you open and close a round bracket. In this brackets you write some conditions which will be discussed later
|
||||
` for()`
|
||||
* Inside the brackets first you write the initial condition i.e the value from where the loop will start. Like in the
|
||||
above program we write int i = 0
|
||||
` for(int i = 0)`
|
||||
* Then you write the semicolon and then condition until when the loop will be executed. In the above code you define
|
||||
i < 1000. It means until value of i is less then 1000 execuete the loop.
|
||||
` for(int i=0;i<=1000) `
|
||||
* Then you define the incremented value that is how much i has to be incremented in each iteration. In the above code
|
||||
we write i++. It means value of i will be incremented by 1 every time.
|
||||
` for(int i=0;i<=1000;i++) `
|
||||
* If there is only one statement inside the loop then the curly bracket is optional but its better to write loop code
|
||||
within brackets so that you don't get confused.
|
||||
``` c++
|
||||
for(int i=0;i<=1000;i++)
|
||||
{
|
||||
}
|
||||
```
|
||||
* Then inside the loop you write what do you want to do. In the above program we output the value of i.
|
||||
|
||||
So, in this way the for loop works
|
||||
|
||||
If you want to print even numbers from 1 to 1000 then your program will look like this
|
||||
|
||||
|
||||
``` c++
|
||||
for (int i = 0;i<=1000;i=i+2)
|
||||
{
|
||||
cout << i << endl;
|
||||
}
|
||||
|
||||
```
|
||||
* The difference in first program and second is the increment part. Rest of code is same. This program will print 0 and
|
||||
then add 2 to it and print 2 on console and so on upto value of i becomes equal to 1000.
|
||||
|
||||
Our final program to print even numbers from 0 to 1000 will look like this.
|
||||
|
||||
``` c++
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
for (int i = 0;i<=1000;i=i+2)
|
||||
{
|
||||
cout << i << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
78
client/src/pages/guide/english/cplusplus/map/index.md
Normal file
78
client/src/pages/guide/english/cplusplus/map/index.md
Normal file
@ -0,0 +1,78 @@
|
||||
---
|
||||
title: Map
|
||||
---
|
||||
|
||||
## Introduction of map
|
||||
|
||||
`map` is an associative container that store elements in key-value pair. Just like in `Java` have collection, associative array in PHP and so on.
|
||||
|
||||
## Benefits of using map
|
||||
* It stores only unique keys and that too in sorted order based on its assigned sorting criteria.
|
||||
* As keys are in sorted order therefore searching element in map through key is very fast i.e. it takes logarithmic time.
|
||||
* In `map` there will be only one value attached with the every key.
|
||||
* `map` can be used as associative arrays.
|
||||
* It might be implemented using balanced binary trees.
|
||||
|
||||
Here is an example:
|
||||
|
||||
```c++
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main (){
|
||||
map<char,int> first;
|
||||
|
||||
//initializing
|
||||
first['a']=10;
|
||||
first['b']=20;
|
||||
first['c']=30;
|
||||
first['d']=40;
|
||||
|
||||
map<char, int>::iterator it;
|
||||
for(it=first.begin(); it!=first.end(); ++it){
|
||||
cout << it->first << " => " << it->second << '\n';
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
a => 10
|
||||
b => 20
|
||||
c => 30
|
||||
d => 40
|
||||
```
|
||||
|
||||
## Creating map object
|
||||
` map<string, int> myMap; `
|
||||
|
||||
## Insertion
|
||||
Inserting data with insert member function.
|
||||
|
||||
`myMap.insert(make_pair("earth", 1));`
|
||||
`myMap.insert(make_pair("moon", 2));`
|
||||
|
||||
We can also insert data in std::map using operator [] i.e.
|
||||
|
||||
`myMap["sun"] = 3;`
|
||||
|
||||
## Accessing map elements
|
||||
|
||||
To access map elements, you have to create iterator for it. Here is an example as stated before.
|
||||
```c++
|
||||
map<char, int>::iterator it;
|
||||
for(it=first.begin(); it!=first.end(); ++it){
|
||||
cout << it->first << " => " << it->second << '\n';
|
||||
}
|
||||
```
|
||||
|
||||
Here you can learn more about map: <a href="http://www.cplusplus.com/reference/map/map/map/" target="_blank">cpluspluc_map</a>
|
||||
|
||||
N.B: All code in example are in C++11 version. You can learn more about C++ version <a href="http://en.cppreference.com/w/cpp/compiler_support" target="_blank">Here</a>
|
||||
|
||||
|
||||
|
@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Object Oriented Programming using C++
|
||||
---
|
||||
|
||||
## Object Oriented Programming using C++
|
||||
|
||||
Object oriented programming aims to implement real world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operates on them so that no other part of code can access this data except that function.
|
||||
Let us learn about different characteristics of an Object Oriented Programming language:
|
||||
### Object:
|
||||
Objects are basic run-time entities in an object oriented system, objects are instances of a class these are defined user defined data types.
|
||||
|
||||
```cpp
|
||||
class person
|
||||
{
|
||||
char name[20];
|
||||
int id;
|
||||
public:
|
||||
void getdetails(){}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
person p1; //p1 is a object
|
||||
}
|
||||
```
|
||||
Object take up space in memory and have an associated address like a record in pascal or structure or union in C.
|
||||
|
||||
When a program is executed the objects interact by sending messages to one another.
|
||||
|
||||
Each object contains data and code to manipulate the data. Objects can interact without having to know details of each others data or code, it is sufficient to know the type of message accepted and type of response returned by the objects.
|
||||
|
||||
### Class:
|
||||
Class is a blueprint of data and functions or methods. Class does not take any space.
|
||||
```cpp
|
||||
class class_name
|
||||
{
|
||||
private:
|
||||
//data members and member functions declarations
|
||||
public:
|
||||
//data members and member functions declarations
|
||||
protected:
|
||||
//data members and member functions declarations
|
||||
};
|
||||
```
|
||||
Class is a user defined data type like structures and unions in C.
|
||||
|
||||
By default class variables are private but in case of structure it is public. in above example person is a class.
|
||||
|
||||
### Encapsulation and Data abstraction:
|
||||
Wrapping up(combing) of data and functions into a single unit is known as encapsulation. The data is not accessible to the outside world and only those functions which are wrapping in the class can access it. This insulation of the data from direct access by the program is called data hiding or information hiding.
|
||||
|
||||
Data abstraction refers to, providing only needed information to the outside world and hiding implementation details. For example, consider a class Complex with public functions as getReal() and getImag(). We may implement the class as an array of size 2 or as two variables. The advantage of abstractions is, we can change implementation at any point, users of Complex class wont’t be affected as out method interface remains same. Had our implementation be public, we would not have been able to change it.
|
||||
|
||||
### Inheritance:
|
||||
Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. Inheritance provides re usability. This means that we can add additional features to an existing class without modifying it.
|
||||
|
||||
|
||||
|
||||
### Polymorphism:
|
||||
Polymorphism means ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends upon the types of data used in the operation.
|
||||
C++ supports operator overloading and function overloading.
|
||||
Operator overloading is the process of making an operator to exhibit different behaviors in different instances is known as operator overloading.
|
||||
Function overloading is using a single function name to perform different types of tasks.
|
||||
polymorphism is extensively used in implementing inheritance.
|
||||
|
||||
|
||||
|
||||
### Dynamic Binding:
|
||||
In dynamic binding, the code to be executed in response to function call is decided at runtime. C++ has virtual functions to support this.
|
||||
|
||||
|
||||
|
||||
### Message Passing:
|
||||
Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function and the information to be sent.
|
@ -0,0 +1,55 @@
|
||||
---
|
||||
title: C++ Overloading
|
||||
---
|
||||
|
||||
C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.
|
||||
|
||||
An overloaded declaration is a declaration that is declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
|
||||
|
||||
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.
|
||||
|
||||
### Function Overloading in C++
|
||||
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
|
||||
|
||||
Following is the example where same function print() is being used to print different data types −
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class printData {
|
||||
public:
|
||||
void print(int i) {
|
||||
cout << "Printing int: " << i << endl;
|
||||
}
|
||||
void print(double f) {
|
||||
cout << "Printing float: " << f << endl;
|
||||
}
|
||||
void print(char* c) {
|
||||
cout << "Printing character: " << c << endl;
|
||||
}
|
||||
};
|
||||
|
||||
int main(void) {
|
||||
printData pd;
|
||||
|
||||
// Call print to print integer
|
||||
pd.print(5);
|
||||
|
||||
// Call print to print float
|
||||
pd.print(500.263);
|
||||
|
||||
// Call print to print character
|
||||
pd.print("Hello C++");
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
When the above code is compiled and executed, it produces the following result −
|
||||
|
||||
```
|
||||
Printing int: 5
|
||||
Printing float: 500.263
|
||||
Printing character: Hello C++
|
||||
```
|
209
client/src/pages/guide/english/cplusplus/queue/index.md
Normal file
209
client/src/pages/guide/english/cplusplus/queue/index.md
Normal file
@ -0,0 +1,209 @@
|
||||
---
|
||||
title: queue
|
||||
---
|
||||
|
||||
## Queues
|
||||
|
||||
`queue` is one of the most used containers in C++. A container is a data structure that stores a collection of objects, some in order, some not. All containers have a different set of functions that allow you to access an object(s) in that collection.
|
||||
|
||||
`std::queue` is part of the C++ standard library (hence the prefix `std::`) and allows you to store data in First In First Out (FIFO) order. NOTE: **All objects within a queue must be of the same data type**
|
||||
|
||||
The data type you store within a queue goes within angle brackets next to the queue keyword. For example, if you would like to store a collection of integers the queue would be `std::queue<int> queue_name`
|
||||
|
||||
### Queue LIFO Explanation
|
||||
|
||||
`queue` allows us to push/enqueue and pop/dequeue in specific order. **Push** means inserting an object at the front of the queue. **Pop** means pulling out the "oldest" object from end of the queue. So when you push it is at the front and when you pop you extract the oldest element.
|
||||
|
||||

|
||||
|
||||
### Queue Operations
|
||||
|
||||
The queue container supports the following operations:
|
||||
- push (enqueue)
|
||||
- pop (dequeue)
|
||||
- empty
|
||||
- size
|
||||
- front
|
||||
- back
|
||||
|
||||
#### Push
|
||||
|
||||
Allows you to inserts a new element at the end of the queue, after its current last element.
|
||||
|
||||
```cpp
|
||||
//Push operation in Queue
|
||||
#include <iostream> // std::cout
|
||||
#include <queue> // std::queue
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::queue<int> q;
|
||||
|
||||
q.push(1); //Pushing 1 at front of the queue
|
||||
q.push(2); //Pushing 2 at front of the queue
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
#### Front
|
||||
|
||||
Allows you to access the next element in the queue without removing it.
|
||||
The next element is the "oldest" element in the queue.
|
||||
|
||||
```cpp
|
||||
//Front operation in Queue
|
||||
#include <iostream> // std::cout
|
||||
#include <queue> // std::queue
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::queue<int> q;
|
||||
|
||||
q.push(1); //Pushing 1 at front of the queue
|
||||
q.push(2); //Pushing 2 at front of the queue
|
||||
|
||||
std::cout<<q.front()<<'\n'; //Accessing the front of the queue
|
||||
std::cout<<q.front()<<'\n'; //Accessing the front of the queue
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
1
|
||||
1
|
||||
|
||||
#### Pop
|
||||
|
||||
Allows you to remove the next element in the queue, effectively reducing its size by one.
|
||||
The element removed is the "oldest" element.
|
||||
|
||||
```cpp
|
||||
//Pop operation in Queue
|
||||
#include <iostream> // std::cout
|
||||
#include <queue> // std::queue
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::queue<int> q;
|
||||
|
||||
q.push(1); //Pushing 1 at front of the queue
|
||||
q.push(2); //Pushing 2 at front of the queue
|
||||
|
||||
std::cout<<q.front()<<'\n'; //Accessing the front of the queue
|
||||
q.pop(); //Removing the oldest element
|
||||
std::cout<<q.front()<<'\n'; //Accessing the front of the queue
|
||||
q.pop(); //Removing the oldest element
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
1
|
||||
2
|
||||
|
||||
#### Size
|
||||
|
||||
Returns the number of elements in the `queue`.
|
||||
|
||||
```cpp
|
||||
//Size operation in Queue
|
||||
#include <iostream> // std::cout
|
||||
#include <queue> // std::queue
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::queue<int> q;
|
||||
|
||||
q.push(1); //Pushing 1 at front of the queue
|
||||
q.push(2); //Pushing 2 at front of the queue
|
||||
|
||||
std::cout<<q.size()<<'\n'; //Accessing the front of the queue
|
||||
q.pop(); //Removing the oldest element
|
||||
std::cout<<q.size()<<'\n'; //Accessing the front of the queue
|
||||
q.pop(); //Removing the oldest element
|
||||
std::cout<<q.size()<<'\n'; //Accessing the front of the queue
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Output:
|
||||
2
|
||||
1
|
||||
0
|
||||
|
||||
#### Empty
|
||||
|
||||
Returns whether the `queue` is empty ,i.e. whether your queue size is zero.
|
||||
It returns `true` if queue's size 0 else returns `false`
|
||||
|
||||
```cpp//Empty operation in Queue
|
||||
#include <iostream> // std::cout
|
||||
#include <queue> // std::stack
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::queue<int> q;
|
||||
|
||||
q.push(1);
|
||||
q.push(2);
|
||||
|
||||
while(q.empty() != true){
|
||||
std::cout<<q.front()<<'\n';
|
||||
q.pop();
|
||||
}
|
||||
|
||||
std::cout<<"Out of loop"<<'\n';
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
1
|
||||
2
|
||||
Out of loop
|
||||
|
||||
#### Back
|
||||
|
||||
Allows you to access the last element in the queue without removing it.
|
||||
The next element is the "newest" element in the queue.
|
||||
|
||||
```cpp
|
||||
//Back operation in Queue
|
||||
#include <iostream> // std::cout
|
||||
#include <queue> // std::queue
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::queue<int> q;
|
||||
|
||||
q.push(1); //Pushing 1 at front of the queue
|
||||
q.push(2); //Pushing 2 at front of the queue
|
||||
|
||||
std::cout<<q.back()<<'\n'; //Accessing the back of the queue
|
||||
std::cout<<q.back()<<'\n'; //Accessing the back of the queue
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
2
|
||||
2
|
||||
|
||||
|
||||
### For More Resources:
|
||||
http://www.cplusplus.com/reference/queue/queue/
|
||||
|
||||
### Citations:
|
||||
Image Courtesy: https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Range For Loop
|
||||
---
|
||||
|
||||
## Range-based for loop
|
||||
|
||||
The ranged-based `for` loop allows easy looping over a range of elements (like elements in a container).
|
||||
|
||||
With traditional `for` loop:
|
||||
|
||||
```cpp
|
||||
std::vector<std::string> stringList {"one", "two", "three"};
|
||||
|
||||
for (size_t il; il < stringList.size(); il++
|
||||
{
|
||||
std::cout << stringList.at(il) << std::endl;
|
||||
}
|
||||
```
|
||||
|
||||
With range-based `for` loop:
|
||||
|
||||
```cpp
|
||||
std::vector<std::string> stringList {"one", "two", "three"};
|
||||
|
||||
for (auto& singleString : stringList)
|
||||
{
|
||||
std:cout << singleString << std::endl;
|
||||
}
|
||||
```
|
95
client/src/pages/guide/english/cplusplus/set/index.md
Normal file
95
client/src/pages/guide/english/cplusplus/set/index.md
Normal file
@ -0,0 +1,95 @@
|
||||
---
|
||||
title: Set
|
||||
---
|
||||
|
||||
A set data structure in c++ is defined the same way a set is defined in the context of mathematics.
|
||||
|
||||
More formally speaking, Sets are a type of associative containers in which each element has to be unique.
|
||||
* The value of the element cannot be modified once it is entered, although deleting an element and inserting a new element is allowed, the same way we do in mathenatics.
|
||||
* Set data sructure can be used to model, well, sets itself. It becomes easy to find intersections, unions etc.
|
||||
* Similar to vector, but only unique values are allowed.
|
||||
* Set arranges the elements in increasing order as and when you insert elements into the set.
|
||||
|
||||
The header file required for using the set data structure is 'set'. i.e, `#include<set>` must be there in your code for you to use the set data structure.
|
||||
|
||||
__Pro tip__:- Use `#include<bits/stdc++.h>` to include all C++ data structures and functions, instead of adding them one by one.
|
||||
<br>
|
||||
Some of the functions that can be performed with a set:-
|
||||
|
||||
1. begin() – Returns an iterator to the first element in the set
|
||||
1. end() – Returns an iterator to the theoretical element that follows last element in the set
|
||||
1. size() – Returns the number of elements in the set
|
||||
1. max_size() – Returns the maximum number of elements that the set can hold
|
||||
1. empty() – Returns whether the set is empty
|
||||
1. erase(const g)- Removes the value ‘g’ from the set
|
||||
1. clear() – Removes all the elements from the set
|
||||
|
||||
|
||||
Let us look at an example :-
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <iterator>
|
||||
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
set <int> myset; //an empty set container. Note that size of the set need not be declared, similar to vector.
|
||||
|
||||
// insert elements in random order
|
||||
myset.insert(65);
|
||||
myset.insert(30);
|
||||
myset.insert(80);
|
||||
myset.insert(20);
|
||||
myset.insert(9);
|
||||
myset.insert(9); // only one 9 will be added to the list.
|
||||
|
||||
|
||||
// printing set myset
|
||||
set <int> :: iterator itr; //an iterator is like a pointer.
|
||||
cout << "\nThe contents of myset : ";
|
||||
for (itr = myset.begin(); itr != myset.end(); ++itr)
|
||||
{
|
||||
cout << '\t' << *itr;
|
||||
}
|
||||
cout << endl;
|
||||
|
||||
|
||||
// remove all elements up to 65 in myset from the beginning:-
|
||||
cout << "\nContents of myset after removal of elements less than 30 : ";
|
||||
myset.erase(myset.begin(), myset.find(30));
|
||||
for (itr = myset.begin(); itr != myset.end(); ++itr)
|
||||
{
|
||||
cout << '\t' << *itr;
|
||||
}
|
||||
|
||||
// remove element with value 50 in myset
|
||||
|
||||
int num = myset.erase(80); //returns true (and deletes) if 80 is there in the list else returns 0.
|
||||
cout<<"\n\n After doing myset.erase(80), "<<num<<" element is removed\n\n";
|
||||
cout<<"Contents of the modified set:\t";
|
||||
for (itr = myset.begin(); itr != myset.end(); ++itr)
|
||||
{
|
||||
cout << '\t' << *itr;
|
||||
}
|
||||
|
||||
cout << endl;
|
||||
|
||||
|
||||
return 0;
|
||||
|
||||
}
|
||||
```
|
||||
```cpp
|
||||
Output:-
|
||||
The contents of myset : 9 20 30 65 80
|
||||
|
||||
Contents of myset after removal of elements less than 30 : 30 65 80
|
||||
|
||||
After doing myset.erase(80), 1 element is removed
|
||||
|
||||
Contents of the modified set: 30 65
|
||||
```
|
||||
|
||||
### Sources
|
||||
1. [Geeks for Geeks](https://www.geeksforgeeks.org/set-in-cpp-stl/)
|
165
client/src/pages/guide/english/cplusplus/stack/index.md
Normal file
165
client/src/pages/guide/english/cplusplus/stack/index.md
Normal file
@ -0,0 +1,165 @@
|
||||
---
|
||||
title: stack
|
||||
---
|
||||
|
||||
## Stacks
|
||||
|
||||
`stack` is one of the most used containers in C++. A container is a data structure that stores a collection of objects, some in order, some not. All containers have a different set of functions that allow you to access an object(s) in that collection.
|
||||
|
||||
`std::stack` is part of the C++ standard library (hence the prefix `std::`) and allows you to store data in Last In First Out (LIFO) order. NOTE: **All objects within a stack must be of the same data type**
|
||||
|
||||
The data type you store within a stack goes within angle brackets next to the stack keyword. For example, if you would like to store a collection of integers the stack would be `std::stack<int> stack_name`
|
||||
|
||||
### Stack LIFO Explanation
|
||||
|
||||
`stack` allows us to push and pop in specific order. **Push** means inserting an object at the top of the stack. **Pop** means pulling out the last inserted object from the top of the stack. So when you push it is at the top and when you pop you extract the last inserted element.
|
||||
|
||||

|
||||
|
||||
### Stack Operations
|
||||
|
||||
The stack container supports the following operations:
|
||||
- push
|
||||
- pop
|
||||
- empty
|
||||
- size
|
||||
- back
|
||||
|
||||
#### Push
|
||||
|
||||
Allows you to insert a new element at the top of the stack, above the current top element.
|
||||
|
||||
```cpp
|
||||
//Push operation in Stack
|
||||
#include <iostream> // std::cout
|
||||
#include <stack> // std::stack
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::stack<int> s;
|
||||
|
||||
s.push(1); //Pushing 1 at top of the stack
|
||||
s.push(2); //Pushing 2 at top of the stack
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
#### Top
|
||||
|
||||
Allows you to access the the top element without removing it from your stack.
|
||||
|
||||
```cpp
|
||||
//Top operation in Stack
|
||||
#include <iostream> // std::cout
|
||||
#include <stack> // std::stack
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::stack<int> s;
|
||||
|
||||
s.push(1); //Pushing 1 at top of the stack
|
||||
s.push(2); //Pushing 2 at top of the stack
|
||||
|
||||
std::cout<<s.top()<<'\n'; //Accessing the top of the stack
|
||||
std::cout<<s.top()<<'\n'; //Accessing the top of the stack
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
2
|
||||
2
|
||||
|
||||
#### Pop
|
||||
|
||||
Removes the element on top of the stack, effectively reducing your stack's size by one.
|
||||
|
||||
```cpp
|
||||
//Pop operation in Stack
|
||||
#include <iostream> // std::cout
|
||||
#include <stack> // std::stack
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::stack<int> s;
|
||||
|
||||
s.push(1); //Pushing 1 at top of the stack
|
||||
s.push(2); //Pushing 2 at top of the stack
|
||||
|
||||
std::cout<<s.top()<<'\n'; //Accessing the top of the stack
|
||||
s.pop(); //Removing element from the top of stack
|
||||
std::cout<<s.top()<<'\n'; //Accessing the top of the stack
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
2
|
||||
1
|
||||
|
||||
#### Size
|
||||
|
||||
Returns the number of elements in the `stack`.
|
||||
|
||||
```cpp
|
||||
//Size operation in Stack
|
||||
#include <iostream> // std::cout
|
||||
#include <stack> // std::stack
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::stack<int> s;
|
||||
|
||||
s.push(1); //Pushing 1 at top of the stack
|
||||
s.push(2); //Pushing 2 at top of the stack
|
||||
|
||||
std::cout<<s.size()<<'\n'; //Showing the size of the stack
|
||||
s.pop(); //Removing element from the top of stack
|
||||
std::cout<<s.size()<<'\n'; //Showing the size of the stack
|
||||
s.pop(); //Removing element from the top of stack
|
||||
std::cout<<s.size()<<'\n'; //Showing the size of the stack
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
2
|
||||
1
|
||||
0
|
||||
|
||||
#### Empty
|
||||
|
||||
Returns whether the `stack` is empty ,i.e. whether your stack size is zero.
|
||||
It returns `true` if stack's size 0 else returns `false`
|
||||
|
||||
```cpp
|
||||
//Empty operation in Stack
|
||||
#include <iostream> // std::cout
|
||||
#include <stack> // std::stack
|
||||
|
||||
int main ()
|
||||
{
|
||||
std::stack<int> s;
|
||||
|
||||
s.push(1);
|
||||
s.push(2);
|
||||
|
||||
while(s.empty() != false){
|
||||
std::cout<<s.top()<<'\n';
|
||||
s.pop();
|
||||
}
|
||||
|
||||
std::cout<<"Out of loop"<<'\n';
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
2
|
||||
1
|
||||
Out of loop
|
@ -0,0 +1,73 @@
|
||||
---
|
||||
title: Switch Statement
|
||||
---
|
||||
|
||||
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
|
||||
|
||||
Syntax:
|
||||
switch(expression) {
|
||||
case constant-expression :
|
||||
statement(s);
|
||||
break; //optional
|
||||
case constant-expression :
|
||||
statement(s);
|
||||
break; //optional
|
||||
|
||||
// you can have any number of case statements.
|
||||
default : //Optional
|
||||
statement(s);
|
||||
}
|
||||
|
||||
The following rules apply to a switch statement −
|
||||
|
||||
The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
|
||||
|
||||
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
|
||||
|
||||
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
|
||||
|
||||
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
|
||||
|
||||
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
|
||||
|
||||
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
|
||||
|
||||
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
|
||||
|
||||
Example:
|
||||
```C++
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main () {
|
||||
// local variable declaration:
|
||||
char grade = 'D';
|
||||
|
||||
switch(grade) {
|
||||
case 'A' :
|
||||
cout << "Excellent!" << endl;
|
||||
break;
|
||||
case 'B' :
|
||||
case 'C' :
|
||||
cout << "Well done" << endl;
|
||||
break;
|
||||
case 'D' :
|
||||
cout << "You passed" << endl;
|
||||
break;
|
||||
case 'F' :
|
||||
cout << "Better try again" << endl;
|
||||
break;
|
||||
default :
|
||||
cout << "Invalid grade" << endl;
|
||||
}
|
||||
cout << "Your grade is " << grade << endl;
|
||||
|
||||
return 0;
|
||||
}```
|
||||
|
||||
Output:
|
||||
You passed
|
||||
Your grade is D
|
||||
|
||||
###Sources
|
||||
https://www.tutorialspoint.com
|
@ -0,0 +1,151 @@
|
||||
---
|
||||
title: IDE and Printing different text
|
||||
---
|
||||
# Introduction to an IDE and printing different text :
|
||||
|
||||
* In the last article, some download links for software required for programming . Software like this is known as an IDE.
|
||||
**IDE stands for Integrated Development Environment**
|
||||
|
||||
## IDEs mainly consist of 3 kinds of software :
|
||||
|
||||
**1 Editor :** A slightly modified text editor to make coding easy. An example of an editor for coding is Notepad++.
|
||||
|
||||
**2 Debugger :** Software that helps you find errors in your program , and resolve them before execution. Imagine FaceBook crashing on loading an application or a game crashing all of a sudden. To prevent faulty execution of a program, the debugger is a programmer's best friend.
|
||||
|
||||
**3 Compiler :** A compiler is that part of the computer which converts your high level program code to simple machine code : 0s & 1s ; so that a computer understands the commands and executes them. From now on, we will be uding the word **compiler** frequently.
|
||||
|
||||
*Q : Try searching for an IDE on Google and run your first program on it . Check the output*
|
||||
|
||||
Now, install the IDE and try changing the text from the program in the last article.
|
||||
|
||||
### Changing text on C++
|
||||
|
||||
* To change text ,change what's typed in the `""` after `cout<<`
|
||||
|
||||
A sample program :
|
||||
|
||||
```cpp
|
||||
|
||||
#include <iostream>
|
||||
using namespace std :
|
||||
int main()
|
||||
{
|
||||
cout << "I Love freeCodeCamp ! ";
|
||||
}
|
||||
```
|
||||
|
||||
The above code returns an error because at line 2, we have used a colon(:) instead of a semicolon(;)
|
||||
So, let's debug the error:
|
||||
|
||||
```C++
|
||||
#include <iostream>
|
||||
using namespace std ;
|
||||
int main()
|
||||
{
|
||||
cout << "I Love freeCodeCamp ! ";
|
||||
return 0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Note that now the program runs perfectly.
|
||||
The output will be : `I Love freeCodeCamp!`
|
||||
|
||||
### Now , let's change the text to something else like this:
|
||||
|
||||
```cpp
|
||||
cout << "Hello World!\t I love freeCodeCamp!";
|
||||
```
|
||||
|
||||
The output will be something different this time:
|
||||
|
||||
```
|
||||
Hello World! I love freeCodeCamp!
|
||||
```
|
||||
|
||||
If you realised , the `\t` command created a _tab space_ between the two texts . This is one kind of special command in C++. These special commands are known as *Escape Sequences* .
|
||||
They are used to print certain special characters a compiler cannot display.
|
||||
|
||||
#### Useful escape sequences:
|
||||
|
||||
* `\'` to print a single inverted comma
|
||||
* `\"` to print a double inverted comma
|
||||
* `\n` to print on a new line
|
||||
* `\t` for a horizontal tab
|
||||
* `\f` for a new page
|
||||
* `\\` for a backslash
|
||||
* `\?` for a question mark
|
||||
|
||||
##### Now, let's try printing numbers and special characters with some escape sequences:
|
||||
|
||||
```cpp
|
||||
cout << "40158 \t 236708 ! \n \\ @ \?" << endl;
|
||||
```
|
||||
|
||||
The output changes to:
|
||||
```
|
||||
40158 236708 !
|
||||
\ @ ?
|
||||
```
|
||||
|
||||
##### Let's try some other ways of printing:
|
||||
|
||||
```cpp
|
||||
cout << "1+2" << endl;
|
||||
cout << 1+2 << endl;
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
* The first output statement is `1+2`
|
||||
* The second output statement is `3`
|
||||
|
||||
This is because we did not add the inverted commas for the second print statement and so, the compiler added the numbers before printing them.
|
||||
|
||||
#### Comments:
|
||||
|
||||
* Comments are an important feature of many programming languages. They allow the programmer to take notes for self help, and won't affect the running of the program.
|
||||
|
||||
**The different types of comments and Syntax of a comment**:
|
||||
|
||||
1 `//` ~ _Single Line Comments_ : The length of these comments is 1 line (the line it is typed on) .
|
||||
2 `/* */` ~ _Multi Line Comments_ : These comments can take up a space of more than one line.
|
||||
|
||||
#### Example of using comments:
|
||||
|
||||
```cpp
|
||||
cout << "Hello Comment" << endl; //cout<<"Hello Comment"<<endl; , Single Line Comment.
|
||||
|
||||
/* This is an example of a multi line comment. No output is generated for this .
|
||||
I now end the comment. :) */
|
||||
```
|
||||
|
||||
The output will be :
|
||||
|
||||
`Hello Comment`
|
||||
|
||||
As you may notice, the comments are ignored during program execution and do not show up on checking the output of the program.
|
||||
It should be noted that while comments do add an extra level of readability to one's code, it's a bad habit to rely too heavily on comments to describe the logic in your code. In general, your code should speak for itself and reflect the intention of the programmer.
|
||||
|
||||
As you may notice, the comments are ignored during program execution and do not show up on checking the output of the program.
|
||||
|
||||
#### Operators
|
||||
* Operators allow you to compare two or more expressions
|
||||
* `==` equal to
|
||||
* `!=` not equal to
|
||||
* `<` less than
|
||||
* `>` greater than
|
||||
* `<=` less than or equal to
|
||||
* `>=` greater than or equal to
|
||||
|
||||
```cpp
|
||||
(7==5);
|
||||
```
|
||||
This evaluates to false
|
||||
|
||||
```cpp
|
||||
(7!=5);
|
||||
```
|
||||
This evaluates to true
|
||||
|
||||
<a href='https://repl.it/L4ox' target='_blank' rel='nofollow'>A summation of all the print statements used in this article. Feel free to tweak around woth the code ! :) </a>
|
@ -0,0 +1,60 @@
|
||||
---
|
||||
title: The Auto Feature
|
||||
---
|
||||
|
||||
## The Auto Feature
|
||||
|
||||
`auto` is a C++11 feature that lets the compiler infer the data type for us in a definition.
|
||||
|
||||
Without `auto`
|
||||
```cpp
|
||||
double x = 10.425;
|
||||
double y = x * x;
|
||||
```
|
||||
|
||||
With `auto`
|
||||
```cpp
|
||||
double x = 10.425;
|
||||
auto y = x * x;
|
||||
```
|
||||
|
||||
Whilst it may seem trivial, it becomes incredibly useful when data types begin to get complicated. For example, if a user wanted to store a vector of employees that had their name and age. One way to store the name and age could be a `pair` with a `string` and an `unsigned int`. This is represented as `std::vector<std::pair<std::string, unsigned int>> employees`. Now suppose we wanted to access the last employee added:
|
||||
|
||||
```cpp
|
||||
std::vector<std::pair<std::string, unsigned int>> employees;
|
||||
|
||||
// without auto
|
||||
std::pair<std::string, unsigned int>> last_employee = employees.back();
|
||||
|
||||
// with auto
|
||||
auto last_employee = employees.back();
|
||||
```
|
||||
|
||||
Once the compiler determines the type on the right side of the `=` it replaces `auto` with that type.
|
||||
|
||||
### `auto` before C++11
|
||||
In some old textbooks containing _very_ old code, the keyword `auto` is used in a very different manner.
|
||||
|
||||
This particular `auto` was a keyword borrowed from C, and was probably the least used keyword of all time.
|
||||
|
||||
In C++, all variables have _automatic duration_, that is, they are defined until you get out of the function they're defined in.
|
||||
|
||||
For example:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
int main()
|
||||
{
|
||||
int a;
|
||||
a = 1; //makes sense, as it was defined in the same function
|
||||
|
||||
return 0;
|
||||
}
|
||||
a = 2; //makes no sense, since a isn't defined here
|
||||
```
|
||||
|
||||
This is a given in C++, and `auto` specified that the variable should have an _automatic duration_, hence the lack of use.
|
||||
|
||||
## Further Reading :
|
||||
* http://www.stroustrup.com/C++11FAQ.html#auto
|
@ -0,0 +1,104 @@
|
||||
---
|
||||
title: C++ If Statement
|
||||
---
|
||||
|
||||
# The IF statement.
|
||||
|
||||
**What does an if statement do?**
|
||||
|
||||
* The `if` statement evaluates the test expression present inside the parenthesis.
|
||||
* The `if` statement uses relational and logical operators to make logical expressions.
|
||||
|
||||
-----------------------------------------------
|
||||
The general form of `if` statement:
|
||||
|
||||
```cpp
|
||||
if (Test Expression / Condition)
|
||||
{
|
||||
// Block of statements if test expression is True
|
||||
}
|
||||
```
|
||||
|
||||
If the value of the test expression is **true**, then the block of
|
||||
code inside the if statement is executed.
|
||||
|
||||
If the value of the test expression is **false**, then the block of
|
||||
code inside the if statement is skipped and your code continues.
|
||||
|
||||
Example `if` statement:
|
||||
|
||||
```cpp
|
||||
int a = 10;
|
||||
|
||||
// true statement
|
||||
if (a < 20)
|
||||
{
|
||||
// execute this block of code
|
||||
}
|
||||
|
||||
// false statement
|
||||
if (a < 0)
|
||||
{
|
||||
// Skip this block of code.
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Example In C++ :
|
||||
|
||||
```cpp
|
||||
// Program to check if number entered by the user is positive
|
||||
// If negative, the block of code is skipped
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int no ;
|
||||
cout << "Enter a number: ";
|
||||
cin >> no;
|
||||
|
||||
// if statement to check if the number is positive
|
||||
if ( no > 0)
|
||||
{
|
||||
cout << "You have entered a positive number: " << no << endl;
|
||||
}
|
||||
|
||||
// If number is not positive, then if statement is skipped a program continues
|
||||
cout << "This step is always printed" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Output:**
|
||||
|
||||
OUTPUT 1:
|
||||
|
||||
```
|
||||
Enter a number: 5
|
||||
You have entered a positive number: 5
|
||||
This step is always printed
|
||||
```
|
||||
This is the output when the number entered is positive.
|
||||
|
||||
OUTPUT 2:
|
||||
|
||||
```
|
||||
Enter a number: -1
|
||||
This step is always printed
|
||||
```
|
||||
This is the output when the number entered is negative.
|
||||
|
||||
<a href='https://repl.it/Mg9X' target='_blank' rel='nofollow'>Try the code yourself ! :) </a>
|
||||
|
||||
|
||||
_CONGRATULATIONS . This is the end of the article on the IF statement_
|
||||
|
||||
**Good Luck to all of you**
|
||||
|
||||
**Happy Coding ! :)**
|
||||
|
||||
**Feel free to ask any queries on FreeCodeCamp's GitHub page or [FreeCodeCamp's Forum .](https://forum.freecodecamp.org/)**
|
@ -0,0 +1,176 @@
|
||||
---
|
||||
title: Operators
|
||||
---
|
||||
|
||||
# Operators :
|
||||
|
||||
* Operators let you perform operations on your data.
|
||||
* The data that is being operated on is called the _operand_ .
|
||||
* The different types of operators in C++ are :
|
||||
* *OPERANDS* are the data on which the operator performs certain commands.
|
||||
* Operators are of 3 types : unary(works on 1 operand), binary(works on 2 operands) , ternary(works on 3 operands).
|
||||
|
||||
### 1 The I/O operators -
|
||||
|
||||
* These operators allow you to direct input and output.
|
||||
## The Input oerator ">>" ##
|
||||
is used to read data from standard input (the "cin" statement) .
|
||||
|
||||
##The Output operator "<<"##
|
||||
is used to send output in the `cout` statement.
|
||||
|
||||
### 2 The Arithmetic operators -
|
||||
|
||||
* These operators allow you to perform basic arithmetic operations.
|
||||
1. The `+` operator *adds* the two operands.
|
||||
2. The `-` operator *subtracts* the two operands.
|
||||
3. The `*` operator *multiplies* the two operands.
|
||||
4. The `/` operator *divides* and gives the *quotient* of the two operands.
|
||||
5. The `%` operator *divides* and gives the *remainder* of the two operands. (Or, for the more mathematically inclined reader, `a % b` is essentially the result of "a mod b"
|
||||
|
||||
### Example of using arithmetic operators :
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int a = 5; //1st operand
|
||||
int b = 10; //2nd operand
|
||||
|
||||
cout << "+ operator " << a+b << "\n"; //Add
|
||||
cout << "- operator " << a-b << "\n"; //Subtract
|
||||
cout << "* operator " << a*b << "\n"; //Multiply
|
||||
cout << "/ operator " << b/a << "\n"; //Find Quotient
|
||||
cout << "modulus operator " << b%a << "\n"; //Find remainder
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
OUTPUT :
|
||||
```
|
||||
+ operator 15
|
||||
- operator -5
|
||||
* operator 50
|
||||
/ operator 2
|
||||
modulus operator 0
|
||||
```
|
||||
|
||||
<a href='https://repl.it/Mge9' target='_blank' rel='nofollow'>Try the code yourself ! :) </a>
|
||||
|
||||
### The increment operator :
|
||||
|
||||
* `++` is known as the increment operator. It increases the value of an integer variable by 1.
|
||||
|
||||
The 2 types of increment :
|
||||
|
||||
* Pre increment first increments the value and then uses it. Example : `int a ; ++a;`
|
||||
* Post increment first uses the variable then increments it. Example : `int b; b++;`
|
||||
|
||||
### The decrement operator :
|
||||
|
||||
* `--` is known as the decrement operator. It decreases the value of an integer variable by 1.
|
||||
|
||||
The 2 types of decrement :
|
||||
|
||||
* Pre decrement first decrements the value and then uses it. Example : `int a ; --a;`
|
||||
* Post decrement first uses the variable then decrements it. Example : `int b; b--;`
|
||||
|
||||
Example of Increment and decrement operators :
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int a = 3 ,b = 4;
|
||||
|
||||
// INCREMENT
|
||||
cout<< "Value of int a PRE INCREMENTED : " << ++a << "\n";
|
||||
cout<< "Value of int b POST INCREMENTED : " << b++ << "\n";
|
||||
cout<< "Value of b is changed after using once : " << b << "\n";
|
||||
|
||||
// DECREMENT
|
||||
cout << "\n"; //go to next line
|
||||
a = 10; //Assigning a new value to a
|
||||
b = 10; //Assigning a new value to b
|
||||
cout << "Value of int a PRE DECREMENTED : " << --a << "\n";
|
||||
cout << "Value of int b POST DECREMENTED : " << b-- << "\n";
|
||||
cout << "Value of b is changed after using once : " << b << "\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
OUTPUT :
|
||||
|
||||
```
|
||||
Value of int a PRE INCREMENTED : 4
|
||||
Value of int b POST INCREMENTED : 4
|
||||
Value of b is changed after using once : 5
|
||||
|
||||
Value of int a PRE DECREMENTED : 9
|
||||
Value of int b POST DECREMENTED : 10
|
||||
Value of b is changed after using once : 9
|
||||
```
|
||||
|
||||
<a href='https://repl.it/Mgg4/2' target='_blank' rel='nofollow'>Try the code yourself ! :) </a>
|
||||
|
||||
### 3 : Relational Operators :
|
||||
|
||||
* These operators tell us the relation among 2 operands and return a boolean value(0 or 1). If the relation is `true` then it results into 1 . If the realtion is false then it results into 0.
|
||||
|
||||
* The 6 relational operators are :
|
||||
1. Less than `<`
|
||||
2. Greater than `>`
|
||||
3. Less than or equal to `<=`
|
||||
4. Greater than or equal to `>=`
|
||||
5. Equal to `==`
|
||||
6. Not equal to `!=`
|
||||
|
||||
|
||||
### 4 : Logical Operators :
|
||||
|
||||
* These operators combine expressions for logical operations . They are :
|
||||
1. Logical AND `&&` : Evaluates to true if both values are true .
|
||||
2. Logical OR `||` : Evaluates to true if any value is true .
|
||||
3. Logical NOT `!` : If *expression* is true then *!expression* is false. This operator reverses the truth value and is a unary operator.
|
||||
|
||||
### 5. Ternary Operators :
|
||||
|
||||
The `?:` operator is the ternary operator, or the _conditional operator_, becuase it can be used to substitute an `if else` statement, or even an `if else if` statement.
|
||||
The syntax:
|
||||
|
||||
`condition ? ValueIfTrue : ValueIfFalse `. This expands to:
|
||||
|
||||
```cpp
|
||||
if(condition)
|
||||
ValueIfTrue;
|
||||
else ValueIfFalse;
|
||||
```
|
||||
|
||||
Calling `ValueIfTrue` a value is a bit wrong, since it need not be a number. Something like this:
|
||||
|
||||
`condition ? FirstLevelTrueValue : ConditionIfFalse ? SecondLevelTrueValue : SecondLevelFalseValue ` also works, and is interpreted as the following `if else if` statement:
|
||||
|
||||
```cpp
|
||||
if(condition)
|
||||
FirstLevelTrueValue;
|
||||
else if(ConditionIfFalse)
|
||||
SecondLevelTrueValue;
|
||||
else SecondLevelFalseValue;
|
||||
```
|
||||
Similarly, nested `if` statements can also be made using ternary operators.
|
||||
|
||||
|
||||
_Camper , You now know what tokens are. The next article will be about <need-to-put-topic> CONGRATULATIONS_
|
||||
|
||||
**Good Luck to all of you**
|
||||
|
||||
**Happy Coding ! :)**
|
||||
|
||||
**Feel free to ask any queries on FreeCodeCamp's GitHub page or <a href='https://forum.freecodecamp.org/' target='_blank' rel='nofollow'>FreeCodeCamp's Forum .</a>**
|
||||
|
@ -0,0 +1,225 @@
|
||||
---
|
||||
title: Tokens Part 1
|
||||
---
|
||||
|
||||
### What are tokens ?
|
||||
|
||||
Tokens are the smallest units of a program which are important to the compiler. There are different kinds of tokens:
|
||||
- Keywords
|
||||
- Operators
|
||||
- Punctuators
|
||||
- Literals
|
||||
- Identifiers
|
||||
|
||||
* **Combination of tokens form an expression**
|
||||
|
||||
### What are Variables ?
|
||||
|
||||
* Textbook definition : Variables are named memory locations whoose data can be altered.
|
||||
|
||||
* But I would like you to think of a variable to be something like a box, something like this :
|
||||

|
||||
|
||||
So, for example :
|
||||
I'm shifting to a new place and I need to arrange my stuff in boxes . Thus there come 2 things to my mind **What kind of stuff will be stored in the box, so that the size off the box is known (the data type)** and **How do I identify the box ?(Naming the variable)**
|
||||
Hence , we know that a variable in C++ needs a *name* and a *data type* and that the value stored in them can be changed.
|
||||
|
||||
### Data Types in C++ :
|
||||
When declaring variables in c++ they must have a name to which you will reffer later on, a value (constant or not) and a type.
|
||||
The type will tell the compiler the values that the variable can use, the possible operations and will save a certain space in memmory.
|
||||
In c++ there are two types of data:
|
||||
* Simple type
|
||||
* Struct type
|
||||
|
||||
### Simple data types
|
||||
|
||||
* Boolean -- bool
|
||||
Works like a switch, can be on or off.
|
||||
* Character -- char
|
||||
Stores a single character.
|
||||
* Integer -- int
|
||||
Stores an [integer](https://en.wikipedia.org/wiki/Integer).
|
||||
* Floating point -- float
|
||||
They can use decimals.
|
||||
* Double floating point -- double
|
||||
Double precision of the float type.
|
||||
|
||||
Here you can see some examples:
|
||||
```cpp
|
||||
bool GameRunning = true;
|
||||
char a;
|
||||
int x = 2;
|
||||
```
|
||||
#### These types can also be modified with modifiers such as:
|
||||
signed
|
||||
unsigned
|
||||
short
|
||||
long
|
||||
|
||||
### Struct data type
|
||||
|
||||
#### Identifiers.
|
||||
|
||||
- Identifiers are the names given to a variable or a class or a function or any user defined function.
|
||||
|
||||
## Rules for naming a variable : ##
|
||||
|
||||
- Start naming with a letter from A-Z or a-z .
|
||||
- Numbers can follow thee first letter but we cannot start naming with numbers.
|
||||
- NO use of spaces or special characters are allowed, instead, use an UNDERSCORE _ .
|
||||
|
||||
#### Declaring a variabe :
|
||||
|
||||
The syntax is as follows
|
||||
<*data type*> <*variable name*>;
|
||||
or
|
||||
<*data type*> <*variable name*> = <*value*>; if we also want to initialize the variable.
|
||||
|
||||
|
||||
For example :
|
||||
```cpp
|
||||
int a ; //declaring a variable named 'a' of type integer.
|
||||
a=4; //initializing a variable
|
||||
int b = 5 ; //declaring and initializing a variable 'b' of type integer.
|
||||
```
|
||||
|
||||
**Examples of declaring a variable:**
|
||||
```cpp
|
||||
int a9;
|
||||
char A;
|
||||
double area_circle;
|
||||
long l;
|
||||
```
|
||||
|
||||
**Wrong ways to declare variables**-
|
||||
```cpp
|
||||
int 9a;
|
||||
char -a;
|
||||
double area of circle;
|
||||
long l!!;
|
||||
```
|
||||
|
||||
- Variable names cannot start with a number
|
||||
- Special characters are not allowed
|
||||
- Spaces are not allowed
|
||||
|
||||
|
||||
You can imagine different boxes of different sizes and storing different things as different variables.
|
||||
|
||||
**NOTES :**
|
||||
1. **The C++ compiler ignores whitespaces and they are generally used for beautification of the code so that it is eassy for any programmer to debug or understand the code.**
|
||||
2. **If a variable is not initialized , it contains a garbage value. Let me give an example:**
|
||||
|
||||
### Scope of Variables
|
||||
All the variables have their area of functioning, and out of that boundary they don't hold their value, this boundary is called scope of the variable. For most of the cases its between the curly braces,in which variable is declared that a variable exists, not outside it. We will study the storage classes later, but as of now, we can broadly divide variables into two main types,
|
||||
|
||||
*Global Variables.
|
||||
|
||||
*Local variables.
|
||||
|
||||
#### Global variables
|
||||
|
||||
Global variables are those, which ar once declared and can be used throughout the lifetime of the program by any class or any function. They must be declared outside the main() function. If only declared, they can be assigned different values at different time in program lifetime. But even if they are declared and initialized at the same time outside the main() function, then also they can be assigned any value at any point in the program.
|
||||
|
||||
Example : Only declared, not initialized.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int x; // Global variable declared
|
||||
int main()
|
||||
{
|
||||
x=10; // Initialized once
|
||||
cout <<"first value of x = "<< x;
|
||||
x=20; // Initialized again
|
||||
cout <<"Initialized again with value = "<< x;
|
||||
}
|
||||
```
|
||||
|
||||
#### Local Variables
|
||||
Local variables are the variables which exist only between the curly braces, in which its declared. Outside that they are unavailable and leads to compile time error.
|
||||
|
||||
Example :
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
int i=10;
|
||||
if(i<20) // if condition scope starts
|
||||
{
|
||||
int n=100; // Local variable declared and initialized
|
||||
} // if condition scope ends
|
||||
cout << n; // Compile time error, n not available here
|
||||
}
|
||||
```
|
||||
|
||||
### Constant Variables
|
||||
Constant variable are the variables which cannot be changed. For example, if you needed "pi" in your code, you would not want to change it after initialization.
|
||||
|
||||
Example :
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
const double PI = 3.14159253;
|
||||
int main()
|
||||
{
|
||||
//Calculating the area of a circle, using user provided radius
|
||||
double radius;
|
||||
//input and output explained in other guide
|
||||
cin>>radius;
|
||||
//pi*r^2
|
||||
double area = PI*radius*radius;
|
||||
cout<<area<<endl;
|
||||
}
|
||||
```
|
||||
|
||||
### Garbage Values in a Variable
|
||||
If a variable is not initialized , it contains a garbage value. For example:
|
||||
|
||||
So in terms of boxes, you can imagine this as -
|
||||
|
||||

|
||||
|
||||
```cpp
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
int a ;
|
||||
cout<<"Garbage value in a : "<<a<<endl; //declaring the variable named 'a' of type integer
|
||||
a=5; //initializing variable.
|
||||
cout<<"New value in a "<<a<<endl;
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### The output is :
|
||||
|
||||
```
|
||||
Garbage value in a : 0
|
||||
New value in a : 5
|
||||
```
|
||||
|
||||
As you can see, there is already a value stored in 'a' before we give it a value(here , it is 0 ). This should remain in the mind of every programmer so that when the variables are used they do not create a logical error and print garbage values.
|
||||
|
||||
<a href='https://repl.it/Mg7j' target='_blank' rel='nofollow'>Try the code yourself ! :) </a>
|
||||
|
||||
|
||||
#### Keywords :
|
||||
|
||||
*Keywords are reserved words that convey a special meaning to the compiler. They **CANNOT** be used for naming in c++.*
|
||||
Examples of Keywords :
|
||||
inline , operator, private int, double ,void , char, template ,using , virtual , break , case , switch , friend, etc.
|
||||
|
||||
**Each of these keywords is used for a special function in C++.**
|
||||
|
||||
_Tokens part 1 is over. See you campers at [Part 2](https://guide.freecodecamp.org/cplusplus/tokens-part-II) of Tokens :)_
|
||||
|
||||
**Good Luck to all of you**
|
||||
|
||||
**Happy Coding ! :)**
|
||||
|
||||
**Feel free to ask any queries on FreeCodeCamp's GitHub page or [FreeCodeCamp's Forum .](https://forum.freecodecamp.org/)**
|
@ -0,0 +1,125 @@
|
||||
---
|
||||
title: Variables
|
||||
---
|
||||
|
||||
Let's discuss something know as variables. Variables are like a bucket. You can put something in it and then change it
|
||||
afterwards when needed.
|
||||
In C++, there are many types of variables like Integers, Strings, Booleans and many other.
|
||||
Let's look at a simple program using integer variables. Integers store whole numbers that are positive, negative or zero. Whole numbers are not fractional numbers for example 1/2, 1/4, and 1/5. Lets look at a simple program which uses an integer
|
||||
variable.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std ;
|
||||
int main()
|
||||
{
|
||||
int a; // Declare an integer variable a
|
||||
a = 5; // Assign value of 5 to variable a
|
||||
cout << a; // Display the value of variable a which contains 5
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
When you execute this program, you will see 5 displayed on the screen
|
||||
|
||||
* Note that in the above program // is placed after the lines. The symbol "//" is for commenting our code. Code after the symbol
|
||||
"//" is not execueted in the line where its placed.
|
||||
|
||||
* On line 5 n simple integer variable is declared.
|
||||
* On line 6 the value 5 is assigned to the variable a. Now whenever we use the variable a in our program its value will be 5
|
||||
unless we change it.
|
||||
* On line 7 we display the value of variable a and 5 is printed on the screen.
|
||||
### Scope of Variables
|
||||
All the variables have their area of functioning, and out of that boundary they don't hold their value, this boundary is called scope of the variable. For most of the cases its between the curly braces,in which variable is declared that a variable exists, not outside it. We will study the storage classes later, but as of now, we can broadly divide variables into two main types,
|
||||
|
||||
*Global Variables.
|
||||
|
||||
*Local variables.
|
||||
|
||||
#### Global variables
|
||||
|
||||
Global variables are those, which ar once declared and can be used throughout the lifetime of the program by any class or any function. They must be declared outside the main() function. If only declared, they can be assigned different values at different time in program lifetime. But even if they are declared and initialized at the same time outside the main() function, then also they can be assigned any value at any point in the program.
|
||||
|
||||
Example : Only declared, not initialized.
|
||||
|
||||
```cpp
|
||||
include <iostream>
|
||||
using namespace std;
|
||||
int x; // Global variable declared
|
||||
int main()
|
||||
{
|
||||
x=10; // Initialized once
|
||||
cout <<"first value of x = "<< x;
|
||||
x=20; // Initialized again
|
||||
cout <<"Initialized again with value = "<< x;`
|
||||
}
|
||||
```
|
||||
|
||||
#### Local Variables
|
||||
Local variables are the variables which exist only between the curly braces, in which its declared. Outside that they are unavailable and leads to compile time error.
|
||||
|
||||
Example :
|
||||
|
||||
```cpp
|
||||
include <iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
int i=10;
|
||||
if(i<20) // if condition scope starts
|
||||
{
|
||||
int n=100; // Local variable declared and initialized
|
||||
} // if condition scope ends
|
||||
cout << n; // Compile time error, n not available here
|
||||
}
|
||||
```
|
||||
|
||||
Now let's read about a new type of variable-
|
||||
#### Static variable
|
||||
|
||||
Static variables : When a variable is declared as static, space for it gets allocated for the lifetime of the program. Even if the function is called multiple times, space for the static variable is allocated only once and the value of variable in the previous call gets carried through the next function call. This is useful for implementing coroutines in C/C++ or any other application where previous state of function needs to be stored.
|
||||
In layman terms , it means that a normal variable when goes out of scope looses it's identity (value) , but a static variable has a global scope and retain it's value till end of program , but unlike global variable it is not necessary to declare it at start of program.
|
||||
|
||||
#### EXTRA-
|
||||
Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime.
|
||||
|
||||
|
||||
#### CODE-
|
||||
|
||||
```
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
void howstaticworks()
|
||||
{
|
||||
static int count = 0; // static variable
|
||||
cout << count << " ";
|
||||
|
||||
/* value is updated and
|
||||
will be carried to next
|
||||
function calls*/
|
||||
count++;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
for (int i=0; i<5; i++)
|
||||
howstaticworks();
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
#### Try yourself
|
||||
just copy the code and paste it in link given.
|
||||
Run on IDE- https://ideone.com/
|
||||
|
||||
|
||||
Output:
|
||||
0 1 2 3 4
|
||||
|
||||
You can see in the above program that the variable count is declared as static. So, its value is carried through the function calls. The variable count is not getting initialized for every time the function is called.
|
||||
|
||||
Let's give the same code a try by removing "static" keyword and guess the output and compare it with one on IDE.
|
||||
The static is now converted into normal variable
|
||||
|
||||
|
173
client/src/pages/guide/english/cplusplus/vector/index.md
Normal file
173
client/src/pages/guide/english/cplusplus/vector/index.md
Normal file
@ -0,0 +1,173 @@
|
||||
---
|
||||
title: Vectors
|
||||
---
|
||||
|
||||
## Vectors
|
||||
|
||||
The C++ `vector` is one of the most used containers in C++. A container is a data structure that stores a collection of objects that can vary from being ordered(like `vector`!) to unordered(like `set`). All C++ containers have a different set of functions that allow you to access an object(s) in that collection, modify and loop over the elements in that data structure.
|
||||
|
||||
|
||||
`std::vector` is part of the C++ standard library (hence the prefix `std::`) and allows you to store contiguous data of the same data type. NOTE: **All objects within a vector must be of the same data type**
|
||||
|
||||
The data type you store within a vector goes within angle brackets next to the vector keyword. For example, if you would like to store a collection of strings the vector would be `std::vector<std::string> vector_name`
|
||||
|
||||
*NOTE*: You must include the vector library whenever using vectors!
|
||||
|
||||
`#include <vector>`
|
||||
|
||||
### Vector Construction
|
||||
There are many convinent ways to construct a vector.
|
||||
|
||||
Using an intializer list - where objects are listed inside a set of braces: `{ }`
|
||||
```cpp
|
||||
std::vector<int> a{1, 2, 3, 4, 5}; // a is a vector of 5 ints: 1, 2, 3, 4 and 5
|
||||
std::vector<std::string> b{"hello", "world"}; // b is a vector of 2 strings: "hello" and "world"
|
||||
std::vector<bool> v; // v is an empty vector
|
||||
```
|
||||
|
||||
Constructing it from another vector (this is known as a copy construction)
|
||||
```cpp
|
||||
std::vector<double> a{1.0, 2.0, 3.0};
|
||||
std::vector<double> b(a); // b is a vector of 3 doubles: 1.0, 2.0 and 3.0
|
||||
```
|
||||
|
||||
Initializing it with the same element:
|
||||
```cpp
|
||||
std::vector<int> a(100, -1); // a is a vector of 100 elements all set to -1
|
||||
```
|
||||
|
||||
### Vector Iterators
|
||||
|
||||
Iterators can be thought of as pointers specifically used for navigating containers
|
||||
(such as vectors). The most important iterators are `begin()` and `end()`.
|
||||
`begin()` returns a pointer to the first item in a vector whereas `end()` points
|
||||
to one position after the last item in a vector. As such looping through a
|
||||
vector can be done as :
|
||||
|
||||
```cpp
|
||||
std::vector<int> vec{1, 2, 3};
|
||||
|
||||
for(auto vec_it = vec.begin(); vec_it != vec.end(); it++){
|
||||
// since vec_it is a pointer and points to the memory address of the item
|
||||
// inside the vector, vec_it must be dereferenced using '*'
|
||||
std::cout << *it << '\n';
|
||||
}
|
||||
/* Output
|
||||
1
|
||||
2
|
||||
3
|
||||
*/
|
||||
```
|
||||
|
||||
### Modifying a Vector
|
||||
|
||||
Pushing items to a vector:
|
||||
```cpp
|
||||
std::vector<int> vec; // constructs an empty vector
|
||||
|
||||
for (int i = 0; i < 10; i = i + 2){
|
||||
vec.push_back(i);
|
||||
}
|
||||
// vec now holds [0, 2, 4, 6, 8]
|
||||
```
|
||||
|
||||
Inserting an item in a particular position is slightly different. The C++ vector insert
|
||||
function works on iterators. It will insert the given item one position before the given
|
||||
iterator.
|
||||
|
||||
```cpp
|
||||
std::vector<unsigned int> vec{3, 400, 12, 45};
|
||||
|
||||
auto iter = vec.begin() + 2; // iter now points to '12'
|
||||
vec.insert(iter, 38); // inserts '38' before '12'
|
||||
|
||||
// vec: [3, 400, 38, 12, 45]
|
||||
```
|
||||
|
||||
### Element Access
|
||||
The standard library provides different functions for accessing particular elements in your vector.
|
||||
|
||||
```cpp
|
||||
std::vector<std::string> a{"test", "element", "access"};
|
||||
|
||||
std::string first_item = a.front(); // gets the first item of the vector ("test")
|
||||
std::string last_item = a.back(); // gets the last item in the vector ("access")
|
||||
|
||||
// To get an element at a specific index (remember: vector indices start at 0)
|
||||
std::string second_item = a.at(2); // gets "element"
|
||||
// OR
|
||||
std::string second_item = a[2]; // gets "element"
|
||||
```
|
||||
|
||||
### Looping over elements in a `vector`
|
||||
|
||||
Looping over elements in a C++ `std::vector` is pretty different from looping over elements in a vector in JavaScript or Ruby. Due to C++ being a thin abstraction of C, you can only loop over elements using these nifty little variables called iterators to access each element.
|
||||
Iterators often come in the form of pointers which are variables that store the memory address of another variable. You can learn more about pointers [here](https://www.tutorialspoint.com/cplusplus/cpp_pointers.htm).
|
||||
However, because iterators act as pointers (or vice-versa), in order to see what they point to, you need to dereference it into a variable of the appropirate type.
|
||||
How do we do this?
|
||||
HERE. WE. GO!
|
||||
```cpp
|
||||
std::vector<std::string> a{"test", "element", "access"};
|
||||
for(auto it = v.begin(); it != v.end(); it++) { //notice use of auto keyword
|
||||
cout<<*it<<endl; //Will print out string that the iterator is currently ppointing to
|
||||
}
|
||||
```
|
||||
From here, you can do all sorts of cool stuff, like manipulating the vector or mess around with it's order as you please!
|
||||
|
||||
### Some useful member functions
|
||||
The standard template library (STL) also provide different *methods* for you:
|
||||
|
||||
```cpp
|
||||
std::vector.size(); // returns the size of the vector (the number of positions in the vector)
|
||||
std::vector.begin(); // returns an iterator which is a pointer to the beginning of the vector
|
||||
std::vector.end(); // returns an iterator which is a pointer to the end of the vector
|
||||
std::vector.empty(); // returns true if the vector is empty, otherwise returns false.
|
||||
std::vector.front(); // returns the first element of the vector.
|
||||
std::vector.back(); // returns the last element of the vector.
|
||||
std::vector.push_back(n); // inserts the element "n" to the end of the vector.
|
||||
std::vector.pop_back(n); // removes the last element of the vector
|
||||
```
|
||||
|
||||
### Vector Iterator
|
||||
The iterators provide another method for accessing elements in your vector.
|
||||
|
||||
Iterator declaration.
|
||||
```cpp
|
||||
std::vector<int> v;
|
||||
//Iterator delcaration for the above vector will correspond to
|
||||
std::vector<int>::iterator it;
|
||||
```
|
||||
Using the iterator to print elements of the vector using for loop
|
||||
```cpp
|
||||
for(it=v.begin(); it!=v.end(); ++it)
|
||||
//std::vector::begin and std::vector::end return iterator pointing to first and last element of the vector respectively.
|
||||
cout<<*it;
|
||||
```
|
||||
|
||||
### Iterating Through a Vector
|
||||
There are different ways to iterate through a vector and access its contents. The following forms are equivalent, the first one involves using a range-based expression (since C++11), the second one uses iterators, and the last one is a index-based iteration
|
||||
|
||||
``` cpp
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
// First declare the vector
|
||||
std::vector<int> myVector{1, 2, 3, 4, 5}; // a is a vector of 5 ints: 1, 2, 3, 4 and 5
|
||||
|
||||
// Using a range based loop (since C++11)
|
||||
for(int element : myVector ){ // Reads like "for every element in myVector"
|
||||
std::cout << "The element is " << element << std::endl;
|
||||
}
|
||||
|
||||
// Using an iterator
|
||||
std::vector<int>::iterator it; // Declare the iterator
|
||||
for(it = myVector.begin(); it != myVector.end(); ++it){
|
||||
std::cout << "The element is " << *it << std::endl; // Dereference the iterator to access its data
|
||||
}
|
||||
|
||||
// Using indices
|
||||
for(std::vector<int>::size_type i = 0; i != myVector.size(); i++){
|
||||
std::cout << "The element is " << myVector[i] << std::endl; // Dereference the iterator to access its data
|
||||
}
|
||||
|
||||
```
|
51
client/src/pages/guide/english/cplusplus/while-loop/index.md
Normal file
51
client/src/pages/guide/english/cplusplus/while-loop/index.md
Normal file
@ -0,0 +1,51 @@
|
||||
---
|
||||
title: While-loop
|
||||
---
|
||||
|
||||
A while loop statement repeatedly executes a target statement as long as a given condition is true.
|
||||
|
||||
Syntax:
|
||||
while(condition) {
|
||||
statement(s);
|
||||
}
|
||||
|
||||
A key point of the while loop is that the loop might not ever run.
|
||||
When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
|
||||
|
||||
|
||||
Example:
|
||||
|
||||
```C++
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main () {
|
||||
// Local variable declaration:
|
||||
int a = 10;
|
||||
|
||||
// while loop execution
|
||||
while( a < 20 ) {
|
||||
cout << "value of a: " << a << endl;
|
||||
a++;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
value of a: 10
|
||||
value of a: 11
|
||||
value of a: 12
|
||||
value of a: 13
|
||||
value of a: 14
|
||||
value of a: 15
|
||||
value of a: 16
|
||||
value of a: 17
|
||||
value of a: 18
|
||||
value of a: 19
|
||||
|
||||
|
||||
###Sources
|
||||
www.tutorialspoint.com
|
Reference in New Issue
Block a user