Skip to main content

Conditional statements

In the last post, we saw about data types and and variables. What we have not discussed is pointers and references. We discuss that along with constants in a future post.

Now let us talk about control structures. If you already know a programming language like C or Java, you can skip this post.

Conditional Statements

C++ has 2 conditional statements and one conditional operators. These are if, switch and ?:

if statement

If statement is used to test a condition and execute a statement if the condition is true. There can be an optional else statement which gets executed if the condition is false.

Syntax :
if (condition) 
     statement1;
else 
    statement2; 

Let us look at some examples



int m;
cin>>m;
if(m>0)
  cout<<"You have entered a positive number"<<endl;
else
  cout<<"The number you typed is non-positive"<<endl;

Note that if and else should be followed by a single statements. If multiple statements are needed, then they must be enclosed in braces - which becomes a block and is treated as one unit.


int m;
cin>>m;
if(m>0)
  cout<<"You have entered a positive number"<<endl;
  cout<<"and its square is"<<m*m<<endl;
else//throws a syntax error
  cout<<"The number you typed is non-positive"<<endl;

In the above code, as if is followed by 2 statements, we get an error "else without if" . To remove this error, put the statements in a block.

int m;
cin>>m;
if(m>0)
  {
     cout<<"You have entered a positive number"<<endl;
     cout<<"and its square is"<<m*m<<endl;
   }
else//throws a syntax error
  cout<<"The number you typed is non-positive"<<endl;

Of course, we can write just an if without an else too.

Chained if and else 

We can write multiple  else if chains, when there is a need to check mutually exclusive conditions like the one shown below.

int m;
cin>>m;
if(m>0) 
    cout<<"You have entered a positive number"<<endl; 
else if(m==0)
  cout<<"Why did you enter a 0?"<<endl;
else 
  cout<<"You entered a negative number"<<endl;

Some more examples


int m;
cin>>m;
bool b=m<0;
if(b)
   cout<<"The number is negative"<<endl;//one
 
if( m)
   cout<<"The number is non-zero"<<endl;//two

cin>>n;
if(m==n && m>0)
   cout<<"Both the numbers are equal and positive"<<endl;//three
In one we are using a Boolean variable to test a condition. if(b) is same as if(b==true) 

In two we are using m itself without any relational operators. if (m) as same as if(m!=0). Because in C++, 0 is false and non-zero is true.

In three we are using && for combining two condition with and operator.  The expression is true only if both the conditions - m==n and m>0 are true.

Let us deviate a little bit here and try to explore the operators. C++ and C have a rich set of operators, some of them obvious, some not so much.

Operators  

In C++ we have the following operators
  • arithmetic operators(+ addition, - subtraction *, multiplication ,/ division and % modulo ) 
  • increment (++) and decrement (--) operators
  • relational operators (< less than,  <= less than or equal to, > greater than, >= greater than or equal to, == equal to, != not equal to)
  • logical operators (|| or, && and, !not). 
  • bitwise operators which are not found in most other languages. - & and, | or, ^ exor, << left shift, >> right shift 
  • ternary operator ?:
  • indirecton and addressof operators - * and &, 
  • member of operator - . (dot)
  • assignment operators - =, +=, -=, *=, /=, %=, |=, &=, ^=
The confusing ones are ==, && and || and assignment operators.

Equality operator is not =, but ==. = is assignment operator. Many newbies make a mistake like this and wonder why the output is wrong. 

int m;
cin>>m;
if(m=1)
  cout<<"the number is one"<<endl;
else
  cout<<"the number is not one"<<endl;
This code shows output as "the number is one", no matter what input is given. The reason is not so obvious to beginners - m=1 is an assignment statement. m is assigned to 1, Now the value of expression in parentheses is 1 - which is result of assignment. As any non-zero value is treated as true in C++, the condition is true.

The correct condition in the above code is  if(m==1) .

Similarly not equal to operator is not <> but !=

Increment operators ++ and --

 Increment operator works on an integer variable and increments it by 1.

The side effects vary depending on whether we use this operator as prefix (pre-increment) or suffix (post-increment)
e.g.
int a = 12;
int b=a++;//a is 13, but b is 12
int c = ++b;//both b and c are 13

 As we see in the example, pre-increment first increment the variable, and then uses it - as in 3rd statement. But post increment first uses the variable in the expression and then increments it. 

-- is the decrement operator which reduces the value of an integer by 1. Even decrement operator can be pre-decrement or post-decrement.

int a = 12;
int b = a--;//b is 12 and a is 11
 

Ternary operator  ?:

Ternary operator is a compact way of writing an if expression. It uses 3 operands instead of 2. First operand is conditional expression. Second operand is the result if the condition is true . Third is the result if condition is false.

Syntax 
      conditional-expression?expr1:expr2

If conditional expression evaluates to true, the result is expr1, else it is expr2.

Let us see an example.

#include<iostream>
using namespace std;
int main(){
    int m;
    bool  even;
    cin>>m;
    even =  m%2==0?true:false;
    cout<<even;
}
  Here we are testing if m%2 is equal to 0. If it is zero, even becomes true. Otherwise it is false.

The output of the program is 1 if input is 12. It is not "true". 

The ternary statement above is equivalent to 

if(m%2==0)
   even = true;
else
   even = false;

Bit-wise operators

Bit-wise operators allow us to modify the numbers using low level operation. | - bitwise OR operator logically ORs individual bits of two operands and gives us the result.
int a = 3,b=4;
a = a|b;
a will be 00000011 ORed with 00000100 = 00000111 which will be 7

Similarly & operators ANDs individual bits of two operands and gives us the result. And ^ operator EXORs individual bits of its operands.

Note : AND operator gives 1 if both operands are 1
           OR operator gives 1 if either of the operands is 1
           EXOR operator gives 1 if either of the operands, but not both is 1.

Assignment operators 

C++ has a new set of operators called assignment operators. They work like this. 

a+=b  is same is a = a+b 
sum+= n*n+5   is sum = sum+n*n+5

We have the following assignment operators - +=, -=, *=, /=, %=.

There are also assignment operators in combination with bitwise operators - |,&,^ 

 Switch statement :

 When there are large number of conditions involving a single expression, instead of using if-else chain, you can use a switch statement.

Syntax

switch(expression)
{
   case value1:statement; 
               statement;
               .....
               break;
   case value2:statement; 
               statement;
               break;
   .....
   default: statement;
            statement;
    ....
}

There are some restrictions regarding the statement though.
  • expression used in switch must be an integer expression
  • value1, value2 etc should be integer literals. 
  • default is optional and that block is executed if none of the values match.
Let us look at an example. 

cout<<"Enter two numbers";
cin>>a>>b;
cout<<"Enter 1 to add 2 to subtract 3 to multiply and 4 to divide";
int option;
cin>>option;
switch(option)
{
    case 1: ans = a+b;
            break;
    case 2: ans = a-b;
            break;
    case 3: ans = a*b;
            break;
    case 4: if(b!=0)
              ans= a/b;
            break;
    default:cout<<"Wrong option";
 }
 cout<<"answer is "<<ans;

If the variable option is entered as 1, then case 1 is selected and a and b are added. And if option is entered as 2, case 2 is selected and so on.

 Should we break?

If we omit to add break statement at the end of each case, the execution will seep through the subsequent cases. In the above example, if we omit break after first case, and if option is 1, first ans=a+b is executed, then ans = a-b is executed.


Comments

Popular posts from this blog

Find the error in C++ program

This C++ program is not compiling. What do you think is the error with the program? #include<iostream> using namespace std; int main() {    int arr[10];    arr={1,2,3,4,5,6,7,8};    cout<<"arr[0]="<<arr[0];    return 0; } Is the error due to Not using printf Initialising the array with only 8 elements instead of 10 Initialising array in the next statement instead of in definition. None of the above  Now if you like this question, there are plenty more questions like this and programs and notes in my app Simplified C++. Download the Simplif ied C++   by Hegdeapps now By the way the correct answer is (3)

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t...

Friends of C++

Friend function Remember that a member which is not public (Private and protected )  can not be accessed from outside the class.  Three are some situations where you may need to access these. Keyword friend  is used for this. A friend functions and classes can access all members of a class.  This concept is controversial. People say friend concept violates data encapsulation  A friend function is a non-member function but still can access all the members of a class including private members. Such a function is declared within class body with the prefix "friend" class Number { int num; public: Number( int m){ /*code*/ } friend void printNum(Number ob); /*friend function*/ }; void printNum (Number obj) { cout << obj.num << "endl" ; } printNum() is not member of class Number . But it can still access all members including private members, because it is a friend. Friend class An object of a friend c...