Practice Exercises C# Sharp - Learn to program with performing exercises C# Sharp

Practice Exercises C# Sharp

Learn to program with performing exercises C# Sharp

Conditional operator, positive & smaller - Practice Exercises C# Sharp
Practice Exercises C# Sharp4,85320940

Conditional operator, positive & smaller - Practice Exercises C# Sharp


Lesson 2:

Flow Control


Exercise 2.31:

Conditional operator, positive & smaller


Objetive:

Create a C# program which asks the user for two numbers and answers, using the conditional operator (?), the following:

- If the first number is positive
- If the second number is positive
- If they are both positive
- Which one is smaller


Source Code:


using System;
public class Conditional
{
    public static void Main()
    {
        int a, b;
        string answer;

        Console.Write("Enter the first number: ");
        a = Convert.ToInt32(Console.ReadLine());

        Console.Write("Enter the second number: ");
        b = Convert.ToInt32(Console.ReadLine());

        if (a > 0)
            Console.WriteLine("a is positive");
        else
            Console.WriteLine("a is not positive");

        if (a > 0)
            answer = "a is positive";
        else
            answer = "a is not positive";
        Console.WriteLine(answer);

        answer = a > 0 ? "a is positive" : "a is not positive";
        Console.WriteLine(answer);

        Console.WriteLine(b > 0 ?
            "b is positive" : "b is not positive");

        answer = (a > 0) && (b > 0) ?
            "both are positive" : "not both are positive";
        Console.WriteLine(answer);

        int smallest = a < b ? a : b;
        Console.WriteLine("Smallest: {0}", smallest);
    }
}
Exercisey 2.31

Share Now:







Privacy Policy:



Google uses associated advertising companies to serve ads when it visits our website. These companies may use the information they obtain from your visits to this and other websites (not including your name, address, email address, or phone number) to provide you with announcements about products and services that interest you. If you would like to learn more about this practice and know your options to prevent these companies from using this information. Click in... Privacy and Terms of Google.

Cookies

This site uses Google cookies to provide its services, to personalize advertisements and to analyze traffic. Google receives information about your use of this website. More information in... Privacy and Terms of Google.