SKIRL
SKIRL

Reputation: 11

Enter two integers a and b (a ≤ b) and output the sum of the squares of all numbers from a to b. (C)

Good evening.I need to input two integers a and b (a ≤ b) and output the sum of the squares of all numbers from a to b. example: Enter two numbers: 4 10 The sum of the squares is 361 I would appreciate your help!

#include <stdio.h>

int main(void)
{
    int a, b;
    printf("Введіть два числа: ");
    scanf("%d %d", &a, &b);

    int N = a;
    while (N < b)
    {
        printf("Сума квадратів: %d\n", a * a + 2 * a * b + b * b);
        N++;
    }
}

I don`t know how to write code correctly.

Upvotes: 0

Views: 651

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

You need to calculate the sum of squares of numbers in a range. So write for example for the range [a, b)

unsigned long long int sum = 0;

for ( ; a < b; ++a )
{
    sum += a * a;
}

printf( "Sum = %llu\n", sum );

Or if you are considering the range like [a, b] then write

unsigned long long int sum = 0;

if ( !( b < a ) )
{
    do
    {
        sum += a;
    } while ( a++ != b );
}

Upvotes: 3

Related Questions