- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Conditionals: Simple Statements

Posted by Tayyab


The "if" Statement
It's time to make decisionsusing the relational operators.

The "if" expression is called a conditional statement (decision statement).  It tests a relationship by using the relational operators.  Based upon the results of these comparisons, decisions are made as to which statement(s) the program will execute next. 
if (test condition)
{
      block of one;
      or more C++ statements;
}
If you put a semicolon after the test condition, the "if" statement will STOP.  The block will not be executed.
The test condition can be any relational comparison (or logically TRUE) statement and must be enclosed in parentheses.  The block of statements is enclosed in French curly braces and are indented for readability.  The braces are NOT required if only ONE statement follows the "if", but it is a good idea to get in the habit of including them.
The block executes only if the test condition is TRUE.  If the test condition is FALSE, the block is ignored and execution continues to the next statement following the block.
Be careful!!!
   A careless mistake may go unnoticed.
if (a = 3)  is almost ALWAYS true.  The condition

a = 3 is actually an "assignment statement" (most likely NOT what you really intended to type), and assignments are consider to be true for any value other than 0.  If the assignment value is 0, such as if (a = 0), the condition is considered false.

whereas:

if (a = = 3)   is true ONLY if the value stored in a is the number 3.  This is most likely what you intended to type.
 

Examples:
// using a character literal
if (grade = = 'A')
{
     cout<<"Put it on the frig!";
}
// logically true test condition -
// when x is a non-zero value the
// test condition is considered true

if (x)
{
     cout<<"Way to go!";
     cout<<"The x is not zero!";
}
// using two variables
if (enemyCount < heroCount)
{
     cout<<"The good guys win!";
}
// using a calculation
if (cost * number = = paycheck)
{
     inventory = 0;
}

The "if ... else" Statements
Let's look at situations when the word"otherwise" can be used in your decision making!
if (test condition)
{
      block of one;
      or more C++ statements;
}
else
{
     block of one;
     or more C++ statements;
}
If the test condition is TRUE, the block of statements following the "if" executes.  If the test condition is FALSE, however, the block of statements following the "else" executes instead.  
Example:
//example of if ... else
cout<<"Enter the name of your city."
cin>>name;
cout<<"Enter the population";
cin>>population;
if (population >= 534187)
{
     cout<<"According to the census, " << city
            <<" is one of \n the 100 largest cities.";
}
else
{
     cout<<"According to the census, " << city
             <<"is not one of \n the 100 largest cities.";
}

The "if ... else if ... else" Statements
Let's look at situations where your program requires more than two situations as the result of a decision.
cout<<"Enter a value for a";
cin>>a;
cout<<"Enter a value for b";
cin>>b;
if(a= = b)
{
     cout<<"They are equal!\n";
}
else if( a < b)
{
     cout<<"The first number "
             << "is smaller.\n";
}
else
{
     cout<<"The second number"
             << is smaller.\n";
}

Notice that it was not necessary to check for a>b in the third situation.  Thetrichotomy principle tells us that numbers are related in one of three ways (a equals b, or a is less than b, or a is greater than b).  In order for the computer to get to the "else" condition in the problem above, it must have answered NO to the first two decisions.  Consequently, there is only ONE possibility left and we do not waste the computer's time checking it.

The "switch" Statement
If your program must select from one of many different actions, the "switch" structure will be more efficient than an "if ..else..." structure.

switch (expression)
{
     case (expression 1):    {
                                            one or more C++ statements;
                                            break;
                                            }
    case (expression 2):     {
                                           one or more C++ statements;
                                           break;
                                           }
   case (expression 3):     {
                                          one or more C++ statements;
                                          break;
                                          }
                    .
                    .
                    .

    default:                        {
                                        one or more C++ statements;
                                        break;
                                        }
}
  • You MUST use a break statement after each "case" block to keep execution from "falling through" to the remaining case statements.
  • Only integer or character types may be used as control expressions in "switch" statements.
  • It is best to place the most often used choices first to facilitate faster execution.
  • While the "default" is not required, it is recommended.

If you need to have several choices give the same response, you need to use the following coding style:
switch (value)
{
     case (1):
     case (2):
     case (3):   {
                       //The case code for 1, 2, 3
                       break;
                       }
     case (4):
     case (5):
     case (6):   {
                      //The case code for 4, 5, 6
                      break;
                      }
     default:    {
                     //The code for other values
                     break;
                      }
}



<< Previous                                                                                                                 Next >>    

0 comments:

Post a Comment

Operators

Posted by Tayyab


An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provides the following types of operators:
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Arithmetic Operators:

There are following arithmetic operators supported by C++ language:
Assume variable A holds 10 and variable B holds 20, then:

Click Here To Show Example
OperatorDescriptionExample
+Adds two operandsA + B will give 30
-Subtracts second operand from the firstA - B will give -10
*Multiplies both operandsA * B will give 200
/Divides numerator by de-numeratorB / A will give 2
%Modulus Operator and remainder of after an integer divisionB % A will give 0
++Increment operator, increases integer value by oneA++ will give 11
--Decrement operator, decreases integer value by oneA-- will give 9

Relational Operators:

There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then:

Click Here To Show Example
OperatorDescriptionExample
==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

Logical Operators:

There are following logical operators supported by C++ language
Assume variable A holds 1 and variable B holds 0, then:

Click Here To Show Example
OperatorDescriptionExample
&&Called Logical AND operator. If both the operands are non-zero, then condition becomes true.(A && B) is false.
||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.(A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.!(A && B) is true.

Bitwise Operators:

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:
pqp & qp | qp ^ q
00000
01011
11110
10011
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:

Click Here To Show Example
OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12 which is 0000 1100
|Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61 which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

Assignment Operators:

There are following assignment operators supported by C++ language:

Click Here To Show Example
OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
<<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

Misc Operators

There are few other operators supported by C++ Language.
OperatorDescription
sizeofsizeof operator returns the size of a variable. For example, sizeof(a), where a is integer, will return 4.
Condition ? X : YConditional operator. If Condition is true ? then it returns value X : otherwise value Y
,Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list.
. (dot) and -> (arrow)Member operators are used to reference individual members of classes, structures, and unions.
CastCasting operators convert one data type to another. For example, int(2.2000) would return 2.
&Pointer operator & returns the address of an variable. For example &a; will give actual address of the variable.
*Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

Operators Precedence in C++:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Click Here To Show Example
Category Operator Associativity 
Postfix () [] -> . ++ - -  Left to right 
Unary + - ! ~ ++ - - (type)* & sizeof Right to left 
Multiplicative  * / % Left to right 
Additive  + - Left to right 
Shift  << >> Left to right 
Relational  < <= > >= Left to right 
Equality  == != Left to right 
Bitwise AND Left to right 
Bitwise XOR Left to right 
Bitwise OR Left to right 
Logical AND && Left to right 
Logical OR || Left to right 
Conditional ?: Right to left 
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left 
Comma Left to right 




<< Previous                                                                                                                 Next >>    

0 comments:

Post a Comment

Modifier Types

Posted by Tayyab


C++ allows the char, int, and double data types to have modifiers preceding them. A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of various situations.
The data type modifiers are listed here:
  • signed
  • unsigned
  • long
  • short
The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition,signed and unsigned can be applied to char, and long can be applied to double.
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example, unsigned long int.
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without the int. The int is implied. For example, the following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;
To understand the difference between the way that signed and unsigned integer modifiers are interpreted by C++, you should run the following short program:
#include <constream.h>

 
/* This program shows the difference between
 * signed and unsigned integers.
*/
int main()
{
   short int i;           // a signed short integer
   short unsigned int j;  // an unsigned short integer

   j = 50000;

   i = j;
   cout << i << " " << j;

   return 0;
}
When this program is run, following is the output:
-15536 50000
The above result is because the bit pattern that represents 50,000 as a short unsigned integer is interpreted as -15,536 by a short.

Type Qualifiers in C++

The type qualifiers provide additional information about the variables they precede.
QualifierMeaning
constObjects of type const cannot be changed by your program during execution
volatileThe modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program.
restrictA pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Only C99 adds a new type qualifier called restrict.




<< Previous                                                                                                                 Next >>    

1 comments:

Post a Comment