WalidKhan Posted October 11, 2023 Posted October 11, 2023 (edited) I'm learning C++ and trying to grasp control structures. I have an array of integers and I want to iterate through it using different control structures to achieve the same result. Here's my array: int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; I would like to calculate the sum of all the elements in the array and display the result. Can you provide code examples using different control structures like for loops, while loops, and do...while loops to accomplish this task? Additionally, if there are any performance or readability differences between these approaches, please explain. I have looked online for a solution, but I want to know how to use control structures in C++ successfully in a variety of scenarios. Edited November 16, 2023 by Phi for All commercial link removed by moderator
Halc Posted October 11, 2023 Posted October 11, 2023 (edited) A for() loop is just a generalized form of a while loop. They're essentially the same thing. A do loop is different only in that it executes the body unconditionally at least once, which is inappropriate for summing up an array since it would generate erroneous results with an empty array. Examples of each, including the invalid do loop. Each assumes a line int sum = 0; at the top. for (int x = sizeof(numbers) / sizeof(int); x; x--) sum += number[x - 1]; for (int x = sizeof(numbers) / sizeof(int); x; sum += number[--x]) {} // alternate way to do it int x = sizeof(numbers) / sizeof(int); while (x--) sum += number[x]; int x = sizeof(numbers) / sizeof(int); do sum += number[--x]; while (x > 0); // wrong // An example of traversing the array forwards instead of backwards // This can be done for any of the loops above, but I find comparison with zero to be more optimized. for (int x = 0; x < sizeof(numbers) / sizeof(int); x++) sum += number[x]; Except for the inline definition of int x, this is pretty much C code, not leveraging C++ features Differences, besides the do loop being buggy, is that the for loop the way I coded it lets x drop out of scope after the loop exits. I find them all fairly equally readable since they're all essentially the same code. Edited October 11, 2023 by Halc
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now