Write a complete c++ program which ignores any negative integers (<0) entered by
ID: 3546808 • Letter: W
Question
Write a complete c++ program which ignores any negative integers (<0) entered by a user from the keyboard and calculates the sum of only the positive integers. Your program should output to the file numbers.out the positive integers (>=0) entered by the user and their sum. Your program should stop after three negative integers are read. Your program should work for any integers entered not just the one in the example below.
Example:
If the user enters -1 3 0 11 0 -2 5 -3
The file Q1.out will contain 3 0 11 0 5 19
where 19 is t he sum of the numbers entered
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int number;
ofstream outfile("numbers.out");
cout << "Enter numbers :";
cin >> number;
int sum =0;
int negative_number_count = 0;
while(true)
{
if(number>=0)
{
sum = sum + number;
outfile << number << " ";
//cout << number << " ";
}
else
negative_number_count++;
if(negative_number_count==3)
break;
cin >> number;
}
outfile << sum << " " << endl;
//cout << sum << " " << endl;
outfile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.