I'm new to c but long story short , i want to write a c program that will accept input from user through an array and it will sum each array element input
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main() {
int array[100];
int sum;
for(int i=0; i<100; i ){
cout<<"Insert element "<<i<<": ";
cin>>array[i];
sum = array[i] //summ with the next array input;
cout<<sum;
}
return 0;
}
means that if i enter any integer the program should be able to give the summation of the inputs in sequence from the first input to the last input
CodePudding user response:
C standard library already has a function to do this which is std::accumulate
:
#include <iostream>
#include <numeric>
int main() {
int array[5] = {1,2,3,4,5};
int total = std::accumulate(std::begin(array), std::end(array), 0);
return 0;
}
If you plan to use not a full array you should use std::begin(array)
, std::begin(array) amount
as ranges.
CodePudding user response:
initialize your sum var to 0 initially and write sum =array[i] instead of what you have written, there is also a limitation in this program as value of sum after all user input should be <=10^9 as int datatype store no. approximately upto 10^9 so take note of this fact also. Write cout<<sum<<endl; instead to be able to distinguish till previous input sum to the new input sum. Hope this will help.
CodePudding user response:
You can use a do while loop:
#include<iostream>
#include<string>
#include<math.h>
int main()
{
int array[100];
int sum=0;
int i=0;
std::cout<<"Insert element"<<" "<<i<<": ";
std::cin>>array[i];
do
{
sum=sum array[i];
std::cout<<sum<<std::endl;
i ;
std::cout<<"Insert element"<<" "<<i<<": ";
}while(std::cin>>array[i]);
return 0;
}
CodePudding user response:
If all you want is the sum then just compute the sum. No need to store anything:
#include <iostream>
#include <string>
#include <math.h>
int main() {
int sum = 0;
for(int i=0; i<100; i ){
std::cout << "Insert element " << i << ": ";
int t;
std::cin >> t;
sum = t
std::cout << sum;
}
}