Showing posts with label Cpp. Show all posts
Showing posts with label Cpp. Show all posts

Saturday, 30 December 2017

Bitwise Operators in C and C++ Programming Languages


Uses of Bitwise Operators and Why to Study Bitwise.

  1. Compression: Occasionally, you may want to implement a large number of Boolean variables, without using a lot of space. A 32-bit int can be used to store 32 Boolean variables. Normally, the minimum size for one Boolean variable is one byte. All types in C must have sizes that are multiples of bytes. However, only one bit is necessary to represent a Boolean value.
  2. Set operations: You can also use bits to represent elements of a (small) set. If a bit is 1, then element i is in the set, otherwise it's not. You can use bitwise AND to implement set intersection, bitwise OR to implement set union.
  3. Encryption: swapping the bits of a string for e.g. according to a predefined shared key will create an encrypted string.
& (bitwise AND): Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
 
| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
 
^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.

 << (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.

>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.

~ (bitwise NOT) Takes one number and inverts all bits of it

Following is example C program.


 

Following are interesting facts about bitwise operators.

  • The left shift and right shift operators should not be used for negative numbers The result of is undefined behabiour if any of the operands is a negative number. For example results of both -1 << 1 and 1 << -1 is undefined. Also, if the number is shifted more than the size of integer, the behaviour is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits. 
  •  The bitwise XOR operator is the most useful operator from technical interview perspective. It is used in many problems. A simple example could be “Given a set of numbers where all elements occur even number of times except one number, find the odd occurring number” This problem can be efficiently solved by just doing XOR of all numbers. For examples click here.
  •  The bitwise operators should not be used in place of logical operators. The result of logical operators (&&, || and !) is either 0 or 1, but bitwise operators return an integer value. Also, the logical operators consider any non-zero operand as 1. For example, consider the following program, the results of & and && are different for same operands. 
int main() 

 int x = 2, y = 5;
 (x & y)? printf("True ") : printf("False ");
 (x && y)? printf("True ") : printf("False ");
 return 0; 

Output: 
False True

    • The left-shift and right-shift operators are equivalent to multiplication and division by 2 respectively. As mentioned in point 1, it works only if numbers are positive. 
    int main() 
    { int x = 19; 
     printf ("x << 1 = %d\n", x << 1); 
    printf ("x >> 1 = %d\n", x >> 1);
    return 0;
    }

    Output:
    38 9

    • The & operator can be used to quickly check if a number is odd or even. The value of expression (x & 1) would be non-zero only if x is odd, otherwise the value would be zero.
    int main()
    {
    int x = 19;
    (x & 1)? printf("Odd"): printf("Even");
    return 0;
    }

    Output: Odd

    • <1 00001000="" b="" d="" is="" n="" printf="" result="" the=""><1 16="" b="">The ~ operator should be used carefully<1 00001000="" b="" d="" is="" n="" printf="" result="" the=""><1 16="" b="">. The result of ~ operator on a small number can be a big number if the result is stored in an unsigned variable. And result may be negative number if result is stored in signed variable (assuming that the negative numbers are stored in 2’s complement form where leftmost bit is the sign bit)
      <1 00001000="" b="" d="" is="" n="" printf="" result="" the=""><1 16="" b="">
    <1 00001000="" b="" d="" is="" n="" printf="" result="" the=""><1 16="" b=""> // Note that the output compiler dependent
    int main()
    {
    unsigned int x = 1;
    printf("SIgned %d \n", ~x);
    printf("Unsigned %ud \n", ~x);
    return 0;
    }


    Output:
    Signed Result -2
    Unsigned Result 24967294d */


    Interesting facts about Operator Precedence and Associativity in C Language

    Operator precedence decides which operator’s operation should be performed first in an expression with more than one operators with different precedence.

    For example 8+ 2 * 10 is calculated as 8 + (2 * 10) and not as (8 + 2) * 10.

    Associativity in C is used when two operators of same precedence present in an expression. Associativity can be either Left to Right or Right to Left.

    For example ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

    Precedence and Associativity are two characteristics of operators that determine the evaluation order of sub expressions in absence of brackets.
    • Associativity is used only when there are two or more operators of same precedence. Associativity doesn’t define the order in which operands of a single operator are evaluated. 
           For example associativity of the * operator is high so 2*3 performed first that 6+1 that is 7 assigned to a.          int a = 1+2*3;
    • All operators with same precedence have same associativity. This is necessary, otherwise there won’t be any way for compiler to decide evaluation order of expressions which have two operators of same precedence and different associativity. 
          For example + and – have same associativity.
    • Precedence and associativity of postfix ++ and prefix ++ are different
    • Precedence of postfix ++ is more than prefix ++, their associativity is also different. Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left. 
    Click here for more on Pre/post increments.
    • Comma has the least precedence among all operators and should be used carefully For example consider the following program, the output is 1.
    #include
    int main()
    {
    int a;
    a = 1, 2, 3; // Evaluated as (a = 1), 2, 3
    printf("%d", a);
    return 0;
    }


     Output:
    1

    Sunday, 24 December 2017

    Operators in C and C++

    Operators are the foundation of any programming language. Thus the functionality of C language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C, operators in Can be categorized in following categories:

    • Arithmetic Operators (+, -, *, /, %, post-increment, pre-increment, post-decrement, pre-decrement)
    • Relational Operators (==, != , >, <, >= & <=) Logical Operators (&&, || and !) 
    •  Bitwise Operators (&, |, ^, ~, >> and <<) • Assignment Operators (=, +=, -=, *=, etc) 
    • Other Operators (conditional, comma, sizeof, address, redirecton) 

    Arithmetic Operators: These are used to perform arithmetic/mathematical operations on operands.

    The binary operators falling in this category are:

    • Addition: The ‘+’ operator adds two operands. For example, x+y. 
    • Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y. 
    • Multiplication: The ‘*’ operator multiplies two operands. For example, x*y. 
    • Division: The ‘/’ operator divides the first operand by the second. For example, x/y. 
    • Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y. 
     The ones falling into the category of unary arithmetic operators are:

    Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x. And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++.

    Decrement: The ‘–‘ operator is used to decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, –x. And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x–.

    Relational Operators: 

    Relational operators are used for comparison of two values. Let’s see them one by one:

    •  ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 1==1 will return true. 
    • ‘!=’ operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 1!=1 will return false. 
    • ‘>’ operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 8>5 will return true.
    • ‘<‘ operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 8<5 operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false.
    • ‘>=’ operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.
    • ‘<=’ operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.


    Logical Operators:

    They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:

    Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero).

    Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.

    Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.

    Short-Circuiting in Logical Operators:


    In case of logical AND, the second operand is not evaluated if first operand is false. For example,  below doesn’t print “Geeks4Coding” as the first operand of logical AND itself is false.

    bool res = ((a == b) && printf("Geeks4Coding"));

    In case of logical OR, the second operand is not evaluated if first operand is true. For example,  below doesn’t print “Geeks4Coding” as the first operand of logical OR itself is true.

    int a=10, b=4;
    bool res = ((a != b) || printf("Geeks4Coding"));

    Constant in C/C++

    Constant is a variables or values in C programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants etc.

    Every constant has some range. The integers that is too big to fit into an int will be taken as a long. Now there are various ranges that differ from unsigned to signed bits. Under signed bit the range of an int, varies from -128 to +127 and under unsigned bit int varies from 0 to 255.

    Defining Constants

    In C program we can define constants in two ways as shown below:
    • Using #define preprocessor directive
    • Using a const keyword.
    Let us now learn about above two ways in details:

    Using #define preprocessor directive : This directive used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:

    #define VarName value

    where Varname is the name given to constant and value is any value assigned to it.

    Below is the C program to explain how to use #define to declare constants:

    #include<stdio.h>
    #define val 10
    #define floatVal 4.5
    #define charVal 'G'

    int main()
    {
    printf("Integer Constant: %d\n",val);
    printf("Floating point Constant: %f\n",floatVal);
    printf("Character Constant: %c\n",charVal);

    return 0;
    }

     

    Output:
     

    Integer Constant: 10
    Floating point Constant: 4.500000
    Character Constant: G

     

    Read Macros and Preprocessors directives in C.

     Using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword. Below program shows how to use const to declare costants of different data types:

    #include<stdio.h>
    int main()
    {
    const int intVal = 10; // int constant
    const float floatVal = 4.14; // Real constant
    const char charVal = 'A'; // char constant
    const char stringVal[10] = "ABC"; // string constant

    printf("Integer constant :%d \n", intVal );
    printf("Floating point constant : %f \n", floatVal );
    printf("Character constant : %c \n", charVal );
    printf("String constant : %s \n", stringVal);

    return 0;
    }

     

    Output:
     

    Integer constant :10
    Floating point constant : 4.140000
    Character constant : A
    String constant : ABC

     

    Learn about Const Qualifier in C.
     

    String Literals : When string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read only block (generally in data segment) that is shared among functions.
     

    char *str = "GfG";
     

    In the above line “GfG” is stored in a read only location, but pointer str is stored in a read-write memory. You can change str to point something else but cannot change value at present str. So this kind of string should only be used when we don’t want to modify string at a later stage in program.
     

    The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory.
     

    int main()
    {
    char *str;

    /* Stored in read only part of data segment */
    str = "GfG";

    /* Problem: trying to modify read only memory */
    *(str+1) = 'n';
    return 0;
    }


    Extern keyword in C / C++

    Keyword extern is used for declaring extern variables in c. This modifier is used with all data types like int, float, double, array, pointer, structure, function etc.

    Facts about extern keyword:

    1. It is default storage class of all global variables as well all functions.

    For example, Analyze following second.c code and its output:

    (a)

    #include <stdio.h>

    int a; //By default it is extern variable

    int main(){

    printf("%d",a);

    return 0;

    }


    Output: 0

    (b)

    #include <stdio.h>

    extern int a;//extern variable

    int main(){

    printf("%d",a);

    return 0;

    }


    Output: Compilation error, undefined symbol i.

    In Both program variable a is extern variable. Read second and third points for explaination.

    (c)
    #include <stdio.h>

    void add(int,int) //extern by default.

    int main(){

    int x=15,y=10;

    add(x,y);

    return 0;

    }


    void sum(int x,int y){

    printf("%d”",x+y);

    }

    Output: 25

    1. When we use extern with any variables it is only declaration that is memory is not allocated for that variable. Hence in second case compiler is showing error unknown symbol a. To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables. For example:

    #include <stdio.h>

    extern int a=1000; //extern variable

    int main(){

    printf("%d",a);

    return 0;

    }


    Output: 1000

    3. If you will not use extern keyword with global variables then compiler will automatically initialize with default value to extern variable.

    4. Default initial value of extern integral type variable is zero otherwise null. For example:

    #include <stdio.h>

    char c;

    int i;

    float f;

    char *str;

    int main(){

    printf("%d %d %f %s",c,i,f,str);

    return 0;

    }


    Output: 0 0 0.000000 (null)

    5. We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally. For example:

    (a)

    #include <stdio.h>

    int main(){

    extern int i=10; //Try to initialize extern variable

    //locally.

    printf("%d",i);

    return 0;

    }

    Output: Compilation error: Cannot initialize extern variable.

    (b)

    #include <stdio.h>

    int main(){

    extern int i; //Declaration of extern variable i.

    int i=10; //Try to locally initialization of

    //extern variable i.

    printf("%d",i);

    return 0;

    }


    Output: Compilation error: Multiple declaration of variable i.

    6. If we declare any variable as extern variable then it searches that variable either it has been initialized or not. If it has been initialized which may be either extern or static* then it is ok otherwise compiler will show an error. For example:

    (a)

    #include <stdio.h>

    int main(){

    extern int i; //It will search the initialization of

    //variable i.

    printf("%d",i);

    return 0;

    }

    int i=20; //Initialization of variable i.
    Output: 20

    (b)

    #include <stdio.h>

    int main(){

    extern int i; //It will search the any initialized

    //variable i which may be static or

    //extern.

    printf("%d",i);

    return 0;

    }

    extern int i=20; //Initialization of extern variable i.


    Output: 20

    (c)

    #include <stdio.h>

    int main(){

    extern int i; //It will search the any initialized

    //variable i which may be static or

    //extern.

    printf("%d",i);

    return 0;

    }

    static int i=20; //Initialization of static variable i.

    Output: 20

    (d)

    #include <stdio.h>

    int main(){

    extern int i; //variable i has declared but not

    //initialized

    printf("%d",i);

    return 0;

    }


    Output: Compilation error: Unknown symbol i.


    7. A particular extern variable can be declared many times but we can initialize at only one time. For example:

    (a)

    extern int i; //Declaring the variable i.

    int i=25; //Initializing the variable.

    extern int i; //Again declaring the variable i.

    #include


    int main(){

    extern int i; //Again declaring the variable i.

    printf("%d",i);

    return 0;

    }


    Output: 25


    (b)

    extern int i; //Declaring the variable

    int i=25; //Initializing the variable

    #include


    int main(){

    printf("%d",i);

    return 0;

    }

    int i=20; //Initializing the variable

    Output: Compilation error: Multiple initialization variable i.

    8. We cannot write any assignment statement globally. For example:

    #include <stdio.h>

    extern int i;

    int i=10; //Initialization statement

    i=25; //Assignment statement

    int main(){

    printf("%d",i);

    return 0;

    }

    Output: Compilation error

    Note: Assigning any value to the variable at the time of declaration is known as initialization while assigning any value to variable not at the time of declaration is known assignment.

    (b)

    #include <stdio.h>

    extern int i;

    int main(){

    i=25; //Assignment statement

    printf("%d",i);

    return 0;

    }


    int i=10; //Initialization statement

    Output: 25

    9. If declared an extern variables or function globally then its visibility will whole the program which may contain one file or many files. For example consider a c program which has written in two files named as first.c and second.c:

    (a)
    //first.c
    #include


    int i=25; //By default extern variable

    int j=5; //By default extern variable

    /**

    Above two line is initialization of variable i and j.

    */

    void main(){

    clrscr();

    sum();

    getch();

    }




    //second.c

    #include


    extern int i; //Declaration of variable i.

    extern int j; //Declaration of variable j.

    void sum(){

    int s;

    s=i+j;

    printf("%d",s);

    }


    Compile and execute above two file first.c and second.c at the same time:


    Saturday, 23 December 2017

    Variables in C


    A variable in simple terms is a storage place which has some memory allocated to it. So basically a variable used to store some form of data. Different types of variables require different amounts of memory and have some specific set of operations which can be applied on them.

    Variable Declaration:


    A typical variable declaration is of the form:

    data type variable_name;

    for multiple variables declaration
    data type vr1_name, var2_name, var3_name;

    A variable name can consist of alphabets (both upper and lower case), numbers and the underscore ‘_’ character. However, the name must not start with a number.

    Variable declaration and definition

    Variable declaration refers to the part where a variable is first declared or introduced before its first use. Variable definition is the part where the variable is assigned a memory location and a value. Most of the times, variable declaration and definition are done together.

    #include <stdio.h>
    //extern int c;
    int main()
    {
    char a = 'a'; // declaration and definition of variable 'a123'

    float b;// This is also both declaration &definition/assigned garbage value.

    printf("%c \n", a,c);

    return 0;
    }

     

    Keyword extern is explained here.

    Lvalues and Rvalues in C


    There are two kinds of expressions in C:
     

    Lvalue 

    Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.
     

    Rvalue 

    The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.
     

    Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −
     

    int g = 20; // valid statement

    10 = 20; // invalid statement; would generate compile-time error


    Basic Syntax of C Program

    A C program basically consists of the following parts −
    • Preprocessor Commands
    • Functions
    • Variables
    • Keywords
    • Statements & Expressions
    • Comments
    Let us take a look at the various parts of the above program

    #include <stdio.h>

    int main() {
    /* multline comment */
    printf("Hello, World! \n");//single line comment

    return 0;
    }
     

    Preprocessor Commands

    #include is a preprocessor command, which tells a C compiler to include stdio.h file from standard library and there won’t be any line with # symbol in object file after compilation, it will get replace by content of stdio.h header file. Learn more about Preprocessor directives. 
     

    Functions

    Main() is the function which tell compiler where to start and there should be only one main() function and printf(),scanf() function are used to print on screen and take input from user.  

    Learn more about Functions

    Variables

    A variable in simple terms is a storage place which has some memory allocated to it. So basically a variable used to store some form of data. Different types of variables require different amounts of memory and have some specific set of operations which can be applied on them.

    Keywords

    Keywords are specific reserved words in C each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the C language are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one!
     

    There are a total of 32 keywords in C:  
    auto             break         case            char            const            continue
    default         do              double          else            enum            extern
    float             for             goto              if               int                  long
    register       return        short             signed        sizeof            static
    struct           switch       typedef        union         unsigned        void
    volatile       while
     
    Learn More about Keywords and Variables 
     

    Expressions and Statements

    An expression represents a single data item--usually a number. The expression may consist of a single entity, such as a constant or variable, or it may consist of some combination of such entities, interconnected by one or more operators. Expressions can also represent logical conditions which are either true or false. However, in C, the conditions true and false are represented by the integer values 1 and 0, respectively

    A statement causes the computer to carry out some definite action. There are three different classes of statements in C: expression statements, compound statements, and control statements.
    An expression statement consists of an expression followed by a semicolon. The execution of such a statement causes the associated expression to be evaluated. For example:
     

    a = 6;
    c = a + b;
    ++j;

     

    The first two expression statements both cause the value of the expression on the right of the equal sign to be assigned to the variable on the left. The third expression statement causes the value of j to be incremented by 1. Again, there is no restriction on the length of an expression statement: such a statement can even be split over many lines, so long as its end is signaled by a semicolon.
     

    A compound statement consists of several individual statements enclosed within a pair of braces { }. The individual statements may themselves be expression statements, compound statements, or control statements. Unlike expression statements, compound statements do not end with semicolons. A typical compound statement is shown below:
     

    {
    pi = 3.141593;
    circumference = 2. * pi * radius;
    area = pi * radius * radius;
    }

     

    This particular compound statement consists of three expression statements, but acts like a single entity in the program in which it appears.

    Comments

    Comments are non-executable code used to provide documentation to programmer. Single Line Comment is used to comment out just Single Line in the Code. It is used to provide One Liner Description of line.

     Compiling And Linking    



     C systems generally consist of several parts: a program development environment, the language and the C Standard Library. C programs typically go through six phases to be executed. These are: edit, preprocess, compile, link, load and execute.
     


    Creating a Program


    Edit a file. This is accomplished with an editor program. Software packages for the C/C++ integrated program development environments such as Eclipse, Codeblock and Microsoft Visual Studio have editors that are integrated into the programming environment. 

    You type a C program with the editor, make corrections if necessary, and then store the program on a secondary storage device such as a hard disk. C program file names should end with the .c extension or save it directly.

    Preprocessing and Compiling a C Program


    Here you give the command to compile the program. The compiler translates the C program into machine language-code (also referred to as object code). In a C system, a preprocessor program executes automatically before the compiler’s translation phase begins.

    The C preprocessor obeys special commands called preprocessor directives, which indicate that certain manipulations are to be performed on the program before compilation. These manipulations usually consist of including other files in the file to be compiled and performing various text replacements. The most common preprocessor directives will discussed soon.
      
    The compiler translates the C program into machine-language code. A syntax error occurs when the compiler cannot recognize a statement because it violates the rules of the language. The compiler issues an error message to help you locate and fix the incorrect statement. The C Standard does not specify the wording for error messages issued by the compiler, so the error messages you see on your system may differ from those on other systems. Syntax errors are also called compile errors, or compile-time errors.

    Source codes in C are saved with .C file extension. Header files or library files have the .H file extension. Every time a program source code is successfully compiled, it creates an .OBJ object file, and an executable .EXE file.




    Linking


    The next phase is called linking. C programs typically contain references to functions defined elsewhere, such as in the standard libraries or in the private libraries of groups of programmers working on a particular project. The object code produced by the C compiler typically contains “holes” due to these missing parts. A linker links the object code with the code for the missing functions to produce an executable image (with no missing pieces). Compile and link a program If the program compiles and links correctly, a file called .out is produced.

    Loading


    The next phase is called loading. Before a program can be executed, the program must first be placed in memory. This is done by the loader, which takes the executable image from disk and transfers it to memory. Additional components from shared libraries that support the program are also loaded.

    Execution


    Finally, the computer, under the control of its CPU, executes the program one instruction at a time. To load and execute the program on a Linux system, type ./a.out at the Linux prompt and press Enter.

    Geeks4Coding

    Contributors

    Popular Posts