Alright I'm fairly new to C++ and I'm getting into some stuff that I can't quiet figure. One thing is I need to add a number to each of the 15 elements of an integer array? Please help, thanks
Printable View
Alright I'm fairly new to C++ and I'm getting into some stuff that I can't quiet figure. One thing is I need to add a number to each of the 15 elements of an integer array? Please help, thanks
:sniff:
Smells like home work, show some effort there buddy.
no it's really not homework, I'm just working on it on my own. It's not for a school thing.
Read about loops.
Loop through each element in the array.
Add the number to each element in the array.
Here's what you need to know...
How to create an array
How to access an element of an array
How to "add a number" to a value/variable
How to make a loop (to do stuff over & over)
There are 3 ways to make a loop. A for-loop, a while-loop, and a do-while-loop.
[EDIT] -
Check-out the cprogramming.com Loop Tutorial and the Array Tutorial. And when you have a chance, read the Board Guidelines. It will help prevent (well maybe minimize) the negative responses. BTW - It is OK to ask for help with your homework as long as you don't ask that it be done for you.
ok, ill put it in pseudo (god i love that word) code for you
that should help you understand the concept (assuming that's what you're struggling with)Code:integer element[15]
while(accumutator <= numberofelements)
{
element[accumulator] = element[accumulator] + numbertoadd
accumular = accumulator + 1 //to make it accumulate
}
Here is a great way for newbs, easy to understand!:):
Outputs:Code:#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
template <class T>
class AddNum
{
T value;
public:
AddNum(const T& x): value(x)
{
}
operator() (T& elem) const
{
elem += value;
}
};
int main()
{
int array[5] = { 5, 8, 9, 10, 12 };
// Output contents of original array to screen
copy(array,array+5,ostream_iterator<int>(cout," "));
cout << endl;
// Add the value 6 to all elements
for_each(array,array+5,AddNum<int>(6));
// Output contents of modified array to screen
copy(array,array+5,ostream_iterator<int>(cout," "));
cout << endl;
return 0;
}
Just kidding about it being easy for newbs. Seriously, like others said just loop through and reassign to each element of the array the original value plus whatever value you wanted to add to it.Code:5 8 9 10 12
11 14 15 16 18
Code:#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int myInts[15] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int sum = accumulate(myInts, myInts+15, 0);
cout << "Total = " << sum << endl;
}