fix(guide): update latest copy from guide repo
This commit is contained in:
committed by
mrugesh mohapatra
parent
73a97354e1
commit
7a860204af
@ -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;
|
||||
'''
|
||||
|
||||
|
36
client/src/pages/guide/english/cplusplus/arrays/index.md
Normal file
36
client/src/pages/guide/english/cplusplus/arrays/index.md
Normal file
@ -0,0 +1,36 @@
|
||||
---
|
||||
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, a 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
|
||||
```
|
||||
|
||||
**Note** that arrays in C++ are not permutable in size, which means that once you've declared a array with size 5 it cant be enlarged or made smaller. In case you really need a bigger array with the same entries, you would have to copy all entries to a new array of bigger size.
|
||||
|
||||
### Access:
|
||||
Elements from an array can be accessed via reference of theire 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}
|
||||
```
|
@ -4,12 +4,14 @@ 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
|
||||
Static cast is used for implicit conversions between primitives and type-overloads.
|
||||
|
||||
##const_cast
|
||||
### 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.
|
||||
@ -18,15 +20,15 @@ Const cast can also result in undefined behaviour. The only application of const
|
||||
const int y = 10; // y is set to 10.
|
||||
const_cast<int &>(y) = 20; // undefined behaviour.
|
||||
```
|
||||
##dynamic_cast
|
||||
### 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
|
||||
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
|
||||
#### 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
|
||||
|
@ -63,12 +63,12 @@ while (i <= 5)
|
||||
Instead of:
|
||||
```cpp
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
if( i == 2)
|
||||
{
|
||||
i = 4;
|
||||
}
|
||||
// Do work
|
||||
{
|
||||
if (i == 2)
|
||||
{
|
||||
i = 4;
|
||||
}
|
||||
// Do work
|
||||
}
|
||||
```
|
||||
|
||||
@ -94,7 +94,7 @@ for (int i = 1; i <= 5; i++)
|
||||
Do:
|
||||
```cpp
|
||||
for (int i = 1; i <= 5; i++)
|
||||
{
|
||||
{
|
||||
//CODE
|
||||
}
|
||||
```
|
||||
|
@ -71,8 +71,13 @@ 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.
|
||||
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
|
||||
____________
|
||||
|
||||
There are a number of different types of compilers. The two listed are the two that are usually packaged with the Windows
|
||||
|
@ -4,7 +4,8 @@ title: Conditional Operator
|
||||
|
||||
## Conditional Operator
|
||||
|
||||
Conditional operator is a ternary operator, that is it needs 3 operands.
|
||||
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 :
|
||||
|
@ -1,33 +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);
|
||||
```
|
||||
Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the expression test comes afterward). Take a look at an example:
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int counter, howmuch;
|
||||
|
||||
cin >> howmuch;
|
||||
counter = 0;
|
||||
do
|
||||
{
|
||||
counter++;
|
||||
cout << counter << '\n';
|
||||
}
|
||||
while ( counter < howmuch);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
---
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
@ -29,3 +29,6 @@ title: Dynamic Memory Allocation
|
||||
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.
|
||||
|
||||
|
@ -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.
|
@ -2,30 +2,47 @@
|
||||
title: For Loop
|
||||
---
|
||||
|
||||
# For Loop
|
||||
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
|
||||
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 insie the for loop like in a while loop. Meaning a syntax like this can also work.
|
||||
|
||||
```
|
||||
for ( init; condition;) {
|
||||
statement(s);
|
||||
increment;
|
||||
}
|
||||
```
|
||||
|
||||
### init
|
||||
This is execute once only.This step allows you to declare and initialize any loop control variables
|
||||
This step allows you to declare and initialize any loop control variables. This step is performed first and only once.
|
||||
|
||||
### condition
|
||||
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
|
||||
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).
|
||||
|
||||
### increment
|
||||
After the body of the for loop executes, the flow of control jumps back up to the increment statement.This can be used to alter the counter variable by simple addition,subtraction,multiplication,division.
|
||||
### 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.
|
||||
|
||||
## Example
|
||||
## IMPLEMENTATION:
|
||||
```C++
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
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 ) {
|
||||
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;
|
||||
}
|
||||
|
||||
@ -43,3 +60,65 @@ 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
|
||||
```
|
||||
|
||||
|
||||
|
@ -45,6 +45,12 @@ int max(int num1, int num2)
|
||||
}
|
||||
```
|
||||
|
||||
## Why are functions important?
|
||||
|
||||
Functions support modularity(breaking down of work into smaller pieces called modules) which is an essential feature of 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 agaun 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)
|
||||
|
26
client/src/pages/guide/english/cplusplus/goto/index.md
Normal file
26
client/src/pages/guide/english/cplusplus/goto/index.md
Normal 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.
|
@ -3,7 +3,7 @@ title: C++
|
||||
---
|
||||
# Hello World! - Your First C++ Program
|
||||
|
||||
## What is C++ ?
|
||||
## 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".
|
||||
@ -16,8 +16,8 @@ _source: Github_
|
||||
### Your First Program in C++
|
||||
|
||||
```cpp
|
||||
#include<iostream>
|
||||
using namespace std ;
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
cout << "Hello World" << endl;
|
||||
@ -43,7 +43,7 @@ using namespace std;
|
||||
|
||||
* The first line tells the computer to use the "iostream" header file for this specific program . A header file is a seperate file with prewritten C++ code. There are many other header files which are requireed for a specific program to run properly. Some of them are : math , vector and string. Header files are generally represented by a ".h" extension (you don't need to add .h when including C++ standard library files)
|
||||
* `iostream` stands for input-output stream . The "iostream" file contains code for allowing the computer to take input and generate an output, using the C++ language.
|
||||
* The second line tells the computer to use the standard namespace which includes features of standard C++. You could write this program without this line, but you'd have to use `std::cout` instead of `cout` on line 4. It makes the code more readable and our lives as programmers easier.
|
||||
* 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
|
||||
|
||||
@ -56,7 +56,7 @@ int main()
|
||||
**NOTE : Every function starts with an opening curly brace "{" and ends with a closing curly brace "}".**
|
||||
* Line 4 indicates the start of the main() function.
|
||||
|
||||
#### Lines 4,5 & 6
|
||||
#### Lines 5, 6 & 7
|
||||
|
||||
```cpp
|
||||
cout << "Hello World" << endl;
|
||||
@ -92,11 +92,11 @@ _You have finished coding your first C++ program and have understood most of the
|
||||
|
||||
**Feel free to ask any questions on FreeCodeCamp's GitHub page or [FreeCodeCamp's Forum.](https://forum.freecodecamp.org/)**
|
||||
|
||||
<a href='https://repl.it/L4k3' target='_blank' rel='nofollow'>Try it yourself ! :) </a>
|
||||
[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 : <a href='http://www.codeblocks.org/downloads/26' target='_blank' rel='nofollow'>Download Here</a>
|
||||
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
|
||||
|
||||
|
@ -2,39 +2,128 @@
|
||||
title: Input and Output
|
||||
---
|
||||
|
||||
## Input and Output
|
||||
## Input and Output with Streams
|
||||
|
||||
* Input stream objects in C++ use 'cin'. This is used to save input data into the program.
|
||||
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 stream objects use 'cout', as shown in the first introduction of C++, to print out statements to the console.
|
||||
### Output with cout
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
The "Hello World" program uses `cout` to print "Hello World!" to the console:
|
||||
|
||||
```C++
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int x;
|
||||
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 << "Enter a number: " << endl; // Ask user for input
|
||||
cin >> x; // Take user input
|
||||
cout << "The output value of int x: " << x << endl;
|
||||
`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.":
|
||||
|
||||
return 0;
|
||||
`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;
|
||||
}
|
||||
```
|
||||
|
||||
* The header file `<iostream>` is required for stream objects.
|
||||
* After declaring a variable, using the `cin` object, input data can be saved into the variable.
|
||||
* The `cout` object prints the data saved into the variable to the console.
|
||||
`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`.
|
||||
|
||||
|
||||
The operators `<<` and `>>` are used to point in the direction of the data.
|
||||
* For `cin`, the `>>` operator is used. You can visualize the input data flowing into the variable.
|
||||
* For `cout`, the `<<` operator is used. You can visualize data from a string or variable flowing into the `cout` object.
|
||||
C's standard printf and scanf statements can also be used with c++ by importing '<cstdio>' header file.
|
||||
|
||||
Try the code <a href="https://repl.it/ND8q/1" target='_blank' rel='nofollow'>here</a> .
|
||||
|
||||
**Happy Coding ! :)**
|
||||
|
||||
**Feel free to ask any queries on FreeCodeCamp's GitHub page or [FreeCodeCamp's Forum .](https://forum.freecodecamp.org/)**
|
||||
## Sources
|
||||
1. http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
|
||||
2. http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
|
||||
|
19
client/src/pages/guide/english/cplusplus/lists/index.md
Normal file
19
client/src/pages/guide/english/cplusplus/lists/index.md
Normal file
@ -0,0 +1,19 @@
|
||||
---
|
||||
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.
|
||||

|
||||
|
||||
|
||||
## How to declare a List
|
||||
If you want to declare a List of Numbers you write:
|
||||
|
||||
'''std::list<int> Numbers;'''
|
@ -53,8 +53,10 @@ d => 40
|
||||
## Insertion
|
||||
Inserting data with insert member function.
|
||||
|
||||
`myMap.insert(make_pair("earth", 1));`
|
||||
`myMap.insert(make_pair("moon", 2));`
|
||||
```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.
|
||||
|
||||
@ -65,9 +67,9 @@ We can also insert data in std::map using operator [] i.e.
|
||||
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';
|
||||
}
|
||||
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>
|
||||
@ -75,4 +77,3 @@ Here you can learn more about map: <a href="http://www.cplusplus.com/reference/m
|
||||
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>
|
||||
|
||||
|
||||
|
||||
|
@ -4,9 +4,11 @@ title: Object Oriented Programming using C++
|
||||
|
||||
## Object Oriented Programming using C++
|
||||
|
||||
Object oriented programming aims to implement real world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operates on them so that no other part of code can access this data except that function.
|
||||
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:
|
||||
|
||||
### 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
|
||||
@ -20,14 +22,14 @@ public:
|
||||
|
||||
int main()
|
||||
{
|
||||
person p1; //p1 is a object
|
||||
person p1; //p1 is an object
|
||||
}
|
||||
```
|
||||
Object take up space in memory and have an associated address like a record in pascal or structure or union in C.
|
||||
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.
|
||||
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.
|
||||
@ -46,29 +48,21 @@ Class is a user defined data type like structures and unions in C.
|
||||
|
||||
By default class variables are private but in case of structure it is public. in above example person is a class.
|
||||
|
||||
### Encapsulation and Data abstraction:
|
||||
Wrapping up(combing) of data and functions into a single unit is known as encapsulation. The data is not accessible to the outside world and only those functions which are wrapping in the class can access it. This insulation of the data from direct access by the program is called data hiding or information hiding.
|
||||
### 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 wont’t be affected as out method interface remains same. Had our implementation be public, we would not have been able to change it.
|
||||
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 re usability. This means that we can add additional features to an existing class without modifying 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.
|
||||
|
||||
### Polymorphism:
|
||||
Polymorphism means ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends upon the types of data used in the operation.
|
||||
C++ supports operator overloading and function overloading.
|
||||
Operator overloading is the process of making an operator to exhibit different behaviors in different instances is known as operator overloading.
|
||||
Function overloading is using a single function name to perform different types of tasks.
|
||||
polymorphism is extensively used in implementing inheritance.
|
||||
|
||||
|
||||
|
||||
### Dynamic Binding:
|
||||
### 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.
|
||||
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.
|
||||
|
@ -13,8 +13,9 @@ You can have multiple definitions for the same function name in the same scope.
|
||||
|
||||
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 {
|
||||
@ -25,12 +26,12 @@ class printData {
|
||||
void print(double f) {
|
||||
cout << "Printing float: " << f << endl;
|
||||
}
|
||||
void print(char* c) {
|
||||
cout << "Printing character: " << c << endl;
|
||||
void print(const string& s) {
|
||||
cout << "Printing string: " << s << endl;
|
||||
}
|
||||
};
|
||||
|
||||
int main(void) {
|
||||
int main() {
|
||||
printData pd;
|
||||
|
||||
// Call print to print integer
|
||||
@ -39,7 +40,7 @@ int main(void) {
|
||||
// Call print to print float
|
||||
pd.print(500.263);
|
||||
|
||||
// Call print to print character
|
||||
// Call print to print string
|
||||
pd.print("Hello C++");
|
||||
|
||||
return 0;
|
||||
@ -51,5 +52,52 @@ When the above code is compiled and executed, it produces the following result
|
||||
```
|
||||
Printing int: 5
|
||||
Printing float: 500.263
|
||||
Printing character: Hello C++
|
||||
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
|
||||
```
|
||||
|
145
client/src/pages/guide/english/cplusplus/preprocessors/index.md
Normal file
145
client/src/pages/guide/english/cplusplus/preprocessors/index.md
Normal 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.
|
||||
|
||||

|
||||
|
||||
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.
|
@ -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 computer’s 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)
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Switch Statement
|
||||
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.
|
||||
@ -12,7 +12,7 @@ switch(expression) {
|
||||
case constant-expression :
|
||||
statement(s);
|
||||
break; //optional
|
||||
|
||||
|
||||
// you can have any number of case statements.
|
||||
default : //Optional
|
||||
statement(s);
|
||||
@ -38,14 +38,14 @@ Example:
|
||||
```C++
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
int main () {
|
||||
// local variable declaration:
|
||||
char grade = 'D';
|
||||
|
||||
switch(grade) {
|
||||
case 'A' :
|
||||
cout << "Excellent!" << endl;
|
||||
cout << "Excellent!" << endl;
|
||||
break;
|
||||
case 'B' :
|
||||
case 'C' :
|
||||
@ -61,7 +61,7 @@ int main () {
|
||||
cout << "Invalid grade" << endl;
|
||||
}
|
||||
cout << "Your grade is " << grade << endl;
|
||||
|
||||
|
||||
return 0;
|
||||
}```
|
||||
|
||||
|
@ -4,34 +4,46 @@ title: The Auto Feature
|
||||
|
||||
## The Auto Feature
|
||||
|
||||
`auto` is a C++11 feature that lets the compiler infer the data type for us in a definition.
|
||||
`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`
|
||||
Without `auto`:
|
||||
```cpp
|
||||
double x = 10.425;
|
||||
double y = x * x;
|
||||
```
|
||||
|
||||
With `auto`
|
||||
With `auto`:
|
||||
```cpp
|
||||
double x = 10.425;
|
||||
auto y = x * x;
|
||||
```
|
||||
|
||||
Whilst it may seem trivial, it becomes incredibly useful when data types begin to get complicated. For example, if a user wanted to store a vector of employees that had their name and age. One way to store the name and age could be a `pair` with a `string` and an `unsigned int`. This is represented as `std::vector<std::pair<std::string, unsigned int>> employees`. Now suppose we wanted to access the last employee added:
|
||||
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
|
||||
// without auto, you have to write:
|
||||
std::pair<std::string, unsigned int>> last_employee = employees.back();
|
||||
|
||||
// with auto
|
||||
// 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.
|
||||
|
||||
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.
|
||||
|
||||
@ -58,3 +70,4 @@ int main()
|
||||
|
||||
## Further Reading :
|
||||
* http://www.stroustrup.com/C++11FAQ.html#auto
|
||||
|
||||
|
@ -6,6 +6,7 @@ title: 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**
|
||||
|
||||
@ -171,3 +172,45 @@ for(std::vector<int>::size_type i = 0; i != myVector.size(); i++){
|
||||
}
|
||||
|
||||
```
|
||||
### 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;
|
||||
}
|
||||
```
|
||||
### 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;
|
||||
}
|
||||
```
|
||||
|
@ -1,5 +1,5 @@
|
||||
---
|
||||
title: While-loop
|
||||
title:While-loop
|
||||
---
|
||||
|
||||
A while loop statement repeatedly executes a target statement as long as a given condition is true.
|
||||
@ -18,7 +18,7 @@ Example:
|
||||
```C++
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
int main () {
|
||||
// Local variable declaration:
|
||||
int a = 10;
|
||||
@ -28,7 +28,7 @@ int main () {
|
||||
cout << "value of a: " << a << endl;
|
||||
a++;
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user