Overflow Underflow
#include
#include
using namespace std;
int main()
{
int i1 = 2147483647;
cout << i1 + 1 << endl;
cout << i1 + 2 << endl;
cout << i1 * i1 << endl;
int i2 = -2147483648;
cout << i2 - 1 << endl;
cout << i2 - 2 << endl;
cout << i2 * i2 << endl;
return 0;
}
Increment Decrement Operators
#include
#include
using namespace std;
int main()
{
int mark = 76;
cout << mark << endl;
mark++;
cout << mark << endl;
++mark;
cout << mark << endl;
mark = mark + 1;
cout << mark << endl;
mark--;
cout << mark << endl;
--mark;
cout << mark << endl;
mark = mark - 1;
cout << mark << endl;
return 0;
}
Implicit Automatic Type Conversion
#include
#include
#include
using namespace std;
int main()
{
int i;
double d;
cout << fixed << setprecision(1);
i = 3;
d = i;
cout << "d = " << d << endl;
d = 5.5;
i = d;
cout << "i = " << i << endl;
i = 6.6;
cout << "i = " << i << endl;
}
Counter-Controlled Loop
#include
#include
using namespace std;
int main()
{
int sum = 0;
int upperbound;
cout << "Enter the upperbound: ";
cin >> upperbound;
for (int number = 1; number <= upperbound; ++number)
{
sum += number;
}
cout << "Sum is " << sum << endl;
cout << "Average is " << (double)sum / upperbound << endl;
int count = 0;
sum = 0;
for (int number=1; number <= upperbound; number=number+2)
{
++count;
sum += number;
}
cout << "Sum of odd numbers is " << sum << endl;
cout << "Average is " << (double)sum / count << endl;
}
Sentinel-Controlled Loop
#include
#include
#include
using namespace std;
int main()
{
int numberIn;
int count = 0;
int sum = 0;
int max = 0;
int min = int_max;
int sentinel = -1;
cout << "Enter a positive integer or " << sentinel << " to exit: ";
while (cin >> numberin && numberin != sentinel)
{
if (numberIn > 0)
{
++count;
sum += numberIn;
if (max < numberIn) max = numberIn;
if (min > numberIn) min = numberIn;
}
else
{
cout << "error: input must be positive! try again..." << endl;
}
cout << "Enter a positive integer or " << sentinel << " to exit: ";
}
cout << endl;
cout << "Count is " << count << endl;
if (count > 0)
{
cout << "Maximum is " << max << endl;
cout << "Minimum is " << min << endl;
cout << fixed << setprecision(2);
cout << "Average is " << (double)sum / count << endl;
}
}
No comments:
Post a Comment