How to resolve the algorithm Sum and product of an array step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Sum and product of an array step by step in the D programming language

Table of Contents

Problem Statement

Compute the sum and product of an array of integers.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum and product of an array step by step in the D programming language

Source code in the d programming language

import std.stdio;

void main() {
    immutable array = [1, 2, 3, 4, 5];

    int sum = 0;
    int prod = 1;

    foreach (x; array) {
        sum += x;
        prod *= x;
    }

    writeln("Sum: ", sum);
    writeln("Product: ", prod);
}


import std.stdio, std.algorithm, std.typecons;

void main() {
    immutable array = [1, 2, 3, 4, 5];

    // Results are stored in a 2-tuple
    immutable r = reduce!(q{a + b}, q{a * b})(tuple(0, 1), array);

    writeln("Sum: ", r[0]);
    writeln("Product: ", r[1]);
}


  

You may also check:How to resolve the algorithm Spinning rod animation/Text step by step in the Haskell programming language
You may also check:How to resolve the algorithm Luhn test of credit card numbers step by step in the TXR programming language
You may also check:How to resolve the algorithm Bitmap/Bézier curves/Quadratic step by step in the Wren programming language
You may also check:How to resolve the algorithm Attractive numbers step by step in the PHP programming language
You may also check:How to resolve the algorithm Tau function step by step in the Sidef programming language