ch3-Ifthen (if and if-else conditionals)

Chapter_3     Exercise_3-1 Guess     Exercise_3-2







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
*/









Chapter_3     Exercise_3-1 BACK_TO_TOP Guess     Exercise_3-2



Comments

Popular posts from this blog

Contents