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 does PHP use foreach loops to iterate over array elements?ComputerScienceOne · Foreach Loops
- How are foreach loops used to iterate over array elements in PHP?ComputerScienceOne · Do-While Loops
- How does the foreach syntax iterate over an array in PHP?ComputerScienceOne · Normalizing a Number
- How can you iterate over indexed and associative arrays in PHP?ComputerScienceOne · Iteration
- How can you iterate over Java arrays?ComputerScienceOne · Basic Usage
- What are enhanced for loops in Java?ComputerScienceOne · Enhanced For Loops
- How does Java use variables and collections in enhanced for loops?ComputerScienceOne · Enhanced For Loops
- How do you access array elements safely in C?ComputerScienceOne · Basic Usage