Do while sentinel
Mar 10, 2017 at 1:37pm UTC
Hi
How do I add a sentinel using a do while loop here so that when I enter -500 the program will close.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int integer, freq_pos = 0, freq_neg = 0, freq_zero = 0, sum_pos = 0, sum_neg = 0, total = 0, min = 0, max, x, y;
for (x = 0; x < 8; x++)
{
cout << "Please enter an integer" << endl;
cin >> integer;
if (integer < min)
{
min = integer;
}
else if (integer == 0)
{
freq_zero = freq_zero + 1;
sum_pos = sum_pos + integer;
}
else if (integer < 0)
{
freq_neg = freq_neg + 1;
sum_neg = sum_neg + integer;
}
else if (integer > 0)
{
freq_pos = freq_pos + 1;
sum_pos = sum_pos + integer;
}
}
cout << "There are " << freq_pos << " positive numbers, " << freq_neg << " negative numbers and " << freq_zero << " zeroes" << endl;
cout << "The lowest number is " << min << endl;
cout << "The sum of all positive values is " << sum_pos << endl;
cout << "The sum of all negative values is " << sum_neg << endl;
return 0;
}
Mar 10, 2017 at 1:54pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
auto constexpr sentinel = -500;
int main()
{
int input{};
do
{
std::cout << "Insert an element \n" ;
std::cin >> input;//suggest input validation
if (input != sentinel)
{
std::cout << input << "\n" ;
}
} while (input != sentinel);
}
Mar 10, 2017 at 2:50pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
int main()
{
const int sentinel = -500 ;
int integer = 0 ;
while ( std::cout << "Please enter an integer: " && // display a prompt
std::cin >> integer && // and if an integer was successfully read in
integer != sentinel ) // and the integer is not the sentinel
{
// process the integer
}
}
Topic archived. No new replies allowed.