changing an array

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

changing an array

Postby antijock » Sun Oct 12, 2003 5:23 pm

two things;
1: how do u make an array start with element 1 instead of element 0
or should i not do that?
2: is there a simple way to add up all the values stored within an array?

I'm using MS visual C++ 6.0

thanks alot

(ugh my bad, i said '2' instead of '0' fixed it though.)
Last edited by antijock on Sun Oct 12, 2003 6:58 pm, edited 1 time in total.
antijock
 
Posts: 6
Joined: Tue Oct 07, 2003 7:43 pm
Location: my computer...

Postby MXP » Sun Oct 12, 2003 6:35 pm

1. I dont understand

2. Yes
Code: Select all
int sum;
for (int i = 0; i < sizeof(array); i++)
    sum += array[i];
Need information on a function I've posted? Chances are it's at the MSDN.
MXP
 
Posts: 6506
Joined: Mon Sep 22, 2003 5:27 pm

Postby punkrockguy318 » Mon Oct 13, 2003 6:38 am

1.You can't. Kindof think as the array number as an offset of the first element in the array(array[3] is 3 elements away from array[0])[/code]
punkrockguy318
 

Postby omnius » Mon Oct 13, 2003 12:11 pm

Code: Select all
int sum;
for (int i = 0; i < sizeof(array); i++)
    sum += array[i];


Prefer instead:
Code: Select all
int sum;
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++)
    sum += array[i];
omnius
 
Posts: 496
Joined: Wed Sep 24, 2003 12:03 pm

Postby raimo » Mon Oct 13, 2003 12:54 pm

The simplest I know is
Code: Select all
#include <numeric>
...
int sum = std::accumulate(array, array + sizeof(array)/sizeof(array[0]), 0);
User avatar
raimo
 
Posts: 372
Joined: Fri Sep 26, 2003 6:50 am
Location: Finland

Postby Alvaro » Mon Oct 13, 2003 2:29 pm

The first thing is, get used to counting from 0. Life is easier that way.

If, for some strange reason, you really want an array that starts at a different number, I just happen to have a solution for you.

int real_underlying_array[100];
int * const fake_array = &real_underlying_array[-1];

Two days ago I used this for the first time. Actually, I wanted to start counting at -34, and I had good reasons for that, but it's a long story.
User avatar
Alvaro
Moderator
 
Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA


Return to For Beginners

Who is online

Users browsing this forum: Google [Bot] and 1 guest