w3resource

C#: Get the absolute value of the difference between two given numbers

C# Sharp Basic: Exercise-20 with Solution

Write a C# program to get the absolute value of the difference between two given numbers. Return double the absolute value of the difference if the first number is greater than the second number.

C# Sharp Exercises: Get the absolute value of the difference between two given numbers

Sample Solution:-

C# Sharp Code:

using System;
using System.Collections.Generic;

// This is the beginning of the Exercise20 class
public class Exercise20 {
    // This is the main method where the program execution starts
    static void Main(string[] args)
    {
        // Displaying the result of the 'result' method with different integer arguments
        Console.WriteLine(result(13, 40)); // Test case 1: 'a' < 'b', returns 'b - a'
        Console.WriteLine(result(50, 21)); // Test case 2: 'a' > 'b', returns '(a - b) * 2'
        Console.WriteLine(result(0, 23));  // Test case 3: 'a' < 'b', returns 'b - a'
    }

    // Method to calculate and return a result based on two integer inputs
    public static int result(int a, int b)
    {      
        if (a > b)
        {
            // If 'a' is greater than 'b', return the difference of 'a' and 'b' multiplied by 2
            return (a - b) * 2;
        }
        // If 'a' is not greater than 'b', return the difference of 'b' and 'a'
        return b - a;
    }
}

Sample Output:

27                                                                     
58                                                                     
23

Flowchart:

Flowchart: C# Sharp Exercises - Get the absolute value of the difference between two given numbers

C# Sharp Code Editor:

Previous: Write a C# program to compute the sum of two given integers, if two values are equal then return the triple of their sum.
Next: Write a C# program to check the sum of the two given integers and return true if one of the integer is 20 or if their sum is 20.

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.