ldiv() Function with Example in C++

C++ ldiv() function: Here, we are going to learn about the ldiv() function with example of cstdlib header in C++ programming language.
Submitted by IncludeHelp, on May 28, 2020

C++ ldiv() function

ldiv() function is a library function of cstdlib header. It is used for integral division, it accepts two parameters (numerator and denominator) and returns a structure that contains the quot (quotient) and rem (remainder).

Syntax of ldiv() function:

C++11:

    ldiv_t ldiv (long int numer, long int denom);

Parameter(s):

  • numer – represents the value of numerator.
  • denom – represents the value of denominator.

Return value:

The return type of this function is ldiv_t, returns a structure that contains the quot (quotient) and rem (remainder).

Example:

    Input:
    long int n = 123456789;
    long int d = 12345678;
    ldiv_t result;

    Function call:
    result = ldiv(n, d);

    Output:
    result.quot = 10
    result.rem = 9

C++ code to demonstrate the example of ldiv() function

// C++ code to demonstrate the example of
// ldiv() function

#include <iostream>
#include <cstdlib>
using namespace std;

// main() section
int main()
{

    long int n = 123456789;
    long int d = 12345678;
    ldiv_t result;

    result = ldiv(n, d);

    cout << "Numerator  : " << n << endl;
    cout << "Denominator: " << d << endl;
    cout << "Quotient   : " << result.quot << endl;
    cout << "Remainder  : " << result.rem << endl;
    cout << endl;

    n = 999988887777;
    d = 1112223334;

    result = ldiv(n, d);

    cout << "Numerator  : " << n << endl;
    cout << "Denominator: " << d << endl;
    cout << "Quotient   : " << result.quot << endl;
    cout << "Remainder  : " << result.rem << endl;
    cout << endl;

    n = 100100234;
    d = 9878762536;

    result = ldiv(n, d);

    cout << "Numerator  : " << n << endl;
    cout << "Denominator: " << d << endl;
    cout << "Quotient   : " << result.quot << endl;
    cout << "Remainder  : " << result.rem << endl;
    cout << endl;

    return 0;
}

Output

Numerator  : 123456789
Denominator: 12345678
Quotient   : 10
Remainder  : 9

Numerator  : 999988887777
Denominator: 1112223334
Quotient   : 899
Remainder  : 100110511

Numerator  : 100100234   
Denominator: 9878762536
Quotient   : 0
Remainder  : 100100234

Reference: C++ ldiv() function




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.