C# Program to Check if a given Year is a Leap Year or Not.

A leap year is a year that contains an extra day, February 29th, making it 366 days instead of the usual 365 days. Leap years are important to ensure that our calendar remains in sync with the solar year.

In this article, we will explore how to write a C# program to determine if a given year is a leap year or not.


Problem Statement.

Write a C# program to check whether a given year is a leap year or not.


Leap Year Criteria

A year is a leap year if it meets one of the following criteria:

  • The year is evenly divisible by 4, but not divisible by 100.
  • The year is divisible by 400.


Example

Let's say we want to check whether the year 2024 is a leap year or not.

Steps to check Leap Year:

  • Check if the year is divisible by 4: 2024 % 4 = 0
  • Check if the year is not divisible by 100: 2024 % 100 != 0
  • Since both conditions are met, 2024 is a leap year.


C# Code to Check a Leap Year.

//C-sharp program to check given year is leap year or not
using System;

class Program {
    static void Main(string[] args) {
        Console.Write("Enter a year: ");
        int year = int.Parse(Console.ReadLine());

        bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

        if (isLeapYear) {
            Console.WriteLine($"{year} is a leap year.");
        } else {
            Console.WriteLine($"{year} is not a leap year.");
        }
    }
}
Output:
Enter a year: 2023
2023 is not a leap year.

Explanation:

1. We take input from the user for the year.
2. We use the ternary operator (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) to check whether the year meets the leap year criteria.
3. If the condition is true, we output that the year is a leap year. Otherwise, we output that it is not a leap year.

C# Program to Find the Maximum of Three Numbers using Ternary Operators.

In this article, we'll explore using the ternary operator to find the maximum of three numbers in a C# program.


Problem Statement: Using ternary operators, write a C# program to find the maximum among three given numbers.

Example: 

Input: num1 = 11, num2 =12, num3 = 7
Output: Largest Number = 12

Input: num1 = 4, num2 = -2, num3 = 5
Output: Largest Number = 5

Let's understand Ternary Operators before moving to the coding part to find the largest number among the three.

What are Ternary Operators?

The ternary operator, also known as the conditional operator, is a concise way to express simple conditional statements in programming languages like C#. It provides a compact syntax to perform an operation based on a condition. 

The general syntax of the ternary operator is:
condition ? expression_if_true : expression_if_false

Here's a breakdown of how the ternary operator works:
  • The condition is an expression that evaluates to either true or false.
  • If the condition is true, the value of expression_if_true is returned.
  • If the condition is false, the value of expression_if_false is returned.
I hope you get a basic idea of how Ternary operators work. Now let's use them to find the largest number.

C# Code to Find a Maximum of Three Numbers using Ternary Operators.

using System;

namespace MaximumOfThreeNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the first number: ");
            int num1 = Convert.ToInt32(Console.ReadLine());

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

            Console.Write("Enter the third number: ");
            int num3 = Convert.ToInt32(Console.ReadLine());

            int max = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);

            Console.WriteLine($"The maximum number is: {max}");
        }
    }
}
Output:
Enter the first number: 20
Enter the second number: 10
Enter the third number: 9
The maximum number is: 20

Ternary operators offer a concise way to perform conditional operations and are especially useful when comparing multiple values.

Similar articles:

C# Program to Calculate the Simple Interest.

Calculating simple interest is a basic financial calculation used to determine the interest earned or paid on a principal amount over a specific period. In this article, we'll learn how to write a C# program to calculate simple interest.


Problem Statement: Write a C# program to calculate the simple interest given the principal amount, rate, and time.

Example:

Suppose the principal amount is $1000, the interest rate is 5%, and the time is 3 years. The program should output:

Simple Interest: $150.00

Steps to Find Simple Interest.

Below are steps that you need to follow to calculate simple interest:

Step 1: Take inputs for principal amount, rate, and time from the user.
Step 2: Calculate simple interest using the formula: Simple Interest = (Principal * Rate * Time) / 100.
Step 3: Print the calculated simple interest.

C# Code to Find Simple Interest.

// C-sharp code implementation to calculate simple interest
using System;

namespace SimpleInterestCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the principal amount: ");
            double principal = Convert.ToDouble(Console.ReadLine());

            Console.Write("Enter the interest rate (in percentage): ");
            double rate = Convert.ToDouble(Console.ReadLine());

            Console.Write("Enter the time (in years): ");
            double time = Convert.ToDouble(Console.ReadLine());

            double simpleInterest = (principal * rate * time) / 100;

            Console.WriteLine($"Simple Interest: ${simpleInterest:F2}");
        }
    }
}
Output:
Enter the principal amount: 1000
Enter the interest rate (in percentage): 8
Enter the time (in years): 4
Simple Interest: $320.00

Similar articles:

C# Program to Find the largest among three numbers.

In many programming scenarios, you might need to determine the largest number among a set of values. This is a common problem and can be solved using conditional statements. In this article, we'll learn how to write a C# program to find the largest among three numbers.


Problem Statement: Write a C# program that finds the largest among three given numbers.

Example:

Input: num1 = 10, num2 =12, num3 = 7
Output: Largest Number = 12

Input: num1 = 8, num2 = -2, num3 = 5
Output: Largest Number = 8

C# Code to Find the Largest Number Among Three.

//C-sharp code to find largest among three numbers
using System;

namespace LargestNumberFinder
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter three numbers: ");
            int num1 = Convert.ToInt32(Console.ReadLine());
            int num2 = Convert.ToInt32(Console.ReadLine());
            int num3 = Convert.ToInt32(Console.ReadLine());

            int largest = num1;

            if (num2 > largest)
            {
                largest = num2;
            }

            if (num3 > largest)
            {
                largest = num3;
            }

            Console.WriteLine($"Largest number among {num1}, {num2}, and {num3} is {largest}.");
        }
    }
}
Output:
Enter three numbers: 10
23
9
Largest number among 10, 23, and 9 is 23.

Code Explanation:
  • The program takes three integers as input using the Console.Write and Console.ReadLine functions.
  • It initializes the largest variable with the value of the first input.
  • Using a series of if statements, it compares the other two inputs with the largest variable and updates it if a larger value is found.

C# Program to Calculate the Factorial of a Number using Loop.

Factorial is a mathematical operation that is used quite often in programming. It involves multiplying a given number by all positive integers that are less than it. In this article, we'll explore how to write a C# program to calculate the factorial of a given number.

Problem Statement: Write a C# program that calculates the factorial of a positive integer.

Example:

Input: num = 5
Output: Factorial of 5 = 120

Explanation: 5 x 4 x 3 x 2 x 1 = 120

Input: num = 7
Output: Factorial of 7 = 5040

Steps to Find Factorial of a Number.

Below are the steps that need to be followed to Find a Factorial of a number in C-Sharp.

Step 1: Take a positive integer input from the user.
Step 2: Initialize a variable factorial to 1. This will store the result of the factorial operation.
Step 3: Use a loop to iterate from 1 to the input number.
Step 4: In each iteration, multiply the factorial by the current iteration value.
Step 5: After the loop completes, the factorial will hold the calculated factorial value.
Step 6: Print the result.

C# Code to Find Factorial of a Number.

// C-sharp code to find factorial of a number.
using System;

namespace FactorialCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a positive integer: ");
            int number = Convert.ToInt32(Console.ReadLine());

            int factorial = 1;
            for (int i = 1; i <= number; i++)
            {
                factorial *= i;
            }

            Console.WriteLine($"Factorial of {number} is {factorial}.");
        }
    }
}
Output:
Enter a positive integer: 7
Factorial of 7 is 5040.

Code Explanation:

1. The program takes a positive integer as input using the Console.Write and Console.ReadLine functions.

2. It then uses a for loop to iterate from 1 to the input number.

3. Inside the loop, the factorial variable is updated by multiplying it with the current value of i.

4. After the loop completes, the program prints the calculated factorial value.

C# Program to check if a given number is Even or Odd.

Even numbers are those that are divisible by 2 without leaving a remainder, while odd numbers are not divisible by 2 without a remainder. In this article, we will explore how to write a simple C# program to check if a given number is even or odd.


Problem Statement: Write a C# program that takes an integer as input and determines whether it is an even or odd number.

Example:

Input: num = 7
Output: 7 is an Odd Number.

Explanation: 7 % 2 = 1

Input: num = 10
Output: 10 is an Even Number.

Explanation: 10 % 2 = 0

Steps to Check Even and Odd Numbers.

Below are the steps that you need to follow to check if the given number is odd or even.
Step 1: Start by taking an integer input from the user.
Step 2: Use the modulo operator % to check if the remainder of dividing the input number by 2 is zero or not.
Step 3: If the remainder is zero, it's an even number. Otherwise, it's an odd number.
Step 4: Print the appropriate message based on the result.

C# code to check Even and Odd Numbers.

// C-sharp code check if a number is even or odd
using System;

namespace EvenOddChecker
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter an integer: ");
            int number = Convert.ToInt32(Console.ReadLine());

            if (number % 2 == 0)
            {
                Console.WriteLine($"{number} is an Even number.");
            }
            else
            {
                Console.WriteLine($"{number} is an Odd number.");
            }
        }
    }
}
Output:
Enter an integer: 12
12 is an Even number.

Code Explanation:

We use the Console.Write and Console.ReadLine functions to take input from the user. The % operator calculates the remainder when the number is divided by 2. If the remainder is zero, the number is even; otherwise, it's odd.

C# Program to Convert Fahrenheit to Celsius.

In this article, we'll explore how to create a simple C# program that takes a temperature in Fahrenheit as input and converts it to Celsius.
Convert Fahrenheit to Celsius.

Problem Statement: Write a C# program that converts a temperature in Fahrenheit to Celsius. Take the temperature in Fahrenheit as user input and display the converted temperature in Celsius.

Example:
Input:
Fahrenheit: 98.6

Output:
98.6°F is equal to 37°C

The formula to convert temperature from Fahrenheit (°F) to Celsius (°C) is as follows:
Celsius (°C) = (Fahrenheit (°F) - 32) × 5/9

C# Code to Convert Fahrenheit to Celsius.

// C-sharp code to calculate celsius
using System;

namespace TemperatureConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Read temperature in Fahrenheit from the user
            Console.Write("Enter the temperature in Fahrenheit: ");
            double fahrenheit = Convert.ToDouble(Console.ReadLine());

            // Convert Fahrenheit to Celsius using the formula
            double celsius = (fahrenheit - 32) * 5 / 9;

            // Display the converted temperature
            Console.WriteLine($"{fahrenheit} F is equal to {celsius:F2} C");

            // Keep the console window open
            Console.ReadLine();
        }
    }
}
Output:
Enter the temperature in Fahrenheit: 45
45 F is equal to 7.22 C

C# Program to Calculate Area of Rectangle.

Calculating the area of a rectangle is a fundamental mathematical operation often encountered in programming. In this article, we'll explore how to write a simple C# program to calculate the area of a rectangle using user-provided input. 


Problem Statement: Write a C# program that takes the length and width of a rectangle as user input and calculates its area. Display the result to the user.

Example: 

Input:
Length (L): 8
Width (W): 5

Output: The area of the rectangle is: 40

Explanation: 
Area = L x W
     = 8 x 5
     = 40

C# Code to Calculate Area of Rectangle.

//C-sharp code to calculate area of Rectangle
using System;

namespace RectangleAreaCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            // Read length and width from the user
            Console.Write("Enter the length of the rectangle: ");
            double length = Convert.ToDouble(Console.ReadLine());

            Console.Write("Enter the width of the rectangle: ");
            double width = Convert.ToDouble(Console.ReadLine());

            // Calculate the area
            double area = length * width;

            // Display the area
            Console.WriteLine($"The area of the rectangle is: {area}");

            // Keep the console window open
            Console.ReadLine();
        }
    }
}
Output:
Enter the length of the rectangle: 8
Enter the width of the rectangle: 4
The area of the rectangle is: 32

Code Explanation:
In the above C-sharp program, Convert.ToDouble() is used to convert the user input from strings to double values for calculations. We also need to add Console.ReadLine() at the end keeps the console window open until the user presses Enter.

This program demonstrates basic user input, data conversion, arithmetic operation, and output formatting in C#. 

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson