Click here to Skip to main content
14,875,910 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C++
#include <bits stdc++.h>
using namespace std;

int main() {
    int sum=0;
    int n;

    while(1){
        cin >> n;
        sum += n;
        if(sum<0)
            break;
        cout << n << '\n';
    }

    return 0;
}


What I have tried:

sum = 0
while sum > 0:
    num = int(input())
    sum = sum + num
    if sum >= 0:
        print(num)
    else:
        break
Posted
Updated 3-Apr-21 7:52am
v2
Comments
jeron1 9-Sep-20 14:00pm
   
I don't know anything about python,
but the first 2 lines seem to be incompatible (the while loop will never be executed as 'sum' is initially not greater than zero). But there's a good possibility that I am completely wrong.
Patrice T 9-Sep-20 15:42pm
   
And you have a question ?

Quote:
sum = 0
while sum > 0:
num = int(input())
sum = sum + num
if sum >= 0:
print(num)
else:
break

Your code first assigns 0 to sum and then checks if sum itsef is greater than 0.
It is very easy to mimic the C++ code beahviour:
Python
sum = 0
while True:
    num = int(input())
    sum = sum + num
    if sum < 0:
        break
    print(num)
   
This is not a code conversion service: we are not here to translate code for you.
Even if we did, what you would end up with would not be “good code” in the target language – they are based on very different frameworks, and what makes something work in one language does not always “translate” directly into another.
So what you end up with is very poor code, that is difficult if not impossible to maintain, that can’t be upgraded nicely, and that will cause you immense headaches if the original is changed. And it’ll be a nightmare to debug if it doesn’t work “straight out of the box”.
Instead, use the source code as a specification for a new app written in and for the target language / framework and write it w=from scratch using the original as a “template”. You will get a much, much better result that will save you a lot of time in the long run.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900