简体   繁体   中英

Accessing array elements in C#

I am having trouble with writing code that takes a user inputted integer and uses that integer to access that element in the array and gets the sum of the element that the user inputted and the one before and after. For example, if a user inputs 1 I would want to have the element 0+1+2. Please let me know if this information isn't enough and I will try to elaborate more.

Edit: To add more information, this is the code I have got done already and haven't had any problems with. The problem I am having is coming up with code that will be efficient in completing the task of adding the indexes from the user input. Another example, if the user inputs 8 I would like the program to add the indexes 7+8+9, the number below the user input, user input and above.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project
{
    class Program
{
    static void Main(string[] args)
    {
        int user;
        int[] numbers = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 };
        Console.Write("Enter a number from 1 to 8:");
        user = Convert.ToInt32(Console.ReadLine());
        if (user > 8 || user < 1)
        {
            Console.WriteLine("Please enter a valid number.");
        }
        for(int sum)
    }
}
}

Well, the sum would be:

int sum = numbers[user - 1] + numbers[user] + numbers[user+1];

Does that answer your question?


EDIT You started to write for (int sum) which doesn't really make sense. The most efficient way is the above, but you can do it with a loop, too:

int sum = 0;
for (int idx = -1; i < 2; i++)
    sum = numbers[user + idx];

However, that's much harder to understand than the above...


EDIT 2 I don't know if the array you provided is the real array you use, but in that case, the answer is even easier:

sum = numbers[user] * 3;

:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM