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#. 

C# Program to Input Two Numbers and Display their Sum.

In this C# programming example, we will learn how to take input from the user for two numbers, calculate their sum, and display the result. This basic program will help you understand how to interact with the user and perform simple arithmetic operations in C#.

Sum of Two Numbers

Problem Statement: Write a C# program that takes two numbers as input from the user, calculates their sum, and displays the result.

Example:

Enter the first number: 5
Enter the second number: 7
The sum of 5 and 7 is: 12


C# Code to Find the Sum of Two Numbers.

//C-sharp code to print sum of two number
using System;

namespace SumCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the first number: ");
            //coverting input string to integer value
            int num1 = Convert.ToInt32(Console.ReadLine());

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

            int sum = num1 + num2;

            Console.WriteLine($"The sum of {num1} and {num2} is: {sum}");
        }
    }
}
Output:
Enter the first number: 12
Enter the second number: 10
The sum of 12 and 10 is: 22

Code Explanation:

Inside the Main method of the above C# code:
  • Console.Write("Enter the first number: "); displays a message asking the user to enter the first number.
  • int num1 = Convert.ToInt32(Console.ReadLine()); reads the user's input and converts it to an integer.
  • Similar steps are followed to get the second number.
  • int sum = num1 + num2; calculates the sum of the two numbers.
  • Console.WriteLine($"The sum of {num1} and {num2} is: {sum}"); displays the result using string interpolation.

Key Points:
  • The Convert.ToInt32() method is used to convert the user's input (which is a string) into an integer.
  • The $ symbol is used for string interpolation, which allows us to embed expressions within strings for dynamic output.
  • The Console.ReadLine() method reads the entire line of text entered by the user, including spaces.

This program demonstrates how to interact with the user, perform arithmetic operations, and output results in C#.

C# program to print 'Hello, World!' to the console.

In this article, we will write our first C# program in which we will learn how to print the message "Hello World" on the Console screen. This is an introduction program we write whenever we start learning any new programming language as a beginner.

Example: 
Output: Hello, World!

Steps to Print a Message on Console in C#.

We need to follow the below steps to print our message to the console screen:

Step 1: Open a C# development environment such as Visual Studio or Visual Studio Code.

Step 2: Create a new C# project or open an existing one.

Step 3: Inside the project, create a new C# source code file with the ".cs" extension.

Step 4: In the source code file, use the Console.WriteLine() statement to print "Hello, World!" to the console.

Step 5: Save the file.

Step 6: Build and run the program to see the output.

C# Code Implementation to Print "Hello World!" on Console.

// C# code to print message on console
using System;

namespace HelloWorldApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
Output:
Hello, World!


Explanation of Working:

1. The using System; directive includes the System namespace, which contains fundamental classes and base types.

2. The namespace HelloWorldApp encapsulates the program's code in a specific namespace.

3. The class Program defines a class called Program, which is the entry point of the application.

4. The static void Main(string[] args) method is the starting point of execution. It's the method that gets executed when the program is run.

5. Console.WriteLine("Hello, World!"); is a statement that prints "Hello, World!" to the console and adds a newline character at the end.

Key Note:
The Console.WriteLine() method is used to display output to the console and automatically moves to the next line after printing the message. (alert-passed)
If you want to print the message without moving to the next line, you can use Console.Write() instead. (alert-passed)

How To Add Image in HTML? Example

Images are an integral part of modern web design. They can be used for logos, illustrations, product images, and more. In HTML, images are inserted using the <img> element, which requires the src attribute to specify the image source (URL).


Syntax to add Image:

To add an image to your HTML document, use the following syntax:

<img src="image-url.jpg" alt="Image Description">

Image Attributes.

The <img> element supports various attributes to control image behavior and appearance:
  • src attribute contains the URL of the image file.
  • alt attribute provides alternative text that is displayed if the image cannot be loaded.
  • width and height use to Set the dimensions of the image.
  • title attributes display a tooltip when the user hovers over the image.

      Example: Adding Image to HTML.

      Let's say you want to add a logo image to your website. You can add by using below HTML code.

      <!DOCTYPE html>
      <html>
      <head>
          <title>Adding Images</title>
      </head>
      <body>
          <h1>Welcome to our Website</h1>
          <img src="images/logo.png" alt="Company Logo" width="200" height="100">
          <p>Explore our products and services.</p>
      </body>
      </html>
      

      Here in the above example, we are defining the path of our image in the src attribute. You can provide a relative or absolute path of your image. Let's understand what is relative and absolute paths.

      Relative Path Vs Absolute Path.

      In web development, you specify the location of a resource such as an image, stylesheet, or script. You can use either relative or absolute paths of the image for the src attribute:
      • Relative Paths: Specify the path relative to the current HTML file.
      • Absolute Paths: Provide the complete URL of the image.
      Example:
      <!-- Relative Path -->
      <img src="images/pic.jpg" alt="Picture">
      
      <!-- Absolute Path -->
      <img src="https://example.com/images/pic.jpg" alt="Picture">
      

      I hope you understand the process of adding an image to your website. Now let's discuss some key points that you should keep in mind while adding any image to your website.

      Tips for Effective Image Usage in HTML.

      Here are some tips to consider for using images effectively on your website:

      Image Quality.

      You should always use high-quality images that are clear, sharp, and properly sized. Avoid pixelated or distorted images, as they can negatively impact the overall appearance of your website.


      Add Alt Text.

      Always include descriptive and meaningful alt text for images. Alt text is essential for accessibility and helps users with visual impairments understand the content of the image.


      Mobile-Friendly Design.

      Ensure that images are responsive and look good on various devices, including smartphones and tablets. Test your website's responsiveness to verify that images scale appropriately.


      Avoid Overloading.

      Use images sparingly and avoid overloading your pages with too many visuals, which can distract or overwhelm users.

      C Program to Reverse Given String.

      Reversing a string is a process of arranging the character of the string in opposite directions. In this C programming tutorial, we are going to learn multiple ways to reverse the given String.

      Example:
      Input: str = Algolesson
      Output: nosseloglA
      
      Input: str = GoodCode
      Output: edoCdooG
      

      Reverse String Using Loop.

      In this approach, we will reverse a string by using a loop that will iterate through the characters of the original string and build the reversed string character by character.

      Below is the C implementation to reverse the string using for loop:
      // C program to reverse the given string 
      #include <stdio.h>
      #include <string.h>
      
      // function to reverse string
      void reverseString(char str[]) {
          int length = strlen(str);
          for (int i = 0; i < length / 2; i++) {
              char temp = str[i];
              str[i] = str[length - i - 1];
              str[length - i - 1] = temp;
          }
      }
      
      int main() {
          char str[100];
          printf("Enter a string: ");
          scanf("%s", str);
      
          reverseString(str);
      
          printf("Reversed string: %s\n", str);
      
          return 0;
      }
      
      Output:
      Enter a string: Algolesson
      Reversed string: nosseloglA
      

      Time Complexity: O(n)
      Space Complexity: O(1)

      Reverse String Using Recursion.

      In this approach, we are going to use Recursion to reverse the given string. 

      Below C code implementation:
      // C program to reverse the given string using recursion
      #include <stdio.h>
      
      void reverseString(char str[], int start, int end) {
          if (start >= end) {
              return;
          }
          char temp = str[start];
          str[start] = str[end];
          str[end] = temp;
          reverseString(str, start + 1, end - 1);
      }
      
      int main() {
          char str[100];
          printf("Enter a string: ");
          scanf("%s", str);
      
          int length = strlen(str);
          reverseString(str, 0, length - 1);
      
          printf("Reversed string: %s\n", str);
      
          return 0;
      }
      
      Output:
      Enter a string: Welcome
      Reversed string: emocleW
      

      In the recursive function, start and end represent the indices of the characters that need to be swapped. The function keeps swapping characters and recursively calling itself with the updated indices until the base case is reached.

      Time Complexity: O(n)
      Space Complexity: O(1)

      DON'T MISS

      Tech News
      © all rights reserved
      made with by AlgoLesson