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:

C# Program to Calculate Sum of Natural Numbers.

Calculating the sum of natural numbers is a fundamental problem in programming. It involves adding up numbers from 1 to a given positive integer. In this article, we will walk through the process of solving this problem using C# and provide a detailed step-by-step guide.


Problem Statement: Write a C# program to calculate the sum of natural numbers up to a given positive integer n.

Example:

Input: n = 5
Output: 15

Explanation:
The sum of Natural Number from 1 to 5 is 15.

Steps to Find Sum of Natural Numbers.

Below are the steps that you need to follow to solve this problem:

Step 1: Take an integer n as input, which represents the upper limit of the natural numbers.
Step 2: Declare a variable sum and set it to 0. This variable will be used to store the sum of the natural numbers.
Step 3: Use a for loop to iterate through numbers from 1 to n.
Step 4: In each iteration of the loop, add the current number to the sum variable.
Step 5: After the loop completes, output the value of the sum variable as the sum of natural numbers from 1 to n.

C# Code to Find Sum of Natural Numbers Using Loop.

// C# code to find the sum of natural numbers
using System;

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

            int sum = 0;
            for (int i = 1; i <= n; i++)
            {
                sum += i;
            }

            Console.WriteLine($"Sum of natural numbers from 1 to {n} is {sum}");
        }
    }
}
Output:
Enter a positive integer: 6
Sum of natural numbers from 1 to 6 is 21

C# Code to Find Sum Natural Number Using Formula.

We can also find the sum of n natural numbers using the formula sum = n * (n + 1) / 2.
// C# code to find the sum of natural numbers
using System;

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

            int sum = 0;
            //formula to calculate sum of natural numbers
            sum = n * (n + 1) / 2;

            Console.WriteLine($"Sum of natural numbers from 1 to {n} is {sum}");
        }
    }
}
Output:
Enter a positive integer: 5
Sum of natural numbers from 1 to 5 is 15

Similar articles:

How To Resolve Collison in Hash Table in C++.

In hash table implementations, collisions occur when two different keys hash to the same index in the array. To handle collisions, various strategies are employed to ensure efficient storage and retrieval of data. In this article, we'll explore some common methods to resolve collisions and provide working examples in C++.


Collision Resolution Methods in Hash Table.

There are multiple ways to resolve collision in Hash Table (Hash Map) but here we are going to learn about three popular collision resolution methods mentioned below:

Now let's discuss each of these methods one by one in detail and use them in Hash Table Implementation.


Method 1: Chaining (Separate Chaining)

Separate Chaining is a popular collision resolution technique used in hash table implementations. It involves maintaining a linked list at each hash table index to handle collisions.


How does Separate Chaining Work?

It involves four important steps to implement the Chaining method to resolve collision:

1. Initialization: Create an array of linked lists, where each list represents a bucket in the hash table.


2. Insertion: When inserting a key-value pair, compute the hash of the key and determine the index in the array. Add the key-value pair to the linked list at that index.


3. Search: To retrieve a value for a given key, calculate the hash to find the index, and then search the linked list at that index for the key.


4. Collision Handling: When multiple keys hash to the same index (collision), they are simply added to the same linked list at that index.


Implementation of Separate Chaining in C++.

// C++ code for the implementation of Chaining in Hash Table
#include <iostream>
#include <list>
#include <utility>

class HashTable {
private:
    static const int tableSize = 10;
    std::list<std::pair<int, int>> table[tableSize];

    int hashFunction(int key) {
        return key % tableSize;
    }

public:
    void insert(int key, int value) {
        int index = hashFunction(key);
        table[index].emplace_back(key, value);
    }

    int get(int key) {
        int index = hashFunction(key);
        for (const auto& pair : table[index]) {
            if (pair.first == key) {
                return pair.second;
            }
        }
        return -1; // Key not found
    }
};

int main() {
    HashTable hashTable;

    hashTable.insert(5, 50);
    hashTable.insert(15, 150);
    hashTable.insert(25, 250);
 
    std::cout << "Value at key 15: " << hashTable.get(15) << std::endl;

    return 0;
}
Output:
Value at key 15: 150

Method 1: Open Addressing.

Open Addressing is another widely used collision resolution technique in hash table implementations. Unlike Separate Chaining, Open Addressing aims to resolve collisions by placing the collided element directly into the hash table itself.

How Open Addressing Works?

It involves four important steps to implement the Open Address method to resolve collision:

1. Initialization: Create an array (hash table) to hold the key-value pairs. Initially, all slots are empty.

2. Insertion: When inserting a key-value pair, compute the hash of the key and determine the index in the array. If the slot is occupied, use a probing sequence (linear, quadratic, etc.) to find the next available slot.

3. Search: To retrieve a value for a given key, calculate the hash to find the index, and then use the same probing sequence to search for the key.

4. Collision Handling: When a collision occurs, Open Addressing attempts to find the next available slot within the array to place the collided element.

Implementation of Open Addressing in C++.

// C++ code to implement Open Addression in Hash Map
#include <iostream>
#include <vector>
using namespace std;

class HashTable {
private:
    static const int tableSize = 10;
    vector<pair<int, int>> table;

    int hashFunction(int key) {
        return key % tableSize;
    }

    int linearProbing(int index, int attempt) {
        return (index + attempt) % tableSize;
    }

public:
    HashTable() : table(tableSize, std::make_pair(-1, -1)) {}

    void insert(int key, int value) {
        int index = hashFunction(key);
        int attempt = 0;

        while (table[index].first != -1) {
            index = linearProbing(index, ++attempt);
        }

        table[index] = make_pair(key, value);
    }

    int get(int key) {
        int index = hashFunction(key);
        int attempt = 0;

        while (table[index].first != -1) {
            if (table[index].first == key) {
                return table[index].second;
            }
            index = linearProbing(index, ++attempt);
        }

        return -1; // Key not found
    }
};

int main() {
    HashTable hashTable;

    hashTable.insert(5, 50);
    hashTable.insert(15, 150);
    hashTable.insert(25, 250);

    cout << "Value at key 15: " << hashTable.get(15) << endl;

    return 0;
}
Output:
Value at key 15: 150

Method 3: Robin Hood Hashing.

Robin Hood Hashing is a variant of Open Addressing, a collision resolution technique used in hash tables. It focuses on distributing collided elements more evenly within the table to achieve better performance.

How Robin Hood Hashing Works?

It involves four important steps to implement the Robin Hood Hashing method to resolve collision:

1. Initialization: Create an array (hash table) to hold the key-value pairs. Initially, all slots are empty.

2. Insertion: When inserting a key-value pair, calculate the hash of the key and determine the index in the array. If the slot is occupied, compare the distances between the desired index and the current index for both the existing element and the new element. If the new element's distance is smaller, swap the elements and continue probing.

3. Search: To retrieve a value for a given key, calculate the hash to find the index, and then use the same probing sequence to search for the key.

4. Collision Handling: Robin Hood Hashing aims to minimize the difference in the probing distances, ensuring a more balanced distribution of elements.

Implementation of Robin Hood Hashing in C++.

// C++ code to implement Robin Hood Hashing
#include <iostream>
#include <vector>
using namespace std;

class HashTable {
private:
    static const int tableSize = 10;
    vector<pair<int, int>> table;

    int hashFunction(int key) {
        return key % tableSize;
    }

public:
    HashTable() : table(tableSize, make_pair(-1, -1)) {}

    void insert(int key, int value) {
        int index = hashFunction(key);
        int distance = 0;

        while (table[index].first != -1) {
            if (distance > tableSize - 1) {
                break; // Avoid infinite loop
            }

            if (distance > index - hashFunction(table[index].first)) {
                swap(key, table[index].first);
                swap(value, table[index].second);
                distance = index - hashFunction(key);
            }

            index = (index + 1) % tableSize;
            distance++;
        }

        table[index] = make_pair(key, value);
    }

    int get(int key) {
        int index = hashFunction(key);
        int distance = 0;

        while (table[index].first != -1) {
            if (table[index].first == key) {
                return table[index].second;
            }
            index = (index + 1) % tableSize;
            distance++;
        }

        return -1; // Key not found
    }
};

int main() {
    HashTable hashTable;

    hashTable.insert(5, 50);
    hashTable.insert(15, 150);
    hashTable.insert(25, 250);

    cout << "Value at key 15: " << hashTable.get(15) << endl;

    return 0;
}
Output:
Value at key 15: 150

Conclusion:

Collision resolution is a critical aspect of hash table implementations. Chaining is a popular method using linked lists to store colliding elements. This ensures efficient storage and retrieval while keeping collision-related complexities under control. In more advanced implementations, other methods like open addressing and Robin Hood hashing are explored to further optimize hash table performance.

Hash Table Implementation in C++ With Example

Introduction

Hash tables, also known as hash maps, are fundamental data structures in computer science that provide efficient key-value pair storage and retrieval. They are widely used to build data storage and indexing systems, databases, and various algorithms and applications that require quick data access. In this article, we will delve into the implementation of a hash table in C++.


What is a Hash Table in C++?

A hash table is a data structure that stores key-value pairs. It uses a hash function to map each key to an index in an array. This index is used to store and retrieve the corresponding value. 

The key idea behind hash tables is to achieve constant-time O(1) average complexity for insertion, deletion, and retrieval operations.

Hash Table Array of Linked List

Working of Hash Tables.

To understand the inner workings of a Hash Table, you need to understand the three important terms explained below:


Hash Function: When a key is provided, a hash function converts the key into an integer called a hash code. This hash code is used to determine the index in the hash table where the value associated with the key will be stored.


Index Mapping: The hash code is mapped to an index in the hash table's underlying array. This process ensures that different keys are distributed uniformly across the array.


Collision Handling: Since hash functions can produce the same hash code for different keys (known as collisions), hash tables need collision resolution strategies. There are various methods to handle collisions, such as chaining or open addressing

You can read our detailed article on "How To Resolve Collision in Hash Table?" to get a better understanding.

Chaining Method: This strategy involves storing multiple values at the same index using a data structure like a linked list. (alert-passed)

Open Addressing Method: In this approach, when a collision occurs, the algorithm searches for the next available slot (based on a predefined sequence) and places the data there. (alert-passed)

So these are the steps and working of a hash table that we use for solving many complex coding problems.


Implementation of Hash Table in C++.

Implementing a hash table from scratch involves designing the data structure, defining hash functions, handling collisions, and providing methods for insertion, retrieval, and deletion. 


Below we have implemented a simple Hash Table in C++ using Array and Linked List for collision resolution. 


C++ Example Code: 

// C++ code for the implementation of Hash Table
#include <iostream>
#include <list>
using namespace std;

// HashTable class
class HashTable {
private: 
    // Size of the hash table
    static const int tableSize = 10;
    // Array of linked lists
    list<pair<int, int>> table[tableSize];
    
    // Hash function to map key to an index
    int hashFunction(int key) {
        return key % tableSize;
    }

public:
    // Insert a key-value pair into the hash table
    void insert(int key, int value) {
        int index = hashFunction(key);
        table[index].emplace_back(key, value);
    }
    
    // Get the value associated with a key
    int search(int key) {
        int index = hashFunction(key);
        for (const auto& pair : table[index]) {
            if (pair.first == key) {
                return pair.second;
            }
        }
        return -1; // Key not found
    }
    
    // Remove a key-value pair from the hash table
    void remove(int key) {
        int index = hashFunction(key);
        table[index].remove_if([&key](const std::pair<int, int>& pair) {
            return pair.first == key;
        });
    }
};

int main() {
    HashTable ht;

    ht.insert(101, 10);
    ht.insert(201, 20);
    ht.insert(302, 30);

    cout << "Value at key 201: " << ht.search(201) << endl;

    ht.remove(201);
    cout << "Value at key 201 after removal: " << ht.search(201) << endl;

    return 0;
}
Output:
Value at key 201: 20
Value at key 201 after removal: -1


Explanation:

1. We define a HashTable class that contains an array of linked lists (table) to store the key-value pairs.
2. The hashFunction method calculates the index for a given key using the modulo operation.
3. The insert method inserts a key-value pair into the appropriate linked list.
4. The get method searches for a key and returns its associated value.
5. The remove method removes a key-value pair from the linked list.
6. In the example usage, we create a hash table, insert key-value pairs, search for a value, and remove a key.

This is the basic working and implementation of the Hash Table (Hash Map) in C++ and implementing it from scratch gives us a better understanding of how it works and its application.

C++ Standard Library (STL) Hash Containers.

In real-life usage, we need not to implement a complete Hash Table from the beginning because C++ provides hash containers as part of the Standard Template Library (STL) that make it easy to use hash tables:
  • std::unordered_map: This is an implementation of a hash table that stores key-value pairs. It provides fast access, insertion, and deletion operations.
  • std::unordered_set: This is a hash table that stores unique elements, allowing efficient membership checking.
Here's an C++ example of how to use std::unordered_map and std::unordered_set:

// C++ code for working of unordered_map and unordered_list
#include <iostream>
#include <unordered_map>
#include <unordered_set>
using namespace std;

int main() {
    unordered_map<string, int> scores;
    scores["Alice"] = 95;
    scores["Bob"] = 85;

    cout << "Alice's score: " << scores["Alice"] << endl;

    unordered_set<int> uniqueNumbers;
    uniqueNumbers.insert(5);
    uniqueNumbers.insert(10);

    if (uniqueNumbers.find(5) != uniqueNumbers.end()) {
        cout << "Number 5 found!" << endl;
    }

    return 0;
}
Output:
Alice's score: 95
Number 5 found!

In this example, we've used std::unordered_map to store student scores and std::unordered_set to store unique numbers.

Usage of Hash Tables.

Hash tables have a wide range of applications due to their fast retrieval times. Some common use cases include:
  • Databases: Hash tables are used for indexing and searching records in databases.
  • Caching: They are used to cache frequently accessed data for quick retrieval.
  • Compiler Symbol Tables: Hash tables store identifiers (variable names, function names) and their corresponding attributes in compilers.
  • Implementing Sets and Maps: Hash tables are used to implement set and map data structures.
  • Network Routing Tables: Hash tables can help route network packets efficiently.

Conclusion.

Hash tables are powerful data structures that enable efficient storage and retrieval of key-value pairs. Remember that real-world hash tables may require handling more complex collision resolution methods, resizing, and more advanced hash functions.

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:

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson