C/C++ Programming Learning-Week 22 ② Sum of non-negative numbers

Topic link

Title description

Constantly input integers through the keyboard, keep reading, and output the sum of all non-negative numbers (before reading the negative number).

Note: For each set of data, a total of n integers are provided for the question.

There are two ways to write this question.
1. Count the sum of the entered numbers until the entered number is negative, and the loop is out of the loop.
2. Read all the numbers, but only calculate the sum of all the non-negative numbers before the first negative number.
The first type of writing program will not read all the input, but it will not be judged wrong...

Input
one n on the first line and n integers on the second line, separated by spaces

Output
outputs a number, which means the sum of all non-negative numbers before the negative number is read.

Sample Input

4
3 4 -6 7

Sample Output

7

Ideas

Starting from the first term, the sum of non-negative numbers is calculated. If a negative number is encountered, it is not calculated, and the number after the first negative number is not calculated.

C++ code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	int n;
	while(cin >> n)
	{
    
    
		long long sum = 0, a, flag = 0;
		for(int i = 0; i < n; i++)
		{
    
    
			cin >> a;
			if(a < 0) flag = 1;
			if(flag == 0) sum += a;
		}
		cout << sum << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113572541