Ad

C++ Basics

C++ Basics

C++ IMPORTANT POINTS

Basics:

  • The data entered by the keyboard is stored in buffer.
  • endl flushes the buffer whereas \n simply puts a new line.
  • Basic rules for naming are same as in C.
  • SOME OF THE MAIN DATA TYPES ARE AS FOLLOWS:
  • The variables declared outside a function are known as global variables and the default values of these variables is 0 (or 0.000000 in case of float).
  • The default value of local variables is garbage value.
  • We can write (float) before any variable/ constant to denote that the variable/ constant is a float variable/ constant.
            e.g. area = (float) 22/7 * r * r;
  • We can write f after any float constant to denote that the constant is a float constant.
  • This is done to prevent confusion of constant between float constant and double constant.
            e.g. area = 3.1425f * r * r;
  • Compound assignment statements are faster than normal statements.
            e.g. sum = sum + a; normal statement
            sum + = a; compound assignment statement

  • When the value is more than the capacity, it will take the value again from the beginning. This is known as Overflow in C++.
            e.g. char c ;
            Here, variable c can store values from -128 to +127, but if a value entered is greater than 127 then it will again go back to -128. It just acts like a loop. If we have a char variable x and x contains (ASCII) value 127. and the operation carried out by us is x++, then that means we are adding 1 to 127, but the limit is 127 itself, then it will go to the beginning i.e. -128. Let us understand by Binary value. The Binary value of 127 is 01111111.

  • BITWISE OPERATORS:
        Types of bitwise operators are as follows:

    • &           (  AND  )

                    Truth Table:
    • |             (   OR   )

                    Truth Table:

    • ^            (  X-OR  )

    
                Truth Table:

    • ~            (  NOT  )
                    It is a unary operator as well as a bitwise operator
                    Truth Table:

    • <<          (  LEFT-SHIFT  )
                    Formula for calculation of x<<i is: -             x*2i
                    

                    Truth Table:

    • >>          (  RIGHT-SHIFT  )
                    Formula for calculation of x>>i is: -                   

                    Truth Table:

NOTE: - In left shift and right shift, sign bit is not included. If the number is negative, it remains negative only and if the number is positive, it remains positive only.


  • FOR EACH LOOP
            e.g.:

            1.                 int a[ ] = { 1,2,3,4,5,6 };

                                for( int x:a )

                                      cout<< x <<endl;



            OUTPUT:         1

                                    2

                                    3

                                    4

                                    5

                                    6

             In this for each loop, x is a variable for a. Through this for loop, it will be iterating in the whole array and each value will be stored in x every time.


            2.                 int a[ 6 ] = { 1,2,3 };

                                for( int x:a )

                                    cout<< x <<endl;



            OUTPUT:         1

                                    2

                                    3

                                    0

                                    0

                                    0

            for-each loop works according to the size of the array, i.e. it will traverse till the last index.

            The for-each loop is introduced in C++ 11.


            3.                 float a[ ] = { 2.5f,5.6f,5,8,7 };

                                for( int x:a )

                                    cout<< x <<endl;
    


            OUTPUT:         2

                                    5

                                    5

                                    8

                                    7

            In this for each loop, as x is an integer variable, hence it is truncating the values of the array a.


            4.                 float a[ ] = { 2.5f,5.6f,5,8,7 };

                                for( float x:a )

                                        cout<< x <<endl;



            OUTPUT:         2.5

                                    5.6

                                    5

                                    8

                                    7


            5.                 float a[ ] = { 2.5f,5.6f,5,8,7 };

                                for( auto x:a )

                                    cout<< x <<endl;



            OUTPUT:         2.5

                                    5.6

                                    5

                                    8

                                    7


            6.                 char a[ ] = { ‘A’ , 66 , ’C’ , 68 };

                                for( auto x:a )

                                    cout<< x <<endl;



            OUTPUT:         A

                                    B

                                    C

                                    D


            7.                 char a[ ] = { ‘A’ , 66 , ’C’ , 68 };

                                for( int x:a )

                                    cout<< x <<endl;



            OUTPUT:         65
                        
                                    66

                                    67

                                    68


  • for-each loop is used for collection of elements example, array.

        Benefit of for-each loop is, size of the array does not need to be known.

        SYNTAX:

                            for( data_type variable_name : array_name )

                            {

                                    cout<< variable_name;

                            }

        If the value of x is changed, it does not affect the original value in the array.

        If we want the value in x to be changed and the change should be reflected in the array, the syntax should be as follows:

                                for( data_type &variable_name : array_name )

                                {    

                                        cout<< variable_name;

                                }

        In this case, reference is added in the name of the variable, so every change done in the variable will be reflected in the array.


  • Using for-each loop for 2D Arrays:

        SYNTAX:

                            for( auto & variable_row_name : array_name )

                            {

                                    for( auto & variable_cloumn_name : variable_row_name)

                                    {

                                                cout<< y <<” ”;

                                    }

                                    cout<< endl ;

                            }

        e.g.

                            int arr[2][3]={ 1, 2, 3, 4, 5, 6 }

                            for( auto &x : arr )

                            {

                                    for( auto &y : x )

                                    {

                                                cout<< y <<” ”;

                                    }

                                    cout<< endl ;

                            }


        Output:               1 2 3

                                    4 5 6

NOTE: if you miss & before row variable or column variable an error will be prompted.


Linear search time complexity: - O(n)                (as it traverses through the whole array)
Binary search time complexity: - O(log(n))        (as its comparisons are minimum)
Hence Binary search is faster.



  • Pointers:

        A pointer is an address variable.

        An address variable stores the address instead of the data, hence the pointer variable will store the address of another variable.

        Declaration of pointer variable:

                        int *p;

        Initialization of pointer variable:

                        p = &var_name ;

        Here, var_name is the variable whose address is being stored in the pointer variable.

        Accessing the data where p is pointing is known as dereferencing.

        Dereferencing of pointer variable:

                        cout<< *p ;


  • HEAP MEMORY

        Heap memory is allocated and accessed dynamically, hence size of the memory required in the heap is decided at runtime.

        Difference between when memory is allocated in heap vs stack


        1. Here, int A[5] ={ 1,2,3,4,5 } is a normal array.

            But to create/allocate memory in heap, we can try the following method:

                    int *p;

                    p=new int[5];

            or

                    int p=new int[5];

            Then, memory is allocated for an array in the heap.

        2. Array or any variable when created inside the stack, gets deleted automatically when it goes outside the scope, whereas array or other memory created inside heap remains in the heap throughout the program, so we have t deallocate the memory by ourselves in the following way:

                    delete p; // for pointer variable

                    delete [ ]p; // for pointer array

                    p=NULL;

            Memory Leak

            If we assign p as NULL before deleting the memory then it is known as memory leak as after assigning p as NULL, p is not pointing towards the memory and the memory address is lost and there is no way for accessing the same address again.

            NULL pointer

            When a pointer is not pointing anywhere, it is known as NULL pointer.

            The array pointer can be modified as follows:

            p[2]=100;

            p[0]=1;

            p[3]=2;

            p[4]=0;

In modern C++, instead of using NULL for pointers, we can use nullptr as it is a built-in literal meant only for pointers.


Once an array is created in a program, it’s size cannot be modified.

Here, size of array A cannot be changed.


Here, size of the array can be changed. Basically, it deletes the old memory and reallocates the new memory with the required size. So, we won’t be able to access the elements of the array with the old size as that memory is deleted.



There are total 5 operations allowed using pointer:

    1. p++

        The pointer will move towards the next location i.e. 202.

    2. p--

        The pointer will backwards of the current memory location. If it was on 202, it will move to 200.

        p++;                      // now p points back to 202

    3. p=p+n

        e.g. p=p+2

        When we say p=p+2, then p moves 2 elements forward.
    4. p=p-n

        e.g. p=p-2

        When we say p=p-2, then p moves 2 elements backward.

        
        Pointer p pointing at A[0] and pointer q pointing at A[3] and diff is a normal integer variable.

    5. Diff=p-q

        Now, the above example will give us the difference between the location two pointers.

        E.g. in the above array if we do p-q, we get 3. This shows that pointer p is 3            elements away from pointer q.


These are the following way to print an element of the array:

1. Arr [ i ]

2. i [ Arr ]

3. * ( Arr + i )

4. *( p + i ) // here p is a pointer to array…. *p= Arr

5. p [ i ] // here p is a pointer to array…. *p= Arr


These are the following way to print the addresses of the elements of the array:

1. &( Arr [ i ] )

2. &( i [ Arr ] )

3. Arr + i

4. p + i // here p is a pointer to array…. *p= Arr

5. &( p [ i ] ) // here p is a pointer to array…. *p= Arr


Problems using Pointers

1. Un-initialized pointers

In this case, the pointer is not pointing anywhere, hence it has a garbage address which may or may not belong to our program. Hence it is an invalid address.

Solution:

Point it to some memory:

        a.      p = & x ;

        b.      p = ( int * )0x5638 ;

        c.      p = new int [ 5 ] ;


2
.     Memory Leak


Solution:

Delete the memory before making the pointer Null


3.      Dangling Pointer

Here pointer p is passed to function fun which is stored in pointer q. Then function fun deleted the memory of pointer Q due to which the memory of pointer p is also deleted and after the function finishes its run, there will be a runtime error at cout statement as p is not pointing at any address/memory now.


  • Reference

When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.

                    #include<iostream>

                    using namespace std;

                    int main()

                    {

                                int x = 10;

                                // ref is a reference to x.

                                int& ref = x;

                                // Value of x is now changed to 20

                                ref = 20;

                                cout << "x = " << x << endl ;

                                // Value of x is now changed to 30

                                x = 30;

                                cout << "ref = " << ref << endl ;


                                return 0;

                    }



Output:               x      =   20

                           ref   =   30


In line a=x , x is on right hand side so we call it as rvalue and in second line x=25 , x is on left hand side so we call it as lvalue.

Rvalue means right hand side, i.e. here whatever is stored in x has to be stored in a.

In the above example, 12 will be stored in a. Rvalue is a data/literal.

Lvalue means right hand side, i.e. here the x is giving the location, i.e. we want 25 to be stored in the location of x, so 25 will be stored at location 200/201.


A reference doesn't consume any memory at all.

Once we have initialized the variable as a reference then we cannot use it as a nickname for any other variable.


Function Pointer or Pointer to a function:


Syntax of Declaration of Function pointer or Pointer to a function:

            Return_type *(pointer_name) (argument_list)

            e.g.

                        int add ( int x, int y)

                        {

                                    int sum=x+y ;

                                    return sum ;

                        }

                        int main( )

                        {

                                    int (*ptr)(int,int);          // declaration of a function pointer

                                    ptr = add;                   //definition of a function pointer

                                    (*ptr)(3,4);                 //calling of a function pointer


                        }


                        void display ( )

                        {

                                    cout<<” HELLO ! ” ;

                        }

                        int main( )

                        {

                                    int (*ptr)( );                      // declaration of a function pointer

                                    ptr = display;                   //definition of a function pointer

                                    (*ptr)();                          //calling of a function pointer

                    }


                    int max ( int x, int y)

                    {

                                    return ( ( x > y ) ? x : y ) ;

                    }

                    int min ( int x, int y)

                    {

                                    return ( ( x < y ) ? x : y ) ;

                    }



                    int main( )

                    {

                                    int (*ptr)(int,int);               // declaration of a function pointer

                                    ptr = max ;                      //definition of a function pointer

                                    (*ptr)(3,4);                      //calling of a function pointer

                                    // here when we write (*ptr)(3,4) , then max function is called

                                    ptr = min ;                      //definition of a function pointer

                                    (*ptr)(3,4);                      //calling of a function pointer

                                    // here when we write (*ptr)(3,4) , then min function is called

                    }

  • In the above example, we are doing different operations with same pointer.
  • In function overriding, internally, Function Pointers are used for achieving runtime polymorphism.
  • One Function Pointer can point on any function which is having same signature (return type and argument list).

FUNCTIONS

1. Function is a piece of program code which performs a specific task maybe a small task but performs it completely.

2. It takes some input as parameters and returns a result as return value.

3. Functions are useful for procedural or modular Programming.

4. If we write a function, we can use it multiple times in our program as well as in other programs and it can be shared with other programmers too.

5. The collection of functions, we call it as a library. In C and, C++ we have many built-in functions in their libraries. We commonly use them to make our programming easy.

6. Every C++ function must have a main function.

Monolithic Programming

It is also known as the imperative programming paradigm. In this programming paradigm, the whole program is written in a single block. We use the goto statement to jump from one statement to another statement. It uses all data as global data which leads to data insecurity.

e.g. If we have a main function which contains 10,000 lines of code, without any other function, then this style of programming is called as Monolithic Programming.

If we write the programs using Monolithic Programming then we may face the following problems:

1. If there’s an error in a single line, then there’s an error in an entire program.

2. Memorising the whole program: Big codes/programs would require ample amount of time and during this time, the programmer should remember everything so as to add more codes to the program.

3. Work cannot be distributed in the team: It’s only job of a single person as the task cannot be divided parts as there is only 1 function called main( ) function.

4. If the codes become very big, it may fit in some computer’s memory and may not fit in some computer’s memory. It depends on the size and the hardware constitution of the computer on which you are running the program.


So, what we prefer is, breaking the program into multiple units.

More will be uploaded soon...

0 Response to "C++ Basics "

Post a Comment

If you have any doubts, please let me know...

Ads Atas Artikel

Ads Center 1

Ads Center 2

Ads Center 3