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.
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.
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.
Of course, we can write just an if without an else too.
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.
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 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 - =, +=, -=, *=, /=, %=, |=, &=, ^=
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;
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
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.
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
Post a Comment