If statement

Hello guys! I decided to start posting about the basic statements in c++. Those statement are:

  • The “if” statement
  • The “for” statement
  • The “while” statement
  • The “do while” statement

Today I am going to talk about the if statement, I hope this helps you figure out how it works and how to use it. Enjoy!

The if statement is one of the most basic syntax and it allows you to control whether a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user’s input. For example, by using an if statement to check a user entered password, your program can decide whether a user is allowed access to the program. 


When programming, the aim of the program will often require the checking of one value stored by a variable against another value to determine whether one is larger, smaller, or equal to the other.

There are a number of operators that allow these checks.

Here are the relational operators, as they are known, along with examples:

  1.  “>”  means greater than ,for example 5>4 is TRUE
  2.  “<” means less than, for example 4
  3. “>=”means greater than or equal, for example 4>=4 is TRUE, while 4>=3 is also TRUE
  4. “<=” means less than or equal, for example 4<=4 is TRUE, while 3<=4 is also TRUE
  5. “==” means equal to, for example 4==4 is TRUE 
  6. “!=” means not equal to, for example 4!=5 is TRUE

Basic If Statement Syntax

The structure of an if statement is as follows: 

     if (TRUE)

         Execute condition



Here is a simple example that shows the syntax: 

   if(5<10)

         cout<<“What a surprise, 5 is lower than 10”;

If you want to add multiple commands in an IF STATEMENT you can use braces:

  if(5<10)

{

         cout<<“Hello!”<<endl;

         cout<<“What a surprise, 5 is lower than 10”;

}

 This will make the program execute both commands.

*”endl” will make sure that the next statement is printed on the next line and stands for end line.

 This is what your program will show without the “endl”:

And this is what your program will show with “endl”.

Be careful when using “endl”! Linux won’t read this command and your program won’t work, a replacement for endl that most programmers use is “\n” which does the exact same thing but is also accepted by linux.

Keep on coding! 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s