Input two numbers and work out their sum, average and sum of the squares of the numbers.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int main(int argc, char ** argv) {
    float number1, number2;
    float sum;

    printf("Input two numbers:\n");
    scanf("%f%f", &number1, &number2);
    sum = number1 + number2;
    printf("Sum: %.2f\n", sum);
    printf("Average: %.2f\n", sum/2);
    printf("Sum of squares: %.2f\n", number1*number1 + number2*number2);
    return 0;

When you compile and execute the above program it produces the following result on Linux:

Input two numbers:
Sum: 11.00
Average: 5.50
Sum of squares: 61.00

Brief Explanation

  • The program requests the user to enter two numbers.
  • scanf function read the numbers and assign them to variables number1 and number2.
  • Using the arithmetic operator + (for addition), the two numbers are added and the result assign to the variable sum.
  • The average is computed by dividing (/) the sum by 2.
  • The arithmetic operator * (for multiplication) is used to compute the square of each number.
  • printf function is used to display the results to the stdout.



0 # Rebeca 2016-04-05 18:14
Hello. Can you tell me please why you have to use the &operator on number1 and number2 when you input them using the scanf function?
Reply | Reply with quote | Quote
0 # Fokwa Divine 2016-04-07 08:13
Good question Rebeca, The operator & returns the address of a variable, so &number1 returns the actual address of the variable number1. Hope it helps. You can also subscribe to our Newsletter on right above to get inform when new exercises are posted. Feel free to ask any further question.
Reply | Reply with quote | Quote

Add comment

Security code