fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,48 @@
Introduction of sets in C++ STL library
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 added to the set, though it is possible to remove and add the modified value of that element. They are implemented using red-black tree.
Benefits of using sets
1. It stores only unique values.
2. Value of the element identifies itself. The value of an element is also the key used to identify it.
3. Provides a fast lookup (O(log n)) using keys i.e. element itself.
4. There are many inbuilt functions in class defining sets that ease the programming.
Example:
'''c++
#include<bits/stdc++.h>
using namespace std;
int main()
{
set <int> s;
s.insert(2); //insert element 2 in set s
s.insert(3);
s.insert(5);
s.insert(2); //inserting same element 2
s.insert(6);
for(auto i:s)
cout<<i<<" ";
cout<<s.size()<<endl; //gives the size of set
s.erase(5); // erasing element 5 from set s
return 0;
}
'''
Creating a set object
'''c++
set <int> s;
'''
Insertion
'''c++
s.insert(value_to_be_inserted);
'''
Accessing set elements
'''c++
set <int>::iterator it;
for(it=s.begin(); it!=s.end(); ++it)
cout<<*it;
'''

View File

@ -0,0 +1,42 @@
---
title: C++ Arrays
---
## What are Arrays?
An array is a series of elements of the same data type which are stored in contiguous memory locations and can be referenced individually.
For example, an array containing 5 integer values called numbers is declared like so:
```C++
int numbers [5];
```
Initializiation:
```C++
//Initialization with entries:
int numbers [5] = {1, 2, 3, 4, 5};
//Initialization with no values:
int numbers [5] = {};
//Initialization with declaration:
int numbers [] = {1, 2, 3, 4, 5};
//Note that here the number of values defines the size of the array.
//In the examples above, the size was fixed beforehand
```
## Types Of Arrays
There are two types of array based on way, we declare it.
**1**. Static array:
Those arrays whose size is defined before compile time like in the examples above, are called static arrays. In these arrays we can't change their size, once they are declared.
**2**. Dynamic array:
Dynamic arrays are those arrays, whose size is not known at compile time and we can define their size at run time. These arrays are created by using **new** keyword and when done with that array we can delete that array by using the **delete** keyword.
### Access:
Elements from an array can be accessed via reference of their position in the array. (Start counting from 0).
Example:
```C++
x = numbers[0]; // = 1. [0] == first position
numbers[2] = 55; // Sets the third position (3) to the new number 55
//numbers[] is now: {1, 2, 55, 4, 5}
```

View File

@ -0,0 +1,82 @@
---
title: Casting
---
## Casting
A cast is a special operator that forces one data type to be converted into another
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;
}
```

View File

@ -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.
![img](https://imgs.xkcd.com/comics/goto.png)
## 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
```

View File

@ -0,0 +1,93 @@
---
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.
![img](https://i.imgur.com/FwZuFGy.png)
#### 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.
NOTE:
to compile and execute your code directly, run
`g++ -o helloWorld helloWorld.cpp; ./helloWorld`
so when you need to compile and run your code multiple times,
up arrow-enter
### Adding Flags
You can also add flags to the compiler to your custom and favor. For example:
`g++ -O2 helloWorld.cpp -o helloWorld`
Some common flags is :
1. -O2 : Optimize your code, so it may run faster
2. -std=c++11 : use c++11 instead of c++98 which is defaulted.
3. -Wall: prompt some warning about some common mistakes which can bug your program.
4. -Wextra: prompt some extra warning.
____________
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.

View File

@ -0,0 +1,61 @@
---
title: Conditional Operator
---
## Conditional Operator
Conditional operator is a ternary operator, that is it needs 3 operands.
It returns one of two values depending on the result of an expression
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;
}
```
The above code however can be used to check more than just two conditions in the following way/syntax:
```cpp
if(condition 1) /* Checks first condition, skips else-if and else
{ entirely if condition 1 checks out */
expression-1;
}
else if(condition 2) /*Checks condition 2, only and only if condition 1
{ is false, if condition 2 is true the comiler will
expression-2; skip the 'else' part and move on */
}
else /*Once if and else-if conditions don't satisfy the
{ compiler will run the expression in else{..}
expression-3; because it does not have a condition to check,
} part of code can also be skipped if not necessary*/
```
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/)**

View File

@ -0,0 +1,41 @@
---
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);
```
Note: Remember to use a semicolon ';' at the end of the condition.
## Details about do-while loop
The do-while loop is used whenever you are sure that a particular process(within the loop) has to be performed at least once. It has many advantages like not initialising the checking variable(eg- char addmore='Y') etc. The semicolon at the end of while is a must.
Do something first and then test if we have to continue. The result is that the do block runs at least 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;
}
```

View File

@ -0,0 +1,35 @@
---
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.
* `new` is preferred over `malloc()` in C++ because new works for objects as well which is the main building block for OOPs.
### 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`;
### Memory Leaks
Leaks are caused when you fail to deallocate dynamic memory you allocated via `New` operator at the end of your program. If you do not deallocate it with the Delete operator, your computer will keep creating new memory in the heap every time the program runs. This causes your computer to slow down because memory is not deleted and your available memory decreases. Many computer programs cause memory leaks over time. However, when you reboot the machine, it will resolve the issue. This is because rebooting releases those spaces in heap memory that were causing memory leaks.

View File

@ -0,0 +1,86 @@
---
title: Eraseremove 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 eraseremove 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 eraseremove 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 eraseremove 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 eraseremove 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
"Eraseremove 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.

View File

@ -0,0 +1,42 @@
---
title: Error Handling
---
# C++ Exception Handling
An exception is a problem that arises during the execution of a program.Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: #try, #catch, and #throw.
* #throw A program throws an exception when a problem shows up. This is done using a throw keyword.
* #catch A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
* #try A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
```CPP
#include <iostream>
using namespace std;
int main()
{
int x = -1;
// Some code
cout << "Before try \n";
try {
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
}
}
catch (int x ) {
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
return 0;
}
```
# Before you go on...
## A review
* Grouping of Error Types.
* Separation of Error Handling code from Normal Code.
* Functions/Methods can handle any exceptions they choose.

View File

@ -0,0 +1,78 @@
---
title: File handling
---
## File Handling
Uptill now we were using `cin` and `cout` for reading and writing data, but what if we wanna write a data into a file or pick up a data from a file? Here our `cin` and `cout` doesnot work so we use a standard c++ library called fstream.
## Data types and description
* #ofstream - This data type represents the output file stream and is used to create files and to write information to files.
* #iftream - This data type represents the output file stream and is used to create files and to write information to files.
* #fstream - This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
## To write in a file
```cpp
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
```
```cpp
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
```
* the getline() function is used to read a line from the opened file
* the ignore() function s used to ignore the extra characters left by previous read statement
## Sources
1.Tutorialspoint

View File

@ -0,0 +1,133 @@
---
title: For Loop
---
A For Loop is a repetitive statement that is used to check for some condition and then based upon the condition a block of code is executed repeatedly until the specified condition is satisfied.
The for loop is distinguished from other looping statements through an explicit loop counter or loop variable which allows the body of the loop to know the exact sequencing of each iteration.
Hence 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);
}
```
It is allowed to place the increment inside the for loop like in a while loop. Meaning a syntax like this can also work.
```
for ( init; condition;) {
statement(s);
increment;
}
```
It is also allowed to ignore the init variables. For example :
```
int a = 1;
for (; a <= 10 ;)
{
cout << a << '\n';
a++;
}
```
Though you can't ignore the condition, because empty condition is defaulted as false, so the for-loop won't run at all.
### init
This step allows you to declare and initialize any loop control variables. This step is performed first and only once.
Note that the variables declared in init can only be used inside the brackets of the for loop.
### condition
Next the condition is evaluated. If it holds true, the body of the loop is executed. If it holds false, the body of the loop does not execute and flow of control jumps to the next iteration(repetition of a process).
### update
The update statement is used to alter the loop variable by using simple operations like addition,subtraction,multiplication or division.
The update statement executes after the execution of the body of the loop.
## IMPLEMENTATION:
```C++
#include <iostream>
using namespace std; // Here we use the scope resolution operator to define the scope of the standar functions as std::
int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) { // The loop will run till the value of a is less than 20
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
##Single lined loop
The body of the for loop need not be enclosed in braces if the loop iterates over only one satatement.
##Example
```c++
#include<iostream.h>
using namespace std;
int main () {
// Single line for loop
for( int a = 10; a < 20; a = a + 1 )
cout << "value of a: " << a << endl;
return 0;
}```
This would generate the same output as the previous program.
i.e
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
```
## Explanation
Here's the initialization condition is first set to a=10. The loop first checks for this condition. It then checks for the condition expression i.e a<20 which holds true as 10<20(for the first case). Now the body of the loop is executed and we get the output "Value of a: 10". Then the update expression is executed which adds the number 1 to 'a' and the value of 'a' gets updated to 11 and the same steps are followed (as above) until the value of v reaches less than 20 i.e 19.
# Range-based for-loop
C++ also has what we call range-based for loops which iterates through all the elements of a container(e.g. array).
## Syntax
```
for ( element: container )
statement(s);
}
```
```
int[5] array = { 1, 2, 3, 4, 5 }
for ( int i: array )
cout << i << endl;
}
Output:
1
2
3
4
5
```

View File

@ -0,0 +1,66 @@
---
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.
One must always make sure, before using a function in the program, the function is defined.
Even if function definition is after the main, just the function name and its arguments have to be declared above, so that compiler knows what is being talked about.
## 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`, but the [return type of main() must always be int](https://stackoverflow.com/a/4207223/).
### 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;
}
## calling a function:
int res;
res=max(5,10);
// if the function returns a value, assign it to that variable, else just call it like function(arg1,arg2);
```
## Why are functions important?
Functions support modularity (breaking down of work into smaller pieces called modules), which is an essential feature of object-oriented programming (OOP) which primarily separates C++ from C.
Having specific functions to perform specific tasks removes confusion and shortens the length of the main function.
The function also performs reusability of code. So the next time you have to calculate the maximum of two different numbers again and again in the same program, you do not need to copy and paste your code. You just have to call the function and it does rest of the work.
## More Information
* [TutorialsPoint](https://www.tutorialspoint.com/cplusplus/cpp_functions.htm)

View File

@ -0,0 +1,26 @@
---
title: goto as a powerful utility
---
# Intro to the use of goto and labels
goto is one of the most powerful yet highly underrated piece of logic in c++. Crazy amount of optimization can be achieved using goto, provided it is used properly.
It does that which it is named as. It goes to the mentioned occurence of the next label,wherever may it be.
# Terminology
goto - The keyword used to go to the particular label.
label - this can be named anything.
# syntax
goto <label>;
(without the <> );
//This takes the exe to the next appearance of label.
goto is something that transcends all loops.To be clearer on this point, here is an example.
https://code.sololearn.com/cI4qqQA8W2q3
However, care must be taken to use goto very carefully, especially in early days of coding as it can lead to crazy issues, if not understood well enough.

View File

@ -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/)**.

View 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:
![Img](http://static1.businessinsider.com/image/59deb30392406c21008b6148-1200/for-bonus-points-heres-the-chart-showing-these-languages-relative-popularity.jpg)
_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` and `std::endl` instead of `endl` 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 5, 6 & 7
```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:
![Img](https://i.imgur.com/d1liGwI.png)
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/)**
[Try it yourself ! :)](https://repl.it/L4k3)
**You may need some software to write and execute C++ code. I recommend using CodeBlocks. There's a download link below :**
Download Link : [Download Here](http://www.codeblocks.org/downloads/26)
* 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/)

View File

@ -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 dont 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.

View File

@ -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 functions 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 doesnt exist in function body.
* If a function contains switch or goto statement.
### Inline functions provide following advantages:
* Function call overhead doesnt 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
```

View File

@ -0,0 +1,129 @@
---
title: Input and Output
---
## Input and Output with Streams
To print things to the console, or read from it, you use `cout` and `cin`, which are so-called `streams`. This metaphor is used because you use streams like you would use a sink, or a tap: you either flush data into a sink (`cout`), or get data out of a tap (`cin`).
### Output with cout
The "Hello World" program uses `cout` to print "Hello World!" to the console:
```C++
#include<iostream>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
}
```
The first two lines at the top are necessary for you to use `cout` and other streams. `#include<iostream>` makes the stream objects abailable, and `using namespace std;` lets you type `cout` directly instead of having to type `std::cout`, that is, having to specify that we want to use `cout` from the `std` namespace.
`cout` stands for "Console Output", and is a so-called _output stream_ that represents the console. When you want to print something to the console, you can put it into `cout`; imagine it as a hole that leads to the terminal. To put things into this hole, one at a time, you use the `<<` operator, a.k.a. the _insertion operator_<sup>1</sup>. The operator can be chained, that is, you can put several things in one after the other. The following will print "The cake is a lie.":
`cout << "The cake " << "is " << "a " << "lie." << endl;`
`endl` stands for "End Line" and is another item that comes from `<iostream>`. When you put `endl` into `cout`, it will print a newline character ("\n") to the console, and also _flush_ `cout`, which means that it will force `cout` to print everything you have put into it *right now*. If you don't put `endl` into `cout`, `cout` might keep the data you've put into it but wait for more data before actually printing it all. This is called _buffering_ and is very good for performance, but if you've already given it everything it's supposed to print, you want `cout` to print it immediatelly. Therefore it is very good practice to end with `endl` in places where it makes sense.
Almost everything can be put into a stream: strings, numbers, variables, expressions, etc. Here area some examples of valid stream insertions:
```C++
// Notice we can use the number 42 and not the string "42".
cout << "The meaning of life is " << 42 << endl;` // Output: The meaning of life is 42
```
```C++
string name = "Tim";
cout << "Except for you, " << name << endl;`// Output: Except for you, Tim
```
```C++
string name = "Tim";
cout << name;
cout << " is a great guy!" << endl;`
// Output: Tim is a great guy!
```
```C++
int a = 3;
cout << a*2 + 18/a << endl;`// Output: 12
```
### A note about whitespace
C++ always puts *you* in control, and only does exactly the things you tell it to do. This can sometimes be surprising, as in the following example:
```C++
string name = "Sarah";
cout << "Good morning" << name << "how are you today? << endl;
```
You might expect it to print "Good morning Sarah how are you today?", but actually, the output would be "Good morningSarahhow are you today?". The reason for this bug is that you did not write spaces in the strings surrounding `name`, and so, since you didn't specify any spaces, `cout` didn't print any. The correct version would be: `cout << "Good morning " << name << " how are you today? << endl;`.
Line breaks don't happen by themselves, either. You might think this would print a recipe on four lines:
```C++
cout << "To make bread, you need:";
cout << "* One egg";
cout << "* One water";
cout << "* Two wheat";
```
but the output is actually all on one line: "To make bread, you need:* One egg* One water* Two wheat". This is because there are no newline characters at the end of the lines, so naturally, C++ assumes we don't want it to print newline characters.
You could fix this by adding `endl`s after every line, because as discussed earlier, `endl` inserts a newline character into the output stream. However, it also forces the buffer to be flushed, which loses us a little performance since we could have printed all the lines in one go. Therefore the best would be to add actual newline characters at the end of the lines, and only use `endl` at the end:
```C++
cout << "To make bread, you need:\n";
cout << "* One egg\n";
cout << "* One water\n";
cout << "* Two wheat" << endl;
```
If you're just printing a small recipe, the time you save is miniscule and not worth the hassle, but if you're printing millions of items, the difference could be very noticeable.
### Input with cin
To read from the console, you use the _input stream_ `cin` in the same way as you would `cout`, but instead of putting things into `cin`, you "take them out". The following program reads two numbers from the user and adds them together:
```C++
#include<iostream>
using namespace std;
int main()
{
int a, b; // Variables to hold the two numbers.
cout << "Please enter the first number:" << endl;
cin >> a;
cout << "Please enter the second number:" << endl;
cin >> b;
cout << "The sum of your numbers is: " << a + b << endl;
}
```
`cin` stands for "Console Input" and is an _input stream_ that represents input from the console. In the expression `cin >> a;`, data is read from `cin` and saved into the variable `a`, using the operator `>>`, the _extraction operator_<sup>2</sup>. The extraction operator reads exactly as much data as required to write into the variable we specify, and skips any whitespace, so if the user types "       6" that will just be read as the value `6`.
It's worth noting that `cin` will stop the whole program to wait for the user to type in their value. The program will not continue until the user has pressed enter, and there is some data to be written into the variable. If the user just presses enter without typing anything, `cin` will keep waiting for a value.
The extraction operator `<<` can be chained too. Here is the same program as last time, but written in a more concise manner:
```C++
#include<iostream>
using namespace std;
int main()
{
int a, b; // Variables to hold the two numbers.
cout << "Please enter two numbers:" << endl;
cin >> a >> b;
cout << "The sum of your numbers is: " << a + b << endl;
}
```
When chained, the extraction operator will first read data from `cin` to fill `a`, and then read data to fill `b`.
C's standard printf and scanf statements can also be used with c++ by importing '<cstdio>' header file.
## Sources
1. http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
2. http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

View File

@ -0,0 +1,33 @@
---
title: C++ Lists
---
# What is a STL List?
Lists in C++ are a powerful tool similar to its more well known cousin, C++ Vectors. While Vectors are a sequential container
where elements are indexed in a continuous chain, Lists are also a sequential container but they are organized differently.
List elements point to its next element so all elements are ordered in sequence but they don't use indexing.
How? You may ask. They do this not by indexing but using a special tool called iterators. Iterators are like special pointers
whose job is to maintain the order of the list elements kind of like the link between two train cars. Here is a nice visual
of how Lists are organized compared to Vectors and Arrays.
![img](https://imgur.com/SiU8uTe.png)
Traversal in a list is slow as compared to Vectors and Arrays, but once a position has been found, insertion and deletion are quick.
## How to declare a List
If you want to declare a List of Numbers you write:
'''std::list<int> Numbers;'''
## Functions used with List
size() : Returns the number of elements in the list
begin() : Returns an iterator pointing to the first element of the list
end() : Returns an iterator pointing to the theoretical last element which follows the last element
push_front(data) Adds a new element with value 'data' at the beginning of the list
push_back(data) Adds a new element with value 'data' at the end of the list
pop_front() Removes the first element of the list
pop_back() Removes the last element of the list
## How to use these Functions
Numbers.size();

View File

@ -0,0 +1,115 @@
---
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 run the loop until a condition finishes.
The difference between While and Do while is that Do while loop always executes atleast once.
The very use of Do while loop can be seen in the scenarios when the number of times that the loop will run depends upon the first iteration of the loop.
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;
}
```

View File

@ -0,0 +1,128 @@
---
title: Map
---
## Introduction of map
`map` is an associative container that store elements in key-value pair. Just like in `Java` we 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; `
## Get Size
Get size of map with size function
```
map<int, int > myMap;
myMap[100] = 3
count << "size of map is " << myMap.size() << '\n';
```
Output:
```
size of map is 1
```
## Insertion
Inserting data with insert member function.
```c++
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;`
If "sun" is already mapped before, this action will override the value mapped to key.
## Erase
Erasing data with erase function
```
map<int, int > myMap;
myMap[10] = 1000;
cout << "before erase, size of map is " << myMap.size() << '\n';
myMap.erase(10);
cout << "after erase, size of map is " << myMap.size() << '\n';
```
Output:
```
before erase, size of map is 1
after erase, size of map is 0
```
## Accessing map value
To access map values, simply call Map[key]. For example:
```
map<string, int > M;
M["abc"] = 1;
M["def"] = 2;
cout << "value of abc is " << M["abc"] << '\n';
cout << "value of def is " << M["def"] << '\n';
```
Output:
```
value of abc is 1
value of def is 2
```
## 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>

View File

@ -0,0 +1,68 @@
---
title: Object Oriented Programming using C++
---
## Object Oriented Programming using C++
Object oriented programming, OOP for short, aims to implement real world entities like inheritance, hiding and polymorphism 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 an object
}
```
Objects 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 (combining) 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 won't be affected as our 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 reusability. 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 on 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. 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.

View File

@ -0,0 +1,103 @@
---
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
```cpp
#include <iostream>
#include <string>
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(const string& s) {
cout << "Printing string: " << s << endl;
}
};
int main() {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print string
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 string: Hello C++
```
### Operator Overloading in C++
Most of the built in operators can also be overloaded in C++. This allows programmers to assign different implementation to operators depending on the arguments. These overloaded operators can work for user defined class.
```
#include<iostream>
using namespace std;
class Complex_Number{
private:
int real;
int imag;
public:
Complex_Number(int i = 0, int j =0)
{
real = i;
imag = j;
}
//Here the operator '+' is being overloaded
Complex_Number operator + (Complex_Number const &a)
{
Complex_Number x;
x.real = real + a.real;
x.imag = imag + a.imag;
return x;
}
void print()
{
cout<<real<<" + i"<<imag<<endl;
}
};
int main()
{
Complex_Number c1(3, 2), c2(1, 1);
//Here, the overloaded operator is called. The numbers get added according to the function defined
Complex_Number c3 = c1 + c2;
c3.print();
}
```
Output for the above program
```
4 + i3
```

View File

@ -0,0 +1,145 @@
---
title: Preprocessors
---
## Preprocessors in C / CPP
As the name suggests Preprocessors are programs that processes our source code before compilation. There are a number of steps involved between writing a program and executing a program in C / C++. Let us have a look at these steps before we actually start learning about Preprocessors.
![Img](https://i.imgur.com/Pb0aTkV.png)
You can see the intermediate steps in the above diagram. The source code written by programmers is stored in the file program.c. This file is then processed by preprocessors and an expanded source code file is generated named program. This expanded file is compiled by the compiler and an object code file is generated named program.obj . Finally the linker links this object code file to the object code of the library functions to generate the executable file program.exe .
Preprocessor programs provides preprocessors directives which tell the compiler to preprocess the source code before compiling. All of these preprocessor directive begins with a `#` (hash) symbol. This (#) symbol at the beginning of a statement in a C/C++ program indicates that it is a pre-processor directive. We can place these pre processor directives anywhere in our program. Examples of some preprocessor directives are: `#include` , `#define`, `#ifndef` etc.
### Types of Preprocessor directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
###Macros:
Macros are piece of code in a program which is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. The `#define` directive is used to define a macro.
```cpp
#include<iostream>
#define LIMIT 3
int main()
{
for(int i=0; i < LIMIT; i++)
{
std::cout<<i<<" " ;
}
return 0;
}
```
Output:
`0 1 2`
In the above program, when the compiler executes the word `LIMIT` it replaces it with 3. The word `LIMIT` in macro definition is called macro template and 3 is macro expansion.
There should not be semi-colon(;) at the end of macro definition. Macro definitions do not need a semi-colon to end.
###File Inclusion:
This type of preprocessor directive tells the compiler to include a file in the source code program. There are two types of files which can be included by the user in the program:
* ####Header File or Standard files:
These files contains definition of pre-defined functions like printf(), ...scanf() etc. These files must be included for working with these functions. ...Different function are declared in different header files. For example ...standard I/O funuctions are in iostream file whereas functions which ...perform string operations are in string file.
####Syntax:
`#include< file_name >`
where file_name is the name of file to be included. The `<` and `>` brackets tells the compiler to look for the file in standard directory.
* ####User defined files:
When a program becomes very large, it is good practice to divide it into smaller files and include whenever needed. These types of files are user defined files. These files can be included as:
...`#include"filename"`
###Conditional Compilation:
Conditional Compilation directives are type of directives which helps to compile a specific portion of the program or to skip compilation of some specific part of the program based on some conditions. This can be done with the help of two preprocessing commands `ifdef` and `endif`.
####Syntax:
```cpp
ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
endif
```
If the macro with name as macroname is defined then the block of statements will execute normally but if it is not defined, the compiler will simply skip this block of statements.
###Other directives:
Apart from the above directives there are two more directives which are not commonly used. These are:
1. #####`#undef` Directive:
The `#undef` directive is used to undefine an existing macro. This directive works as:
#####Syntax:
`#undef LIMIT`
Using this statement will undefine the existing macro LIMIT. After this statement every `#ifdef LIMIT` statement will evaluate to false.
2. #####`#pragma` Directive:
This directive is a special purpose directive and is used to turn on or off some features. This type of directives are compiler-specific i.e., they vary from compiler to compiler. Some of the `#pragma` directives are discussed below:
##### `#pragma startup` and `#pragma exit`:
These directives helps us to specify the functions that are needed to run before program startup( before the control passes to main()) and just before program exit (just before the control returns from main()).
```cpp
#include<stdio.h>
void func1();
void func2();
#pragma startup func1
#pragma exit func2
void func1()
{
printf("Inside func1() ");
}
void func2()
{
printf("Inside func2() ");
}
int main()
{
printf("Inside main() ");
return 0;
}
```
Output:
`Inside func1() Inside main() Inside func2() `
<br>
The above code will produce the output as given below when run on GCC compilers:
<br>
Output:
`Inside main()`
<br>
This happens because GCC does not supports #pragma startup or exit. However you can use the below code for a similar output on GCC compilers.
```cpp
#include<stdio.h>
void func1();
void func2();
void __attribute__((constructor)) func1();
void __attribute__((destructor)) func2();
void func1()
{
printf("Inside func1()\n");
}
void func2()
{
printf("Inside func2()\n");
}
int main()
{
printf("Inside main()\n");
return 0;
}
```
##### `#pragma warn` Directive:
This directive is used to hide the warning message which are displayed during compilation.
We can hide the warnings as shown below:
#####`#pragma warn -rvl`:
This directive hides those warning which are raised when a function which is supposed to return a value does not returns a value.
#####`#pragma warn -par`:
This directive hides those warning which are raised when a function does not uses the parameters passed to it.
#####`#pragma warn -rch`:
This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable.

View 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.
![alt text](https://github.com/mohammadaziz313/helloworld/blob/master/Fifo_queue.png "FIFO Queue Enqueue and Dequeue Example")
### 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)

View File

@ -0,0 +1,95 @@
---
title: Random Functions
---
* Random numbers are a convenient way to introduce randomisation into your program. For example, if you want to run any simulations, or play games, delete random indices of an array etc, then random numbers is the way to go.
* The header file to include for using random numbers in c++ is ` cstdlib`.
* *Pro tip:-* You can use `cpp #include<bits/stdc++.h> ` to include all functions from all header files.
Function:- rand()
- Returns a pseudo-random number(integer) from 0 to RAND_MAX. Does not take any arguments.
- RAND_MAX is the maximum permissible integer number. It is compiler depedent and usually is 2147483647.
Below is an example:-
```cpp
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
cout << rand() << endl;
cout << rand() << endl;
cout << rand() << endl;
return 0;
}
/*
Output:- (Note that the output is random and will differ from what is mentioned here)
1804289383
846930886
1681692777
*/
```
Now, run the program once again. And again. And again. What do you see?
The same output gets printed again and again.
Lets head back to the definition of rand() function:-
rand():- *Returns a **pseudo-random** number(integer) from 0 to RAND_MAX. Does not take any arguments.*
So what is a pseudorandom number?
* As the name suggests, a number that is not truly random is pseudorandom.
* Psuedorandom numbers arent cryptographically secure and are vulnerable to attacks.
* In the context of C++, the number appears random, but not truly random. The function assumes that every number from 0 to RAND_MAX is equally likely and spits out one number. (In reality,
this is not the case, but it is close). For example, the number 5 is used almost everywhere. If a random number spits 5, you might not think that the number is infact, random.
* The random funtion rand() takes a very big number, applies modulo by a large prime number and does all sorts of operations on a number and returns a value. However complicated it is, its still possible to break it.
How do we get an unique set of random numbers durng every program execution?
We use `void srand(int seed)`;
* "Seed" is the name given to a number that makes the random sequence generator start at a different starting point everytime. This makes sure that the random function does not spit out the same values during program run.
* **It is important to only invoke the srand call ONCE at the beginning of the program.**
* There is no need for repeat calls to seed the random number generator (in fact, it will make your number less evenly
distributed).
* A commonly used technique is to seed the random number generator using the clock, since clock gives you a different output everytime you look at it. So, for the seed, you can take the output of time and plug it into the random number generator.
* The time() function will return the computers time. This is expressed in terms of the number of
seconds that have elapsed since Jan 1, 1970 (the Epoch).
* The function time(NULL) will return the number of seconds elapsed in computer time.
* The header file that must be included for time functions: `ctime'.
Code snippet:
```cpp
#include <ctime>
srand(time(NULL));
cout << rand();
/*
Output: (Will differ from computer to computer, and because of the seed, will also differ from time to time, literally. :D)
1696269016
*/
```
This produces different values each time the program is run.
Bonus: Tweaking the rand() to your convenience.
* Since rand() returns a random number from 0 to RAND_MAX, if you want a number between 0 and 8 for example, then do
-rand()%9.
Any number modulo 9 will return a value from 0 to 8.
* More formally, if you want a number between L (inclusive) and U (inclusive), you must do
`int num = L + rand()%(U-L+1).`
Explanation:- rand()%(U-L + 1) returns a random (pseudo-random, dont forget) number betwwen 0 and (U-L). Hence, adding L makes sure we get a value between L and U.
Summary:-
1. int rand(): Returns a random number between 0 and RAND_MAX.
1. void srand(int seed): Used to seed the random number generator. It is sufficient to call this function only *once*.
### Sources:- [Random Number Generation](http://www.math.uaa.alaska.edu/~afkjm/csce211/handouts/RandomFunctions)

View File

@ -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;
}
```

View 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/)

View File

@ -0,0 +1,174 @@
---
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.
![alt text](https://github.com/mohammadaziz313/helloworld/blob/master/Lifo_stack.png "LIFO Stack Push and Pop Example")
### 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
## Uses of Stack
1. Expression Evaluation and Conversion.
stacks are used to evaluate and convert expressions like prefx, postfix and infix expression.
2. In Recursive functions to keep information about the active functions or subroutines.
3. In Backtracking, as in DFS algorithm.
4. Memory management, run-time environment for nested language features. etc

View File

@ -0,0 +1,13 @@
---
title: STL Algorithms
---
## STL Algorithms
STL stands for Standard Template Library. It consists various containers like Vectors,Stack,Queue etc. It also consists of some commonly used algorithms like sorting,count etc. The below image shows the quick outline of STL. We will discuss the algorithms part.
![STL Outlook](https://i.imgur.com/daIlXQI.png "STL-Outlook")
### References:
1. [GeeksForGeeks - STL Tutorial](https://www.geeksforgeeks.org/cpp-stl-tutorial/)
2. [Alibaba Cloud - Quick STL Tutorial](https://www.alibabacloud.com/forum/read-531)

View File

@ -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

View File

@ -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 the part of the computer which converts your high level program code to machine code : 0s & 1s ; so that the computer's Central Processing Unit (CPU) can understand the commands and execute them. From now on, we will be using 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 quotation marks 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.They also help another programmer to understand your code.
**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>

View File

@ -0,0 +1,74 @@
---
title: The Auto Feature
---
## The Auto Feature
`auto` is a C++11 feature that lets the compiler infer the data type for you in a definition. This can save you a lot of typing, especially with complicated types.
Without `auto`:
```cpp
double x = 10.425;
double y = x * x;
```
With `auto`:
```cpp
double x = 10.425;
auto y = x * x;
```
While it may seem trivial, it becomes incredibly useful when data types begin to get complicated. For example, assume you want to store a [`vector`](https://guide.freecodecamp.org/cplusplus/vector) of employees, and you are only interested in 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 declared as `std::vector<std::pair<std::string, unsigned int>> employees`. Now suppose you want to access the last employee added:
```cpp
std::vector<std::pair<std::string, unsigned int>> employees;
// without auto, you have to write:
std::pair<std::string, unsigned int>> last_employee = employees.back();
// with auto, you just have to write:
auto last_employee = employees.back();
```
Once the compiler determines the type on the right side of the `=` it replaces `auto` with that type.
However,it should be noted that it is mandatory to intialize the variable marked as auto while declaring so that the compiler can know the type of that variable.
In modern versions of C++ (since C++14), `auto` can also be used in a function declaration as the return type. The compiler will then infer the return type from the return statement inside of the function. Following the example with employees:
```
std::vector<std::pair<std::string, unsigned int>> employees;
auto get_last_employee() {
return employees.back(); // Compiler knows the return type from this line.
}
```
The compiler will know from the line with the return statement that the return type from the function should be `std::vector<std::pair<std::string, unsigned int>>`.
While quite technical, the [cppreference page on auto](http://en.cppreference.com/w/cpp/language/auto) describes many more usages of `auto` and the details of when it can and can't be used.
### `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

View File

@ -0,0 +1,105 @@
---
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 there is only one statement after the if statement the '{ }' are not necessarily required . But if there are more number of statements after if statement, then it is mandatory to put all those statements in '{}'.
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/)**

View File

@ -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>**

View File

@ -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 :
![Img](https://i.imgur.com/YdbgWHL.png)
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 -
![Img](https://i.imgur.com/YdbgWHL.png)
```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/)**

View File

@ -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

View File

@ -0,0 +1,235 @@
---
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.
Vectors are similar to ArrayLists in Java since you don't have to specify the length of the container. Compared to an array where you have to define how large it is, its size depends on its contents.
`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
}
```
### Sorting A Vector In Ascending Order
Sorting a vector based on ascending order can be done with the help of Sort() in C++.
``` cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> v{ 10, 5, 82, 69, 64, 70, 3, 42, 28, 0 };
sort(v.begin(), v.end());
cout << "Vector Contents Sorted In Ascending Order:\n";
for(int e : v){
cout << e << " ";
}
return 0;
}
```
In C++11, you can also sort with lambda function, which can be useful.
```cpp11
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int > v {3, 1, 2};
sort(v.begin(), v.end(), [] (int i, int j) -> bool {
return i < j;
} );
cout << "Vector Contents Sorted In Ascending Order:\n";
for (int e : v)
cout << e << " ";
return 0;
}
```
### Sorting Vector In Descending Order
Sorting Vector in descending order can be done with the help of third argument namely greater<int>() in Sort() in C++.
``` cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> v{ 10, 5, 82, 69, 64, 70, 3, 42, 28, 0 };
sort(v.begin(), v.end(), greater<int>());
cout << "Vector Contents Sorted In Ascending Order:\n";
for(int e : v){
cout << e << " ";
}
return 0;
}
```
You can also sort in descending using lamda like the one above.

View File

@ -0,0 +1,53 @@
---
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