Basic C# coding Practice

 

// Q1. Reverse number without 3rd variable
		int a= 20;
		int b =30;
		a = a+b;
		b= a-b;
		a= a-b;
		
		Console.WriteLine(a +" "+b);

// Q2 Chech string is Palindrome or not - EG:- MADAM
		string str1 = "";
		Console.WriteLine("Eater a string");
		str1 = Console.ReadLine();
		char[] arr = str1.ToCharArray();
		Array.Reverse(arr);
		String str_rev = new String(arr);
		
		if(str_rev.Equals(str1)){
			Console.WriteLine("{0} is pelindrom", str1);
		}
		else {
			Console.WriteLine("{0} is not pelindrom", str1);
		}

//Q3. can we stroe Different Type data IN Array without using clooection
		// Answer - yes, we can do that by creting an array of object type
		Object[] arr = new Object[3];
		arr[0]=11;
		arr[1]="SKS";
		arr[2]=10.5;
		foreach(object item in arr){
		 Console.WriteLine(item);
		}

//Q write a prime number b/w to value 
		Console.WriteLine("Enter two Integer for all Prime number in b/w");
		int start = int.Parse(Console.ReadLine());
		int end = int.Parse(Console.ReadLine());
		
		for(int i=start; i<=end; i++){
			if(IsPrime(i)){
				Console.Write(i +" ");
			}
		}
	}
	public static bool IsPrime(int num) {
		if (num<=1) return false;
		// Check the divisibility from 2 to sqrt(n)
		for(int i=2; i*i<=num;i++){
			if(num %i ==0) return false;
		}
		return true;
	}


    //Q: Reverse string
	// Answer 1. usnig Array.Reverse()
	// 2. Using Linq Reverse()
	// 3. Using a for loop with StringBuilder
	// 4. Using another Empty string 
		string str ="mohan";
	// M-1 usnig Array.Reverse()
		if(string.IsNullOrEmpty(str)){
			Console.WriteLine("Empty String.");
		}
		char[] charArray = str.ToCharArray();
		Array.Reverse(charArray);
		Console.WriteLine(new string(charArray));
	// M-2 Using Linq Reverse() - Use System.Linq
		string RevStr =new string (str.Reverse().ToArray());
		Console.WriteLine(RevStr);
	// M-3 Using a for loop with StringBuilder - Use System.Text
		StringBuilder revrsed = new StringBuilder(str.Length);
		for(int i = str.Length-1;i>=0;i--){
			revrsed.Append(str[i]);
		}
		Console.WriteLine(revrsed.ToString());
	// M-4 Using another Empty string 
		string revStr = String.Empty;
		for(int i=str.Length-1; i>=0;i--){ 
			revStr +=str[i];
		}
		Console.WriteLine(revStr);

Q) what is yield in c#

The yield keyword in C# is used in an iterator block to provide a custom iteration without creating a temporary in-memory collection.

It enables lazy evaluation and deferred execution, which means items are generated and returned one at a time, only when requested by the consuming code (e.g., a foreach loop).

Key Concepts and Usage

The yield keyword has two primary forms:

  • yield return expression: Returns a single element of the sequence and pauses the execution of the iterator method, saving its current state. Execution resumes from the preserved location the next time the caller requests the next item in the sequence.

  • yield break: Terminates the iteration entirely and signals that there are no more elements in the sequence, transferring control back to the caller permanently.

Requirements and Limitations

  • Return Type: A method, property, or operator using yield must return one of the iterator interfaces: IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.

  • Method Signature: The method cannot have ref or out parameters.

  • Block Restrictions: yield return cannot be used inside try-catch blocks, but it can be used in a try block if it only has a corresponding finally block. yield break can be used in try or catch blocks.

  • Context: It cannot be used in anonymous methods or lambda expressions.

Example

Here is an example demonstrating the difference between returning a List<T> and using yield return.

Without yield (Immediate Execution):

The entire list is populated in memory before being returned to the caller.

public static IEnumerable<int> GetNumbersWithoutYield()
{
    List<int> numbers = new List<int>();
    Console.WriteLine("Populating list...");
    for (int i = 0; i < 5; i++)
    {
        numbers.Add(i);
    }
    Console.WriteLine("Returning list.");
    return numbers;
}

With yield (Deferred Execution/Lazy Evaluation):

Each number is generated and returned on demand as the caller iterates through it, saving memory and processing time if only a partial sequence is consumed.

public static IEnumerable<int> GetNumbersWithYield()
{
    Console.WriteLine("Iterator starting...");
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine($"Yielding {i}");
        yield return i; // Pauses here
    }
    Console.WriteLine("Iterator ending.");
}

// Consuming code
foreach (var number in GetNumbersWithYield())
{
    Console.WriteLine($"Consumed {number}");
}

Output of the yield example:

Iterator starting...
Yielding 0
Consumed 0
Yielding 1
Consumed 1
Yielding 2
Consumed 2
Yielding 3
Consumed 3
Yielding 4
Consumed 4
Iterator ending.

The output shows how control flows back and forth between the consumer and the iterator method, demonstrating the state-preserving and lazy nature of yield.


		// Reverse Number
		
		//M-1: Digit Extraction
		int num = 12345;
		int reverse= 0;
		while(num!=0){
		 	 int reminder = num % 10; // Extract the last digit
			reverse = (reverse *10) + reminder;// Append the digit to the reversed number
			num /=10;// Remove the last digit from the original number
		}
		Console.WriteLine(reverse);
		// M-2 String Conversion and Array.Reverse()
		int number = 123456;
		string s = Math.Abs(number).ToString();
		char[] charArray = s.ToCharArray();
		Array.Reverse(charArray);
		string reveersedString = new string(charArray);
		int reversedNum = int.Parse(reveersedString);
		
		Console.WriteLine(reversedNum);

Comments

Popular posts from this blog