Jump to content

Understanding Control Structures in C++: Looping Through an Array

Featured Replies

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 by Phi for All
commercial link removed by moderator

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 by Halc

Please sign in to comment

You will be able to leave a comment after signing in

Sign In Now

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.