Ifthen.cpp
TCP1, p. 129
download
// Demonstration of if and if-else conditionals
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int i;
cout << "Type a number and 'Enter'" << endl;
cin >> i;
if(i > 5)
{cout << "It's greater than 5" << endl;}
else if(i < 5)
{cout << "It's less than 5" << endl;}
else {cout << "It's equal to 5" << endl;}
// More formal:
if(i > 5)
{cout << "It's greater than 5" << endl;}
else // i <= 5
{
if(i < 5) {cout << "It's less than 5" << endl;}
else {cout << "It's equal to 5" << endl;}
}
cout << "Type a number and 'Enter'" << endl;
cin >> i;
if(i < 10)
{
if(i > 5) // "if" is just another statement
{cout << "5 < " << i << " < 10" << endl;}
else {cout << i << " <= 5" << endl;}
}
else // Matches "if(i < 10)"
{cout << i << " >= 10" << endl;}
return 0;
}
/*
g++ Ifthen.cpp -o Ifthen
./Ifthen
Type a number and 'Enter'
1
It's less than 5
It's less than 5
Type a number and 'Enter'
2
2 <= 5
./Ifthen
Type a number and 'Enter'
5
It's equal to 5
It's equal to 5
Type a number and 'Enter'
6
5 < 6 < 10
./Ifthen
Type a number and 'Enter'
7
It's greater than 5
It's greater than 5
Type a number and 'Enter'
10
10 >= 10
*/
Comments
Post a Comment