Find the Sum of values of an Array that are in the Even position including the 0th index.
The scenario is looking like the below image.
According to the scenario we have to loop through the array and check the position of the array items.
Here is the solution to the program.
Including the 0th index
public class Program
{
public static void Main(string[] args)
{
int[] arr = { 10, 20, 30, 40, 50 }; // declaring and initializing the arr variable with the array items.
int result = 0;// declaring a variable to store result
for (int i = 0; i < arr.Length; i++) // for loop for reading each value
{
if (i % 2 == 0)// checking the index position is even by finding mod value 0
{
result += arr[i]; // sum of the values those sartisfy the condition
}
}
Console.WriteLine(result); //printing the result
}
}
O/P- 90
Excluding the 0th index
public class Program
{
public static void Main(string[] args)
{
int[] arr = { 10, 20, 30, 40, 50 }; // declaring and initializing the arr variable with the array items.
int result = 0;// declaring a variable to store result
for (int i = 0; i < arr.Length; i++) // for loop for reading each value
{
if (i!=0 && i % 2 == 0)// checking the index position is not 0 and even by finding mod value 0
{
result += arr[i]; // sum of the values those sartisfy the condition
}
}
Console.WriteLine(result); //printing the result
}
}
O/P- 80
Happy Coding...