Concept

How can you simulate a foreach loop when iterating over an array in C?

ComputerScienceOne / Other Issues

"C does not support a traditional foreach loop. When iterating over a collection like an array, you iterate an index variable, typically with a for loop. However, there are some syntactic tricks that you can use to get the same effect. Some of this will be a preview of Chapter 20 where we discuss arrays in C, but in short, you can assign a variable to an element in an array in iteration statement:\n\ndouble arr[] = {1.41, 2.71, 3.14};\n\nint n = 3;\n\nint i = 0;\n\ndouble x;\n\nfor(x=arr[0]; i<n; x=arr[++i]) {\n\n//x now holds the i-th element in arr\n\n}\n\nThe initialization sets the variable x to the first element in the array, arr[0] . The loop continues for as many elements as there are in the array, n . The iteration does two things: it assigns x to the next element in the array while at the same time incrementing the index variable using the prefix increment operator (see Section 2.3.6)."

Related Ideas

How can you simulate a foreach loop when iterating over an array in C? | ComputerScienceOne | Bifalgorithm | Bifalgorithm