settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: In C# check if the number is both greater than 20 and is odd

+5 votes

Help me to write a program in C# that that prints if the number is both:

  • GREATER than 20
  • And is ODD

Here is a sample output:

n

Result

63

true

17

false

22

false

23

true

20

false

 

asked in C# category by user mitko

2 Answers

+1 vote

You can use the if-else statement and check whether a number is EVEN by using: n % 2 == 0 (modular division);

... and from there be smarter and check if the number is ODD by using: n % 2 != 0 (modular division) with !


THE CODE:


using System;

class BigAndOdd
{
    static void Main()
    {
        Console.WriteLine("Please write your number:");
        int n = int.Parse(Console.ReadLine());

        if ((n > 20) && (n % 2 != 0))
        {
            Console.WriteLine("True");
        }
        else
        {
            Console.WriteLine("False");
        }
    }
}
answered by user sam
edited by user golearnweb
+1 vote

Or you can also (without if-else statement):

    1. Declare two variables (n and result).
    2. Read the user input from the console. (int.Parse(Console.ReadLine());).
    3. Check if the input number is greater than 20 and odd by using the logical operators:
       a. > or < checks if the value on the left of the operator is greater/less than the value on the right side of the operator;
       b. Using the formula n % 2 != 0 you check whether the entered number is odd.
       c. && checks if the left expression AND the right expression both have true values;
       d. Save the result of the verification in the result variable;
    4. Print the result on the console (Console.WriteLine(result));)

You can use this code instead of the above one:

using System;

class CheckNumber
{
    static void Main()
    {
        Console.WriteLine("Write your number:");
        int n = int.Parse(Console.ReadLine());

        bool result = (n > 20) && (n % 2 != 0);
        Console.WriteLine(result); //true or false
    }
}
answered by user samfred5830
edited by user golearnweb
...