3 - Write a prog ram to find the sum of positive number . if the user enters a negative…
- User
3
Write a prog ram to find the sum of positive number . if the user enters a negative number , the loop ends . the negative number entered is not added to the sum .
- Assistant
Here's a Python program that calculates the sum of positive numbers entered by the user:
sum = 0 while True: num = int(input("Enter a number: ")) if num < 0: break sum += num print("The sum of positive numbers is:", sum)In this program, we initialize a variable named
sumto store the sum of positive numbers. We use awhile Trueloop to keep asking the user for numbers until a negative number is entered. Inside the loop, we get input from the user using theinput()function and convert it to an integer using theint()function. If the number is negative, we break out of the loop. Otherwise, we add the positive number to the sum. Finally, we print the sum of positive numbers. - User
C++
- Assistant
Certainly! Here's the same program written in C++:
#include <iostream> int main() { int num, sum = 0; while (true) { std::cout << "Enter a number: "; std::cin >> num; if (num < 0) { break; } sum += num; } std::cout << "The sum of positive numbers is: " << sum << std::endl; return 0; }In this C++ program, we declare variables
numandsum, similar to the Python program. We use awhile (true)loop to keep asking the user for numbers until a negative number is entered. Inside the loop, we usestd::coutto display the message andstd::cinto get input from the user. If the number is negative, we break out of the loop. Otherwise, we add the positive number to the sum. Finally, we usestd::coutto print the sum of positive numbers.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.