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

14 - Write a program c++ to calculate positive n umbers till 50 only . If the user…

  1. User

    14

    Write a program c++ to calculate positive n umbers till 50 only . If the user enters a negative number, that number is skipped from the calculation

  2. Assistant

    Here is a C++ program that calculates positive numbers up to 50, skipping any negative numbers entered by the user:

    #include <iostream>
    
    int main() {
        int number;
        int sum = 0;
    
        std::cout << "Enter positive numbers till 50 (negative numbers will be skipped):\n";
    
        do {
            std::cout << "Enter a number: ";
            std::cin >> number;
    
            if (number < 0)
                continue;
    
            sum += number;
        } while (number <= 50);
    
        std::cout << "Sum of positive numbers up to 50 is: " << sum << std::endl;
    
        return 0;
    }
    

    In this program, we use a do-while loop to continuously ask the user for input until the number entered is greater than 50. Inside the loop, we check if the number is negative using an if statement. If it is negative, we use the continue statement to skip the rest of the loop and move on to the next iteration. Otherwise, we add the number to the sum variable.

    After the loop ends, we print the sum of all the positive numbers entered by the user up to 50.

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