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!

14
  • 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.. Commented Jan 10, 2017 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 Commented Jan 10, 2017 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. Commented Jan 10, 2017 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. Commented Jan 10, 2017 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. Commented Jan 10, 2017 at 23:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

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.