Data Types in C#.

Data types in C# are fundamental building blocks that define the kind of data a variable can hold. As C# is a strongly typed language, variables and expressions must have consistent data types and type conversions are limited or controlled by the language rules. 

Before learning about different data types and their usage let us learn what is data type and why it is important.

Data Types in C#

What is Data Types?

In programming, data types specify the type of data that can be stored in a variable. They determine the size, format, and range of values that a variable can hold. C# provides a rich set of data types, which can be broadly categorized into two groups: 

  • Value Types 
  • Reference Types.


Value Types C#.

Value types represent data directly, and their values are stored directly in memory. When you work with a value type, you manipulate the actual data rather than a reference to it.

Here is the list of some common value types in C#:

  • Integer Types: int, unit, short, ushort, long, ulong.  
  • Floating-Point Types: float, double, decimal.
  • Boolean Type: bool.
  • Character Type: char.
  • Enumerations: A user-defined value type that consists of a set of named integral constants. 
  • Nullable Value Types: Allows value types to have a value of null in addition to their normal range of values.
  • User-Defined Types: You can also define your own data types using classes and structs, making C# highly extensible and suitable for complex data modeling.
Example:
// Integer Types 
int myInt = 42;
uint myUInt = 12345U;
short myShort = -12345;
ushort myUShort = 56789;
long myLong = 123456789012345L;
ulong myULong = 987654321012345UL;

// Floating-Point Types
float myFloat = 3.1415927f;
double myDouble = 2.718281828459045;
decimal myDecimal = 123.456m;

// Boolean Type
bool isTrue = true;
bool isFalse = false;

// Character Type
char myChar = 'A';



Reference Type in C#.

Reference types store references (memory addresses) to the actual data. When you work with a reference type, you manipulate a reference to the data rather than the data itself. 

Here are some common reference types in C#:
  • String Type: Represents a sequence of characters (a string of text).
  • Object Type: The base type for all other types in C#. It can hold values of any data type.
Example:
string myString = "Hello, World!";

object myObject = 42;

List of Data Types in C#.

Here's a summary of common data types in C#, along with their characteristics and valid value ranges:

Data Type Description Valid Range or Values
int 32-bit signed integer -2,147,483,648 to 2,147,483,647
uint 32-bit unsigned integer 0 to 4,294,967,295
short 16-bit signed integer -32,768 to 32,767
ushort 16-bit unsigned integer 0 to 65,535
long 64-bit signed integer -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong 64-bit unsigned integer 0 to 18,446,744,073,709,551,615
float Single-precision float ±1.5 x 10^-45 to ±3.4 x 10^38
double Double-precision float ±5.0 x 10^-324 to ±1.7 x 10^308
decimal Decimal float ±1.0 x 10^-28 to ±7.9 x 10^28
bool Boolean value true or false
char Unicode character Any valid Unicode character
string Sequence of characters Any string of text
object Base type for all types Any C# data type
enum User-defined constants A set of named integral constants

Variables in C#.

Variables are fundamental building blocks in the world of programming. They serve as containers for storing data that your program can read, modify, and utilize during its execution. In this article, we are going to learn about the types of variables available in C# and how to declare and define them in our program.


Types of Variables in C#.

In C#, variables come in two primary categories: value types and reference types. The choice between these types depends on the kind of data you want to store and how you intend to use it. Let's learn each type one by one in detail.


1. Value Type Variables.

Value types directly store the data value itself. They are stored in memory, and when you copy or pass a value type variable to a method or another variable, you're working with a copy of the actual data. 

Here is the list of a few commonly used Value Type variables in C#:

  • int: Represents integer numbers.
  • float: Represents single-precision floating-point numbers.
  • double: Represents double-precision floating-point numbers.
  • bool: Represents Boolean values (true or false).
  • char: Represents a single character.
  • struct: Represents user-defined value types.

Example:

// Value type variables
int age = 25;
float temperature = 98.6f;
bool isStudent = true;

2. Reference Type Variables.

Reference types store a reference (memory address) to the actual data stored elsewhere in memory. When you copy or pass a reference type variable, you're working with a reference to the same data.

Here is the list of a few commonly used Reference Type variables in C#:

    • string: Represents a sequence of characters.
    • class: Represents user-defined reference types.
    • interface: Defines a contract for classes to implement.
    • delegate: Represents a method that can be passed as an argument.
    • object: The base type for all other types in C#.
    Example:
    // Reference Type Variable
    string name = "John";
    List<int> numbers = new List<int> { 1, 2, 3 };
    

    Declaring and Initializing Variables.

    In C#, you declare a variable by specifying its data type followed by a name for the variable. You can also assign an initial value during declaration or assign a value later in your code. 

    Example:
    // Declaration with initialization
    int age = 25;
    
    // Declaration without initialization
    float temperature;
    
    // Assignment after declaration
    temperature = 98.6f;
    

    You can also declare multiple variables of the same type in a single line:
    int x = 5, y = 10, z = 15;
    

    Rules for Variable Names.

    Variable names in C# must adhere to specific rules to ensure the readability and maintainability of your code. Here are some essential rules for naming variables:
    • Variable names are case-sensitive, so myVariable and MyVariable are different.
    • Names can consist of letters, digits, and the underscore character _.
    • Names must begin with a letter or an underscore.
    • Variable names cannot be a C# keyword or reserved word (e.g., int, class, if).
    Here are some examples of invalid variable names:
    int 123number;         // Starts with a digit.
    string my-variable;    // Contains an invalid character (-).
    double if;             // Uses a C# keyword as a name.
    

    Best Practice for Variable Naming.

    To write clean, maintainable code, consider following these best practices for variable naming:
    • Use descriptive names that convey the variable's purpose. For example, use totalAmount instead of amt.
    • Follow a consistent naming convention. Common conventions include PascalCase for class names (MyClass), camelCase for method and variable names (myVariable), and UPPERCASE for constants (MAX_VALUE).
    • Avoid using single-letter variable names, except for loop counters (i, j, k) or generic type parameters (T).
    • Use meaningful prefixes or suffixes when necessary. For instance, prefix boolean variables with "is" or "has" (isLoggedIn, hasPermission).
    • Keep variable names concise but not overly abbreviated. Aim for a balance between clarity and brevity.
    I hope you got a basic understanding of variables in C# and how to define or declare them. You should always create a meaningful variable that helps others to understand the use and purpose of that variable in the program.

    C# Keywords and Identifiers.

    When you dive into the world of C# programming, you encounter various building blocks that form the foundation of your code. Two fundamental concepts you'll frequently encounter are keywords and identifiers. Understanding what these are, how they work, and their significance is crucial for writing clean, efficient, and readable code.

    Keywords in C#.

    Keywords are predefined words in C# that have special meanings and purposes. They are reserved for specific roles within the language and cannot be used as identifiers, such as variable or method names. Keywords provide the structure and logic for your code.

    C# has a rich set of keywords that are integral to its syntax and functionality. Let's explore some of these keywords with examples:

    Example:
    class Person {
        public string Name { get; set; }
        
        public void Greet() {
            Console.WriteLine("Hello, " + Name);
        }
    }
    

    Here, class, public, string, get, set, void, return, and Console are keywords used to define a class and its properties and methods. 

    Identifiers in C#.

    Identifiers are user-defined names for program elements such as variables, classes, methods, and parameters. They help make your code more readable and understandable. 

    Identifiers must adhere to these rules:
    • Begin with a letter (uppercase or lowercase) or an underscore.
    • Subsequent characters can be letters, digits, or underscores.
    • C# is case-sensitive, so MyVariable and myvariable are distinct identifiers.
    • Avoid using C# keywords as identifiers.
    Valid identifiers: myVariable, _privateField, CalculateArea, StudentRecord.
    Invalid identifiers: 3rdPlace (starts with a digit), class (a C# keyword).

    Example:
    int numberOfApples = 10;
    string studentName = "John";
    

    In this example, numberOfApples and studentName are identifiers used for variables.

    Use of Keywords and Identifiers.

    Keywords and identifiers work together in C# code to create and manipulate program elements.

    1. Keywords and Identifiers are used together for Declaring Variables.
    int age; // 'int' is a keyword, 'age' is an identifier
    age = 25;
    

    2. Keywords and Identifiers are used together for Defining Classes.
    class Circle {
        public double Radius { get; set; } // 'class', 'public', 'double', and 'Radius' are keywords and identifiers
        public double CalculateArea() {
            return Math.PI * Radius * Radius; // 'Math', 'PI', '*' are keywords and identifiers
        }
    }
    

    3. Keywords and Identifiers are used together for Method Naming.
    public void SayHello(string name) {
        Console.WriteLine("Hello, " + name); // 'SayHello', 'string', 'name', '+' are keywords and identifiers
    }
    

    From the above examples, you got an idea of how and where we can use keywords and identifiers in our C# code. 

    Contextual Keywords in C#.

    Contextual keywords in C# are a special set of identifiers with a specific meaning within a particular context in the C# programming language. Unlike regular keywords, which have predefined meanings and cannot be used as identifiers, contextual keywords only have significance in specific code contexts where they are relevant. In other contexts, they can be used as regular identifiers like variable names or class names.

    Example:
    // Contextual Keywords
    var query = from student in students
                where student.Age > 18
                select student;
    

    Here in the above example, var, from, where, and select are contextual keywords used in LINQ queries.

    Conclusion.

    Keywords and identifiers are the building blocks of your C# code. Keywords define the language's structure and logic, while identifiers give names to program elements. Understanding their roles and using them effectively is essential for writing clean, maintainable code.

    C# Sharp History and Versions.

    C# (pronounced "C-sharp") is a versatile, high-level programming language developed by Microsoft Corporation. Since its inception, C# has become one of the most popular and widely used programming languages, powering a broad range of applications in various domains.

    Founder of C# Programming Anders Hejlsberg

    History of C# Programming.

    C# was created by Microsoft as part of its .NET initiative in the early 2000s. The language was designed by Anders Hejlsberg, a Danish computer programmer with a remarkable track record in developing programming languages. Hejlsberg had previously worked on Turbo Pascal and Delphi, and his expertise greatly contributed to C#'s success.

    The development of C# began in 1999, and it was officially introduced to the public in 2000 as part of Microsoft's .NET Framework 1.0. C# was positioned as the primary language for building Windows applications on the .NET platform.

    C# Relation with .Net.

    C# is closely associated with the .NET ecosystem, a comprehensive framework for building Windows applications and web services. The language was designed to work seamlessly with the .NET Framework, enabling developers to create a wide range of applications, from desktop software to web applications and cloud services.

    Different Versions of C# Available.

    C# has gone through several iterations, with each version introducing new features, improvements, and capabilities. Here is a brief overview of the major C# versions:

    C# 1.0 (2000): The initial release of C# included fundamental features like classes, inheritance, interfaces, and garbage collection. It was tightly integrated with the .NET Framework 1.0.

    C# 2.0 (2005): C# 2.0 brought generics, partial classes, anonymous methods, and nullable value types. These additions improved code reusability and made it easier to work with collections.

    C# 3.0 (2007): C# 3.0 introduced language enhancements such as lambda expressions, extension methods, and the LINQ (Language Integrated Query) framework. These features streamlined data manipulation and querying.

    C# 4.0 (2010): Version 4.0 introduced optional and named parameters, dynamic types, and improved support for COM interop. These additions enhanced code flexibility and interoperation with other languages.


    C# 5.0 (2012): C# 5.0 introduced asynchronous programming using the async and await keywords. This feature simplified the development of asynchronous and responsive applications.


    C# 6.0 (2015): C# 6.0 added features like string interpolation, null-conditional operators (?. and ?[]), and read-only properties and auto-properties. These features aimed to improve code readability and reduce boilerplate code.


    C# 7.0 (2017): C# 7.0 brought enhancements such as pattern matching, local functions, and tuples. These features enhanced code expressiveness and simplification.

    C# 8.0 (2019): C# 8.0 introduced several significant features, including nullable reference types, asynchronous streams, and default interface methods. These additions improved code safety and versatility.

    C# 9.0 (2020): C# 9.0, introduced record types, pattern-matching improvements, and new features for simplifying code. It also introduced source generators, allowing developers to generate code at compile time.

    C# 10.0 (2021): C# 10.0 was released in the year 2021 and contains several features like global using directives, interpolated strings as format strings, file-scoped namespaces, and more.

    How To Validate Email ID in C#?

    Validating email addresses is a common task in C# applications, especially when dealing with user input or processing email-related functionality. It is very important to validate an Email ID before storing it in our database.


    All Email IDs must follow a specific format and must belong to some domain. Here in this article, we are going to cover three different methods that we can use for email validation. 


    Email Format Validation.

    In C# we can validate an Email ID using the below methods:

    • Using Regular Expression.
    • Using Built-in Library Function.
    • Using Custom Validation.

    Let's understand each of these methods in detail with C-sharp Code.


    Method 1: Using Regular Expression.

    Using a regular expression is a robust way to validate email addresses. It allows you to define complex patterns that match valid email formats.


    C# Example Code:

    // C#-sharp code to validate email id using Regular Expression
    using System;
    using System.Text.RegularExpressions;
    
    class EmailValidator
    {
        public static bool IsValidEmail(string email)
        {
            // Define a regular expression pattern for valid email addresses
            string pattern = @"^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$";
    
            // Use Regex.IsMatch to check if the email matches the pattern
            return Regex.IsMatch(email, pattern);
        }
    
        static void Main()
        {
            string email = "example@email.com";
            bool isValid = IsValidEmail(email);
            
            Console.WriteLine($"Is {email} a valid email address? {isValid}");
        }
    }
    
    Output:
    Is example@email.com a valid email address? True
    

    Explanation of Above C# Code:
    • We define a regular expression pattern that describes valid email addresses.
    • The pattern ^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$ checks for common email format rules.
    • Regex.IsMatch(email, pattern) tests if the email string matches the pattern.
    • The IsValidEmail method returns true if the email is valid.

    Method 2: Using Regular Expression.

    C# also provides a built-in library, System.Net.Mail, for email-related tasks, including email address validation.

    C# Example Code:

    // C#-sharp code to validate email id using Built-in Library
    using System;
    using System.Net.Mail;
    
    class EmailValidator
    {
        public static bool IsValidEmail(string email)
        {
            try
            {
                var mailAddress = new MailAddress(email);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }
    
        static void Main()
        {
            string email = "algolesson@email.com";
            bool isValid = IsValidEmail(email);
            
            Console.WriteLine($"Is {email} a valid email address? {isValid}");
        }
    }
    
    Output:
    Is algolesson@email.com a valid email address? True
    

    Explanation of Above C# Code:
    • We create a MailAddress object with the given email string.
    • If the email string is not a valid email address, a FormatException is thrown.
    • We catch the exception and return false for invalid emails.

    Method 3: Using Custom Validation.

    For basic validation without using regular expressions or libraries, you can implement a simple custom validation method.

    C# Example Code:

    // C#-sharp code to validate email id using Custom Validation
    using System;
    
    class EmailValidator
    {
        public static bool IsValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
                return false;
    
            if (!email.Contains("@") || !email.Contains("."))
                return false;
    
            // Additional checks can be added based on your requirements
            
            return true;
        }
    
        static void Main()
        {
            string email = "algolesson@email.com";
            bool isValid = IsValidEmail(email);
            
            Console.WriteLine($"Is {email} a valid email address? {isValid}");
        }
    }
    
    Output:
    Is algolesson@email.com a valid email address? True
    

    Explanation of Above C# Code:
    • We perform basic checks like ensuring the email is not null or empty and contains both "@" and ".".
    • You can add additional checks based on your specific requirements.

    So these are a few methods that you can use to validate your email id in C# choose any one of them that is best for you according to your use and requirement.

    C# Program to Formats Data and Time Value.

    Date and time values are crucial in applications for various purposes, such as displaying timestamps, scheduling events, or formatting data for reports. In C#, the DateTime structure is used to work with date and time values. You can format these values into human-readable strings using the ToString method.


    The format string used with the DateTime.ToString method allows you to customize how the date and time are displayed. Here we are going to look at some examples of format strings and the resulting formatted date and time:


    1. "yyyy-MM-dd HH:mm:ss": This format string displays the date and time in the format "Year-Month-Day Hour:Minute:Second."

    C# Code:

    // C-sharp program to print current date and time
    using System;
    
    public class HelloWorld
    {
        public static void Main(string[] args)
        {
            DateTime dateTime = DateTime.Now;
            string formattedDateTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
            Console.WriteLine(formattedDateTime);
        }
    }
    
    Output:
    2023-09-02 14:46:04
    

    2. "dd/MM/yyyy": This format string displays the date in the format "Day/Month/Year."

    C# Code:

    // C-sharp program to print current date and time
    using System;
    
    public class HelloWorld
    {
        public static void Main(string[] args)
        {
            DateTime dateTime = DateTime.Now;
            string formattedDateTime = dateTime.ToString("dd/MM/yyyy");
            Console.WriteLine(formattedDateTime);
        }
    }
    
    Output:
    25/09/2023
    

    3. "MMMM dd, yyyy": This format string displays the date as "Month Day, Year."

    C# Code:

    // C-sharp program to print current date and time
    using System;
    
    public class HelloWorld
    {
        public static void Main(string[] args)
        {
            DateTime dateTime = DateTime.Now;
            string formattedDateTime = dateTime.ToString("MMM dd, yyyy");
            Console.WriteLine(formattedDateTime);
        }
    }
    
    Output:
    July 24, 2023
    

    4. "hh:mm tt": This format string displays the time in a 12-hour clock format with "AM" or "PM."

    C# Code:

    // C-sharp program to print current date and time
    using System;
    
    public class HelloWorld
    {
        public static void Main(string[] args)
        {
            DateTime dateTime = DateTime.Now;
            string formattedDateTime = dateTime.ToString("hh:mm tt");
            Console.WriteLine(formattedDateTime);
        }
    }
    
    Output:
    04:40 PM

    I hope you get some idea about how to get date and time values in the C# programming language. There are many different ways to customize and format the Date and Time value.

    Basic Format Specifiers.

    Below is the list of some commonly used Format Specifiers:
    • "d": Short date pattern (e.g., "7/25/2023").
    • "D": Long date pattern (e.g., "Monday, July 25, 2023").
    • "t": Short time pattern (e.g., "3:30 PM").
    • "T": Long time pattern (e.g., "3:30:45 PM").
    • "f": Full date and short time pattern (e.g., "Monday, July 25, 2023 3:30 PM").
    • "F": Full date and long time pattern (e.g., "Monday, July 25, 2023 3:30:45 PM").
    • "g": General date and short time pattern (e.g., "7/25/2023 3:30 PM").
    • "G": General date and long time pattern (e.g., "7/25/2023 3:30:45 PM").
    • "yyyy-MM-dd": Custom date format (e.g., "2023-07-25").
    • "HH:mm:ss": Custom time format (e.g., "15:30:45").

    Custom Format Specifiers.

    In addition to the predefined format specifiers, you can create custom format strings. Here's how to use some common custom specifiers:
    • "yyyy": Four-digit year (e.g., "2023").
    • "MM": Two-digit month (e.g., "07" for July).
    • "dd": Two-digit day (e.g., "25").
    • "HH": Two-digit hour (24-hour clock, e.g., "15").
    • "hh": Two-digit hour (12-hour clock, e.g., "03").
    • "mm": Two-digit minute (e.g., "30").
    • "ss": Two-digit second (e.g., "45").
    • "fff": Milliseconds (e.g., "123").

    C# Code to Customize Data and Time Format.

    // C-sharp program to customize current date and time
    using System;
    
    public class HelloWorld
    {
        public static void Main(string[] args)
        {
            DateTime now = DateTime.Now;
            
            // "7/25/2023"
            string shortDate = now.ToString("d"); 
            // "Monday, July 25, 2023"
            string longDate = now.ToString("D"); 
            // "3:30 PM"
            string shortTime = now.ToString("t");
            // "3:30:45 PM"
            string longTime = now.ToString("T");
            // "Monday, July 25, 2023 3:30"
            string fullDateTime = now.ToString("F");
            // "2023-07-25 15:30:45"
            string customFormat = now.ToString("yyyy-MM-dd HH:mm:ss"); 
            
            Console.WriteLine(shortDate);
            Console.WriteLine(longDate);
            Console.WriteLine(shortTime);
            Console.WriteLine(longTime);
            Console.WriteLine(fullDateTime);
            Console.WriteLine(customFormat);
        }
    }
    
    Output:
    09/02/2023
    Saturday, 02 September 2023
    15:22
    15:22:07
    Saturday, 02 September 2023 15:22:07
    2023-09-02 15:22:07
    

    Formatting date and time values in C# is essential for displaying information to users or storing timestamps in a specific format. By using format specifiers, you can control how date and time values are presented. Understanding the available format options and creating custom formats when necessary will help you work effectively with date and time values in your C# applications.

    C# Program to Find Fibonacci Series.

    Problem Statement: Write a C# program to generate a Fibonacci series of n terms. The program should display the first n numbers in the Fibonacci sequence.

    Example:

    Input: n = 10
    Output: 
    Fibonacci Series of 10 terms:
    0 1 1 2 3 5 8 13 21 34
    

    Steps to Print Fibonacci Series.

    Below are steps that you need to follow to print a Fibonacci series in C# Sharp:

    Step 1: Take an integer n as input, which represents the number of terms in the Fibonacci series.
    Step 2: Initialize three variables: firstTerm and secondTerm to 0 and 1 (the initial terms of the Fibonacci sequence), and nextTerm to 0 (to hold the next term to be calculated).
    Step 3: Display a header message, such as "Fibonacci Series of n terms."
    Step 4: Use a for loop to generate the Fibonacci series. Start the loop from 0 and iterate n times.
    Step 5: In each iteration of the loop, calculate the nextTerm as the sum of firstTerm and secondTerm.
    Step 6: Update firstTerm and secondTerm to prepare for the next iteration. Set firstTerm to the value of secondTerm, and secondTerm to the value of nextTerm.

    Step 7: Display the nextTerm as the current term in the Fibonacci sequence.

    C# Sharp Code to Print Fibonacci Series.

    // C-sharp code to print Fibonacci Series
    using System;
    
    namespace FibonacciSeries
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.Write("Enter the number of terms: ");
                int n = Convert.ToInt32(Console.ReadLine());
    
                int firstTerm = 0, secondTerm = 1, nextTerm;
    
                Console.WriteLine($"Fibonacci Series of {n} terms:");
                for (int i = 0; i < n; i++)
                {
                    if (i <= 1)
                        nextTerm = i;
                    else
                    {
                        nextTerm = firstTerm + secondTerm;
                        firstTerm = secondTerm;
                        secondTerm = nextTerm;
                    }
                    Console.Write(nextTerm + " ");
                }
            }
        }
    }
    
    Output:
    Enter the number of terms: 8
    Fibonacci Series of 8 terms:
    0 1 1 2 3 5 8 13 
    

    Similar articles:

    C# Program to Generate a Multiplication Table for a Given Number.

    Problem Statement: Write a C# program to generate a multiplication table for a given number n. The table should display the products of n multiplied by numbers from 1 to 10.

    Example:

    Input: n = 5
    Output:
    Multiplication Table for 5:
    5 x 1 = 5
    5 x 2 = 10
    5 x 3 = 15
    5 x 4 = 20
    5 x 5 = 25
    5 x 6 = 30
    5 x 7 = 35
    5 x 8 = 40
    5 x 9 = 45
    5 x 10 = 50
    

    Steps to Solve the Problem:

    Below are the steps that you need to follow to print a multiplication table of any given number:

    Step 1: Take an integer n as input, which represents the number for which the multiplication table needs to be generated.
    Step 2: Display a header message, such as "Multiplication Table for n."
    Step 3: Use a for loop to iterate through numbers from 1 to 10.
    Step 4: In each iteration of the loop, calculate the product of n multiplied by the current loop variable.
    Step 5: Display the multiplication equation, including n, the current loop variable, and the product.

    C# Code Implementation for Multiplication Table.

    // C-sharp code to print multiplication table
    using System;
    
    namespace MultiplicationTable
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.Write("Enter a number: ");
                int n = Convert.ToInt32(Console.ReadLine());
    
                Console.WriteLine($"Multiplication Table for {n}:");
                for (int i = 1; i <= 10; i++)
                {
                    int product = n * i;
                    Console.WriteLine($"{n} x {i} = {product}");
                }
            }
        }
    }
    
    Output:
    Enter a number: 8
    Multiplication Table for 8:
    8 x 1 = 8
    8 x 2 = 16
    8 x 3 = 24
    8 x 4 = 32
    8 x 5 = 40
    8 x 6 = 48
    8 x 7 = 56
    8 x 8 = 64
    8 x 9 = 72
    8 x 10 = 80

    Explanation:

    The above program uses a for loop to generate the multiplication table for the given number. The loop iterates from 1 to 10, calculating the product in each iteration.

    Similar articles:

    DON'T MISS

    Tech News
    © all rights reserved
    made with by AlgoLesson