Amr Shawkat
Amr Shawkat

Reputation: 13

Subtracting a sequence of numbers using for loop in C Programming

int myfunc(int a, int b)
{
    int result = a;
    for(int index = a - 1; index >= b; index--)
    {
        result -= index;
    }
    return result;
}

How to make this function subtract numbers from the smallest number to the greatest number depending on the values of a and b that I choose ? (e.g. if a = 5 and b = 8 , then the program would type 5-6-7-8 = -16)

Upvotes: 0

Views: 2370

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

For starters the variable index is redundant.

To avoid an overflow (at least in most cases) the variable result should have the type long long int instead of int. For example if you will run your function like

myfunc( INT_MIN , INT_MIN + 3 );

(provided that you have included the header <limits.h>) when if the type of the variable result is int then the function will return the value -6 (actually the behavior is undefined in this case) while if the variable result has the type long long int then you will get the correct result 4294967290.

The function can look the following way

long long int myfunc( int a, int b )
{
    if ( b < a )
    {
        int tmp = b;
        b = a;
        a = tmp;
    }
 
    long long int result = a;

    while ( a < b )
    {
        result -= ++a;
    }

    return result;
}

Here is a demonstrative program.

#include <stdio.h>

long long int myfunc( int a, int b )
{
    if ( b < a )
    {
        int tmp = b;
        b = a;
        a = tmp;
    }
 
    long long int result = a;

    while ( a < b )
    {
        result -= ++a;
    }

    return result;
}

int main(void) 
{
    printf( "%lld\n", myfunc( 8, 5 ) );
 
    return 0;
}

The program output is

-16

Upvotes: 0

yano
yano

Reputation: 5265

You're going the "wrong direction". Look at what you want to do:

5-6-7-8 = -16
^ ^ ^ ^
a | | |
 a+1| |
   a+2|
     a+3

So start at a+1 and count up to b

int result = a;
for(int index = a + 1; index <= b; index++)
{
    result -= index;
}
// result = -16 for a=5, b=8

Demo

Upvotes: 1

Related Questions