24 Feb 2024
Beginner
To find the maximum number in an array in C# without using any built-in methods, you can iterate through the array and keep track of the maximum number encountered. Here's how you can do it:
using System;
class Program
{
static void Main(string[] args)
{
// Sample array
int[] numbers = { 10, 5, 8, 20, 3, 15 };
// Variable to store the maximum number
int max = numbers[0]; // Initialize max with the first element of the array
// Iterate through the array starting from the second element
for (int i = 1; i < numbers.Length; i++)
{
// Check if the current element is greater than the current max
if (numbers[i] > max)
{
// Update max if the current element is greater
max = numbers[i];
}
}
// Print the maximum number
Console.WriteLine("The maximum number in the array is: " + max);
}
}
In the above code:
- We initialize
maxwith the first element of the array. - We iterate through the array starting from the second element.
- In each iteration, we compare the current element with the current maximum (
max). - If the current element is greater than the current maximum, we update
maxwith the value of the current element. - Finally, we print out the maximum number after the loop has finished iterating through the array.