w3resource

C Exercises: Compute the sum of the two given integer values. If the two values are the same, then return triple their sum


1. Triple Sum Condition

Write a C program to compute the sum of the two input values. If the two values are the same, then return triple their sum.

C Code:

#include <stdio.h> // Include standard input/output library

int test(int x, int y); // Declare the function 'test' with two integer parameters

int main(void)
{
    // Call the function 'test' with arguments 1 and 2 and print the result
    printf("%d", test(1, 2));

    // Print a newline for formatting
    printf("\n");

    // Call the function 'test' with arguments 2 and 2 and print the result
    printf("%d", test(2, 2));
}
// Function definition for 'test'
int test(int x, int y)
{
    // Conditional expression: If x is equal to y, return (x + y) multiplied by 3, otherwise return x + y
    return x == y ? (x + y) * 3 : x + y;
}

Sample Output:

3
12

Explanation:

int test(int x, int y) {
  return x == y ? (x + y) * 3 : x + y;
}

The above function takes in two integer parameters, x and y. It uses the ternary operator to check if x is equal to y. If x is equal to y, it returns the result of (x + y)*3. Otherwise, it returns the result of x + y.

Time complexity and space complexity:

Time complexity: The time complexity of the function is O(1) as the function involves a single conditional operation and two arithmetic operations that take constant time.

Space complexity: The space complexity of the function is O(1) as the function only uses a fixed amount of space to store the variables and the return value.

Pictorial Presentation:

C Programming Algorithm: Compute the sum of the two given integer values. If the two values are the same, then return triple their sum

Flowchart:

C Programming Algorithm Flowchart: Compute the sum of the two given integer values. If the two values are the same, then return triple their sum.

For more Practice: Solve these Related Problems:

  • Write a C program to compute the sum of two integers, but return double their sum if either number is odd.
  • Write a C program to compute the sum of two given numbers. If the sum is even, return half the sum.
  • Write a C program that takes two integers and returns four times their sum if both numbers are equal.
  • Write a C program to compute the sum of two numbers. If the absolute difference between them is less than 5, return 5.

Go to:


PREV : C Basic Declarations and Expressions Exercises Home
NEXT : Absolute Difference from 51.

C Programming Code Editor:



What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.