Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Saturday, 16 November 2024

Coding Test: Extension method

Create an extension method to filter out odd and even numbers from a collection like a list or array. Below is an example of how you can write such extension methods.

1. Extension Method to Filter Odd Numbers

This method filters odd numbers from a collection of integers.

using System;
using System.Collections.Generic;

public static class NumberExtensions
{
    // Extension method to get odd numbers from an IEnumerable<int>
    public static IEnumerable<int> GetOddNumbers(this IEnumerable<int> numbers)
    {
        foreach (var number in numbers)
        {
            if (number % 2 != 0)
            {
                yield return number;
            }
        }
    }

    // Extension method to get even numbers from an IEnumerable<int>
    public static IEnumerable<int> GetEvenNumbers(this IEnumerable<int> numbers)
    {
        foreach (var number in numbers)
        {
            if (number % 2 == 0)
            {
                yield return number;
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        // Filter odd numbers using extension method
        var oddNumbers = numbers.GetOddNumbers();
        Console.WriteLine("Odd Numbers:");
        foreach (var number in oddNumbers)
        {
            Console.WriteLine(number);
        }

        // Filter even numbers using extension method
        var evenNumbers = numbers.GetEvenNumbers();
        Console.WriteLine("Even Numbers:");
        foreach (var number in evenNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

Output: 

Odd Numbers: 1 3 5 7 9 Even Numbers: 2 4 6 8 10

Summary:

  • The GetOddNumbers and GetEvenNumbers methods are simple extension methods that work on any collection implementing IEnumerable<int>.
  • yield return is used in the methods to lazily return the filtered numbers without creating a new list upfront, making it memory efficient.
Continue Reading →

Coding Test : find common character between two string

 Try to find common character with it's count between two strings and display it console.

Input:  string1: Dotnet , string2: Hotstar

Output:  o - 1, t - 2

  string str1 = "Dotnet";
  string str2 = "Hotstar";

  List<char> lst1 = str1.ToList();
  List<char> lst2 = str2.ToList();
  Dictionary<char, int> commonCharsDic = new Dictionary<char, int>();

  foreach (char c in lst1)
  {
      if (lst2.Contains(c))
      {
          int val;
          if (commonCharsDic.TryGetValue(c, out val))
              commonCharsDic[c] = val + 1;
          else
              commonCharsDic.Add(c, 1);

          lst2.Remove(c);
      }
  }

  foreach (var item in commonCharsDic)
      Console.WriteLine("{0}-{1}", item.Key, item.Value);

 // Output: o-1 , t-2

below is another similar logic


  string str1 = "Dotnet";
  string str2 = "Hotstar";

  List<char> lst1 = str1.ToList();
  List<char> lst2 = str2.ToList();
 
  var res2 = lst1.Intersect(lst2).ToList();
  Dictionary<char, int> dict = new Dictionary<char, int>();

  foreach (var item in res2)
      dict.Add(item, 0);

  foreach (var item in lst1)
  {
      if (lst2.Contains(item))
          dict[item] = dict[item] + 1;

      lst2.Remove(item);
  }

  foreach (var item in dict)
      Console.WriteLine("{0}-{1}", item.Key, item.Value);

 // Output: o-1 , t-2


Continue Reading →

Tuesday, 31 October 2023

C# String data type : Exercises

 C# String data type : Exercises, Practice, Solution

Write a C# Sharp program to find the length of a string without using a library function.

  using System;  
  public class Exercise2
  {  
      public static void Main()
  {
      string str; /* Declares a string of size 100 */
      int l= 0;
   
        Console.Write("Input the string : ");
        str = Console.ReadLine();
 
           foreach(char chr in str)
          {
              l += 1;
          }
     Console.Write("Length of the string is : {0}\n\n", l);
    }
  }

Write a program in C# Sharp to count the total number of words in a string.

  using System;  
  public class Exercise5
  {  
      public static void Main()
      {
          string str;
          int i, wrd,l;
   
            Console.Write("Input the string : ");
            str = Console.ReadLine();
   
             l = 0;
             wrd = 1;
 
      /* loop till end of string */
      while (l <= str.Length - 1)
      {
          /* check whether the current character is white space or new line or tab character*/
          if(str[l]==' ' || str[l]=='\n' || str[l]=='\t')
          {
              wrd++;
          }
 
          l++;
      }
 
     Console.Write("Total number of words in the string is : {0}\n", wrd);
    }
  }

Write a program in C# Sharp to compare two strings without using a string library functions.

  using System;  
  public class Exercise6
  {  
      public static void Main()
  {
      string str1, str2;
      int flg=0;
      int i = 0, l1, l2, yn = 0;
     
        Console.Write("Input the 1st string : ");
        str1 = Console.ReadLine();    
       
        Console.Write("Input the 2nd string : ");
        str2 = Console.ReadLine();    
 
      l1=str1.Length;
      l2=str2.Length;
      /*compare checking when they are equal in length*/    
      if(l1==l2)
    {
      for(i=0;i<l1;i++)
        {
            if(str1[i] != str2[i])
            {
              yn= 1;
              i= l1;       
            }
        }
    }
  /*initialize the flag where they are equal, smaller and greater in length*/  
      if(l1 == l2)
          flg=0;
      else if(l1 > l2)
          flg=1;
      else if(l1 < l2)
          flg=-1;
  /*display the message where the strings are same or smaller or greater*/  
      if(flg == 0)
      {
         if(yn==0)
         Console.Write("\nThe length of both strings are equal and \nalso, both strings are same.\n\n");
         else
              Console.Write("\nThe length of both strings are equal \nbut they are not same.\n\n");
      }
      else if(flg == -1)
      {
         Console.Write("\nThe length of the first string is smaller than second.\n\n");
      }
      else
      {
         Console.Write("\nThe length of the first string is greater than second.\n\n");
      }
    }
  }

Write a program in C# Sharp to count the number of alphabets, digits and special characters in a string.

using System;  
  public class Exercise7  
  {  
   public static void Main()
  {
      string str;
      int alp, digit, splch, i,l;
      alp = digit = splch = i = 0;
 
        Console.Write("Input the string : ");
        str = Console.ReadLine();
        l=str.Length;
 
       /* Checks each character of string*/
 
      while(i<l)
      {
          if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
          {
              alp++;
          }
          else if(str[i]>='0' && str[i]<='9')
          {
              digit++;
          }
          else
          {
              splch++;
          }
 
          i++;
      }
 
     Console.Write("Number of Alphabets in the string is : {0}\n", alp);
     Console.Write("Number of Digits in the string is : {0}\n", digit);
     Console.Write("Number of Special characters in the string is : {0}\n\n", splch);
    }
  }

Write a program in C# Sharp to copy one string to another string.

using System;  
public class Exercise8  
{  
    public static void Main()
{
    string str1;
    int  i,l;

      Console.Write("\n\nCopy one string into another string :\n");
      Console.Write("-----------------------------------------\n");  
      Console.Write("Input the string : ");
      str1 = Console.ReadLine();
     
      l=str1.Length;
      string[] str2=new string[l];

    /* Copies string1 to string2 character by character */
    i=0;
    while(i<l)
    {
        string tmp=str1[i].ToString();
        str2[i] = tmp;
        i++;
    }
   Console.Write("\nThe First string is : {0}\n", str1);
   Console.Write("The Second string is : {0}\n", string.Join("",str2));
   Console.Write("Number of characters copied : {0}\n\n", i);
  }
}

Write a C# Sharp program to count the number of vowels or consonants in a string.

  public class Exercise9  
  {  
  public static void Main()
  {
      string str;
      int i, len, vowel, cons;
     
      Console.Write("Input the string : ");
      str = Console.ReadLine();  
 
      vowel = 0;
      cons = 0;
      len = str.Length;
 
      for(i=0; i<len; i++)
      {
 
          if(str[i] =='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' || str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U')
          {
              vowel++;
          }
          else if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
          {
              cons++;
          }
      }
     Console.Write("\nThe total number of vowel in the string is : {0}\n", vowel);
     Console.Write("The total number of consonant in the string is : {0}\n\n", cons);
    }
  }

Write a C# Sharp program to find the maximum number of characters in a string.  Click here

Find the character and Number of Occurrence in given word where number of Occurrence is more then 1

            string val = "Interview";

            Dictionary<string, int> dict = new Dictionary<string, int>();
            for (int i = 0; i < val.Length; i++)
            {
                string c = val[i].ToString().ToLower();
                if (dict.ContainsKey(c))
                {
                    dict[c] = dict[c] + 1;
                }
                else
                {
                    dict[c] = 1;
                }
            }

            foreach (var d in dict.Where(x=> x.Value > 1))
            {
                Console.WriteLine("Key: "+d.Key+" Value: "+d.Value);
            }

Output:

Key: i Value: 2

Key: e Value: 2


Continue Reading →

Tuesday, 14 April 2015

Abstract Vs. Static

Can you create abstract function as Static?
A static member cannot be marked as override, virtual, or abstract.

Can you create static function in Abstract class?
Yes.

Example: 

namespace ConsoleApplication2
{
    public abstract class ps
    {
        public ps()
        {
        }
        public ps(string a)
        {

        }
        public abstract string getMessage();
        public static void Helloworld() { Console.WriteLine("hello"); }

         //A static member cannot be marked as override, virtual, or abstract
        //public static abstract void Helloworld() { Console.WriteLine("hello"); }
        //public static abstract string GetName();
    }

    public class Program :ps
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p.getMessage());
            Helloworld();
            Console.Read();
        }

        public override string getMessage()
        {
            return "message hello.";
        }
    }
}

Is it required to override all abstract function in derived class?
Yes
Continue Reading →

Thursday, 2 April 2015

Console Program

1: Program to find remainder without using modulo or % operator
class Program
{
    // This function returns remainder of
    // num/divisor without using %
    // (modulo) operator
    static int getRemainder(int num, int divisor)
    {
        return (num - divisor * (num / divisor));
    }

    //initialize an array with 20 numbers and print count of it's all prime number
    static void Main(string[] args)
    {
        Console.Write(getRemainder(10, 3));
        Console.ReadLine();
    }
}
Output : 1

2: I have a string "nbaguarirot". you have to Check if it contains all the characters of nagarro word in sequence.
namespace nagarro
{
    public class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.checkString("nbaguarirot");
            Console.ReadLine();
        }

        public void checkString(string name)
        {
            StringBuilder builder = new StringBuilder();
            char[] myarray = { 'n', 'a', 'g', 'a', 'r', 'r', 'o' };

            int i = 0;
            foreach (char item in myarray)
            {
                for (int a= i; a <= name.Length; a++)
                {
                    char val = Convert.ToChar(name.Substring(i, 1));
                    if (item == val)
                    {
                        builder.Append(val);
                        i++; break;
                    }
                    else
                    {
                        i++;
                        continue;
                    }
                }
            }
            StringBuilder b = new StringBuilder();
            b.Append("nagarro");

            if (b.Equals(builder))
            {
                Console.Write("true");
            }
            else
            {
                Console.Write("false");
            }
        }
    }
}

3: Reverse a string without any function?
  string str = "", reverse = "";
  int len = 0;
  Console.WriteLine("Enter a String");
  str = Console.ReadLine();
 
  len = str.Length - 1;
  while (len >= 0)
  {
      reverse = reverse + str[len];
      len--;
  }
 
  Console.WriteLine("Reverse String is {0}", reverse);


Continue Reading →

Thursday, 12 February 2015

C# Program - to Check Number is Even or Odd

This C# Program checks if a given integer is Odd or Even. Here if a given number is divisible by 2 with the remainder 0 then the number is an Even number. If the number is not divisible by 2 then that number will be an Odd number.

   class Program
        {
            static void Main(string[] args)
            {
                int i;
                Console.Write("Enter a Number : ");
                i = int.Parse(Console.ReadLine());
                if (i % 2 == 0)
                {
                    Console.Write("Entered Number is an Even Number");
                    Console.Read();
                }
                else
                {
                    Console.Write("Entered Number is an Odd Number");
                    Console.Read();
                }
            }

        }
Continue Reading →

C# Program - to Check Leap Year or Not

This C# Program Checks Whether the Entered Year is a Leap Year or Not.When A year is divided by 4. If remainder becomes 0 then the year is called a leap year..

namespace Program
    {
        class leapyear
        {
            static void Main(string[] args)
            {
                leapyear obj = new leapyear();
                obj.readdata();
                obj.leap();
            }
            int y;
            public void readdata()
            {
                Console.WriteLine("Enter the Year in Four Digits : ");
                y = Convert.ToInt32(Console.ReadLine());
            }
            public void leap()
            {
                if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
                {
                    Console.WriteLine("{0} is a Leap Year", y);
                }
                else
                {
                    Console.WriteLine("{0} is not a Leap Year", y);
                }
                Console.ReadLine();
            }
        }

     }
Continue Reading →

C# Program - Armstrong Number

This C# Program is written to Check Whether the Entered Number is an Armstrong Number or Not . An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself.

    class programme
    {
        static void Main(string[] args)
        {
            int number, remainder, sum = 0;
            Console.Write("Enter the Number: ");
            number = int.Parse(Console.ReadLine());
            for (int i = number; i > 0; i = i / 10)
            {
                remainder = i % 10;
                sum = sum + remainder * remainder * remainder;

            }
            if (sum == number)
            {
                Console.Write("Entered Number is an Armstrong Number");
            }
            else
                Console.Write("Entered Number is not an Armstrong Number");
            Console.ReadLine();
        }
    }


Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives