C++ Programming: If Statements (Lesson 3)

If statements allow you to control whether a program enters a section of code or not based on whether a condition is true or false. The structure of an if statement is simple: if() { Execute everything in this block } Here is a simple program that reads a value from a user. #include <iostream>; using namespace std; int main() { int x; cout << "Enter a number: "; cin>> x; if (x<10) { cout<<"You entered a value less than 10 n"; } } Here is the table of the relational operatirs that allow you to compare values.
> greater than
< less than
>= greater than or equal to
<= less than or equal to
== lequal to
!= not lequal to
C++ allows you to store the results of comparisons by using a special type called bool. Here is an example. #include using namespace std; int main() { int x; cin >>x; bool is_x_two = x==2; if (is_x_two) { cout<< "Yay! x is 2! n"; } } The else statement allows you to do if/else comparisons. The code after else is executed when the condition checked by the if statement is false. Here’s an example that tests whether the user provided a negative number or not: #include using namespace std; int main() { int x; cout <> x; if (x<0) { cout<< "You entered a negative number n"; } else { cout << "You entered a non-negative number n"; } } You can use else-if when there are multiple conditional statements. #include using namespace std; int main() { int x; cout <> x; if (x<0) { cout<< "You entered a negative number n"; } else if (x==0) { cout<<"You entered zero n"; } else { cout << "You entered a non-negative number n"; } } C++ object strings allow you to compare strings. Here is a program for a password checker. #include # include using namespace std; int main() { string password; cout << "Enter a password: "; getline(cin, password); if (password=="xyzzy") { cout<< "Access allowed n"; } else { cout << "Bad password. Denied access! n"; } } Boolean not operator accepts one input. If that input is true, it return false and vice versa. For example: if(!0) { cout <<"!0 evaluates to true"; } Boolean and returns if both inputs are true: if(1 && 2) { cout <<"Both 1 and 2 evaluate to true"; } Boolean or return true if either, or both, of the two values provided are true. Boolean or is written as || in C++.
This material is from the textbook Jumping into C++ by Alex Allain. I strongly recommend this book if you are new to programming and want to learn more than what I described here.
Click for Lesson 2 Click for Lesson 4
This entry was posted in Programming and tagged , . Bookmark the permalink.