Monday, July 26, 2010

Code from class today; also recursive definition of division via repeated subtraction

int mult(int x, int y)
{
    int result = 0;
    for (int i = 0; i < y; i++)
        result += x;
    return result;
}

int mult(int x, int y)
{
    if (y == 0) return 0;
    if (y == 1) return x;
    return x + mult(x, y-1);
}


x / 1 = x
x / n = (x - n) / (n - 1)

100 / 10 = ( 100 - 10) / (10 - 1)


int sum(int a[], int capacity)
{
    int total = 0;
    for(int i = 0; i < capacity; i++)
        total += a[i];
    return total;
}

main()
{
    int x[5] = {6, 10, 23, 12, 1};
    cout << sum(x, 5);
}

No comments:

Post a Comment