Thursday, September 3, 2015

The For loop in C++

Syntax: 
    for (initialization; condition; increase) 
         statement;
How does it works:
1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once.
2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed).
3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
Example:
#include<iostream>
using namespace std;
int main(){
int i;
for(i=0;i<10;i++)
cout<<i<<" ";    //statement;
return 0; 
}
Result:
for loop example

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