1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| #include <iostream> int main() { using namespace std; cout << "Enter a number: " ; int nX; cin >> nX; if (nX > 10) cout << nX << "is greater than 10" << endl; else cout << nX << "is not greater than 10" << endl; return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| #include <iostream> int main() { using namespace std; cout << "Enter a number: " ; int nX; cin >> nX; if (nX > 10) { // both statements will be executed if nX > 10 cout << "You entered " << nX << endl; cout << nX << "is greater than 10" << endl; } else { // both statements will be executed if nX <= 10 cout << "You entered " << nX << endl; cout << nX << "is not greater than 10" << endl; } return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| int main() { using namespace std; cout << "Enter a number: " ; int nX; cin >> nX; if (nX > 10) cout << nX << "is greater than 10" << endl; else if (nX < 5) cout << nX << "is less than 5" << endl; // could add more else if statements here else cout << nX << "is between 5 and 10" << endl; return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| #include <iostream> int main() { using namespace std; cout << "Enter a number: " ; int nX; cin >> nX; if (nX > 10) // it is bad coding style to nest if statements this way if (nX < 20) cout << nX << "is between 10 and 20" << endl; // who does this else belong to? else cout << nX << "is greater than 20" << endl; return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| #include <iostream> int main() { using namespace std; cout << "Enter a number: " ; int nX; cin >> nX; if (nX > 10) { if (nX < 20) cout << nX << "is between 10 and 20" << endl; else // attached to inner if statement cout << nX << "is greater than 20" << endl; } return 0; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| #include <iostream> int main() { using namespace std; cout << "Enter a number: " ; int nX; cin >> nX; if (nX > 10) { if (nX < 20) cout << nX << "is between 10 and 20" << endl; } else // attached to outer if statement cout << nX << "is less than 10" << endl; return 0; } |
1
2
3
4
5
6
7
8
9
10
11
| #include <iostream> #include <cmath> // for sqrt() void PrintSqrt( double dValue) { using namespace std; if (dValue >= 0.0) cout << "The square root of " << dValue << " is " << sqrt (dValue) << endl; else cout << "Error: " << dValue << " is negative" << endl; } |
1
2
3
4
5
6
7
8
9
10
11
| int DoCalculation( int nValue) { // if nValue is a negative number if (nValue < 0) // early return an error code return ERROR_NEGATIVE_NUMBER; // Do calculations on nValue here return nValue; } |
1
2
3
4
5
6
7
| int min( int nX, int nY) { if (nX > nY) return nY; else return nX; } |
1
2
3
4
| int min( int nX, int nY) { return nX > nY ? nY : nX; } |
0 comments: