From b7efdb5712a61d374f10ec952cb34959715850c8 Mon Sep 17 00:00:00 2001 From: Arnish Baruah Date: Wed, 19 Oct 2022 10:23:52 +0530 Subject: [PATCH] Add CPP --- cpp/arrays/arrays.md | 110 ++++++++ cpp/basics/constants.md | 78 ++++++ cpp/basics/data-types.md | 56 ++++ cpp/basics/fundamentals.md | 52 ++++ cpp/basics/introduction.md | 65 +++++ cpp/basics/operators.md | 253 ++++++++++++++++++ cpp/basics/strings.md | 117 ++++++++ cpp/basics/tokens.md | 81 ++++++ cpp/basics/variables.md | 34 +++ .../conditional-statements.md | 196 ++++++++++++++ cpp/control-statements/loops.md | 85 ++++++ cpp/enum-and-typedef/enum.md | 24 ++ cpp/enum-and-typedef/typedef.md | 27 ++ cpp/functions/functions.md | 184 +++++++++++++ cpp/index.json | 126 +++++++++ cpp/oops/oops.md | 184 +++++++++++++ cpp/pointers/pointers.md | 100 +++++++ cpp/structures/structures.md | 105 ++++++++ 18 files changed, 1877 insertions(+) create mode 100644 cpp/arrays/arrays.md create mode 100644 cpp/basics/constants.md create mode 100644 cpp/basics/data-types.md create mode 100644 cpp/basics/fundamentals.md create mode 100644 cpp/basics/introduction.md create mode 100644 cpp/basics/operators.md create mode 100644 cpp/basics/strings.md create mode 100644 cpp/basics/tokens.md create mode 100644 cpp/basics/variables.md create mode 100644 cpp/control-statements/conditional-statements.md create mode 100644 cpp/control-statements/loops.md create mode 100644 cpp/enum-and-typedef/enum.md create mode 100644 cpp/enum-and-typedef/typedef.md create mode 100644 cpp/functions/functions.md create mode 100644 cpp/index.json create mode 100644 cpp/oops/oops.md create mode 100644 cpp/pointers/pointers.md create mode 100644 cpp/structures/structures.md diff --git a/cpp/arrays/arrays.md b/cpp/arrays/arrays.md new file mode 100644 index 0000000..1db839a --- /dev/null +++ b/cpp/arrays/arrays.md @@ -0,0 +1,110 @@ +Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index. + +Index starts from 0 to size-1. + +Arrays can be one-dimensional, multi-dimensional in C++ language. The more popular and frequently used arrays are one-dimensional and two-dimensional arrays. + +Arrays store the collection of data sequentially in memory and they must share same data type. + +# How to declare an array? + +### One dimentional Array: + +```c +data-type array-name[size]; +``` + +### Two dimensional array: + +```c +data-type array-name[size][size]; +``` + +## Examples + +### One dimentional Array: + +```c +int a[5]; +``` + +### Two dimentional Array: + +```c +int a[2][3]; +int b[][3]; // is also valid +``` + +# How to initialize arrays + +### One dimentional Array: + +```c +int a[5] = {1,2,3,4,5}; +``` + +### Two dimentional Array: + +```c +int a[2][3] = { + {1,2,3}, + {4,5,6} + }; +``` + +# How to access array elements + +Array elements can be accessed by using indices. Array indices starts from `0`. `Array[n-1]` can be used to access nth element of an array. + +## Examples + +### One dimentional array: + +```c +#include +using namespace std; + +int main() +{ + int arr[5] = {1,2,3,4,5}; + int n = sizeof(arr)/sizeof(arr[0]); // gives length of an array + cout << "Length of the array:" << n << endl; + cout << "first element: " << arr[0] << endl; // prints first element of the array + cout << "last element: " << arr[n-1]; // prints last element of the array + return 0; + +} + +``` +### Check result [here](https://onecompiler.com/cpp/3vmbf4ed9) + +### Two dimentional array: + +```c +#include +using namespace std; + +int main() +{ + int a[2][3] = { + {1,2,3}, + {4,5,6} + }; + for(int i=0; i<2; i++) // iterates for each row + { + for(int j=0; j<3; j++) // iterates for each column + { + cout << a[i][j] << " "; + } + cout << endl; + } +} +``` +### Check result [here](https://onecompiler.com/cpp/3vmbfbbzg) + +## Summary + +* Arrays is a collection of homogeneous data. +* Arrays stores data sequentially in memory. +* Arrays are finite. + diff --git a/cpp/basics/constants.md b/cpp/basics/constants.md new file mode 100644 index 0000000..1233617 --- /dev/null +++ b/cpp/basics/constants.md @@ -0,0 +1,78 @@ + +Literals/constants are used to represent fixed values which can't be altered later in the code. + +## 1. Integer literals + +Interger literals are numeric literals. Below are the examples of various types of literals + +```c +79 // decimal (base 10) +0253 // octal (base 8) +0x4F // hexadecimal (base 16) +22 // int +53u // unsigned int +79l // long +7953ul // unsigned long +``` + +## 2. Float point literals + +Float point literals are also numeric literals but has either a fractional form or an exponent form. + +```c +79.22 // valid +79E-5L // valid +53E // not valid as it is incomplete exponent +.e22 // not valid as missing integer or fraction +``` + +## 3. Boolean literals + +There are two Boolean literals which are part of standard C++ keywords − + +* true value representing true. + +* false value representing false + +## 4. Character literals + +Character literals are represented with in single quotes. For example, `a`, `1` etc. A character literal can be a simple character (e.g., 'a'), an escape sequence (e.g., '\n'), or a universal character (e.g., '\u02C0'). + +|Escape sequence| Description| +|----|----| +|\n | New line| +|\r | Carriage Return| +|\? | Question mark| +|\t | Horizontal tab| +|\v | Vertical tab| +|\f |Form feed| +|\\ | Backslash| +|\' | Single quotation| +|\" | Double quotation| +|\0 | Null character| +|\? | ? Question mark| +|\b |Back space| +|\a | alert or bell| + +## 5. String literals + +String literals are represented with in double quotes. String literals contains series of characters which can be plain characters, escape sequence or a universal character. + +```c +"Hello World" +``` + +## How to define constants + +You can use either `#define` or `const` to define constants as shown below. + +* Using #define + +```c +#define identifier-name value +``` +* Using Const + +```c +const datatype variable-name = value; +``` diff --git a/cpp/basics/data-types.md b/cpp/basics/data-types.md new file mode 100644 index 0000000..994a1dc --- /dev/null +++ b/cpp/basics/data-types.md @@ -0,0 +1,56 @@ +As the name suggests, data-type specifies the type of the data present in the variable. Variables must be declared with a data-type. + +There are three different types of Data types in C++. + +| Types | Data-type| +|----|----| +|Basic | int, char, float, double, short, short int, long int etc | +|Derived | array, pointer etc | +|User Defined Data Type | structure, enum, Class, Union, Typedef | + + +## 1. Basic data types + +Basic data types are generally arithmetic types which are based on integer and float data types. They support both signed and unsigned values. Below are some of the oftenly used data types + +| Data type | Description | Range | Memory Size| +|----|----|----|----|----| +| int| used to store whole numbers|-32,768 to 32,767|2 bytes| +|short int| used to store whole numbers|-32,768 to 32,767| 2 bytes| +|long int| used to store whole numbers| -2,147,483,648 to 2,147,483,647| 4 bytes| +|float| used to store fractional numbers|6 to 7 decimal digits| 4 bytes| +|double| used to store fractional numbers|15 decimal digits| 8 bytes| +|char|used to store a single character|one character|1 bytes| +|bool| Boolean data type| 1 byte| + +### Examples + +```c +#include +using namespace std; + +int main() +{ + +int x = 90; +int y = sizeof(x); +cout << "size of x is: " << y << endl; + +float f = 3.14; +cout << "size of float is: " << sizeof(f) << endl; + +double d = 2.25507e-308; +cout << "size of double is: " << sizeof(d) << endl; + +char c = 'a'; +cout << "size of char is: " << sizeof(c) << endl; + +return 0; +} + +``` +#### Run [here](https://onecompiler.com/cpp/3vm83rs6y) + +## 2. Derived or User defined Data types + +Derived Data types and user defined dta types are the ones which are derived from fundamental data types and are defined by user. Arrays, Pointers, functions etc. are examples of derived data types. Enum, Structures, Class, union, enum, typedef etc are User defined data types. Let's learn more about them in next chapters. diff --git a/cpp/basics/fundamentals.md b/cpp/basics/fundamentals.md new file mode 100644 index 0000000..86641f8 --- /dev/null +++ b/cpp/basics/fundamentals.md @@ -0,0 +1,52 @@ +## Sample C++ program + +```c +#include +using namespace std; +int main() { + cout << "Hello World!!"; + return 0; +} +``` + +**`#include `** : iostream is a inbuilt header library which allows you to deal with input and output objects like cout etc. + +**`using namespace std`** : The above line means that the object and variable names can be used from standard library. + +**`cout`** : cout is used to print the output. + +**`main()`** : main function is the entry point of any C++ program. + +**`return 0`** : To end the main function + +# Compile & Run a C++ Program + +## How to compile a program in C++ + +* Open your terminal, navigate to the directory where you have saved your program. Consider `firstprogram.cpp` is the name of your program. + +```c +sudo g++ -o firstprogram firstprogram.cpp +``` + +## How to run a C++ program + +``` +./firstprogram +``` + +## Using Onecompiler + +* You don't need to install any software or compiler. +* Just goto [OneCompiler](https://onecompiler.com/cpp) and enjoy programming without any installation. + +## Comments + +1. Single line comments + +`//` is used to comment a single line + +2. Multi line comments + +`/**/` is used to comment multiple lines. + diff --git a/cpp/basics/introduction.md b/cpp/basics/introduction.md new file mode 100644 index 0000000..f8060e7 --- /dev/null +++ b/cpp/basics/introduction.md @@ -0,0 +1,65 @@ +C++ is a widely used middle-level programming language. + +* Supports different platforms like Windows, various Linux flavours, MacOS etc +* C++ supports OOPS concepts like Inheritance, Polymorphism, Encapsulation and Abstraction. +* Case-sensitive +* C++ is a compiler based language +* C++ supports structured programming language +* C++ provides alot of inbuilt functions and also supports dynamic memory allocation. +* Like C, C++ also allows you to play with memory using Pointers. + +## Why you should learn C++? + +* Many databases like MySQL, MongoDB, MemSQL, etc are written in C++ +* C and C++ are used in developing major operating systems such as Windows, Linux, Android, Ubuntu, iOS etc. +* C++ has large community support. +* C++ is used in writing compilers, web browsers, Games and even in embedded systems. +* C++ developers are offered with high salaries. +* C++ is considered as a foundational language to learn advanced programming languages. + +## Why C++ is popular? + +* C++'s greatest strength is it's scalability and hence challenging 3D games are often built in C++. +* C++ is fourth popular language according to [Tiobe Index](https://www.tiobe.com/tiobe-index/) +* Applications which are critically reliable on speed and resource usage are usually preferred to be built in C++. +* Good community support. + +# Installation + +## 1. on MacOS + +* Install [Xcode](https://developer.apple.com/xcode/) from Appstore. +* Once installed, accept the terms and conditions and provide your MAC password. +* Now, components will get installed. + +## 2. on Windows + +* There are many C++ compilers available in the market which are free to use. +* Download C++ compiler from [VS-C-andC++](https://visualstudio.microsoft.com/vs/features/cplusplus/) +* Run the executable file. + +## 3. on Linux + +* Most Linux operating systems are pre-installed with GCC. + +```shell +gcc -version +``` +* For Ubuntu and Debian, use the below command + +```shell +sudo apt-get update +sudo apt-get install GCC +sudo apt-get install build-essential +``` +* For redhat, use the below command + +```shell +yum groupinstall 'Development Tools' +``` + +## 4. Using Onecompiler + +* You don't need to install any software or compiler. +* Just goto [OneCompiler](https://onecompiler.com/) and choose the programming language as C++ and enjoy programming without any installation. + diff --git a/cpp/basics/operators.md b/cpp/basics/operators.md new file mode 100644 index 0000000..75fec89 --- /dev/null +++ b/cpp/basics/operators.md @@ -0,0 +1,253 @@ +Let us understand the below terms before we get into more details. + +### 1. Operator + +An operator is a symbol which has special meaning and performs an operation on single or multiple operands like addition, substraction etc. In the below example, `+` is the operator. + +```c +#include +using namespace std; + +int main() +{ + int x, y, sum; + x = 10; + y = 20; + + sum = x + y; + cout << "Sum : " << sum; + + return(0); +} +``` +### Check result [here](https://onecompiler.com/cpp/3vmb5yays) + +### 2. Operand + +An operand is what operators are applied on. In the above example `x` and `y` are the operands. + +# Types of Operators in C++ + +## 1. Arithmetic Operators + +C++ arithmetic operators are used to perform arithmetic operations on operands. + +|Operator| Description | Example| +|----|----|----| +| + | Used to perform Addition | 8+2 = 10| +| - | Used to perform Subtraction | 12-2 = 10| +| * | Used to perform Multiplication | 5*2 = 10| +| / | Used to perform Division | 100/10 = 10| +| % | Used to return Remainder | 40%10 = 0| +| ++ | Used to perform Increment | int a=10; a++; // a becomes 11| +| -- | Used to perform Decrement | int a=10; a--; // a becomes 9| + + +### Example + +```c +#include +using namespace std; + +int main() +{ + int x, y, sum, diff, product, division, mod, inc, dec; + x = 90; + y = 10; + + sum = x + y; + cout << "Sum : " << sum << endl; + + diff = x - y; + cout << "Difference : " << diff << endl; + + product = x * y; + cout << "Product : " << product << endl; + + division = x / y; + cout << "Division : " << division << endl; + + mod = x % y; + cout << "Remainder : " << mod << endl; + + inc = x++; + cout << "x value after incrementing : " << x << endl; + + dec = x--; + cout << "x value after decrementing : " << x; + + return(0); + +} +``` +### Check Result [here](https://onecompiler.com/cpp/3vmb6bf4b) + +## 2. Relational Operators + +C++ relational operators are used to compare two operands. + +| Operator | Description| Usage| +|----|----|----| +| == | Is equal to | x == y| +| != | Not equal to | !=x | +| > | Greater than | x > y | +| >= | Greater than or equal to | x >= y| +| < | Less than| x < y | +| <= | Less than or equal to| x <= y| + +### Example + +```C +#include +using namespace std; + +int main() +{ + int x = 90; + int y = 10; + + if ( x == y) { + cout << "x and y are equal" << endl; + } + + if ( x != y) { + cout << "x and y are not equal" << endl; + } + + if ( x > y) { + cout << "x is greater than y" << endl; + } + + if ( x < y) { + cout << "x is less than y" << endl; + } +} +``` +### Check Result [here](https://onecompiler.com/cpp/3vmb6ppv9) + +## 3. Bitwise Operators + +C++ bitwise operators are used to perform bitwise operations on operands. + +|Operator| Description| Usage| +|----|----|----| +| & | Bitwise AND | (x > y) & (y > z)| +| \| | Bitwise OR | (x > y) \| (y > z)| +| ^ | Bitwise XOR | (x > y) ^ (y > z)| +| ~ | Bitwise NOT | (~x)| +| << | Bitwise Left Shift| x << y| +| >> | Bitwise Right Shift| x >> y| + +## 4. Logical operators + +Below are the logical operators present in the C++. + +|Operator| Description| Usage| +|----|----|----| +| && | Logical AND | (x > y) && (y > z)| +| \|\| | Logical OR | (x > y) \|\| (y > z)| +| ! | Logical NOT | (!x)| + +## 5. Assignment Operators + +Below are the assignment operators present in the C++. + +|Operator| Description| Usage| +|----|----|----| +| = | Assign| int x = 10;| +| += | Add and assign| int x=10; x+=30; // x becomes 40| +| -= | Subtract and assign| int x=40; x-=10; // x becomes 30| +| *= | Multiply and assign| int x=10; x*=40; // x becomes 400| +| /= | Divide and assign| int x=100; x /= 10;// x becomes 10| +| %= | Modulus and assign| int x=100; x%=10; // x becomes 0| +| <<= | Left shift and assign| x <<= 2 is same as x = x << 2| +| >>= | Right shift and assign| x >>= 2 is same as x = x >> 2| +| &= | Bitwise and assign| x &= 10 is same as x = x & 10| +| ^= | Bitwise exclusive OR and assign| x ^= 10 is same as x = x ^ 10| +| \|= |Bitwise inclusive OR and assign | x \|= 10 is same as x = x \| 10| + +### Example + +```C +#include +using namespace std; + +int main() +{ + int x = 10; // assigning 10 to x +cout << "x value: " << x << endl; + +x+=30; +cout << "x value after += operation: " << x << endl; + +x-=10; +cout << "x value after -= operation: " << x << endl; + +x*=10; +cout <<"x value after *= operation: " << x << endl; + +x/=10; +cout <<"x value after /= operation: " << x << endl; + +x%=10; +cout <<"x value after %= operation: " << x; + +} +``` + +### Check Result [here](https://onecompiler.com/cpp/3vmb6zaez) + +## 6. Misc Operator + +* Ternary Operator + +If the operator is applied on a three operands then it is called ternary. This is also known as conditional operator as a condition is followed by `?` and true-expression which is followed by a `:` and false expression. This is oftenly used as a shortcut to replace if-else statement + +### Example + +```c +#include +using namespace std; + +int main() +{ + int x = 10; + int y = 90; + + int z = x > y ? x : y; + + cout << "Larger Number is: " << z; +} +``` +### Check Result [here](https://onecompiler.com/cpp/3vmb79s3q) + +* sizeof() + +This operator is used to return the size of a variable. + +```c +#include +using namespace std; + +int main() +{ + + int x = 90; + int y = sizeof(x); + + cout <<"Size of x is: " << y; +} +``` +### Check Result [here](https://onecompiler.com/cpp/3vmb7cnag) + +## Summary + +| Operator type | Description| +|----|-----| +| Arithmetic Operator|+ , - , * , / , %| +| comparision Operator| < , > , <= , >=, != , ==| +| Bitwise Operator| & , ^ , \|, ^ , ~, <<, >> | +| Logical Operator| && , \|\|, ! | +| Assignment Operator|= , += , -= , *= , /= , %=, <<=, >>=, &=, ^=, \|= | +| Ternary Operator| ? : | +| sizeof operator| sizeof() | diff --git a/cpp/basics/strings.md b/cpp/basics/strings.md new file mode 100644 index 0000000..a7ce8b6 --- /dev/null +++ b/cpp/basics/strings.md @@ -0,0 +1,117 @@ +String is a sequence of characters terminated with a null character `\0` at the end. There are two types of strings in C++. + +1. C-Strings +2. Strings that are objects of string class + +# How to declare strings + +Declaring strings is similar to one-dimensional character array. Below is the syntax: + +```c +char var-name[size]; +// or +string str; +``` + +# How to initialize strings + +Strings can be initialized in a number of ways: +```c +char str[] = "OneCompiler"; + +char str[20] = "OneCompiler"; + +char str[] ={'O','n','e','C','o','m','p','i','l','e','r','\0'}; + +char str[20] ={'O','n','e','C','o','m','p','i','l','e','r','\0'}; + +string str = "OneCompiler"; +``` + +# How to read strings from console + +```c +#include +using namespace std; +int main() +{ + char str[20]; + cin >> str; // to read the string values from stdin + cout << "You have entered: " << str; // to print the sting + return 0; +} +``` +### Check Result [here](https://onecompiler.com/cpp/3vmbntfpm) + +Consider if you have given `One Compiler` as input in the stdin. Surprisingly you get `One` alone as output. That is because a white space is present between `One` and `Compiler`. So how can you read a entire line which also has white spaces in it. + +Consider your input string is `Hello Everyone.. Happy Learning!!` + +```c +#include +using namespace std; + +int main() +{ + string str; + getline(cin, str); // to read string from stdin + cout << "String entered is : " << str ; + return 0; +} +``` + +### Check Result [here](https://onecompiler.com/cpp/3vmbnzg24) + +# String Functions + +C++ has various in-built string functions which can manipulate null-terminated strings. + +| Function name | Description| +|----|----| +|strlen(str)| to return the length of string str| +|strcat(str1, str2)| to concatenate string str2 onto the end of string str1.| +|strcpy(str1, str2)| To copy string str2 into string str1.| +|strcmp(str1, str2)| returns 0 if str1 and str2 are the same and less than 0 if str1 < str2 and a positive number if str1 > str2| +|strchr(str, c)| Returns a pointer to the first occurrence of character c in string str| +|strstr(str1, str2)| Returns a pointer to the first occurrence of string str2 in string str1| + + +## Examples + +```c +#include +using namespace std; +#include + +int main() +{ + + char str1[20] = "Happy"; + char str2[20] = "learning"; + char str3[20]; + char str4[20] = "learning"; + + int length, cmp , cmp1 ; + + length = strlen(str1); // to find length of a string + cout << "length of string is : " << length << endl; + + strcat( str1, str2); // concatenates str1 and str2 + cout << "Concatenation of str1 and str2: " << str1 << endl; + + strcpy(str3, str1); // to copy a string into another + cout << "string copy of str1 to str3 : " << str3 << endl; + + cmp = strcmp(str2,str4); // to compare two strings + cout << "string compare result : "<< cmp << endl; + + + cmp1 = strcmp(str1,str4); // to compare two strings + cout << "string compare result : " << cmp1 << endl; + + return 0; + +} +``` + +### Check result [here](https://onecompiler.com/cpp/3vmbp94k9) diff --git a/cpp/basics/tokens.md b/cpp/basics/tokens.md new file mode 100644 index 0000000..919772a --- /dev/null +++ b/cpp/basics/tokens.md @@ -0,0 +1,81 @@ + +Token can be referred as the smallest possible unit in C++. Token is divided into six categories as follows. + +## 1. Keywords + +Keywords are the reserved words in a programming language. Both C and C++ supports the below 31 keywords + +```c +auto double int struct +break else long switch +case enum register typedef +char extern return union +const float short unsigned +continue for signed void +default goto sizeof volatile +do if static while +``` + +The below keywords are present in C++ but not in C + +``` +asm dynamic_cast namespace reinterpret_cast bool +explicit new static_cast false catch +operator template friend private class +this inline public throw const_cast +delete mutable protected true try +typeid typename using virtual wchar_t +``` + + +## 2. Identifiers + +Identifiers are the user defined names for variables, functions and arrays. + +Rules for defining an identifier: +* They must be less than or equal to 31 characters. +* No special characters. +* Must start with a letter or under score. +* Can contain letters, digits, or underscore only. + +## 3. Strings + +String is an array of characters ended with null character. Characters are enclosed in single quotes where as strings are always enclosed in double quotes. + +```c +char str[]="onecompiler"; +``` + +## 4. Operators + +Operators are the symbols which specifies an action when applied on variables. + +* Arithmetic operators +* Relational Operators +* Logical Operators +* Assignment Operators +* Conditional Operators +* Bitwise Operators +* Unary Operators + +## 5. Constants + +Constants are the fixed values. Constant values can't be changed once defined. + +``` c +const datatype variable_name; +``` + +## 6. Special Characters + +Few characters have special meaning and hence these can't be used for other purposes. + +* `{}` : spcifies start and end of code blocks +* `[]` : Used for arrays +* `()` : Used for functions +* `,` : used to seperate variables, constants etc +* `*` : used for pointers +* `#` : used as a macro processor. +* `~` : used as a destructor to free memory +* `.` : used to access a member of a structure + diff --git a/cpp/basics/variables.md b/cpp/basics/variables.md new file mode 100644 index 0000000..e6a95f7 --- /dev/null +++ b/cpp/basics/variables.md @@ -0,0 +1,34 @@ + +Variables are like containers which holds the data values. A variable specifies the name of the memory location. + +## How to declare variables + +```c +data-type variable-name = value; +``` +In the above syntax, assigning value is optional as you can just declare the variable and then assign value at later point in the program. Also, the value of a variable can be changed at any time. + +## Naming convention of variables + +* Variable names can have only letters (both uppercase and lowercase letters), digits and underscore(`_`). +* Variables naming cannot contain white spaces like `first name` which is a invalid variable name. +* First letter of a variable should be either a letter or an underscore(`_`). +* Variable type can't be changed once declared as C++ is a strongly typed language. +* In C++, Variable names are case sensitive and hence Name and name both are different. +* It is always advisable to give some meaningful names to variables. + +### Example + +```c +int x = 10; // declaring int variable and assigning value 10 to it +char grade = 'A'; // declaring char variable and assigning value A to it +``` +The above can also be written like below + +```c +int x; // declaring int variable +char grade; // declaring char variable + +x = 10; // assigning value 10 to x variable +grade = 'A'; //and assigning value A to grade variable +``` diff --git a/cpp/control-statements/conditional-statements.md b/cpp/control-statements/conditional-statements.md new file mode 100644 index 0000000..5d065ea --- /dev/null +++ b/cpp/control-statements/conditional-statements.md @@ -0,0 +1,196 @@ +When ever you want to perform a set of operations based on a condition(s) If / If-Else / Nested ifs are used. + +You can also use if-else , nested IFs and IF-ELSE-IF ladder when multiple conditions are to be performed on a single variable. + +## 1. If + +### Syntax + +```c +if(conditional-expression) +{ + //code +} +``` +### Example + +```c +#include +using namespace std; + +int main() +{ + int x = 30; + int y = 30; + + if ( x == y) { + cout << "x and y are equal"; + } +} +``` +#### Check result [here](https://onecompiler.com/cpp/3vmbfhgq9) + +## 2. If-else + +### Syntax + +```c +if(conditional-expression) +{ + //code +} else { + //code +} +``` +### Example + +```c +#include +using namespace std; + +int main() +{ + + int x = 30; + int y = 20; + + if ( x == y) { + cout << "x and y are equal"; + } else { + cout <<"x and y are not equal"; + } +} +``` +#### Check result [here](https://onecompiler.com/cpp/3vmbfnjv3) + +## 3. If-else-if ladder + +### Syntax +```c +if(conditional-expression-1) +{ + //code +} else if(conditional-expression-2) { + //code +} else if(conditional-expression-3) { + //code +} +.... +else { + //code +} +``` + +### Example +```c +#include +using namespace std; + +int main() +{ + int age = 15; + + if ( age <= 1 && age >= 0) { + cout << "Infant"; + } else if (age > 1 && age <= 3) { + cout << "Toddler"; + } else if (age > 3 && age <= 9) { + cout << "Child"; + } else if (age > 9 && age <= 18) { + cout << "Teen"; + } else if (age > 18) { + cout << "Adult"; + } else { + cout << "Invalid Age"; + } + +} +``` +#### Check result [here](https://onecompiler.com/cpp/3vmbfzw6a) + +## 4. Nested-If + +Nested-Ifs represents if block within another if block. + +### Syntax +```c +if(conditional-expression-1) { + //code + if(conditional-expression-2) { + //code + if(conditional-expression-3) { + //code + } + } +} +``` + +### Example +```c +#include +using namespace std; + +int main() +{ + int age = 50; + char resident = 'Y'; + if (age > 18) + { + if(resident == 'Y'){ + cout << "Eligible to Vote"; + } + } +} +``` +#### Check result [here](https://onecompiler.com/cpp/3vmbg4fkb) + +## 5. Switch + +Switch is an alternative to IF-ELSE-IF ladder and to select one among many blocks of code. + +### Syntax + +```c +switch(conditional-expression){ +case value1: + //code + break; //optional +case value2: + //code + break; //optional +... + +default: + //code to be executed when all the above cases are not matched; +} +``` +### Example +```c +#include +using namespace std; + +int main() +{ + int day = 3; + + switch(day){ + case 1: cout << "Sunday"; + break; + case 2: cout << "Monday"; + break; + case 3: cout << "Tuesday"; + break; + case 4: cout << "Wednesday"; + break; + case 5: cout << "Thursday"; + break; + case 6: cout << "Friday"; + break; + case 7: cout << "Saturday"; + break; + default: cout << "Invalid day"; + break; + } +} +``` +#### Check Result [here](https://onecompiler.com/cpp/3vmbg85we) diff --git a/cpp/control-statements/loops.md b/cpp/control-statements/loops.md new file mode 100644 index 0000000..01c5323 --- /dev/null +++ b/cpp/control-statements/loops.md @@ -0,0 +1,85 @@ +## 1. For + +For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations are known in advance. + +### Syntax + +```c +for(Initialization; Condition; Increment/decrement){ +//code +} +``` +### Example + +```c +#include +using namespace std; + +int main() +{ + for (int i = 1; i <= 5; i++) { + cout << i << endl; + } +} +``` + +#### Check Result [here](https://onecompiler.com/cpp/3vmbgeg6b) + +## 2. While + +While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations is not known in advance. + +### Syntax + +```c +while(condition){ +//code +} +``` +### Example + +```c +#include +using namespace std; + +int main() +{ + +int i=1; + +while ( i <= 5) { + cout << i << endl; + i++; +} +} +``` +#### Check result [here](https://onecompiler.com/cpp/3vmbgh3az) + +## 3. Do-while + +Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once. + +### Syntax + +```c +do{ +//code +} while(condition); +``` +### Example + +```c +#include +using namespace std; + +int main() +{ + int i=1; + do { + cout << i << endl; + i++; + } while (i<=5); +} +``` + +#### Check result [here](https://onecompiler.com/cpp/3vmbgkg2p) \ No newline at end of file diff --git a/cpp/enum-and-typedef/enum.md b/cpp/enum-and-typedef/enum.md new file mode 100644 index 0000000..140835d --- /dev/null +++ b/cpp/enum-and-typedef/enum.md @@ -0,0 +1,24 @@ +Enumeration data type is a user-defined data type in C++. `enum` keyword is used to declare a new enumeration types in C++. + +### Syntax + +```c +enum name{constant1, constant2, constant3, ....... } var-list; +``` +### Example + +```c +#include +using namespace std; + + +enum month{January, February, March, April, May, June, July, August, September, October, November, December} name; + +int main() +{ + name = June; + cout << name; + return 0; +} +``` +### Run [here](https://onecompiler.com/cpp/3vm845a9w) diff --git a/cpp/enum-and-typedef/typedef.md b/cpp/enum-and-typedef/typedef.md new file mode 100644 index 0000000..0f8a50f --- /dev/null +++ b/cpp/enum-and-typedef/typedef.md @@ -0,0 +1,27 @@ +Typedef is used to explicitly define new data type names by using the keyword `typedef`. It defines a name for an existing data type but doesn't create a new data type. + +Typedefs helps in portability as you can just change the typedefs alone when you move from one system to another. + +## Syntax + +```c +typedef data-type name; +``` + +## Example + +```c +#include +using namespace std; + + +int main() +{ + typedef unsigned int distance; // typedef of int + distance d1; + d1 = 150; + cout << "Distance is: " << d1; + return 0; +} +``` +### Check result [here](https://onecompiler.com/cpp/3vm85rv7t) diff --git a/cpp/functions/functions.md b/cpp/functions/functions.md new file mode 100644 index 0000000..5c8b913 --- /dev/null +++ b/cpp/functions/functions.md @@ -0,0 +1,184 @@ +Functions is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. + +Functions allows you to divide your large lines of code into smaller ones. Usually the division happens logically such that each function performs a specific task and is up to developer. + +Two types of functions are present in C++: + +1. Library Functions + +Library functions are the in-built functions which can be used directly by the programmers. No need to define them as they are already defined in header files. + +2. User defined functions + +User defined functions are the ones which are written by the programmer based on the requirement. Programmers define them on their own. + +## How to declare a Function + +```c +return_type function_name(parameters); +``` + +## How to call a Function + +```c +function_name (parameters) +``` +## How to define a Function +```c +return_type function_name(parameters){ +//code +} +``` +# Different ways of calling a user-defined functions + +You can call functions in different ways as given below based on the criteria. + +1. Function with no arguments and no return value. +2. Function with no arguments and a return value. +3. Function with arguments and no return value. +4. Function with arguments and a return value. + +Let's look examples for the above types. + +## 1. Function with no arguments and no return value. + +```c +#include +void greetings(); +int main() +{ + greetings(); +} + +void greetings() +{ + cout << "Hello world!!"; +} +``` +### check result [here](https://onecompiler.com/cpp/3vmbjbjgn) + +## 2. Function with no arguments and a return value. + +```c +#include +using namespace std; +int sum(); +int main() +{ + int result; + result = sum(); + cout << "Sum : " << result; +} + +int sum() { + int x, y, sum; + x = 10; + y = 20; + + sum = x + y; + return (sum); // returning sum value +} +``` +### check result [here](https://onecompiler.com/cpp/3vmbjd9yd) + +## 3. Function with arguments and no return value. + +```c +#include +using namespace std; + +int sum(int , int ); +int main() +{ + int x= 10, y = 20; + sum(x,y); // passing arguments to function sum +} + +int sum(int x , int y) { + int sum; + sum = x + y; + cout << "Sum : " << sum; + return 0; +} +``` + +### Check result [here](https://onecompiler.com/cpp/3vmbjgdvn) + +## 4. Function with arguments and a return value. + +```c +#include +using namespace std; + +int sum(int , int ); // function declaration + +int main() +{ + int x= 10, y = 20; + int result; + + result = sum(x, y); // passing arguments to function sum + cout << "Sum : " << result; + + +} + +int sum(int x , int y) { //function definition + int sum; + sum = x + y; + return sum; // returning sum value +} +``` +### Check result [here](https://onecompiler.com/cpp/3vmbhyses) + +## calling a function inside same function(recursion): +```c +#include +using namespace std; + +int increase(int ); // function declaration + +int main() +{ + int x= 10; + int result; + + result = increase(x); // passing arguments to function increase + cout << "Result after increasing : " << result; + + +} + +int increase(int x ) { //function definition + int new_result = x + 1; + return increase(new_result); // calling itself +} +``` +### Check result [here](https://onecompiler.com/cpp/3yk82ucqf) +However this will continue increasing the value of the parameter due to which it will call the same function again again. To avoid this we can set a limit which will stop the function from calling itesf after we cross the limit. This is also known as base case. + + +```c +#include +using namespace std; + +int increase(int ); // function declaration + +int main() +{ + int x= 10; + int result; + + result = increase(x); // passing arguments to function increase + cout << "Result after increasing : " << result; + + +} + +int increase(int x ) { //function definition + if(x > 20) return x; //base case + int new_result = x + 1; + return increase(new_result); // calling itself +} +``` +### Check result [here](https://onecompiler.com/cpp/3yk82ucqf) diff --git a/cpp/index.json b/cpp/index.json new file mode 100644 index 0000000..7369526 --- /dev/null +++ b/cpp/index.json @@ -0,0 +1,126 @@ +{ + "_id": "cpp", + "title": "C++", + "description": "C++ Tutorial - Learn the concepts of C++ programming language, practice the sample programs and try yourself using our free editor.", + "created": "2019-10-01", + "updated": "2020-07-07", + "cover": "", + "index": [ + { + "title": "Basics", + "path": "basics", + "links": [ + { + "title": "Introduction to C++", + "path": "introduction" + }, + { + "title": "Fundamentals", + "path": "fundamentals" + }, + { + "title": "Tokens", + "path": "tokens" + }, + { + "title": "Data Types", + "path": "data-types" + }, + { + "title": "Variables", + "path": "variables" + }, + { + "title": "Constants", + "path": "constants" + }, + { + "title": "Operators", + "path": "operators" + }, + { + "title": "Strings", + "path": "strings" + } + ] + }, + { + "title": "Arrays", + "path": "arrays", + "links": [ + { + "title": "Arrays", + "path": "arrays" + } + ] + }, + { + "title": "Enumeration and Typedef", + "path": "enum-and-typedef", + "links": [ + { + "title": "Enumeration", + "path": "enum" + }, + { + "title": "Typedef", + "path": "typedef" + } + ] + }, + { + "title": "Control Statements", + "path": "control-statements", + "links": [ + { + "title": "Conditional Statements", + "path": "conditional-statements" + }, + { + "title": "Loops", + "path": "loops" + } + ] + }, + { + "title": "Functions", + "path": "functions", + "links": [ + { + "title": "Functions", + "path": "functions" + } + ] + }, + { + "title": "Pointers", + "path": "pointers", + "links": [ + { + "title": "Pointers", + "path": "pointers" + } + ] + }, + { + "title": "Structures", + "path": "structures", + "links": [ + { + "title": "Structures", + "path": "structures" + } + ] + }, + { + "title": "OOPS", + "path": "oops", + "links": [ + { + "title": "OOPS", + "path": "oops" + } + ] + } + ] +} \ No newline at end of file diff --git a/cpp/oops/oops.md b/cpp/oops/oops.md new file mode 100644 index 0000000..96ff892 --- /dev/null +++ b/cpp/oops/oops.md @@ -0,0 +1,184 @@ +C++ is a partial OOP language, though it supports Classes, objects, inheritance, encapsulation, abstraction, and polymorphism. As creation of class is optional and you can use global variables which violates encapsulation and you can use friend function in C++ which can access private and protected members of other classes, and hence C++ is not a pure OOP language. + +## What is OOP + +Object Oriented programming is a methodology based on objects instead of functions and procedures. OOP provides liberty to users to create objects as they want and create methods to handle the objects created. + +## OOP concepts + +## 1. Classes and objects + +Object is a basic unit in OOP, and is an instance of the class. + +Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. + +### How to create a Class + +`class` keyword is required to create a class. + +### Example + +```c +class mobile { + public: // access specifier which specifies that accessibility of class members + string name; // string variable (attribute) + int cost; // int variable (attribute) +}; // unlike fucntions class should always end with a semicolon + +``` +### How to create a Object + +```c +mobile m1; +``` +### How to define methods in a class + +You can define methods in class in two ways + +1. Declare and define inside the class + +```c +class mobile { + public: // access specifier which specifies that accessibility of class members + string name; // string variable (attribute) + int cost; // int variable (attribute) + void hello(){//method declaration and definition inside the class + cout<<"Hello world!!"; + } +}; + +``` +2. Declare inside the class and define it outside + +```c +class mobile { + public: // access specifier which specifies that accessibility of class members + string name; // string variable (attribute) + int cost; // int variable (attribute) + void hello(); //method declaration +}; + +void mobile::hello(){ //method definition + cout<<"Hello world!!"; +} +``` +## Constructors : +A constructor is a special type of member function which is called automatically when an object is created. +Example : +``` +class Mobile { + public: + // creating a constructor + Mobile() { + // code + } +}; +``` +## Types of Constructors : + +There are three types of Constructors : +### 1. Deafault Constructors : +A constructor with no parameters are called Deafault Constructors. The parameters will be supplied at the time of compilation. + +``` +class Mobile { + + public: + int price; + // creating a default constructor + Mobile()// see no parameters has been passed while creating default constuctors + { + price = 300; + } +}; +int main() +{ + Mobile m;// Mobile is the class-name and m is an object + cout<<"$"<