0
static string[] myFriends = new string[] {"Robert","Andrew","Leona","Ashley"};

How do I go about pulling the names from this static string array, so that I can use them separately on different lines? Such as:

Robert is sitting in chair 1

Andrew is sitting in chair 2

Leona is sitting in chair 3

Ashley is sitting in chair 4

I'm guessing I would have to assign them to values, then in a WriteLine Command, I would input {1}, {2}, {3} etc. for each corresponding name?

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

namespace Friends
{
class Program
{
    public void count(int inVal)
    {
        if (inVal == 0)
            return;
        count(inVal - 1);

        Console.WriteLine("is sitting in chair {0}", inVal);
    }

    static void Main()
    {
        Program pr = new Program();
        pr.count(4);
    }

    static string[] myStudents = new string[] {"Robert","Andrew","Leona","Ashley"};

}
}

I want to add the names to the "is sitting in chair" line.

2
  • 2
    show us your code so that we can correct you! Commented Oct 11, 2013 at 2:45
  • As a side note: you mentioned that this is an exercise in recursive functions. Please understand that this is more an example of when NOT to use recursion. Commented Oct 11, 2013 at 7:09

2 Answers 2

1

I think the for or foreach as @TGH mentions is the way to go. It's not a good use of recursion, though it sounds like a textbook exercise instead of industrial use of recursion anyway.

If you want to fix yours as-is, using recursion, change the method to:

public void count(int inVal)
{
    if (inVal == 0)
        return;
    count(inVal - 1);

    // arrays are 0-based, so the person in chair 1 is at array element 0
    Console.WriteLine("{0} is sitting in chair {1}", myStudents[inVal-1], inVal);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Okay I changed it as-is, and it works perfectly! Thank you all and thank you jglouie!! Thanks for the comment about arrays too! :)
0

Use Linq extension to simpify the code to :

int chairNo =1;
myFriends.ToList().ForEach(x =>  Consol.WriteLine(string.Format("{0} is sitting in chair {1}", x, chairNo++)));

Remember to put following on top; using System.Linq;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.