Topics covered on Wednesday, 2010-08-11
Sample Program (compute1.cpp)
1 // compute1.cpp
2 // Prompt user for 2 numbers and and operation (+ or -) and
3 // print out result of the operation
4 // Copyright (C) 2010, Raj Mathur
5 #include <iostream>
6 #include <cstdlib>
7 using namespace std;
8 int main(int argc, char *argv[])
9 {
10 char
11 op;
12 int
13 number_1 = 0;
14 int
15 number_2 = 0;
16 int
17 result;
18 // Get operation type (p == plus, m == minus)
19 cout << "Enter operation: (p)lus or (m)inus: ";
20 cin >> op;
21 // Get values to be used for computation
22 cout << "What is the first number? ";
23 cin >> number_1;
24 cout << "What is the second number? ";
25 cin >> number_2;
26 // Check operation and do it
27 if( op == 'p' )
28 {
29 result = number_1 + number_2;
30 }
31 else if( op == 'm' )
32 {
33 result = number_1 - number_2;
34 }
35 else
36 {
37 cerr << "Only operations (p)lus and (m)inus are permitted, sorry" << endl;
38 exit(1);
39 }
40 // Display it
41 cout << "The result is: " << result << endl;
42 exit(0);
43 }
- The if statement checks a condition and executes the following code if the condition is true.
- If the condition is not true, the else portion is executed.
- C++ treats all non-zero values as true and 0 as false when evaluating conditions.
Comparison Operators
C++ provides the following comparison operators:
| Operator | Function |
a == b | a and b are equal |
a != b | a is not equal to b |
a < b | a is less than b |
a <= b | a is less than or equal to b |
a > b | a is greater than b |
a >= b | a is greater than or equal to b |
Logical Operatots
C++ provides the following logical operators:
| Operator | Function |
c1 && c2 | Logical AND: both conditions c1 and c2 are true |
c1 || c2 | Logical OR: either or both conditions c1 or c2 are true |
!c1 | Logical NOT: reverse of condition c1 |
Sample Program (compute1.cpp) revisited
1 // compute1.cpp
2 // Prompt user for 2 numbers and and operation (+ or -) and
3 // print out result of the operation
4 // Copyright (C) 2010, Raj Mathur
5 #include <iostream>
6 #include <cstdlib>
7 using namespace std;
8 int main(int argc, char *argv[])
9 {
10 char
11 op;
12 int
13 number_1 = 0;
14 int
15 number_2 = 0;
16 int
17 result;
18 // Get operation type (p == plus, m == minus)
19 cout << "Enter operation: (p)lus or (m)inus: ";
20 cin >> op;
21 // Validate operation
22 if( op != 'p' && op != 'm' )
23 {
24 cerr << "Please enter only 'p' for plus and 'm' for minus." << endl;
25 exit(1);
26 }
27 // Get values to be used for computation
28 cout << "What is the first number? ";
29 cin >> number_1;
30 cout << "What is the second number? ";
31 cin >> number_2;
32 // Do the operation
33 if( op == 'p' )
34 {
35 result = number_1 + number_2;
36 }
37 else
38 {
39 result = number_1 - number_2;
40 }
41 // Display it
42 cout << "The result is: " << result << endl;
43 exit(0);
44 }