C# loop arrays

I having trouble outputting:
“ The main color of grapes is purple.”
“The main color of apples is red.”
“The main color of limes is green.”
“The main color of lemons is yellow.”

My output keep printing:
The main color of grapes is purple. 4 time. HELP PLZ!

Here’s my code:
//strings for randomthings
string randomThings = new string {“grapes”, “apples”, “limes”, “lemons” };
//strings for colors
string colors = new string {“purple”, “red”, “green”, “yellow” };

            for (int j = 0; j < colors.Length; j++)
            {
                if (randomThings[j] == "grapes")
                {
                    Console.WriteLine("The main color of " +randomThings[0] + " is " + colors[0]);
                    //Console.WriteLine("The main color of " + randomThings[1] + " is " + colors[1]);
                }

            }

48%20AM

You don’t need an if statement to print the output you are looking for. Inside your for loop you only need a Console.WriteLine(); statement. j is going to start at 0, and increase in value by 1 each time the code inside its block { } executes, so you should use j as the index for your for your arrays instead of 0. Using 0, you are accessing the first element of each array every time the code executes.

Thanks for your feedback. I tried that already but i did not print out the way i wanted to. I want it to print out a one sentence for each string. like- “ The main color of grapes is purple.” then “The main color of apples is red.” and so on.

The way I’ve described it will do exactly that. Your code should resemble this. You’ll have to substitute in your variable names, and array values.

string[] letters = new string[] {"A", "B", "C"};
string[] foods = new string[] {"apple", "banana", "carrot"};

for (int i = 0; i < letters.Length; i++) {
  Console.WriteLine(letters[i] + " is for " + foods[i] + ".");
}

Output:

A is for apple.
B is for banana.
C is for carrot.

Happy coding!

1 Like

Appreciate your help!

1 Like