C++ Output Formatting

Formatting output plays an important role and it makes the output easy to read and understand. C++ provides several input / output manipulators. There are two types of I / O manipulators: setw() and setprecision(). To use these manipulations, you must include the header file iomanip.h

#include < iomanip.h >

C++ Setw() Manipulator

The setw() manipulator set the width of the specified area for the output.It takes the size of the field as a parameter.For example, the code :

    cout<< setw(6) << "P";
    Output :- _ _ _ _ _ P

    cout<< setw(8) << 22;
    Output :- _ _ _ _ _ _ 2 2

    cout<< setw(8) << 4444;
    Output :- _ _ _ _ 4 4 4 4

    cout<< setw(8) << 666666;
    Output :- _ _ 6 6 6 6 6 6

C++ Setprecision() Manipulator

Setprecision() Manipulators sets the total number of digits to be displayed when the manipulator floating point number is printed.

    cout<< Setprecision(5) << 123.456;
    Output :- 123.46      \\It will print the output to the screen(Notice the rounding)

    cout<< Setprecision(2) << 1.1658;
    Output :- 1.2

    cout<< Setprecision(4) << 125.721;
    Output :- 125.7

    cout<< Setprecision(6) << 125.6987;
    Output :- 125.699

Precedence of Operators

The associativity of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses.

For example A = 3 + 5 * 3; here, A is assigned 18, not 24 because operator * has higher precedence than +, so it first gets multiplied with 5*3 and then adds into 3.
Operators are listed top to bottom, in descending precedence.
Following table lists the precedence order of operators:

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

Exercise:-

1. Which operator has the highest Precedence?

A. +
B. *
C. ||
D. ++

View Answer


2. Which operator has the lowest Precedence?

A. +
B. &
C. ,
D. ++

View Answer



Program :-

C++ Program to Find LCM

#include <iostream>
using namespace std;
int main()
{
    int n1, n2, max;
    cout << "Enter two numbers: ";
    cin >> n1 >> n2;
    
    // maximum value between n1 and n2 is stored in max
    max = (n1 > n2) ? n1 : n2;
    do
    {
        if (max % n1 == 0 && max % n2 == 0)
        {
            cout << "LCM = " << max;
            break;
        }
        else
            ++max;
    } while (true);
    
    return 0;
}


Output :

Enter two numbers: 12
18
LCM = 36





Visit :


Discussion


* You must be logged in to add comment.