Wednesday, June 26, 2013

C++ (beginner) logical operators

If operator


The form of if operator

if ( conditions)
{
          actions
}

The program will do the actions between {    } brackets if the condition is true. 

As you can see in the code above we got outputed "a is bigger than b" because in our condition operator the condition was true.

if we want for our condition to do something if condition is not true we have to add "else" statement.
if(a>b)
    cout<<"a is bigger than b"<<endl;
else
    cout<<"b is bigger than a"<<endl;
now if a will be less than b the line after "else" will be completed.

there are some operators which can be used in if statement

==  (2 equal signs) we write this when we want to check if something is equal to another thing.
if(a==b)
    dosomething

<  checking of one thing is less than the other one
if(a<b)
     dosomething;
> checking if one thing is bigger than the other one.

if(a>b)
   dosomething;

<= checking if something less or equal to the other one.

if(a<=b)
   dosomething;

>= checking if something is more or equal to the otehr one.

if(a>=b)
   dosomething;

if we want to write w reverse statement in other words we want to tell the program to do something if the statement is not true we use ! sign.
example
if(  ! (a==b))
   dosomething;
now he will do something if the statement is not true.

How to check multiple conditions in one IF statement.

there are 2 operators 
&&  and ||
&& stands for the word "and"
|| stands for the word "or"
&& means that the condition is true if both statements are true.
|| means that the condition is true if at least one of the statemnets is true
example

int a=10;
int b=10;
int c=7;
if(a==10 && b==10 && c==10)
     dosomething;

for the condition to be true all of the variables must be 10, this means that the system won't do anything,.

if(a==10 || b==10 || c==10)
     dosmoething;

In this case if at least one of them is equal to 10 the System will proceed. 




  

No comments:

Post a Comment