Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

3 - Write a prog ram to find the sum of positive number . if the user enters a negative…

  1. 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 .

  2. 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 sum to store the sum of positive numbers. We use a while True loop to keep asking the user for numbers until a negative number is entered. Inside the loop, we get input from the user using the input() function and convert it to an integer using the int() 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.

  3. User

    C++

  4. 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 num and sum, similar to the Python program. We use a while (true) loop to keep asking the user for numbers until a negative number is entered. Inside the loop, we use std::cout to display the message and std::cin to 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 use std::cout to print the sum of positive numbers.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.