coleen feador
coleen feador

Reputation: 9

My code is not working and it missing something for the array

string[] names = { "Al Dente", "Anna Graham", "Earle Bird", "Ginger Rayle", "Iona Ford" };

int i = 0;
while (i < names.Length)
{
    Console.WriteLine(names[0]);
}

why is my code not working I feel its something very simple to modify I want it to output them calling it names. What am I missing?

Upvotes: 0

Views: 130

Answers (5)

it is recommended to create a reference for the array like this

string[] names = new string[] { "Al Dente", "Anna Graham", "Earle Bird", "Ginger Rayle", "Iona Ford" };

but your mistake here is in the loop, you have to make a counter that increments or decrements like this:

int i = 0;
while (i < names.Length)
{
    Console.WriteLine(names[i]);
    i++;
}

OR, if you want ot print names in REVERSE order :

int i = names.Length;
while (i > 0)
{
    Console.WriteLine(names[i]);
    i--;
}

Upvotes: 0

Erik BRB
Erik BRB

Reputation: 315

Or you can use for:

string[] names = { "Al Dente", "Anna Graham", "Earle Bird", "Ginger Rayle", "Iona Ford" };

for (int i = 0; i < names.Length; i++)
{
    Console.WriteLine(names[i]);
}

Upvotes: 0

mihai
mihai

Reputation: 4722

while (i < names.Length)
{
    Console.WriteLine(names[i]);
    i++;
}

You can also try the shorter version

foreach(var name in names)
    Console.WriteLine(name);

or even

names.ForEach(Console.WriteLine);

Upvotes: 1

Steve
Steve

Reputation: 216293

You never exit from the loop because the variable i is never incremented and thus is always zero

string[] names = { "Al Dente", "Anna Graham", "Earle Bird", "Ginger Rayle", "Iona Ford" };

int i = 0;
while (i < names.Length)
{
    // Write the i-th element of the array
    Console.WriteLine(names[i]);

    // Increment i of one to allow the loop to exit when i reaches the names.Length value
    i++;
}

then you want surely print the i element of the array at each loop so use names[i]

To avoid these problems then you could use a foreach loop

foreach(string s in names)
    Console.WriteLine(s);

Upvotes: 1

rosstex
rosstex

Reputation: 823

You need Console.WriteLine(names[i]);, with names[i] rather than names[0]. You also aren't incrementing i! Something like:

string[] names = { "Al Dente", "Anna Graham", "Earle Bird", "Ginger Rayle", "Iona Ford" };

int i = 0;
while (i < names.Length)
{
    Console.WriteLine(names[i]);
    i++;
}

Upvotes: 0

Related Questions