Skip to content

hkc1226/LearningCpp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 

Repository files navigation

LearningCpp :

Introduction to C++ programming:

  • C++ is developed by Bjarne Stroustrup as an extension to C language.

  • It is a cross-platform and object-oriented programming language.

  • It is used to create high-performance applications.

  • It provides high-level of control over system resources and memory.

Main differences between C++ & C:

  • C++ :

    • Supports both procedural & object-oriented programming.

    • Encapsulate both Data & Functions together as an object.

    • Supports both Built-in & User-defined data types.

    • Object driven language beacause of OOPs.

    • Namespace features are present in C++ programming to avoid name collisions.

    • Standard IO header is #include <iostream.h> or #include <iostream>.

  • C :

    • Supports procedural programming but not OOPs.

    • Data & Functions are separated because of procedural programming.

    • Supports only Built-in data types but not User-defined data types.

    • Function driven language because it is procedural programming.

    • Namespace features are not present in C-programming.

    • Standard IO header is #include <stdio.h> or #include <stdio>.

    Learn more about differences between C++ & C.

Minimal requirements to run a C++ code:

Requirements:

  • A C++ compiler installed on your system to compile C++ code into machine readable format. Most widely used C++ compilers are:

    • GNU Compiler Collection (GCC): download here

    • Clang

    • Microsoft Visual C++ Compiler (For Microsoft VS code user)

  • A Text-editor or an Integrated Development Environment (IDE).

    • Text-editor : Notepad++, Sublime text, Atom.

    • IDE : Turbo C/C++, Visual Studio Code, Code::Blocks, Eclipse, Xcode.

Follow the steps to run your code:

After complete installation of an IDE and a text-editor.

  • Write your code in the text-editor and save it with .cpp / .cc / .cxx / .c++ extension.

  • Once .cpp file is saved, open any terminal or command prompt.

  • Navigate to the folder where .cpp files are saved.

  • Now Compile and Run with the following command:

    • To Build / Compile : Write command g++ -o filename filename.cpp or g++ -std=c++11 filename.cpp -o filename in command line and Hit Enter.

      command to compile cpp code

          // To compile / build C++ code.
          >> g++ -o filename filename.cpp
                          OR
          >> g++ -std=c++11 demo.cpp -o demo
      
    • To Run : Write given command below in command line and Hit Enter.

      command to run cpp code

          // To run C++ code.
          >> filename.exe // In window cmd prompt.
                          OR
          >> ./filename // In VS Code terminal
      

Life cycle of C++ code:

  • Life cycle of C++ code involves the following steps:

    • Creating source code and save source code with some filename followed by appropriate extension. such as .cpp, .c++, .cc or .cxx.

    • Compile the code.

    • On successful compilation of source code, it will create an object file with extension .obj.

    • Then the object file is linked with required liberary for the proper execution of code.

    • After that an executable file is created with the name filename.exe.

    • Now the code is ready for execution.

    flows-of-cpp-code

Basic Structure of C++ programming:

  • Here is the basic structure of C++ code.

    Basic Structure of Cpp

        // Basic structure of C++ code.
    
        #include <iostream>
    
        using namespace std;
    
        int main() {
          // Code goes here
          return 0;
        }
    

Explanation:

  • Line 1: This is a single line comment, not executable by compiler.

  • Line 3: consists of a Preprocessor Directives & Header File Liberary.

    • Preprocessor directives: #include, #define etc.

      • It instructs the compiler and processed before code compilation. It starts with hash ( # ) character.

      • #include: Used to include header file liberary.

        Preprocessor directive > include

            #include <iostream>
            #include <cmath>
            #include <string>
        
      • #define: Used for defining constant or macros.

        img1

            // Defining constant.
            // Syntax:
            #define constName constVal
        

        img2

            // Defining Macros.
            // Syntax:
            #define MACRO_NAME(parameters) macro_body
        
            // Example:
            #define SQUARE(x) ((x)*(x))
        
    • Header file liberary: <iostream>, <cmath>, <ctime>, <fstream>, <string> etc.

      • Each header file liberary offers a wide range of functionalities to use within the C++ code.

      • <iostream> : Provides facilities for performing input and output operations.

        1. It defines several classes and objects that allow you to work with input streams ( std::cin ) and output streams ( std::cout, std::cerr, std::clog ).

        2. Provides escape characters like ( std::endl, std::ends )

      • <cmath> : Provides a collection of mathematical functions.

        1. Trigonometric functions: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), sinh(x), cosh(x), tanh(x) etc.

        2. Exponential & Logarithmic Functions: exp(x), log(x), log10(x), log2(x), pow(x, y) etc.

        3. Square root and Absolute functions: sqrt(x), fabs(x)

        4. Rounding functions: ceil(x), floor(x), round(x) etc.

      • <ctime> : Provides functionality for working with date and time information.

      • <string> : Defines the string class and related functions for string manipulation.

        #include <string>
        

        1. String declaration and initialization:

        std::string str1 = "Hello World!";
        

        2. Strings concatenation:

        std::string str1 = "Hrishikesh ";
        std::string str2 = "Kumar";
        std::string result = str1 + str2;
        
        // Output:
        Hrishikesh Kumar
        

        3. Accessing character from string:

        std::string str1 = "Hrishikesh";
        char i_th_char = str[i];
        char j_th_char = str[j];
        

        4. String manipulation:

        • Finding substrings:

          // find index position of first matched character.
          
          std::string str1 = "hrishikesh";
          size_t k_pos = str1.find("k");
          std::cout << k_pos;
          
        • Erasing substrings:

          // erase 3 characters starting from index-3.
          
          std::string str1 = "hrishikesh";
          std::cout << str1.erase(3,3);
          
        • Replacing substrings:

          // replace 3 characters starting from index-3 by "Kumar".
          
          std::string str1 = "hrishikesh";
          std::cout << str1.replace(3,3,"Kumar");
          

        5. String conversion:

        • String to Integer: ( stoi(str) )

          // convert string into integer value.
          
          std::string str1 = "5";
          int num = std::stoi(str1);
          std::cout << "String to int: " << num ;
          
        • String to Float: ( stof(str) )

          // convert string into float value.
          
          std::string str1 = "5.755";
          float num = std::stof(str1);
          std::cout << "String to float: " << num ;
          
        • Integer/Float to String: ( to_string(int_num/float_num) )

          // convert integer into string.
          // convert int/float into string.
          
          float num1 = 56.3;
          int num2 = 435;
          std::string str1 = std::to_string(num1);
          std::string str2 = std::to_string(num2);
          std::cout << "float to string: " << str1 << std::endl;
          std::cout << "int to string: " << str2;
          

      NOTE : Never terminates the header files with semicolon ( ; )

  • Line 5: using namespace std; It includes namespace standard liberary to prevent naming conflicts.

    • Used to organize code into logical groups.

    • Allows to remove prefix std:: from every standard liberary functions.

    • When we use using namespace std; directives. Then -

      • std::cout can be written as cout.

      • std::cin can be written as cin.

      • std::endl can be written as endl etc.

  • Line 7: int main() It is the main() function that we'll see in every C++ code.

    • Actually code execution begins inside main() function.

    • main() function must have a return type of int.

  • Line 7 col-12: ( { ) : Begins the main() function body.

  • Line 8: Spaces for function body to be written here enclosed within curly braces ( { // function body } ).

  • Line 9: return 0; Terminates the code execution inside main() function.

  • Line 10 col-1 : ( } ) : Ends the main() function body.

Some standard liberary objects:

  • cout :

    • Used with ( << ) to write/print output values/text on console/display.

    • By default cout does not insert any new line automatically after the completion of cout statement(s).

    • Use newline-character ( \n ) or endl to jump to new line.

      cout-example

        #include <iostream>
      
        using namespace std;
        int main(){
          cout<<"hello world";
          cout<<"This is first cpp programm.";
          return 0;
        }
      
        /* =============================== */
        /*              Output:            */
        /* =============================== */
        hello worldThis is first cpp programm.
      
  • cin :

    • Used with ( >> ) to Reads data from the keyboard or other input devices.

    • It automatically adds newline-character ( \n ) after reading the input data(s).

    • cin considers white-space as terminating character.

      cin-example

    • To retain white-space, use getline() method.

          // Syntax:
          getline(cin, stringName);
      
          // instead of `cin >> stringName;`
      
    • e.g:-

      getline-example

    [NOTE :]

    1. ( >> ) : known as Stream extraction operator or simply Extraction operator.

    2. ( << ) : known as Stream insertion operator or simply Insertion operator.

  • endl : Terminate the current line and jump into a new-line.

    • e.g:-

      endl-example

        #include <iostream>
      
        using namespace std;
        int main(){
          cout<<"hello world"<<endl;
          cout<<"This is first cpp programm.";
          return 0;
        }
      
        /* =============================== */
        /*              Output:            */
        /* =============================== */
        hello world
        This is first cpp programm.
      

Escape Sequence:

  • newline character (\n) : Terminate the current line and jump into a new-line.

  • tabspace character (\t) : Insert a tabspace (that is equivalent to 4-space character) between current-line and new-line or within a line.

  • backslash character (\\) : Insert a backslash character.

  • double quote character (\") : Insert a double quote character.

    • e.g:-

      2-esc-seq

          #include <iostream>
      
          using namespace std;
      
          int main(){
            cout<<"1. New-line character.\n";
            cout<<"2. tab-space\tcharacter."<<endl;
            cout<<"3. backslash\\character.\n";
            cout<<"4. \"double quote\"";
            return 0;
          }
      
          /* ================================= */
          /*             Output:               */
          /* ================================= */
          1. New-line character.
          2. tab-space	character.
          3. backslash\character.
          4. "double quote"
      

Comment style in Cpp :

  • There are two ways to write comment in Cpp.

    comment-style

      // This is single line comment.
    
      /*
      This
      is
      multiline
      comment.
      */
    

Variable Declaration:

  • Variables: Variables in C++ are like containers to store data values.

  • Variables declaration: There can be couple of ways to declare a variable in C++.

    • Assign value to variable while declaring it.

      var-dec-1

          // Syntax:
          dataType varName = value;
      
          // Example:
          int num = 24;
          float n = 2.34;
          char character = 'H';
          string str = "Hrishikesh";
      
    • Declaring varible and assigning it later.

      var-dec-2

          // Syntax:
          dataType varName;
          varName = value;
      
          // Example:
          float n;
          string str;
          n = 2.01;
          str = "C++";
      
    • Declaring more than one variable of same type in a single statement.

      var-dec-3

          // Syntax:
          dataType var1 = val1, var2 = val2, ..., varN = valN;
      
          // Example:
          int a = 12, b = 43, c = 23;
          string fname = "Hrishikesh", lname = "Kumar";
      
    • Declaring variables and then assigning it later.

      var-dec-4

          // Syntax:
          dataType var1, var2, ..., varN;
          var1 = val1, var2 = val2, ..., varN = valN;
          // If multiple variables have same value.
          var1 = var2 = ... = value
      
          // Example:
          int a, b, c, d, e, f;
          a = 12, b = 43, c = 23;
          d = e = f = 101;
      

NOTE : If a variable is assigned with new value, its earlier value will be overwritten if any.

Constant Declaration:

  • A value is declared as constant which is not likely to be changed further in the code.

  • A constant declaration must follow the rules to avoid any occurance of errors in following cases:

    • must be assigned during its declaration.

    • should not be re-assigned after its declaration.

      incorrect-const-dec

  • It is declared using const keyword in C++.

    const-dec

        // Syntax:
        const dataType varName = value;
    
        // Example:
        const float PI = 3.1428;
        const int daysPerWeek = 7;
    

Identifiers:

  • Identifiers are actually used to name variables. There are some important rules to follow while creating an identifier/variable.

    • It must contains only letters, digits and underscores ( _ ).
    • It must start with either letter or underscore but not digit.
    • Identifiers are case-sensitive.
    • White-space(s) are not allowed in identifier.
    • Special characters (!, @, #, $, %...etc.) are not allowed except underscore ( _ ).
    • Reserved keyword in Cpp are not allowed to be used as an identifier.

Data types in C++:

Primitive data types:

  • Various primitive data types that are supported in C++ are:

    • bool ( 1 byte ) : Only two values: true = 1, false = 0.

    • char ( 1 byte ) : can be assined with only one character within single quote : like 'e'.

    • int ( 2 or 4 bytes ) : stores only non-decimal numbers with smaller range.

    • float ( 4 bytes ) : stores only decimal numbers with smaller range.

    • double ( 8 bytes ) : stores only decimal numbers with larger range.

    • string ( 32 bytes ) : stores sequence of characters within double quotes ( " " ) and Not built-in type, but behaves like one.

Decimal number precision:

  • It sets the number of digits after decimal ( . ).

    • float : 6 or 7 digits.

    • double : 15 digits.

Qualifiers:

  • Qualifiers in C++ are used to manipulate the size (or range) and/or sign or behaviour of the primitive data types. such as int, float, double.

    • Qualifiers that are used to manipulate the sizes of data types:

      • short ( 2 bytes ) : stores only non-decimal numbers with smaller range than int generally.

      • long ( 4 bytes ) : stores only non-decimal numbers with larger range than int.

      • long long ( 8 bytes ) : stores only non-decimal numbers with larger range than long.

      • double long ( 16 bytes ) : stores only decimal numbers with larger range.

    • Qualifiers that are used to manipulate the sign of data types:

      • signed ( 4 bytes ) : Stores both positive and negative values.

      • unsigned ( 4 bytes ) : Stores only positive values.

    • Qualifiers that are used to manipulate the behaviour of data types:

      • const : It restricts the re-assigning new values to the variable prefixed with const keyword. Any modification results in an errors.

Operators in C++ :

  • Operators are used to perform specific operations on operand(s) (variable(s) or value(s)).

  • There are typically three types of operators:

    • Unary operators: Unary operators operates on single operands.
      • Increment ( ++ )
      • Decrement ( -- )
      • Logical operator ( ! )
      • Bitwise operator ( ~ )
    • Binary operators: Binary operators operates on two operands.
      • Arithmatic operators ( +, -, *, /, % )
      • Assignment operators ( =, +=, -=, *=, /=, %= )
      • Relational or Comparison operator ( ==, !=, >, <, >=, <= )
      • Logical operator ( &&, || )
      • Bitwise operator ( &, |, ^, <<, >> )
    • Ternary operators: Ternary operators involves three operands or expressions or components.
      • Conditional/Ternary operator ( condition ? exp1 : exp2 )

Arithmatic operators:

  • Arithmatic operators are binary operators that are used to perform mathematical operations on operands. Various arithmatic operators are:

    • Addition ( + ) : used to adds two or more numbers.

    • Subtraction ( - ) : used to find difference between two numbers.

    • Multiplication ( * ) : used to find product of two or more numbers.

    • Division ( / ) : used to divide a number by another number.

    • Modulus ( % ) : used to find remainder when a number is divided by another number.

Assignment operators:

  • Assignment operators are also type of binary operators which is shorter way to use arithmatic operators.

  • Assign updated value to left operand by performing some mathematical task on itself.

Simple assignment :

  • Assignment ( = ) : used to assign the value of right operand to the left operand.

Compound assignment :

  • Addition assignment ( += ) : used to update value of left operand by adding value of right operand to the initial value of left operand.

  • Subtraction assignment ( -= ) : used to update value of left operand by subtracting value of right operand from the initial value of left operand.

  • Multiplication assignment ( *= ) : used to update value of left operand by multiplying value of right operand with initial value of left operand.

  • Division assignment ( /= ) : used to update value of left operand after dividing left operand by right operand.

  • Modulus assignment ( %= ) : It stores the remainder to left operand when number itself (value of left operand) is divided by right operand.

  • Bitwise-AND assignment ( &= )

  • Bitwise-OR assignment ( |= )

  • Bitwise-XOR assignment ( ^= )

  • Right-Shift assignment ( >>= )

  • Left-Shift assignment ( <<= )

Unary operators:

  • Increment ( ++ ) : It is used to update the value of operand by adding value 1 to its initial value.
  • Decrement ( -- ) : It is used to update the value of operand by subtracting value 1 from its initial value.

[NOTE:] Both these operator can be used in two ways:

1. post-increment or post-decrement.
2. pre-increment or pre-decrement.

Learn more

Relational/Comparision operators:

  • Relational operators are also binary operators used to compare two values and determine the relationship between them.

  • It returns a boolean value ( 0 or 1 ) based on the comparison result.

  • Different types of relational operators are:

    • Is Equal to ( == ) : Checks if the values of two operands are equal.

      • Returns 1 if values are equal.

      • Returns 0 if values are not equal.

    • Not Equal to ( != ) : Checks if the values of two operands are not equal.

      • Returns 1 if values are not equal.

      • Returns 0 if values are equal.

    • Greater than ( > ) : Checks if the value of the left operand is greater than the value of the right operand.

      • Returns 1 if left operand > right operand.

      • Returns 0 if left operand < right operand.

    • Less than ( < ) : Checks if the value of the left operand is less than the value of the right operand.

      • Returns 1 if left operand < right operand.

      • Returns 0 if left operand > right operand.

    • Greater than or Equal to ( >= ) : Checks if the value of the left operand is greater than or equal to the value of the right operand.

      • Returns 1 if left operand >= right operand.

      • Returns 0 if left operand < right operand.

    • Less than or Equal to ( >= ) : Checks if the value of the left operand is less than or equal to the value of the right operand.

      • Returns 1 if left operand <= right operand.

      • Returns 0 if left operand > right operand.

Logical operators:

  • Logical operators are used to perform logical operations on boolean values or expressions.

  • It returns boolean value ( 1 or 0 ) as result after evaluating the expression.

  • There are three types of logical operation in C++ :

    • Logical AND ( && ) : Checks if all the boolean values and/or relational expressions are true.

      • Returns 1 : if all the boolean values and/or expressions are true.

      • Returns 0 : if atleast one boolean value or expression are false.

      [NOTE:]
      As early as the expression encounters a false value or condition, it stops further evaluation of the expression and return 0.

    • Logical OR ( || ) : Checks if atleast one boolean values or relational expressions are true.

      • Returns 1 : if atleast one boolean value or relational expression are true.

      • Returns 0 : if all the boolean values and/or relational expressions are false.

      [NOTE:]
      As early as the expression encounters a true value or condition, it stops further evaluation of the expression and return 1.

    • Logical NOT ( ! ) : It is used to negate the value of its operand.

      • Returns 1 : if the value of operand is false.

      • Returns 0 : if the value of operand is true.

      [NOTE:]
      The logical NOT operator is often used in conditional statements, loops, and boolean expressions to modify the logical state of expressions.

Bitwise operators:

  • It performs bit-level specific operations on integral operands (integer data types).

  • These operators manipulate individual bits of integers directly.

  • Firstly, it converts the operands into binary numbar (that is in form of 0 & 1). then perform bitwise operation on each bits.

  • There are various types of bitwise operators:

    • Bitwise AND ( & ) : Sets each bit to 1 if corresponding bits of each operands are 1, otherwise sets it to 0.

      &

    • Bitwise OR ( | ) : Sets each bit to 1 if either of the corresponding bits of operands is/are 1, otherwise sets it to 0.

      |

    • Bitwise XOR ( ^ ) : Sets each bit to 1 if only one of the two corresponding bits of the operands is 1, otherwise sets it to 0.

      xor

    • Bitwise NOT ( ~ ) : It reverse each bits of an operand from 1 to 0 and vice-versa.

      ~

    • Right Shift ( >> ) : Shifts the bits of the left operand to the right by a number of positions specified by the right operand. Vacated bits are filled with zeros.

      >>

    • Left Shift ( << ) : Shifts the bits of the left operand to the left by a number of positions specified by the right operand. Vacated bits are filled with zeros.

      <<

Ternary or Conditional operators:

  • It is a unique operator in programming languages that operands on three operands.

  • It is oftenly used as shorthand for if-else conditional statement.

  • It is also known as Conditioinal operators.

  • Syntex:

    conditinal-operator-syntax

            // Syntax : Conditional Operator
    
            condition ? expression1 : expression2
    
  • Working of conditional operators ( ? : ) - It takes three operands as given:

    1. condition : It is a test condition to evaluate result on the basis of which conditional statement will produce the result either expression1 or expression2.

    2. expression1 : This expression will be executed only if the condition is true.

    3. expression2 : This expression will be executed only if the condition is false.

  • Example : conditional-operator-example

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published