Blog

  • Numbers in C++

    Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types.

    Defining Numbers in C++

    You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++ −

    #include <iostream>
    using namespace std;
     
    int main () {
       // number definition:
       short  s;
       int    i;
       long   l;
       float  f;
       double d;
       
       // number assignments;
       s = 10;      
       i = 1000;    
       l = 1000000; 
       f = 230.47;  
       d = 30949.374;
       
       // number printing;
       cout << "short  s :" << s << endl;
       cout << "int    i :" << i << endl;
       cout << "long   l :" << l << endl;
       cout << "float  f :" << f << endl;
       cout << "double d :" << d << endl;
     
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    short  s :10
    int    i :1000
    long   l :1000000
    float  f :230.47
    double d :30949.4
    

    Math Operations in C++

    In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use.

    C++ has a rich set of mathematical operations, which can be performed on various numbers. Following table lists down some useful built-in mathematical functions available in C++.

    To utilize these functions you need to include the math header file <cmath>.

    Sr.NoFunction & Purpose
    1double cos(double);This function takes an angle (as a double) and returns the cosine.
    2double sin(double);This function takes an angle (as a double) and returns the sine.
    3double tan(double);This function takes an angle (as a double) and returns the tangent.
    4double log(double);This function takes a number and returns the natural log of that number.
    5double pow(double, double);The first is a number you wish to raise and the second is the power you wish to raise it t
    6double hypot(double, double);If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse.
    7double sqrt(double);You pass this function a number and it gives you the square root.
    8int abs(int);This function returns the absolute value of an integer that is passed to it.
    9double fabs(double);This function returns the absolute value of any decimal number passed to it.
    10double floor(double);Finds the integer which is less than or equal to the argument passed to it.

    Following is a simple example to show few of the mathematical operations −

    #include <iostream>
    #include <cmath>
    using namespace std;
     
    int main () {
       // number definition:
       short  s = 10;
       int    i = -1000;
       long   l = 100000;
       float  f = 230.47;
       double d = 200.374;
    
       // mathematical operations;
       cout << "sin(d) :" << sin(d) << endl;
       cout << "abs(i)  :" << abs(i) << endl;
       cout << "floor(d) :" << floor(d) << endl;
       cout << "sqrt(f) :" << sqrt(f) << endl;
       cout << "pow( d, 2) :" << pow(d, 2) << endl;
     
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    sign(d)     :-0.634939
    abs(i)      :1000
    floor(d)    :200
    sqrt(f)     :15.1812
    pow( d, 2 ) :40149.7
    

    Random Numbers in C++

    There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function.

    Following is a simple example to generate few random numbers. This example makes use of time() function to get the number of seconds on your system time, to randomly seed the rand() function −

    #include <iostream>
    #include <ctime>
    #include <cstdlib>
    
    using namespace std;
     
    int main () {
       int i,j;
     
       // set the seed
       srand( (unsigned)time( NULL ) );
    
       /* generate 10  random numbers. */
       for( i = 0; i < 10; i++ ) {
    
      // generate actual random number
      j = rand();
      cout &lt;&lt;" Random Number : " &lt;&lt; j &lt;&lt; endl;
    } return 0; }

    When the above code is compiled and executed, it produces the following result −

    Random Number : 1748144778
    Random Number : 630873888
    Random Number : 2134540646
    Random Number : 219404170
    Random Number : 902129458
    Random Number : 920445370
    Random Number : 1319072661
    Random Number : 257938873
    Random Number : 1256201101
    Random Number : 580322989
    
  • C++ Functions

    A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.

    You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is such that each function performs a specific task.

    A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function.

    The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.

    A function is known with various names like a method or a sub-routine or a procedure etc.

    Defining a Function

    The general form of a C++ function definition is as follows −

    return_type function_name( parameter list ) {
       body of the function
    }
    

    A C++ function definition consists of a function header and a function body. Here are all the parts of a function −

    • Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
    • Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
    • Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
    • Function Body − The function body contains a collection of statements that define what the function does.

    Example

    Following is the source code for a function called max(). This function takes two parameters num1 and num2 and return the biggest of both −

    // function returning the max between two numbers
     
    int max(int num1, int num2) {
       // local variable declaration
       int result;
     
       if (num1 > num2)
    
      result = num1;
    else
      result = num2;
    return result; }

    Function Declarations

    A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

    A function declaration has the following parts −

    return_type function_name( parameter list );
    

    For the above defined function max(), following is the function declaration −

    int max(int num1, int num2);
    

    Parameter names are not important in function declaration only their type is required, so following is also valid declaration −

    int max(int, int);
    

    Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

    Calling a Function

    While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.

    When a program calls a function, program control is transferred to the called function. A called function performs defined task and when it’s return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.

    To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example −

    #include <iostream>
    using namespace std;
     
    // function declaration
    int max(int num1, int num2);
     
    int main () {
       // local variable declaration:
       int a = 100;
       int b = 200;
       int ret;
     
       // calling a function to get max value.
       ret = max(a, b);
       cout << "Max value is : " << ret << endl;
     
       return 0;
    }
     
    // function returning the max between two numbers
    int max(int num1, int num2) {
       // local variable declaration
       int result;
     
       if (num1 > num2)
    
      result = num1;
    else
      result = num2;
    return result; }

    I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result −

    Max value is : 200
    

    Function Arguments

    If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

    The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

    While calling a function, there are two ways that arguments can be passed to a function −

    Sr.NoCall Type & Description
    1Call by ValueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
    2Call by PointerThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
    3Call by ReferenceThis method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

    By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

    Default Values for Parameters

    When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.

    This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider the following example −

    #include <iostream>
    using namespace std;
     
    int sum(int a, int b = 20) {
       int result;
       result = a + b;
      
       return (result);
    }
    int main () {
       // local variable declaration:
       int a = 100;
       int b = 200;
       int result;
     
       // calling a function to add the values.
       result = sum(a, b);
       cout << "Total value is :" << result << endl;
    
       // calling a function again as follows.
       result = sum(a);
       cout << "Total value is :" << result << endl;
     
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    Total value is :300
    Total value is :120
    
  • File Handling

    The concept of files in COBOL is different from that in C/C++. While learning the basics of ‘File’ in COBOL, the concepts of both languages should not be corelated. Simple text files cannot be used in COBOL, instead PS (Physical Sequential) and VSAM files are used. PS files will be discussed in this module.

    To understand file handling in COBOL, one must know the basic terms. These terms only serve to understand the fundamentals of file handling. Further in depth terminology would be discussed in the chapter ‘File Handling Verbs’. Following are the basic terms −

    • Field
    • Record
    • Physical Record
    • Logical Record
    • File

    The following example helps in understanding these terms −

    Program Structure

    Field

    Field is used to indicate the data stored about an element. It represents a single element as shown in the above example such as student id, name, marks, total marks, and percentage. The number of characters in any field is known as field size, for example, student name can have 10 characters. Fields can have the following attributes −

    • Primary keys are those fields that are unique to each record and are used to identify a particular record. For example, in students marks file, each student will be having a unique student id which forms the primary key.
    • Secondary keys are unique or non-unique fields that are used to search for related data. For example, in students marks file, full name of student can be used as secondary key when student id is not known.
    • Descriptors fields are used to describe an entity. For example, in students marks file, marks and percentage fields that add meaning to the record are known descriptors.

    Record

    Record is a collection of fields that is used to describe an entity. One or more fields together form a record. For example, in students marks file, student id, name, marks, total marks, and percentage form one record. The cumulative size of all the fields in a record is known as the record size. The records present in a file may be of fixed length or variable length.

    Physical Record

    Physical record is the information that exists on the external device. It is also known as a block.

    Logical Record

    Logical record is the information used by the program. In COBOL programs, only one record can be handled at any point of time and it is called as logical record.

    File

    File is a collection of related records. For example, the students marks file consists of records of all the students.

  • Table Processing

    Arrays in COBOL are known as tables. An array is a linear data structure and is a collection of individual data items of same type. Data items of a table are internally sorted.

    Table Declaration

    Table is declared in Data Division. Occurs clause is used to define a table. Occurs clause indicates the repetition of data name definition. It can be used only with level numbers starting from 02 to 49. Do not use occurs clause with Redefines. Description of one-dimensional and two-dimensional table is as follows −

    One-Dimensional Table

    In a one-dimensional table, occurs clause is used only once in declaration. WSTABLE is the group item that contains table. WS-B names the table elements that occur 10 times.

    Syntax

    Following is the syntax for defining a one-dimensional table −

    01 WS-TABLE.
       05 WS-A PIC A(10) OCCURS 10 TIMES.
    

    Example

    Live Demo

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-TABLE.
    
      05 WS-A PIC A(10) VALUE 'TUTORIALS' OCCURS 5 TIMES.     
    PROCEDURE DIVISION. DISPLAY "ONE-D TABLE : "WS-TABLE. STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    ONE-D TABLE : TUTORIALS TUTORIALS TUTORIALS TUTORIALS TUTORIALS
    

    Two-Dimensional Table

    A two-dimensional table is created with both data elements being variable length. For reference, go through the syntax and then try to analyze the table. The first array (WS-A) can occur from 1 to 10 times and the inner array (WS-C) can occur from 1 to 5 times. For each entry of WS-A, there will be corresponding 5 entries of WS-C.

    Syntax

    Following is the syntax for defining a two-dimensional table −

    01 WS-TABLE.
       05 WS-A OCCURS 10 TIMES.
    
      10 WS-B PIC A(10).
      10 WS-C OCCURS 5 TIMES.
         15 WS-D PIC X(6).

    Example

    Live Demo

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-TABLE.
    
      05 WS-A OCCURS 2 TIMES.
         10 WS-B PIC A(10) VALUE ' TUTORIALS'.
         10 WS-C OCCURS 2 TIMES.
            15 WS-D PIC X(6) VALUE ' POINT'.
    PROCEDURE DIVISION. DISPLAY "TWO-D TABLE : "WS-TABLE. STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    TWO-D TABLE :  TUTORIALS POINT POINT TUTORIALS POINT POINT
    

    Subscript

    Table individual elements can be accessed by using subscript. Subscript values can range from 1 to the number of times the table occurs. A subscript can be any positive number. It does not require any declaration in data division. It is automatically created with occurs clause.

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-TABLE.
    
      05 WS-A OCCURS 3 TIMES.
         10 WS-B PIC A(2).
         10 WS-C OCCURS 2 TIMES.
            15 WS-D PIC X(3).
    PROCEDURE DIVISION. MOVE '12ABCDEF34GHIJKL56MNOPQR' TO WS-TABLE. DISPLAY 'WS-TABLE : ' WS-TABLE. DISPLAY 'WS-A(1) : ' WS-A(1). DISPLAY 'WS-C(1,1) : ' WS-C(1,1). DISPLAY 'WS-C(1,2) : ' WS-C(1,2). DISPLAY 'WS-A(2) : ' WS-A(2). DISPLAY 'WS-C(2,1) : ' WS-C(2,1). DISPLAY 'WS-C(2,2) : ' WS-C(2,2). DISPLAY 'WS-A(3) : ' WS-A(3). DISPLAY 'WS-C(3,1) : ' WS-C(3,1). DISPLAY 'WS-C(3,2) : ' WS-C(3,2). STOP RUN.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    WS-TABLE  : 12ABCDEF34GHIJKL56MNOPQR
    WS-A(1)   : 12ABCDEF
    WS-C(1,1) : ABC
    WS-C(1,2) : DEF
    WS-A(2)   : 34GHIJKL
    WS-C(2,1) : GHI
    WS-C(2,2) : JKL
    WS-A(3)   : 56MNOPQR
    WS-C(3,1) : MNO
    WS-C(3,2) : PQR
    

    Index

    Table elements can also be accessed using index. An index is a displacement of element from the start of the table. An index is declared with Occurs clause using INDEXED BY clause. The value of index can be changed using SET statement and PERFORM Varying option.

    Syntax

    Following is the syntax for defining Index in a table −

    01 WS-TABLE.
       05 WS-A PIC A(10) OCCURS 10 TIMES INDEXED BY I.
    

    Example

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-TABLE.
    
      05 WS-A OCCURS 3 TIMES INDEXED BY I.
         10 WS-B PIC A(2).
         10 WS-C OCCURS 2 TIMES INDEXED BY J.
            15 WS-D PIC X(3).
    PROCEDURE DIVISION. MOVE '12ABCDEF34GHIJKL56MNOPQR' TO WS-TABLE. PERFORM A-PARA VARYING I FROM 1 BY 1 UNTIL I >3 STOP RUN. A-PARA. PERFORM C-PARA VARYING J FROM 1 BY 1 UNTIL J>2. C-PARA. DISPLAY WS-C(I,J).

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    ABC
    DEF
    GHI
    JKL
    MNO
    PQR
    

    Set Statement

    Set statement is used to change the index value. Set verb is used to initialize, increment, or decrement the index value. It is used with Search and Search All to locate elements in table.

    Syntax

    Following is the syntax for using a Set statement −

    SET I J TO positive-number
    SET I TO J
    SET I TO 5
    SET I J UP BY 1
    SET J DOWN BY 5
    

    Example

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-TABLE.
    
      05 WS-A OCCURS 3 TIMES INDEXED BY I.
         10 WS-B PIC A(2).
         10 WS-C OCCURS 2 TIMES INDEXED BY J.
            15 WS-D PIC X(3).
    PROCEDURE DIVISION. MOVE '12ABCDEF34GHIJKL56MNOPQR' TO WS-TABLE. SET I J TO 1. DISPLAY WS-C(I,J). SET I J UP BY 1. DISPLAY WS-C(I,J). STOP RUN.

    JCL to execute the above COBOL program.

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    ABC
    JKL
    

    Search

    Search is a linear search method, which is used to find elements inside the table. It can be performed on sorted as well as unsorted table. It is used only for tables declared by Index phrase. It starts with the initial value of index. If the searched element is not found, then the index is automatically incremented by 1 and it continues till the end of table.

    Example

    Live Demo

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-TABLE.
    
      05 WS-A PIC X(1) OCCURS 18 TIMES INDEXED BY I.
    01 WS-SRCH PIC A(1) VALUE 'M'. PROCEDURE DIVISION. MOVE 'ABCDEFGHIJKLMNOPQR' TO WS-TABLE. SET I TO 1. SEARCH WS-A
      AT END DISPLAY 'M NOT FOUND IN TABLE'
      WHEN WS-A(I) = WS-SRCH
      DISPLAY 'LETTER M FOUND IN TABLE'
    END-SEARCH. STOP RUN.

    JCL to execute the above COBOL program.

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    LETTER M FOUND IN TABLE
    

    Search All

    Search All is a binary search method, which is used to find elements inside the table. Table must be in sorted order for Search All option. The index does not require initialization. In binary search, the table is divided into two halves and it determines in which half the searched element is present. This process repeats till the element is found or the end is reached.

    Example

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO.
    
    DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-TABLE.
    
      05 WS-RECORD OCCURS 10 TIMES ASCENDING KEY IS WS-NUM INDEXED BY I.
      10 WS-NUM PIC 9(2).
      10 WS-NAME PIC A(3).
    PROCEDURE DIVISION. MOVE '12ABC56DEF34GHI78JKL93MNO11PQR' TO WS-TABLE. SEARCH ALL WS-RECORD
     AT END DISPLAY 'RECORD NOT FOUND'
     WHEN WS-NUM(I) = 93
     DISPLAY 'RECORD FOUND '
     DISPLAY WS-NUM(I)
     DISPLAY WS-NAME(I)
    END-SEARCH.

    JCL to execute the above COBOL program −

    //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
    //STEP1 EXEC PGM = HELLO

    When you compile and execute the above program, it produces the following result −

    RECORD FOUND 
    93
    MNO
    
  • C++ decision making statements

    Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

    Following is the general form of a typical decision making structure found in most of the programming languages −

    C++ decision making

    C++ programming language provides following types of decision making statements.

    Sr.NoStatement & Description
    1if statementAn ‘if’ statement consists of a boolean expression followed by one or more statements.
    2if…else statementAn ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the boolean expression is false.
    3switch statementA ‘switch’ statement allows a variable to be tested for equality against a list of values.
    4nested if statementsYou can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
    5nested switch statementsYou can use one ‘switch’ statement inside another ‘switch’ statement(s).

    The ? : Operator

    We have covered conditional operator “? :” in previous chapter which can be used to replace if…else statements. It has the following general form −

    Exp1 ? Exp2 : Exp3;
    

    Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

    The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

  • C++ Loop Types

    There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

    Programming languages provide various control structures that allow for more complicated execution paths.

    A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages −

    Loop Architecture

    C++ programming language provides the following type of loops to handle looping requirements.

    Sr.NoLoop Type & Description
    1while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
    2for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
    3do…while loopLike a ‘while’ statement, except that it tests the condition at the end of the loop body.
    4nested loopsYou can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.

    Loop Control Statements

    Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

    C++ supports the following control statements.

    Sr.NoControl Statement & Description
    1break statementTerminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
    2continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
    3goto statementTransfers control to the labeled statement. Though it is not advised to use goto statement in your program.

    The Infinite Loop

    A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless loop by leaving the conditional expression empty.

    #include <iostream>
    using namespace std;
     
    int main () {
       for( ; ; ) {
    
      printf("This loop will run forever.\n");
    } return 0; }

    When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop.

  • Operators in C++

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provide the following types of operators −

    • Arithmetic Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Assignment Operators
    • Misc Operators

    This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

    Arithmetic Operators

    There are following arithmetic operators supported by C++ language −

    Assume variable A holds 10 and variable B holds 20, then −

    OperatorDescriptionExample
    +Adds two operandsA + B will give 30
    Subtracts second operand from the firstA – B will give -10
    *Multiplies both operandsA * B will give 200
    /Divides numerator by de-numeratorB / A will give 2
    %Modulus Operator and remainder of after an integer divisionB % A will give 0
    ++Increment operator, increases integer value by oneA++ will give 11
    Decrement operator, decreases integer value by oneA– will give 9

    Relational Operators

    There are following relational operators supported by C++ language

    Assume variable A holds 10 and variable B holds 20, then −

    OperatorDescriptionExample
    ==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
    !=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
    >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
    <Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
    >=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
    <=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

    Logical Operators

    There are following logical operators supported by C++ language.

    Assume variable A holds 1 and variable B holds 0, then −

    OperatorDescriptionExample
    &&Called Logical AND operator. If both the operands are non-zero, then condition becomes true.(A && B) is false.
    ||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.(A || B) is true.
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.!(A && B) is true.

    Bitwise Operators

    Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −

    pqp & qp | qp ^ q
    00000
    01011
    11110
    10011

    Assume if A = 60; and B = 13; now in binary format they will be as follows −

    A = 0011 1100

    B = 0000 1101

    —————–

    A&B = 0000 1100

    A|B = 0011 1101

    A^B = 0011 0001

    ~A  = 1100 0011

    The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −

    OperatorDescriptionExample
    &Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12 which is 0000 1100
    |Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61 which is 0011 1101
    ^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
    ~Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.(~A ) will give -61 which is 1100 0011 in 2’s complement form due to a signed binary number.
    <<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
    >>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

    Assignment Operators

    There are following assignment operators supported by C++ language −

    OperatorDescriptionExample
    =Simple assignment operator, Assigns values from right side operands to left side operand.C = A + B will assign value of A + B into C
    +=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand.C += A is equivalent to C = C + A
    -=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand.C -= A is equivalent to C = C – A
    *=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand.C *= A is equivalent to C = C * A
    /=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand.C /= A is equivalent to C = C / A
    %=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand.C %= A is equivalent to C = C % A
    <<=Left shift AND assignment operator.C <<= 2 is same as C = C << 2
    >>=Right shift AND assignment operator.C >>= 2 is same as C = C >> 2
    &=Bitwise AND assignment operator.C &= 2 is same as C = C & 2
    ^=Bitwise exclusive OR and assignment operator.C ^= 2 is same as C = C ^ 2
    |=Bitwise inclusive OR and assignment operator.C |= 2 is same as C = C | 2

    Misc Operators

    The following table lists some other operators that C++ supports.

    Sr.NoOperator & Description
    1sizeofsizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and will return 4.
    2Condition ? X : YConditional operator (?). If Condition is true then it returns value of X otherwise returns value of Y.
    3,Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list.
    4. (dot) and -> (arrow)Member operators are used to reference individual members of classes, structures, and unions.
    5CastCasting operators convert one data type to another. For example, int(2.2000) would return 2.
    6&Pointer operator & returns the address of a variable. For example &a; will give actual address of the variable.
    7*Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

    Operators Precedence in C++

    Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

    For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

    Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    Category Operator Associativity 
    Postfix () [] -> . ++ – –  Left to right 
    Unary + – ! ~ ++ – – (type)* & sizeof Right to left 
    Multiplicative  * / % Left to right 
    Additive  + – Left to right 
    Shift  << >> Left to right 
    Relational  < <= > >= Left to right 
    Equality  == != Left to right 
    Bitwise AND Left to right 
    Bitwise XOR Left to right 
    Bitwise OR Left to right 
    Logical AND && Left to right 
    Logical OR || Left to right 
    Conditional ?: Right to left 
    Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left 
    Comma Left to right 
  • Storage Classes in C++

    A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program

    • auto
    • register
    • static
    • extern
    • mutable

    The auto Storage Class

    The auto storage class is the default storage class for all local variables.

    {
       int mount;
       auto int month;
    }
    

    The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables.

    The register Storage Class

    The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can’t have the unary ‘&’ operator applied to it (as it does not have a memory location).

    {
       register int  miles;
    }
    

    The register should only be used for variables that require quick access such as counters. It should also be noted that defining ‘register’ does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.

    The static Storage Class

    The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

    The static modifier may also be applied to global variables. When this is done, it causes that variable’s scope to be restricted to the file in which it is declared.

    In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.

    #include <iostream>
     
    // Function declaration
    void func(void);
     
    static int count = 10; /* Global variable */
     
    main() {
       while(count--) {
    
      func();
    } return 0; } // Function definition void func( void ) { static int i = 5; // local static variable i++; std::cout << "i is " << i ; std::cout << " and count is " << count << std::endl; }

    When the above code is compiled and executed, it produces the following result −

    i is 6 and count is 9
    i is 7 and count is 8
    i is 8 and count is 7
    i is 9 and count is 6
    i is 10 and count is 5
    i is 11 and count is 4
    i is 12 and count is 3
    i is 13 and count is 2
    i is 14 and count is 1
    i is 15 and count is 0
    

    The extern Storage Class

    The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use ‘extern’ the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.

    When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file.

    The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.

    First File: main.cpp

    #include <iostream>
    int count ;
    extern void write_extern();
     
    main() {
       count = 5;
       write_extern();
    }

    Second File: support.cpp

    #include <iostream>
    
    extern int count;
    
    void write_extern(void) {
       std::cout << "Count is " << count << std::endl;
    }
    

    Here, extern keyword is being used to declare count in another file. Now compile these two files as follows −

    $g++ main.cpp support.cpp -o write
    

    This will produce write executable program, try to execute write and check the result as follows −

    $./write
    5
    

    The mutable Storage Class

    The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override const member function. That is, a mutable member can be modified by a const member function.

  • C++ Modifier Types

    C++ allows the char, int, and double data types to have modifiers preceding them. A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of various situations.

    The data type modifiers are listed here −

    • signed
    • unsigned
    • long
    • short

    The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition, signed and unsigned can be applied to char, and long can be applied to double.

    The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example, unsigned long int.

    C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without int. It automatically implies int. For example, the following two statements both declare unsigned integer variables.

    unsigned x;
    unsigned int y;
    

    To understand the difference between the way signed and unsigned integer modifiers are interpreted by C++, you should run the following short program −

    #include <iostream>
    using namespace std;
     
    /* This program shows the difference between
       * signed and unsigned integers.
    */
    int main() {
       short int i;           // a signed short integer
       short unsigned int j;  // an unsigned short integer
    
       j = 50000;
    
       i = j;
       cout << i << " " << j;
    
       return 0;
    }

    When this program is run, following is the output −

    -15536 50000
    

    The above result is because the bit pattern that represents 50,000 as a short unsigned integer is interpreted as -15,536 by a short.

    Type Qualifiers in C++

    The type qualifiers provide additional information about the variables they precede.

    Sr.NoQualifier & Meaning
    1constObjects of type const cannot be changed by your program during execution.
    2volatileThe modifier volatile tells the compiler that a variable’s value may be changed in ways not explicitly specified by the program.
    3restrictA pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Only C99 adds a new type qualifier called restrict.
  • C++ Constants/Literals

    Constants refer to fixed values that the program may not alter and they are called literals.

    Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.

    Again, constants are treated just like regular variables except that their values cannot be modified after their definition.

    Integer Literals

    An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

    An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.

    Here are some examples of integer literals −

    212         // Legal
    215u        // Legal
    0xFeeL      // Legal
    078         // Illegal: 8 is not an octal digit
    032UU       // Illegal: cannot repeat a suffix
    

    Following are other examples of various types of Integer literals −

    85         // decimal
    0213       // octal
    0x4b       // hexadecimal
    30         // int
    30u        // unsigned int
    30l        // long
    30ul       // unsigned long
    

    Floating-point Literals

    A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.

    While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.

    Here are some examples of floating-point literals −

    3.14159       // Legal
    314159E-5L    // Legal
    510E          // Illegal: incomplete exponent
    210f          // Illegal: no decimal or exponent
    .e55          // Illegal: missing integer or fraction
    

    Boolean Literals

    There are two Boolean literals and they are part of standard C++ keywords −

    • A value of true representing true.
    • A value of false representing false.

    You should not consider the value of true equal to 1 and value of false equal to 0.

    Character Literals

    Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide character literal (e.g., L’x’) and should be stored in wchar_t type of variable . Otherwise, it is a narrow character literal (e.g., ‘x’) and can be stored in a simple variable of char type.

    A character literal can be a plain character (e.g., ‘x’), an escape sequence (e.g., ‘\t’), or a universal character (e.g., ‘\u02C0’).

    There are certain characters in C++ when they are preceded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes −

    Escape sequenceMeaning
    \\\ character
    \’‘ character
    \”” character
    \?? character
    \aAlert or bell
    \bBackspace
    \fForm feed
    \nNewline
    \rCarriage return
    \tHorizontal tab
    \vVertical tab
    \oooOctal number of one to three digits
    \xhh . . .Hexadecimal number of one or more digits

    Following is the example to show a few escape sequence characters −

    #include <iostream>
    using namespace std;
    
    int main() {
       cout << "Hello\tWorld\n\n";
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    Hello   World
    

    String Literals

    String literals are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.

    You can break a long line into multiple lines using string literals and separate them using whitespaces.

    Here are some examples of string literals. All the three forms are identical strings.

    "hello, dear"
    
    "hello, \
    
    dear"
    
    "hello, " "d" "ear"
    

    Defining Constants

    There are two simple ways in C++ to define constants −

    • Using #define preprocessor.
    • Using const keyword.

    The #define Preprocessor

    Following is the form to use #define preprocessor to define a constant −

    #define identifier value
    

    Following example explains it in detail −

    #include <iostream>
    using namespace std;
    
    #define LENGTH 10   
    #define WIDTH  5
    #define NEWLINE '\n'
    
    int main() {
       int area;  
       
       area = LENGTH * WIDTH;
       cout << area;
       cout << NEWLINE;
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    50
    

    The const Keyword

    You can use const prefix to declare constants with a specific type as follows −

    const type variable = value;
    

    Following example explains it in detail −

    #include <iostream>
    using namespace std;
    
    int main() {
       const int  LENGTH = 10;
       const int  WIDTH  = 5;
       const char NEWLINE = '\n';
       int area;  
       
       area = LENGTH * WIDTH;
       cout << area;
       cout << NEWLINE;
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    50
    

    Note that it is a good programming practice to define constants in CAPITALS.