Sheet 2 (Functions) - Q2

 avatar
itsLu
c_cpp
a year ago
886 B
2
Indexable
/* B. Write a program to calculate the result of the following equation
using two functions only
((3+4+5+6)/(9*11*13*15) - (7*10*13*...*19)/(10+15+20+...+40)) */
#include <iostream>
using namespace std;

int stepped_Sum (int firstTerm, int lastTerm, int step)
{
    int sum = 0;
    for (int k = firstTerm ; k <= lastTerm ; k += step) //or k = k + step
        sum += k;
    // or sum = sum + k;
    return sum;
}

int stepped_Mul (int firstTerm, int lastTerm, int step)
{
    int mul = 1;
    for (int k = firstTerm ; k <= lastTerm ; k += step) //or k = k + step
        mul *= k;
    // or mul = mul * k;
    return mul;
}

int main ()
{
    int a, b, c, d;
    float fin;
    a = stepped_Sum(3, 6, 1);
    b = stepped_Mul(9, 15, 2);
    c = stepped_Mul(7, 19, 3);
    d = stepped_Sum(10, 40, 5);
    fin = (a*1.0/b) - (c*1.0/d);
    cout << fin;
}
Leave a Comment