LEARN C++ (BASICS)
Introduction
Syntax
The following code is written in C++
We shall look at each element of the following code in detail to understand the syntax of C++
#include <iostream>: This is a header file library. <iostream> stands for standard input-output stream. It allows us to include objects such as cin and cout, cerr etc.
using namespace std: Means that names for objects and variables can be used from the standard library. It is also used as additional information to differentiate similar functions.
int main(): The function main is called just as in C. Any code inside its curly brackets {} will be executed.
cout: is an object used to print a particular text after << in quotes. In our example it will output "Hello World". (for personal reference we can say it is similar to printf in c)
return 0: Terminates the function main
Note:
- Every C++ statement ends with a semicolon ';'
- Compiler ignores white spaces. Multiple line spaces are used to make the code more readable.
Omitting Name spaces:
C++ programs run without the standard namespace library. This can be done by writing std keyword followed by :: operator inside int main()
Example:
Output
Using the cout object
As discussed earlier the cout object, together with the << operator, is used to output values/print text.
You can add as many cout objects as you want. However, note that it does not insert a new line at the end of the of each object all of them will be printed in a single line.
Example:
Output:
New Lines
In order to insert a new line after each object declaration \n is used. Or another way to do so is using end1 manipulator
Output:
Note: \n is the preferred way to break lines.
User Input
As we have already discussed earlier cin is used to get user input. This is paired along with the extraction operator (>>)
The following example reads a value from the user and prints it on the screen.
Example:
Fundamentals of c++
Comments
Comments are used by the programmer to make the code understandable so that it can be improvised later and to make it more readable. It can also be used to prevent execution when testing alternative code.
There are two ways to write Comments: singled-lined or multi-lined.
Single line comments
Single-line comments are initiated with two forward slashes (//). This comments the entire line after the two slashes.
Example:
Output:
Multi Line comments
Multi-line comments start with /* and ends with */
The text in between both of these will not be executed by the compiler. Hence comments can we written in multiple lines
Example:
Variables & Identifiers
Just as in C, there are different types of variables defined with some specific keywords. Variables are defined as 'a data item that may take on more than one value during the run time of a program'. Variable has to be of a specified data type.
int: Stores all kinds of integers e.g. 12, 873
double: Stores floating point numbers which are decimals e.g. 12.3, 16.1
char: Stores single letters, or we can say characters of a string e.g. 'G', 'g'
string: Collection of characters makes a string. These are written in double quotes e.g."Demo Code"
bool: Stored values are either true or false. Shorthand for 'Boolean'.
How to declare a Variable?
Just as in C, we need to mention it's data type followed by the variable and equate it to it's value. However assigning a value to the variable is not necessary.
Syntax:Example:
double num=5;
Note: The value of the variable can be overwritten by declaring the variable again later in the code. In order to make the value of variable fixed and avoid over-writting's possibility the const keyword is used.
C++ Identifiers
Identifiers are the names of functions, variables, structures etc. (the elements we define) used to identify them.
All c++ identifiers must be identified with unique names.
Examples include x,y as well as age, num etc.
Note: Using informative identifiers such as num, age are suggested to increase readability of code.
Rules for constructing identifier names:
- Can consist of letters, digits and underscores
- Must begin with a letter or an underscore
- These are case sensitive
- Whitespaces or special characters like !, #, %, etc. Are not allowed
- Reserved words such as int or cout cannot be used as names
Data types
We already introduced data types earlier in the variables section.
Here is an example of a code with all the data types used for revision purpose.
Space each data type occupies
Int - 4 bytes
Float - 4 bytes
Double - 8 bytes
Char - 1 byte
Bool – 1 byte
Note: Since string is a collection of characters it occupies the space equivalent to that of the addition of the space occupied by each character in that string.
What is the difference between float and Double?
Both of them differ in their size. Float occupies 4 bytes however double occupies 8 bytes. This implies they also differ in the precision they provide. The precision of float is only six decimal digits, while double variables have a precision of about 15 digits. Hence it is safer to use double unless you are concerned about how much memory is being occupied.
Operators
Operators are used in C++ to perform desired operations on particular values or variables.
C++ operators are classified into the following categories:
. Arithmetic operators
. Assignment operators
. Relational operators
. Logical operators
. Bitwise operators
The order of priority given to these operators are:
Assignment > Arithmetic > Relational > Logical > Bitwise
Arithmetic Operators:
Assignment Operators
These are used to assign values to variables. Often the short hand properties are used to simplify the code.
Relational Operators
These are used to compare to values. These return values as either true (1) or false (0)
Bitwise Operator
Steps to performing Bitwise Operation
1-Convert the numbers into Binary
2-Perform Operation
3-Convert answer into Decimal
For left shift multiply the number by 2 for right shift divide the number by 2
Strings
Strings are a collection of characters joint together. They are defined within double quotes. In order to include strings in C++ it is necessary to declare an additional header file <string>.
Syntax:Example:
Note: A string in C++ is actually an object, which contain functions that can perform certain operations on strings.
String Length
The length of a string is found using the length() function
Example:
Access Characters of a string
We know that a string is an array of characters. Hence a particular character of a string can be accessed by the index number inside the square brackets[ ]. These signify the position of the character.
Example:Output:
Alter string characters
Index numbers inside square brackets can be used to change string character.
Example:
Output:
Input a string from a User
Example:
Output:
Note: The cin function will only read a single word and the not multiple words. Hence only the first word will be displayed.
String Concatenation
'+' operator is used to add string together.
Example:
Output:
Results of Concatenation
Number + Number = Number
String + String = String
Number + String = Error
Math and Booleans
Find Maximum and Minimum of two numbers
The max(x,y) and min(x,y) can be used to find the highest and lowest values, respectively of x and y.
Examples:
For max(x,y)
Output:
Example:
For min(x,y)
Output:
Note : In order to introduce other math functions we need to include <cmath> header file
sqrt() : Finds the square root of a number
round() : rounds a number
log() : Finds the logarithm of the number.
Example:
Output:
Some other important functions included are sin() , cos() , tan() , exp() , pow() and many more including most trigonometric functions.
Boolean Expressions:
These give values as either yes or no, on or off, true or false.
Bool datatype as mentioned earlier gives these values.
Output :
If---Else
The conditional statement keywords:
Use if to execute the code block if the the condition is true
Use else to execute the code block, if the same condition is false
Use else if to execute a new condition to test, if the previous condition is false
What can the different conditions be?
Less than: a<b
Less than or equal to: a<=b
Greater than: a>b
Greater than or equal to: a>=b
Equal to a==b
Not Equal to: a!=b
The following is an if.. else example
Example:
The following is an else if..example
Example:
Ternary Operator:
If only one condition/statement is to be executed the conditional operator(ternary operator) can be used instead.
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Left side of the semicolon will be executed if statement is true else if it is false right side will be executed.
Example :Output:
Loops
There are three kinds of loops; while, do while and for. These are used to repeat a particular code of block multiple times until the condition satisfies.
While loop
syntax
The following loop runs till 5 after i=6 the loop's condition becomes false and it no longer works.
Example:
output:
The Do while Loop
This loop will execute the code block once before checking if the condition is true, then for the second time it will repeat the loop as long as the condition is true. Hence the condition is tested after execution
Syntax
Example
For Loop
This is the most used loop
Syntax
Example:
Switch
Switch statement is used to select one of many code blocks to be executed. This can be used as an substitute for if.. else statements and vica-versa.
Syntax
What happens? The variable's value is compared with that of each case. Whichever case matches the value, that code block is executed.
Important Keywords
break: it breaks out of the switch block so that all the codes of other cases aren't executed.
default: This sets a standard code, which is executed if none of the other cases are executed.
Example:
Output:
Break and Continue
Break: We already discussed about one of the use of this statment earlier.The break statement can also be used to jump out of a loop.
Output
Continue: The continue statement breaks one time repetition of the loop if a specified condition occurs and continues with the next iteration in the loop.
Example
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i <= 10; i++) {
if (i == 6) {
continue;
}
cout << i << "\n";
}
return 0;
}
Output
Array
Arrays follow contiguous memory allocation ( a classical memory allocation model that assigns a process consecutive memory block ). They are used to store multiple values in a single variable.
Value in the square bracket specifies the number of elements in the array.
Way to Define a array.
For strings
For number
Access the elements of a array
Elements of a array are accessed by referring to the index numbers.
Example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fruits[3] = {"Banana", "Mango", "Apple"};
cout << fruits[0];
return 0;
}
Change an array element
This is also done by referring to index numbers
Example:
Loops and Arrays
Array elements can be looped.
Example:
}
return 0;
} [/code]
Output:
Note: Array's size doesn't have to be defined inside the square bracket. But if it is not defined it will only be as big as the elements that are inserted into it.
In the following code 3 is the arrays maximum size. However if the size is specified the array will occupy that much space even if space is left empty.
Example:
Pointers and references
References
The & operator is used to create references. References are like alias of a variable. i.e you can refer same variable via the reference variable.
Example:
Now either 'subject or study can be used to refer to the subject variable. Hence value of it which is maths can be got by any of these two methods.
Example:
Output:
Memory Address
When a variable is created in C++, it occupies some memory and hence it is allocated a particular location, where it is stored. & is used to get the memory address of a variable; which is the location of where the variable is stored.
Example :
Outpot :
Note:The location is in hexadecimal form. The location of storage will vary every time and so the display of output will show different values.
Creating Pointers:
A pointer is a variable that stores the memory address as its value.
The pointer is created using *. It points to an address of the same datatype variable. The address is then assigned to the pointer.
Example:
Output:
Note
* Does two different things in the code:
When used in declaration (string* p), it creates a pointer variable and points to an address.
When not used in declaration, it act as a operator which gives the value at a given address.
Functions
Functions
The purpose of creating a function is so that a block of code can be executed multiple times when a function is called.
Data known as parameters is passed into the function.
The function main() is predefined and is mandatory in program. However there are other functions which are user defined.
How to create a function?
Syntax:
Note: Void means the function doesn't have a return value
Function Calling
To call a function we are to write the function's name followed by brackets () and a semicolon;
Example:
Note: The function can be called multiple times and that's what makes it useful.
Example
Output:
Note: If a user-defined function as in the above example is declared after the main() function the code will throw an error. It is because C++ works from top to bottom in a sequential flow.
Hence another way of writing the function, if the function is written below main() is :
Example:
Function Parameters
Data can be passed to a function as a parameter. These are variables inside of functions. These are specified withing the brackets with their datatypes.
Syntax:
In the following example Honey is an argument , however name is a parameter
Example:
Outpot :
Return Values
In the following example the keyword return is used. Using int instead of void helps us to derive a return value. However as discussed earlier void doesn't return a value.
Example:
Call by Reference
You can also pass a reference to the function by using pointers of such as in the following example:
Output:
Function Overloading
This property is special to C++. Using Function overloading multiple functions can have the same name with different parameters.
Example:
Output:
Note: It is better to over load one function instead of defining two functions to do the same thing. Remember multiple functions can have the same name until their datatype or parameters differ.
C++ Class
Classes/Objects
What is object oriented programming?
This consists of creating objects that contain data and functions. This is different from procedural programming that performs operations on data sequentially. Classes and objects are two main aspects of object oriented programming.
Example:
Class: Fruits
Objects: Apple, Mango, Cherry
Another aspect of this programming is attributes (e.g. Color and size) and methods (e.g. Break and speed) of various objects.
Create a Class
To create a class we use the keyword class.
In the following example the class keyword is used to create a class. Public is the access specifier (In detail later in this module). The variables declared within the class Num and Name_string are attributes. At last use of a semicolon is mandatory.
Example:
Create a object
An object is created from a class
The syntax includes creating an object of Name_class specify the class name, followed by the object name.
We can access the class attributes using (.) on the object
Example:
Output:
Class Methods
Methods are functions that belongs to the class.
Functions can be defined inside of class or outside it. You can access methods exactly the same way you access classes by using (.)
Inside Class Definition
Example:Outside Class Definition
Example:
Note: As in functions parameters can be here as well
Access Specifiers
The public keyword that occurs in all our class examples is our access specifier. Access specifiers defines the accessibility of classes, methods, and other members.
There are three kinds of access specifiers in C++
- Public : members can be accessed (or viewed) from outside the class
- Private : members cannot be accessed (or viewed) from outside the class
- Protected : members cannot be accessed from outside the class, however, they can be accessed in inherited classes. (We can define inherited classes as those which inherit attributes and methods from one class to another.)
We have already looked at examples of public. We will look at the private access specifier with an example:
Example:
outpot:
error
Class Constructors
This is a special method. Called once an object of a class is created. In order to create a constructor use the same name as the class, followed by brackets ().
Example:output:
Note: Just like regular functions constructors can also take parameters which can be used for initialising values for attributes.
Note: Constructors can be defined outside the class however it has a different syntax.
Steps:
1-Declare the constructor inside the class
2-Define it outside of the class by mentioning the name of the class
3-Use :: operator, followed by the name of the class
Example:
Output:
Class Destructor
Class Destructor as it's name suggests is a function which deletes an object.
A destructor function is called when
(1) Function ends
(2) Program ends
(3) Block consisting of local variables ends
(4) Delete operator is called
Destructors have same name as the class only with a tilde (~)
Destructors do not allow parameters and only one destructor in a class.
Example:Class Inheritance
As mentioned earlier, inheritance is handy in understanding the role of the 'protected' access specifier. It is possible to inherit attributes and methods from one class to another.
There are two important terms for it's description:
Derived class : Inherited from another class
Base class: Class being inherited from
This can be understood better from the parent child analogy. Parents are the ones passing on their characteristics to us and we inherit them. Hence Derived class is the child and Base class the parent.
We use the colon (:) symbol to inherit from a class
Example:Multi-level Inheritance:
A class can also be derived from a class, which is already derived from another class.
Example
Output:
Multiple Inheritance
Class derived from multiple base class, using a comma separated list
Example:
Output:
NOTES
even if you sit and read this 10 times you cant do anything with it you have to start coding
how should i use this guide
1 hour every day each day one part first understand the thing and then copy the code
run it and make another verison yourself without any help when you fully understand the thing
move to the next part
dont go over 1 hour of work each day
have nice day.
credit : learn.onlinegdb.com
This guide was created by its original author on the Steam Community. Are you the author and want it removed? Request removal.