To add all the numbers between two values, simply multiply the number of values between both numbers by adding the first and the last and dividing by two:
Therefore, the sum of all the numbers between 4 and 10 is:
int números = (7 * (4 + 10)) / 2;
To be taken into account.
-
printf
and scanf
are the console reading functions of C, in C ++ the stream objects are used: std::cout
and std::cin
.
Proposal.
int main()
{
int numeroinicial, numerofinal;
std::cout << "Introduce el numero inicial";
std::cin >> numeroinicial;
std::cout << "Introduce el numero final";
std::cin >> numerofinal;
std::cout << "La suma de los valores entre " << numeroinicial
<< " y " << numerofinal
<< " es " << ((numerofinal - numeroinicial + 1) * (numeroinicial + numerofinal)) / 2;
return 0;
}
Note that the above code assumes that numeroinicial
will be less than numerofinal
.
If instead of arithmetically you want to do it cyclically, you can use a for
loop:
int main()
{
int numeroinicial, numerofinal;
std::cout << "Introduce el numero inicial";
std::cin >> numeroinicial;
std::cout << "Introduce el numero final";
std::cin >> numerofinal;
int suma{};
for (int valor = numeroinicial; valor < numerofinal; ++valor)
suma += valor;
std::cout << "La suma de los valores entre " << numeroinicial
<< " y " << numerofinal
<< " es " << suma;
return 0;
}
You can also generate ( std::generate
) a collection of numbers within the range and accumulate them ( std::accumulate
):
int main()
{
int numeroinicial, numerofinal;
std::cout << "Introduce el numero inicial";
std::cin >> numeroinicial;
std::cout << "Introduce el numero final";
std::cin >> numerofinal;
std::vector valores(numerofinal - numeroinicial + 1);
std::generate(valores.begin(), valores.end(), [i = b]() mutable { return i++; });
std::cout << "La suma de los valores entre " << numeroinicial
<< " y " << numerofinal
<< " es " << std::accumulate(valores.begin(), valores.end(), 0);
return 0;
}