1

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;
}
3
  • 6
    Why are you using the same variable, as the loop counter in cin>>i;? Why don't you use different variable for read value? Commented Dec 13, 2019 at 19:15
  • 1
    Code works just fine here: wandbox.org/permlink/naZfBzsuB3Hj3itO Commented Dec 13, 2019 at 19:15
  • 2
    Unrelated: Prefer for (int i=0; i<n; i++) to for (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. Commented Dec 13, 2019 at 19:22

1 Answer 1

4

The problem is that you're using the same variable (i) for looping and input.

for (int i=1; i<=n; i++)
{
        cin>>i;

Whatever gets entered in that cin>>i ruins the logic of your program. Add one separate input variable and keep your i for the loop.

Example:

#include <iostream>

int main() {
    int n, sum = 0;
    std::cout << "How many numbers do you want to enter? \n";
    std::cin >> n;
    std::cout << std::endl;

    std::cout << "Enter numbers: \n";
    for(int i = 1; i <= n; i++) {
        std::cout << i << ": ";

        int input;
        if(std::cin >> input) {
            if(input > 0) {
                sum = sum + input;
            }
            std::cout << sum << std::endl;
        } else
            break; // user failed to enter a number
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

When I said "Whatever gets entered ..." I meant "there is only one number that would not ruin the logic of your program and it has the value i in every iteration" - I hope that makes sense.
Thanks! I think I got it. I am a beginner, we study this at school, maths high school, and this stuff is not easy for 5th grade. we only have two hous a week, not enough.
@Imemi You're welcome! It's great that you study this in 5:th grade! It never stops being fun, promise! (... and as always, a disclaimer: there are rumours about people who liked programming and now don't - rumours)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.