Write a C# function called CompareNumbers to compare two numbers and return a co
ID: 3594621 • Letter: W
Question
Write a C# function called CompareNumbers to compare two numbers and return a code that indicates their relationship: 0 if they are equal, 1 if the first number is larger, and -1 if the first number is smaller. Your main module should prompt the user for the two numbers and pass them to the function. The result is printed in your main module.
The output should look like this (note that it should work for any values that are input; these are just examples).
Enter a number: 10
Enter a number: 21
10 is smaller than 21
Explanation / Answer
using System;
namespace name
{
class domath
{
// method that takes 2 integers and compares them
public int CompareNumbers (int a, int b)
{
if(a==b)
return 0;
if(a>b)
return 1;
return -1;
}
static void Main(string[] args)
{
// taking input of 2 integers
int a,b, result;
Console.WriteLine("Enter first number: ");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number: ");
b = Convert.ToInt32(Console.ReadLine());
domath n = new domath();
result = n.CompareNumbers(a, b);
// printing text for output
if(result == 0)
Console.WriteLine("{0} and {1} are equal",a,b);
if(result == 1)
Console.WriteLine("{0} is greater than {1}",a,b);
if(result == -1)
Console.WriteLine("{0} is smaller than {1}",a,b);
}
}
}
/*SAMPLE OUTPUT
Enter first number:
10
Enter second number:
10
10 and 10 are equal
Enter first number:
10
Enter second number:
21
10 is smaller than 21
Enter first number:
21
Enter second number:
10
21 is greater than 10
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.