I have to write a programme in c++ where user enters a number N, then on a second line he enters as many numbers as N, no more. The ouput shoud be the sum of all positive numbers among the entered numbers. I have to use for loop. Also we have not covered much so far, only if statements.
The code I have tried gives the sum of positive numbers only, but I can't make the programme use N inputs and stop. It either calculates only one or continues as long as user enters numbers.
#include <iostream>
using namespace std;
int main ()
{
int n, sum=0;
cin>> n;
cout<<endl;
cout<<"Enter numbers"<<endl;
for (int i=1; i<=n; i++)
{
cin>>i;
if(i>0)
{sum=sum+i;
}
cout<<sum<<endl;
}
return 0;
}
cin>>i;? Why don't you use different variable for read value?for (int i=0; i<n; i++)tofor (int i=1; i<=n; i++)because everything in C++ starts at 0 and runs to n-1. Forcing origin 1 indexing will cause a great many problems.