In this example I’ll show you how to save the odd numbers within the numbers received from the user to the array.
In this example, we will get 10 numbers from the user. We will calculate the number of odd numbers among the received numbers.
Output:
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class Program { static void Main(string[] args) { int[] numbers = new int[10]; int oddCount = 0; for (int i = 0; i < numbers.Length; i++) { Console.Write("Enter a number: "); numbers[i] = Convert.ToInt32(Console.ReadLine()); if (numbers[i] % 2 != 0) oddCount++; } //Store odd numbers into an array int[] oddNumbers = new int[oddCount]; for (int i = 0; i < numbers.Length; i++) { if (numbers[i] % 2 != 0) oddNumbers[--oddCount] = numbers[i]; } for (int i = 0; i < oddNumbers.Length; i++) { Console.Write(oddNumbers[i] + " "); } Console.ReadLine(); } } |