1
Create a program in C++. Have a vector of integers of 10 positions filled by the user. Print the sum of the components of this vector.
I made the code below but it does not print the values of the vectors.
#include <iostream>
using namespace std;
#define SIZE 10
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int valor[SIZE];
int total, i, a;
// a = sizeof(valor)/ sizeof(valor[0]);
for (i = 1; i <= sizeof(valor)/ sizeof(valor[0]); i++)
{
cout<<"Digite o valor: ";
cin>>valor[i];
}
for ( i = 0; i < 10; i++)
{
cout<< valor[i];
}
for ( i = 1; i < 10; i++)
{
a = a + valor[i];
}
cout<< a;
return 0;
}
What’s the point of using
sizeof(valor)/ sizeof(valor[0])
and not simplySIZE
? If the variablea
is an accumulator so you need to initialize it with 0 and the indexi
from 0, or makea = valor[0];
since its loop part of index 1.– anonimo
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site
– Maniero
As @Maniero demonstrated, if you know the size of the array previously, use this. To start, in C++, if you don’t know what you’re doing (or why), in practice you might be using Std::vector instead of making arrays "in the hand". In C, the story is another. C/C++, unlike other mainstream languages (PHP, Python, Ruby, etc...), you must knowing the size of what you’re dealing with, unless need be dynamic. That is, if your array doesn’t have to be dynamic, assume your size is static and use this to your advantage.
– nmindz