0

I am very confused on how to change a for loop into a foreach loop. I have a piece of code that is similar to a program that I working on to implement a foreach loop into.

{
    class Program
    {
        static void Main(string[] args)
        {
            int entered = 0;
            string ayethatsprettygood;
            bool dothesalamander = false;

        string[] zipcode;
        zipcode = new string[10] {"12789", "54012", "54481", "54982", "60007", "60103", "60187", "60188", "71244", "90210" };        //This array is the zipcodes

        double[] prices;
        prices = new double[10] { 2.40, 3.00, 3.50, 4.00, 4.50, 5.00, 5.25, 5.75, 6.10, 10.003 };             //This array is the prices

        Console.Write("Enter a Zipcode:");
        ayethatsprettygood = Console.ReadLine();


        for (int i = 0; i < zipcode.Length; i++) {

            if (ayethatsprettygood == zipcode[i])

            {
                dothesalamander = true;
                entered = i;
                break;
            } 

        }

        if (dothesalamander == true)
        {

            Console.WriteLine("We deliver to this zipcode {0} the price of delivery is {1}", zipcode[entered], prices[entered].ToString("C2"));
        }
        else
            Console.WriteLine("We don't deliver to this zipcode {0}",ayethatsprettygood);


 {


   class Program
    {
        static void Main(string[] args)
        {
            int entered = 0;
            string ayethatsprettygood;
            bool dothesalamander = false;

            char[] pizzasize;
            pizzasize = new char[4] { 'S', 'M', 'L', 'X' };        //This array is the zipcodes

            double[] pizzaprices;
            pizzaprices = new double[4] { 6.99, 8.99, 12.50, 15.00 };             //This array is the prices

            Console.Write("Enter a Pizza Size:");
            ayethatsprettygood = Console.ReadLine();


        foreach(char pizzaprice in pizzaprices ) 
        {

                if (ayethatsprettygood == pizzaprice)

                {
                    dothesalamander = true;
                    entered = pizzaprice;
                    break;
                }

            }

            if (dothesalamander == true)
            {

                Console.WriteLine("The size of the pizza is {0} the price is {1}", pizzasize[entered], pizzaprices[entered].ToString("C2"));
            }
            else
                Console.WriteLine("Sorry you entered an invalid size {0}", ayethatsprettygood);







        }



    }
}

if anyone could help me complete this program it would be really helpful! Thank You!

  • this is not a code service site nor is it a site where you should be asking others to complete your homework assignments If you have not consulted with your instructor nor shown up to class or paid attention, then sounds like you need to start doing the basics first. Go visit your instructor and tell them that you do not understand the assignment and would like more tutoring / explanation of the task at hand.. – MethodMan Jan 10 '17 at 23:06
  • also learn how to use variable naming conventions what in the world is this `string ayethatsprettygood;` strings in `C# have double " "` wrapped around them when defining string variable values – MethodMan Jan 10 '17 at 23:08
  • I did ask my teacher but he said just learn it on your own. I am trying to figure out how to do it but I just need someone to guide me in the right direction. Our instructor just gives us the program and makes us learn it on our own then he checks it. – Victor Hughes Jan 10 '17 at 23:12
  • Sounds like a terrible instructor; but this question is still not a good fit (or even answerable from what I can tell) as is. There are mentorship/tutoring sites out there, perhaps you should try one of those. – BradleyDotNET Jan 10 '17 at 23:13
  • I am just stuck on understanding how foreach loops work because in for loops you have your loop control variable along with your ++ but it just confuses me. – Victor Hughes Jan 10 '17 at 23:16
  • That sounds like a much better question (especially if you could expound on it a bit). Could you please edit your question to *that* (using pieces of this as examples if it helps) and clarify where your confusion is? Perhaps write how you would do this with a `for` loop so we can see where the disconnect is? – BradleyDotNET Jan 10 '17 at 23:20
  • I changed the topic and I put my code in for the for loop @BradleyDotNET – Victor Hughes Jan 10 '17 at 23:32
  • I've been working on my program and I stuck on one certain part where I am using the if function and the == operator cant be used with char or string – Victor Hughes Jan 10 '17 at 23:43
  • I actually don't see a problem with your current code; unless you are iterating over the wrong array could you be more specific as to what behavior you are seeing/the problem is? – BradleyDotNET Jan 10 '17 at 23:51
  • Yes I am itterating over the array where if what I entered = what is in the array it would display the output since it is a parallel array but I cant use the == operator for using my if function. – Victor Hughes Jan 10 '17 at 23:57
  • Ah, that makes *so* much more sense now – BradleyDotNET Jan 10 '17 at 23:59
  • How would I fix this error @BradleyDotNET – Victor Hughes Jan 11 '17 at 00:02
  • Sorry, took a while to put up a full answer; let me know if its still confusing. – BradleyDotNET Jan 11 '17 at 00:10
  • Thank you so much for helping me fix my error @BradleyDotNET – Victor Hughes Jan 11 '17 at 00:20

2 Answers2

1

With an ordinary for loop, you manage the index yourself, and if you are iterating through an array, you have to use the index to look up items.

var a = new string[] {"This","Is","An","Array"};
for (var i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i = i + 1)
{
    var s = a[i];
    Console.WriteLine(s);
}

With a foreach loop, the framework uses a special interface (IEnumerable) to do the iteration and lookup for you:

var a = new string[] {"This","Is","An","Array"};
foreach (var s in a)
{
    Console.WriteLine(s);
}

Most arrays, lists, dictionaries, and other types of collections implement IEnumerable, so you can use this technique to go through most lists. If IEnumerable isn't available, you can't use foreach.

The foreach construct requires less typing, and iterations can run in parallel (using Parallel.ForEach), so it has some advantages. The main disadvantage is that there is no guarantee what order the elements will be processed, plus you no longer have access to a variable that has the index in it. This could be an issue in certain cases, e.g. copying data between two arrays, where order might be important.

Also, while using the enumerator, deleting and adding items is highly discouraged if not outright impossible due to confusion it can introduce.

Community
  • 1
  • 1
John Wu
  • 50,556
  • 8
  • 44
  • 80
1

foreach is not a very good choice when you are utilizing parallel arrays (hint, parallel arrays are not actually used all that often, or ever, in "real" code).

The reason is, as you discovered, that you have no idea what a given item's index is (foreach does not guarantee linear traversal, though it often is in practice). Here are three ways of solving the problem:


Assume Linear Traversal

You can setup a counter outside of the loop and increment it with every iteration. Assuming that foreach starts at index 0 and increments by 1, you will still have your index:

int iterationIndex = 0;
foreach (item in collection)
{
     iterationIndex++;
}

Of course, if the assumption is wrong (in practice, traversal is usually linear, and always is on arrays and lists) then your code will break.


Search the array

You know which item you are looking for; you can use an array/list method to get its index:

int index = collection.IndexOf(item);
var parallelItem = parallelCollection[index];

This breaks down if collection has multiple instances of item (effectively a duplicate key).


Use a class (Correct answer!)

All of this is moot if you discard parallel arrays and use objects. Say I have a pizza class:

public class Pizza
{
    public double Size {get; set}
    public double Price {get; set;}
}

Now the data association is handled by the framework and I can write:

Pizza requestedPizza;
foreach (Pizza pizza in allPizzas)
{
     if (pizza.Price == enteredPrice)
     {
         requestedPizza = pizza;
         break;
     }
}
Console.WriteLine($"Found pizza size {requestedPizza.Size} that matches price {requestedPizza.Price}");

For future use, that whole foreach is totally unnecessary, LINQ will write it for us:

Pizza requestedPizza = allPizzas.FirstOrDefault(p => p.Price == requestedPrice);
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117