In this tutorial I will show how to find Odd numbers in C#. I have given two example first example is very simple.
- First example I have used simple for loop to find Odd numbers.
- Second example I have created a Linq for finding Odd Numbers.
C# Code: First example I have used simple for loop to find Odd numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Program { static void Main(string[] args) { int[] numbers = new int[] { 10, 12, 20, 21, 23, 25, 26, 23, 20, 17, 85, 60, 30, 35 }; Console.WriteLine("\nAll Numbers"); for (int i = 0; i < numbers.Length; i++) { Console.Write("{0} ", numbers[i]); } Console.WriteLine("\n\nOdd Numbers"); for (int i = 0; i < numbers.Length; i++) { if (numbers[i] % 2 != 0) Console.Write("{0} ", numbers[i]); } Console.ReadLine(); } } |
C# Code: Second example I have created a Linq for finding Odd Numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Program { static void Main(string[] args) { int[] numbers = new int[] { 10, 12, 20, 21, 23, 25, 26, 23, 20, 17, 85, 60, 30, 35 }; Console.WriteLine("\nAll Numbers"); numbers.ToList().ForEach(number => Console.Write("{0} ", number)); Console.WriteLine("\n\nOdd Numbers"); var oddNumbers = numbers.ToList().Where(number => number % 2 != 0).ToList(); oddNumbers.ForEach(number => Console.Write("{0} ", number)); Console.ReadLine(); } } |
Output: