Sunday, July 20, 2014

Conditional Execution Using Operator (?:)

Conditional Execution Using Operator (?:)
C++ has an interesting and powerful operator called the conditional operator that is similar to a compacted if-else construct.
Syntax:
(conditional expression evaluated to bool) ? expression1 if true : expression2 if false;

Such an operator can be used in compactly evaluating the greater of two given numbers,
as seen here:
int a=8, b=12, max;
max = (a > b)? a : b; // max contains greater of a and b

Example:
#include <iostream>
using namespace std;
int main(){
    cout << “Enter two numbers: ” << endl;
    int a = 8, b = 0;
    cin >> a;
    cin >> b;
    int max = (a > b)? a : b;
    cout << “The greater of “ << a << “ and  "<< b << “ is: “ << max << endl;
    return 0;

    getch();
}
Output:
Enter two numbers: 
123
27
The greater of 123 and 27 is: 123 

Using switch...case statement in C++

Conditional Processing Using switch...case
The objective of switch-caseis to enable you to check a particular expression against a host of possible constants and possibly perform a different action for each of those different values. The new C++ keywords you would often find in such a construct are switch, case, default, and break.
Syntax:
switch(expression){
case constant1:
          Statements for first case;
          break;
case constant2:
          Statements for second case;
          break;
// And so on…
default:
          DoStuffWhenExpressionIsNotHandledAbove;
          break;
}

Example:
#include <conio.h>
#include <iostream>
using namespace std;
int main(){
int month, year;
cout<<"Input month"; cin>>month;
cout<<"Input year"; cin>>year;
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
cout<<"Month is 31 days"; 
                        break;
case 4: case 6: case 9: case11:
cout<<"Month is 30 days";  
                        break;
case 2:
if((year%4==0 && year%100!=0)|| year%400==0)
cout<<"Month is 29 days"; 
else
cout<<"Month is 28 days"; 
}
getch();
return 0;

}


Using if statements in C++

1. Conditional Programming Using if 
Syntax:
if (conditional expression)
         Do something when expression evaluates true;
Example:
if (x == 100)
             cout << "x is 100 ";


2. Conditional Programming Using if … else
Syntax:
if (conditional expression)
          Do something when expression evaluates true;
else // Optional
          Do something elsewhen condition evaluates false;
Example:
if (x == 100)
             cout << "x is 100 ";
else
             cout << "x is not 100";
3. Executing Multiple Statements Conditionally
Syntax:

if (condition){
            // condition success block
           Statement 1;
           Statement 2;
}
else{
           // condition failure block
          Statement 3;
          Statement 4;
}
Example:
if (x >100)
{
     cout << "x > 100 ";
     cout << x;
}
else
{
     cout << "x <= 100 ";
     cout << x;
}
4. Nested if Statements
Syntax:

if (expression1)
{
        DoSomething1;
        if(expression2)
               DoSomething2;
        else
               DoSomethingElse2;
}
else
        DoSomethingElse1;
Example:
float mark;
cout<<"Input mark: "; cin>>mark;
if(mark>=0 && mark<=10){
      if(mark>=8.5)
               cout<<"A";
      else if(mark>=7.0)
               cout<<"B";
      else if(mark>=5.5)
               cout<<"C";
      else if(mark>=4.0)
               cout<<"D";
      else
               cout<<"F";
}
else
      cout<<"Mark wrong !";

Sunday, July 13, 2014

Managing Multi-Dimensional Array in C++

Abour Multi-Dimensional Array:
In C++, you can model two-dimensional arrays, but you are not restricted to just two dimensions. Depending on your need and the nature of the application, you can model multidimensional arrays in memory
Declaring and Initializing Multidimensional Arrays
Syntax:
int Arr [2][3];
int Arr [2][3] = {{0, 1, 2}, {3, 4, 5}};
int Arr[3][3] = {{154, 219, 362}, {101, 248, 417}, {921,675, 811}};

Accessing Elements in a Multidimensional Array
#include <iostream>
using namespace std;
int main(){
   int Arr[3][3] = {{154, 219, 362}, {101, 248, 417}, {921,675, 811}};
   cout << “row 0: “ << Arr[0][0] << “ “<< Arr[0][1] << “ “<< Arr[0][2] << endl;
   cout << “row 1: “ << Arr[1][0] << “ “<< Arr[1][1] << “ “<< Arr[1][2] << endl;
   cout << “row 2: “ << Arr[2][0] << “ “<< Arr[2][1] << “ “<< Arr[2][2] << endl;
   getch();
   return 0;
}
Example
#include<iostream>
#include<math.h>
int arr[5][5],n;
// input matrix
void Input(){
        cout<<"\n Input the number element of matrix:\n";
        do{
               cout<<"\n n= "; cin>>n;
               if(n<2||n>5)  cout<<"\n Input n again ";
        } while (n<2||n>5);

        // Input matrix
        cout<<"\n Input matrix:\n";
        for(int i=0;i<n;i++)
               for(int j=0;j<n;j++){
                   cout<<"\n arr["<<i<<"]["<<j<<"]="; cin>>arr[i][j]; 
               }
}
// Print matrix
void Print(){
        cout<<"\n Matrix:\n";
        for(int i=0;i<n;i++){
                for(int j=0;j<n;j++)
               cout<<arr[i][j]<<"\t";
                cout<<"\n";
         }

}
//main function
int main(){        
        Input();
        Print();
        getch();
        return 0;
}

Managing One-Dimensional Array in C++

What is an Array:
An array is “a group of elements forming a complete unit
The following are characteristics of an array:
- An array is a collection of elements.
- All elements contained in an array are of the same kind.

- This collection forms a complete set.

Declaring and Initializing static arrays
Syntax:
element-type array-name [number of elements] = {optional initial values}
Example:
int MyNumber[] ={1,2,3,4,5}
int MyNumber[4] = {32, 87, 120, 247};
int MyNumber[4] = {0}; // initialize all integers to 0

Accessing data stored in an Array
#include <iostream>
using namespace std;
int main (){
    int Arr[4] = {32, 87, 120, 247};
    cout << “First element at index 0: “ << Arr[0] << endl;        //32
    cout << “Second element at index 1: “ << Arr[1] << endl;  //87
    cout << “Third element at index 2: “ << Arr[2] << endl;      //120
    cout << “Fourth element at index 3: “ << Arr[3] << endl;    //247
    return 0;

}

Modifying Data Stored in an Array
#include <iostream>
using namespace std;
int main(){
    const int length = 4;
    int Arr [length] = {0};
    cout << “Enter index of the element to be changed: “;
    int nElementIndex = 0;
    cin >> nElementIndex;
    cout << “Enter new value: “;
    cin >> Arr [nElementIndex];
    cout << “First element at index 0: “ << Arr [0] << endl;
    cout << “Second element at index 1: “ << Arr [1] << endl;
    cout << “Third element at index 2: “ << Arr [2] << endl;
    cout << “Fourth element at index 3: “ << Arr [3] << endl;
    return 0;

}
Example:
#include<iostream> 
int main(){
        int a[100],n;
// Input n
        do{ 
              cout<<"\n n= "; cin>>n; 
              if(n<1||n>100)   cout<<"\n Input n again !";
        }while (n<1||n>100);
 // input array
        for (int i=0; i<n;i++){
               cout<<"\n a["<<i<<"]= "; 
               cin>>a[i];  
        }
// Print array
        cout<<"\n Print values of array: ";
        for (i=0;i<n;i++)
               cout<<a[i]<<", ";
         getch();
         return 0;

Sunday, June 29, 2014

Operators in C++


The numerical operators in C++ can be grouped into five types: arithmetic, assignment, comparison, logical and bitwise operators.
1. Arithmetic operators
Example
x = 4 + 5;   // x=9 // addition
x = 13 - 3;   // x=10 // subtraction
x = 6 * 3;   // x=18 // multiplication
x = 10 / 3; // x=3 // division
x = 10 % 3; // x=1 // modulus (division remainder)

2. Assignment operators
a. Assign a value to a variable
x=10;
b. Assign a variable to a variable
int a=10, b;
b=a;
c. Assign a expression to a variable
int a, b=5, c=6;
a=b+d;

3. Combined assignment operators
Example
int x=10;
x += 5;  // x = x+5  // x=15;
x -= 4;  // x = x-4;  //x=6;
x *= 3; // x = x*3;  //x=30;
x /= 2; // x = x/2;  //x=5;
x %= 3; // x = x%3; //x=1;

4. Operators to Increment (++) and Decrement (--)
Example
int x=6;
x++;   // x = x+1;  //x=7; 
x--;    // x = x-1;   //x=5;
Both of these can be used either before or after a variable.
x++;   // post-increment
x--;     // post-decrement
++x;   // pre-increment
--x;     // pre-decrement
The result on the variable is the same whichever is used. The difference is that the 
post-operator returns the original value before it changes the variable, while the 
pre-operator changes the variable first and then returns the value.
x = 5; y = x++; // y=5, x=6
x = 5; y = ++x; // y=6, x=6

5. Comparison operators
The comparison operators compare two values and return either true or false. They are mainly used to specify conditions, which are expressions that evaluate to either true or false.
Example:
bool x = (2 == 3); // false // equal to
x = (2 != 3); // true // not equal to
x = (2 > 3); // false // greater than
x = (2 < 3); // true // less than
x = (2 >= 3); // false // greater than or equal to

x = (2 <= 3); // true // less than or equal to

6. Logical operators
bool x = (true && false);  // false // logical and
x = (true || false);  // true // logical or

x = !(true);  // false // logical not

7. Bitwise operators
int x = 5 & 4; // 101 & 100 = 100 (4) // and
x = 5 | 4; // 101 | 100 = 101 (5) // or
x = 5 ^ 4; // 101 ^ 100 = 001 (1) // xor
x = 4 << 1; // 100 << 1 =1000 (8) // left shift
x = 4 >> 1; // 100 >> 1 = 10 (2) // right shift
x = ~4; // ~00000100 = 11111011 (-5) // invert
The bitwise operators also have combined assignment operators.
int x=5; x &= 4; // 101 & 100 = 100 (4) // and
x=5; x |= 4; // 101 | 100 = 101 (5) // or
x=5; x ^= 4; // 101 ^ 100 = 001 (1) // xor
x=5; x <<= 1;// 101 << 1 =1010 (10)// left shift

x=5; x >>= 1;// 101 >> 1 = 10 (2) // right shift

Wednesday, June 11, 2014

Declare Constant and Use Constant in C++

Syntax:
#define <constant_name> <value> 

or 
const <data_type> <constant_name> = <value>

Declare:
#define MAX 100 
#define PI 3.14 
#define Newline '\n'

const int MAX = 100;
const float PI = 3.14;
const char answer = ‘Y’;

Escape Sequences
Escape Sequences      Represents
\a                                     Bell (alert)
\b                                     Backspace
\f                                      Formfeed
\n                                     New line
\r                                      Carriage return
\t                                      Horizontal tab
\v                                     Vertical tab
\'                                      Single quotation mark
\"                                     Double quotation mark
\\                                      Backslash
\?                                     Literal question mark

Example 1: Calculate Area, Circumference of Circle using const keyword 

#include <iostream>
#include <conio.h>
using namespace std;
const double Pi=3.14;
double Radius, Area, Circumference;
int main(){
cout<<"Input Radius of Circle: "; cin>>Radius;
Area = Pi * Radius * Radius;
Circumference = 2 * Pi * Radius;
cout<<"Area of Circle = "<<Area<<endl;
cout<<"Circumference of Circle = "<<Circumference;
getch();
return 0;
}

Example 2: Calculate Circle using #define keyword 
#include <iostream>
#include <conio.h>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main(){
double radius=7.0;       
  double circle;   
  circle = 2 * PI * radius;
  cout <<"CIRCLE: " <<circle;
  cout << NEWLINE;
getch();
return 0;
}

Tuesday, June 10, 2014

List Keywords You Can't Use as Variable or Constant Names

Some words are reserved by C++, and you can't use them as variable names or constant names. These keywords have special meaning to the C++ compiler.
asm      else          new                       this
auto     enum        operator                throw
bool     explicit     private                   true
break   export      protected               try
case     extern       public                    typedef
catch    false         register                  typeid
char     float          reinterpret_cast     typename
class    for            return                    union
const   friend        short                     unsigned
goto    signed       const_cast             using
 if        sizeof        virtual                    continue
void    default       inline                     static 
delete  int             static_cast             volatile
do       long          struct                     wchar_t
double mutable    switch                    while
dynamic_cast       namespace            template

Monday, June 9, 2014

Examples: How to use variables in C++


Example 1: Integer Variables
Syntax: int variable;       //comment

#include <iostream>
using namespace std;
int term;  // term used in two expressions
int main(){
term = 4 * 7; 
cout <<"Twice " << term << " is "<< 2*term <<endl; 
cout <<"Three times " << term << " is " << 3*term <<endl; 
return 0;
}

Example 2: Floating Point Variables
Syntax:  float variable;     //comment

#include <iostream>
#include <conio.h>
using namespace std;
int i;    // an integer variable
float f; // a floating point number 
int main(){
f = 1.0 / 2.0;          // assign floating 0.5 
cout<<" f= "<<f<<endl;
i = 1 / 3;              // assign integer 0 
cout<<" i= "<<i<<endl;
f = (1 / 2) + (1 / 2);  // assign floating 0.0 
cout<<" f= "<<f<<endl;
f = 3.0 / 2.0;          // assign floating 1.5 
cout<<" f= "<<f<<endl;
i = f;                  // assign integer 1 
cout<<" i= "<<i<<endl;
return 0;
}

Example 3: Characters Variables
Syntax:  char variable;   //comment

#include <iostream>
#include <conio.h>
using namespace std;
char c1;  // first character 
char c2;  // second character 
char c3;  // third character 
int main(){
c1 = 'X'; 
c2 = 'Y'; 
c3 = 'Z'; 
cout << c1 << c2 << c3 << " reversed is "<<c3 << c2 << c1 << "\n";
return 0;
}

Friday, June 6, 2014

Variable and Using Variable in C++

Declaring Variables to Access and Use Memory
When programming in languages like C++, you define variables to store those values. Defining a variable is quite simple and follows this pattern:
       variable_type variable_name;
               or
       variable_type variable_name = initial_value;

Example:
     int i;   // variable_type: int;  variable_name: i;
     float x=1.25;  //variable_type: float;  variable_name: x; initial_value: 1.25

Declaring and Initializing Multiple Variables of a Type
You could condense the declaration of these multiple variables to one line of code that would

look like this:


Variable Types in C++:

Using Type bool to Store Boolean Values
A sample declaration of an initialized Boolean variable is
     bool male = true;
An expression that evaluates to a Boolean type is

     bool shopping = (UserSelection == “no”);

Using Type char to Store Character Values
     char User_Input = 'A';     // initialized char to ‘A’

Using Type short, int, long to Store Signed Integer Values
     short Age = 22;
     int Number = -70000;
     long LargeNumber = -70000;    //on some platforms, long is an int

     
Using Type float, double to Store Floating-Point Values
     float PI=3.14;
     double x=a/b;

Thursday, June 5, 2014

Writting Your First C++ Application (Hello Word !)

Create a new project and write a basic program "Hello World"
Now that you know the tools and the steps involved, it is time to program your first C++ application. If you are on Windows and using Microsoft Visual C++ Express, you can follow these steps:
1. Create a new project via the menu option File -> New -> Project.

2. Choose type Win32 Console Application.

3.  And uncheck the Use Precompiled Header option.

4. Name your project Hello and replace the automatically generated contents in Hello.cpp with the code snippet:

Building and Executing Your First C++ Application
If you’re using Microsoft Visual C++ Express, press Ctrl + F5 to run your program directly via the IDE. This compiles, links, and executes your application. 


You could also do the individual steps: 
1. Right-click the project and select Build to generate the executable.
2. Navigate to the path of the executable using the command-prompt (typically under the Debug directory of the project folder).
3. Run it by typing the name of the executable.

Friday, May 9, 2014

Functions in C++

Functions in C++

Functions in C++ are the same as functions in C. Functions are artifacts that enable you to divide the content of your application into functional units that can be invoked in a sequence of your choosing. A function, when called (that is, invoked), typically returns a value to the calling function. The most famous function is, of course, main(). It is recognized by the compiler as the starting point of your C++ application and has to return an int (i.e., an integer). 

You as aprogrammer have the choice and usually the need to compose your own functions. Example 1.1 is a simple application that uses a function to display statements on the screen using std::cout with various parameters.

Example 1.1. Declaring, Defining,and Calling a Function That Demonstrates Some Capabilities of std::cout

1: #include <iostream>
2: using namespace std;
3:
4: // Function declaration
5: int DemoConsoleOutput();
6:
7: int main()
8: {
9: // Call i.e. invoke the function
10: DemoConsoleOutput();
11:
12: return 0;
13: }
14:
15: // Function definition
16: int DemoConsoleOutput()
17: {
18: cout << “This is a simple string literal” << endl;
19: cout << “Writing number five: “ << 5 << endl;
20: cout << “Performing division 10 / 5 = “ << 10 / 5 << endl;
21: cout << “Pi when approximated is 22 / 7 = “ << 22 / 7 << endl;
22: cout << “Pi more accurately is 22 / 7 = “ << 22.0 / 7 << endl;
23:
24: return 0;
25: }
Output:
This is a simple string literal
Writing number five: 5
Performing division 10 / 5 = 2
Pi when approximated is 22 / 7 = 3
Pi more accurately is 22 / 7 = 3.14286

Tuesday, May 6, 2014

The concept of namespaces in C++

The concept of namespaces in C++


The reason you used std::cout in the program and not only cout is that the artifact (cout) that you want to invoke is in the standard (std) namespace.

What are namespaces ?

Assume that you didn’t use the namespace qualifier in invoking cout and assume that cout existed in two locations known to the compiler - which one should the compiler invoke ? 
This causes a conflict and the compilation fails. This is where namespaces get useful. Namespaces are names given to parts of code that help in reducing the potential for a naming conflict. By invoking std::cout, you are telling the compiler to use that one unique cout that is available in the std namespace.

Many programmers find it tedious to repeatedly add the std namespace specifier to their code when using cout and other such features contained in the same. The using namespace declaration as demonstrated in Example 1.1 will help you avoid this repetition.

Example 1.1: The using namespace declaration

1: // Pre-processor directive
2: #include <iostream>
3:
4: // Start of your program
5: int main()
6: {
7: // Tell the compiler what namespace to search in
8: using namespace std;
9:
10: // Write to the screen using std::cout 
11: cout << “Hello World” << endl;
12:
13: // Return a value to the OS
14: return 0;
15: }


Note: By telling the compiler that you are using the namespace std, you don’t need to explicitly mention the namespace on Line 11 when using std::cout or std::endl.

A more restrictive variant of Example 1.1 is shown in Example 1.2 where you do not include a namespace in its entirety. You only include those artifacts that you wish to use.

Example 1.2: Another demonstration of the using keyword

1: // Pre-processor directive
2: #include <iostream>
3:
4: // Start of your program
5: int main()
6: {
7: using std::cout;
8: using std::endl;
9:
10: /* Write to the screen using cout */
11: cout << “Hello World” << endl;
12:
13: // return a value to the OS
14: return 0;
15: }


Note: Line 8 in Example 1.1 has now been replaced by Lines 7 and 8 in Example 1.2. The difference between using namespace std and using std::cout is that the former allows all artifacts in the std namespace to be used without explicitly needing to specify the namespace qualifier std::. With the latter, the convenience of not needing to disambiguate the namespace explicitly is restricted to only std::cout and std::endl.