Search code examples
c#for-loopxamarin-studio

Rewriting a Value in a For Loop


[ Resovled. Thanks again! I dunno why loops always trip me up, haha. ]

Yet another loop question. I think this is going to be my calling card. This time, I'm working with C#. Trying to figure out a good way to phrase this, but say this is my base code:

string[] daftChildren = new string[] { "Deidra", "Jolie", "Johnna", 
                                       "Kayben", "Saber", "Adam" };

for (int i = 0; i < daftChildren.Length; i ++) {
    Console.WriteLine(daftChildren[i] + " is a member of the family.");
    if (daftChildren[i] == "Saber") {
        Console.Write("Saber is a part of the family... for now.");
    }
}

The code is self explanatory: I'm using the for loop to list each member of the family. If one of the family members listed is Saber, then it prints "Saber is a part of the family... for now." But here's the rub.

With the above code, my output will print "Saber is a part of the family" and "Saber is a part of the family... for now." How do I write it so only if block prints.

I hope I asked this clearly enough. Thanks for the help in advance!


Solution

  • A really sneaky way to do it:

    string[] daftChildren = new string[] { "Deidra", "Jolie", "Johnna", "Kayben", "Saber", "Adam" };
    
        for (int i = 0; i < daftChildren.Length; i ++) {
            Console.Write(daftChildren[i] + " is a member of the family.");
            if (daftChildren[i] == "Saber") {
                Console.Write(".. for now.");
            }
            Console.WriteLine();