Tuesday 30 September 2014

• Complements • Subtraction using complements.



• Complements
• Subtraction using complements.

By the end of this class you should be able to:

• Obtain the r’s and (r-1)’s complements in decimal, binary,
and any other number system
• Perform subtraction by addition of the complements


Decimal number complements:

9’s complement of the decimal number N = (10n
 – 1) – N
= n (9’s) – N
i.e. {subtract each digit from 9}

Example Æ 9’s complement of 134795 is 865204
Similarly

1’s complement of the binary number N = (2n
 -1) – N = n (1’s) – N
Example Æ 1’s complement of 110100101 is 001011010
which can be obtained by replacing each one by a zero and each
zero by one.

r’s complement: EE200(class 2-2) Prof. M.M. Dawoud 2of 5
10’s complement of the decimal number N = 10n
 – N = (r-1)’s
complement + 1

Example Æ 10’s complement of 134795 is 865205


Example Æ find the 9’s and 10’s complements of 314700.

Answer Æ 9’s complement = 685299
 10’s complement=685300

Rule: To find the 10’s complement of a decimal number leave all
leading zeros unchanged. Then subtract the first non-zero digit
from 10 and all the remaining digits from 9’s.

The 2’s complement of a binary number is defined in a similar
way.

Example: Find the 1’s and 2’s complements of the binary
number 1101001101

Answer Æ 1’s complement is 0010110010
 2’s complement is 0010110011

Example: Find the 1’s and 2’s complements of 100010100

Answer Æ 1’s complement is 011101011
 2’s complement is 011101100

Subtraction using r’s complement:

To find M-N in base r, we add M + r’s complement of N

Result is M + (rn
 – N)

1) If M > N then result is M – N + rn (rn is an end carry and
can be neglected.
 EE200(class 2-2) Prof. M.M. Dawoud 3of 5
2) If M < N then result is rn
 –(N-M) which is the r’s complement
of the result.

Example: Subtract (76425 – 28321) using 10’s complements.


Answer Æ 10’s complement of 28321 is 71679

 Then add Æ 7 6 4 2 5
 + 7 1 6 7 9

 1 4 8 1 0 4

Therefore the difference is 48104 after discarding the end carry.


Example: subtract (28531 – 345920)

Answer Æ It is obvious that the difference is negative. We
also have to work with the same number of digits, when dealing
with complements.

 10’s complement of 345920 is 654080

 Then add Æ 0 2 8 5 3 1
 + 6 5 4 0 8 0

 6 8 2 6 1 1
Therefore the difference is negative and is equal to the 10’s
complement of the answer.
 Difference is Æ - 317389

The same rules apply to binary.

Example: subtract (11010011 – 10001100)

Discard
No end carry EE200(class 2-2) Prof. M.M. Dawoud 4of 5
Answer Æ 2’s complement of 10001100 is 01110100

Then add Æ 1 1 0 1 0 0 1 1
 + 0 1 1 1 0 1 0 0

 1 0 1 0 0 0 1 1 1
The difference is positive and is equal to 01000111

The same rules apply to subtraction using the (r-1)’s
complements. The only difference is that when an end carry is
generated, it is not discarded but added to the least significant
digit of the result. Also, if no end carry is generated, then the
answer is negative and in the (r-1)’s complement form.


Example: Subtract (76425 – 28321) using 9’s complements.
Answer Æ 9’s complement of 28321 is 71678

 Then add Æ 7 6 4 2 5
 + 7 1 6 7 8

 1 4 8 1 0 3
 1
 4 8 1 0 4



Example: subtract (11010011 – 10001100) using 1’s complement.

Answer Æ 1’s complement of 10001100 is 01110011

Then add Æ 1 1 0 1 0 0 1 1
 + 0 1 1 1 0 0 1 1

 1 0 1 0 0 0 1 1 0
 1

Discard
Difference
Difference EE200(class 2-2) Prof. M.M. Dawoud 5of 5
 1 0 1 0 0 0 1 1 1 

Tuesday 23 September 2014

Make a simple currency converter for 3 currencies



Question :  You are required to write a program for Currency Exchange rates. The basic idea is that user/reader will be able to interchange different currencies using our program. User will have three options i.e. Pakistani Rupees, US Dollars, and Euro. In the end of the program, user should be asked if he/she wants to make another conversion. If user presses y then the whole program should start again. If user presses n then the program should terminate.



 #include <iostream>  
 using namespace std;  
 void main()  
 {  
      int amount=0;  
      char choice1, choice2, choice3='Y';  
      while (choice3=='Y')  
      {  
           cout<<"Select the currencies that you want to exchange\n";  
           cout<<" - Enter R for Pakistani Rupees\n";  
           cout<<" - Enter E for Euro\n";  
           cout<<" - Enter D for Dollar\n"<<endl;  
           cout<<"Please select the currency that you want to convert"<<endl;  
           cin>>choice1;  
           cout<<"Please enter the currency that you want to convert into"<<endl;  
           cin>>choice2;  
           cout<<"Enter Amount: ";  
           cin>>amount;  
           if ( choice1=='R' && choice2=='E')  
           {  
                //division of input rupees by 112 to convert into euros  
                cout<<amount <<" Rupees = "<<amount/112<<" Euros"<<endl;    
           }  
           if ( choice1=='R' && choice2=='D')  
           {  
                //division of input rupees by 84 to convert into dollars  
                cout<<amount <<" Rupees = "<<amount/84<<" Dollars"<<endl;   
           }  
           if ( choice1=='E' && choice2=='R')  
           {  
                //multiplication of input Euros by 112 to convert into rupees  
                cout<<amount <<" Euros = "<<amount*112<<" Rupees"<<endl;   
           }  
           if ( choice1=='E' && choice2=='D')  
           {  
                //multiplication of input Euros by 1.33 to convert into dollars  
                cout<<amount <<" Euros = "<<amount*1.33<<" Dollars"<<endl;   
           }  
           if ( choice1=='D' && choice2=='R')  
           {  
                //multiplication of input dollars by 84 to convert into rupees  
                cout<<amount <<" Dollars = "<<amount*84<<" Rupees"<<endl;   
           }  
           if ( choice1=='D' && choice2=='E')  
           {  
                //division of input dollars by 1.33 to convert into euros  
                cout<<amount <<" Dollars = "<<amount/1.33<<" Euros"<<endl;   
           }  
           cout<<"Do you want to make another conversion? ( Y/N ) :";  
           cin>>choice3;  
      }  
      cout<<"Goodbye :) "<<endl;  
 }  

Tuesday 3 June 2014

Dangling point.

 What is a dangling pointer?
   
A dangling pointer arises when you use 
the address of an object after
its lifetime is over. This may occur 
in situations like returning
addresses of the automatic variables
from a function or using the
address of the memory block after 
it is freed. The following
code snippet shows this:

          class Sample
          {
          public:
                  int *ptr;
                  Sample(int i)
                  {
                   ptr = new int(i);
                  }

                  ~Sample()
                  {
                   delete ptr;
                  }
                  void PrintVal()
                  {
cout << "The value is " << *ptr;
                  }
          };

          void SomeFunc(Sample x)
          {
cout << "Say i am in someFunc " << endl;
          }

          int main()
          {
           Sample s1 = 10;
           SomeFunc(s1);
           s1.PrintVal();
          }

In the above example when PrintVal() function is
called it is called by the pointer that has been
freed by the       destructor in SomeFunc.

void pointer

void *

Sometimes we know we want a pointer, but we don't necessarily know or care what it points to. The C/C++ language provides a special pointer, the void pointer, that allows us to create a pointer that is not type specific, meaning that it can be forced to point to anything.Why is this useful? One common application of void pointers is creating functions which take any kind of pointer as an argument and perform some operation on the data which doesn't depend on the data contained. A function to "zero-out" memory (meaning to turn off all of the bits in the memory, setting each byte to the value 0) is a perfect example of this.

void memzero(void *ptr, size_t len)
{
 for(; len>0; len--) {
  *(char *)ptr = 0;
 }
}
This function takes a pointer to any piece of memory, meaning that we can pass in any kind of pointer we want, and the number of bytes to zero out. It then walks along the memory zeroing out each byte. Without void pointers, it would be more difficult to write a generic function like this.

Other example
void increaseChar (char* charData)
{
    ++(*charData);
}

void increaseInt (int* intData)
{
    ++(*intData);
}

int main ()
{
  char a = 'x';
  int b = 1602;
  increaseChar (&a);
  increaseInt (&b);
  cout << a << ", " << b << endl;
  string str;
  cin >> str;
  return 0;
}

string

C-Strings (Character Arrays)
STRING: It is an array of type char.
Syntax for declaration
char <array/string name> [max. number of characters to be stored +1];
The number of elements that can be stored in a string is always n-1, if the size of the array specified is n. This is because 1 byte is reserved for the NULL character '\0' i.e. backslash zero. A string is always terminated with the NULL character.
Example:
char str[80]; 
In the above example, str can be used to store a string with 79 characters.
Initializing a string
A string can be initialized to a constant value when it is declared.
char str[ ] = "Good";
    Or

char str[]={'G','o','o','d','\0'};
Here. 'G' will be stored in str[0], 'o' in str[1] and so on.
Note: When the value is assigned to the complete string at once, the computer automatically inserts the NULL character at the end of the string. But, if it is done character by character, then we have to insert it at the end of the string.
Reading strings with/without embedded blanks
To read a string without blanks cin can be used
cin>>str;
To read a string with blanks cin.getline() or gets() can be used.
cin.getline(str,80);
   -Or-
gets(str);
Printing strings
cout and puts() can be used to print a string.
cout<<str:
   Or
puts(str);
Note: For gets( ) and puts(), the header file stdio.h has to be included. puts() can be used to display only strings. It takes a line feed after printing the string.
cin
gets()
It can be used to take input of a value of any data type.
It can be used to take input of a string.
It takes the white space i.e. a blank, a tab, or a new line character as a string terminator.
It does not take the white space i.e. a blank, a tab, or a new line character, as a string terminator.
It requires header file iostream.h
It requires the header file stdio.h
Example:
char S[80];
cout<<"Enter a string:”;
cin>>S;
Example:
char S[80];
cout<<"Enter a string:";
gets(S);

cout
puts()
It can be used to display the value of any data type.
It can be used to display the value of a string.
It does not take a line feed after displaying the string.
It takes a line feed after displaying the string.
It requires the header file iostream.h
It requires the header file stdio.h
Example:
char S[80]="Computers";
cout<<S<<S;

Output:
ComputersComputers
Example:
char S[80]="Computers";
puts(S);
puts(S);

Output:
Computers
Computers
Counting the number of characters in a string and printing it backwards
#include<iostream.h>
#include<stdio.h>
int main( )
{
  char str[80];
  cout<<"Enter a string:";
  gets(str);
  for(int l=0; str[l]!='\0';l++);  //Loop to find length
    cout<<"The length of the string is : "<<l<<endl ;
  for(int i=l-1;i>=0;i--)    //Loop to display the string backwards
    cout<<str[i];
  return 0;
}
Function to count the number of words in a string
void count(char S[])
{
  int words=0;
  for(int i=0;S[i]!='\0';i++)
  {
    if (S[i]==' ')
      words++;                   //Checking for spaces
  }
  cout<<"The number of words="<<words+1<<endl;
}
Function to find the length of a string
int length(char S[ ])
{
  for(int i=0;S[i]!='\0';i++);
     return i;
}
Function to copy the contents of string S2 to S1
void copy(char S1[ ], char S2[ ])
{
   for(int i=0;S2[i]!='\0';i++)
      S1[i]=S2[i];
   S1[i]='\0';
}
Function to concatenate the contents of string S2 to S1
void concat(char S1[ ], char S2[ ])
{
   for(int l=0;S1[l]!='\0';l++);
     for(int i=0;S2[i]!='\0';i++)
         S1[l++]=S2[i];
     S1[l]='\0';
}
Function to compare strings STR1 to STR2.
The function returns a value>0 if //STR1>STR2, a value<0 if STR1<STR2, and value 0 if STR1=STR2
int compare(char STR1[ ],char STR2[])
{
  for(int I=0;STR1[I]==STR2[I] && STR1[I]!='\0'&&STR2[I]!='\0'; I++);
     return STR1[I]-STR2[I];
}
To reverse the contents of string S and store it in string Rev
void Reverse(char S[], char Rev[])
{
   for(int C1=0; S[C1]!='\0'; C1++);
      C1--;
   for(int C2=0;C1>=0;C2++,C1--)
      Rev[C2]=S[C1];
   Rev[C2]='\0';
}
Function to check whether a string S is a palindrome or not
int Palin(char S[])
{
   for(int L=0;S[L]!='\0';L++);    //To find length
      for(int C=0;(C<L/2) && (S[C]==S[L-C-1]);C++);
         return (C==L/2)?1:0; //Returns 1 if Palindrome else 0
}
Function to change the case of string S to uppercase
void Upper(char S[])
{
   for(int i=0;S[i]!='\0';i++)
      S[i] = (S[i]>='a' && S[i]<='z')?(S[i]-32):S[i];
}
Function to change the case of string S to lower case
void Lower(char S[])
{
   for(int i=0;S[i]!='\0';i++)
       S[i] = (S[i]>='A' && S[i]<='Z')?(S[i]+32):S[i];
}
Function to extract n characters from left side of the string and store it in a different string.
Example: 4 characters from ENVIRONMENT=ENVI
int SLeft(char S[ ], int n, char result[ ])
{
   for(int l=0;S[l]!='\0';l++);
     if(n<=I)    //characters extracted should be <=length
     {
        for(int i=0;i<n;i++)
            result[i]=S[i];
        result[i]='\0';
        return 1;
     }
     else
        return 0;
}
Function to extract n characters from right side of the string and store it in a different string.
Example: 4 characters from ENVIRONMENT=MENT
int SRight(char S[ ], int n, char result[ ])
{
   for(int l=0;S[l]!='\0';l++);
     if(n<=I)     //characters extracted should be <=length
     {
        for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
            result[j]=S[i];
        result[j]='\0';
        return 1;
     }
     else
        return 0;
}
Function to extract n characters from specified location loc of the string and store it in a different  string.
Example: 4 characters from third location in string ENVIRONMENT= VIRO
int substring(char S[ ], int n, int loc, char result[ ])
{
  for(int l=0;S[l]!='\0';l++);
     if(n<=I)      //characters extracted should be <=length
     {
        for(int j=0;i=l-n;S[i]!=’/0’;i++,j++)
           result[j]=S[i];
        result[j]='\0';
        return 1;
     }
     else
        return 0;
}


Two Dimensional Array

Two Dimensional Array
It is a collection of data elements of same data type arranged in rows and columns (that is, in two dimensions).
Declaration of Two-Dimensional Array
Type arrayName[numberOfRows][numberOfColumn];
For example,
int Sales[3][5];
Initialization of Two-Dimensional Array
An two-dimensional array can be initialized along with declaration. For two-dimensional array initialization, elements of each row are enclosed within curly braces and separated
by commas. All rows are enclosed within curly braces.
int A[4][3] = {{22, 23, 10},
              {15, 25, 13},
              {20, 74, 67},
              {11, 18, 14}};
Referring to Array Elements
To access the elements of a two-dimensional array, we need a pair of indices: one for
the row position and one for the column position. The format is as simple as:
name[rowIndex][columnIndex]

Examples:
cout<<A[1][2];      //print an array element
A[1][2]=13;         // assign value to an array element
cin>>A[1][2];       //input element
Using Loop to input an Two-Dimensional Array from user
int mat[3][5], row, col ;
for (row = 0; row < 3; row++)
  for (col = 0; col < 5; col++)
    cin >> mat[row][col];
Arrays as Parameters
Two-dimensional arrays can be passed as parameters to a function, and they are passed by reference. When declaring a two-dimensional array as a formal parameter, we can omit the size of the first dimension, but not the second; that is, we must specify the number of columns. For example:
   void print(int A[][3],int N, int M)
In order to pass to this function an array declared as:
   int arr[4][3];
we need to write a call like this:
   print(arr);
Here is a complete example: 
#include <iostream>
using namespace std;
void print(int A[][3],int N, int M)
{
  for (R = 0; R < N; R++)
    for (C = 0; C < M; C++)
       cout << A[R][C];
}
int main ()
{
  int arr[4][3] ={{12, 29, 11},
                  {25, 25, 13},
                  {24, 64, 67},
                  {11, 18, 14}};
  print(arr,4,3);
  return 0;
}
Function to read the array A
void Read(int A[][20], int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
    {
      cout<<"(R<<','<<")?";
      cin>>A[R][C];
     }
}
Function to display content of a two dimensional array A
void Display(int A[][20],int N, int M)
{
  for(int R=0;R<N;R++)
  {
     for(int C=0;C<M;C++)
        cout<<setw(10)<<A[R][C];
     cout<<endl;
   }
}
Function to find the sum of two dimensional arrays A and B
void Addition(int A[][20], int B[][20],int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
      C[R][C]=A[R][C]+B[R][C];
}
Function to multiply two dimensional arrays A and B of order NxL and LxM
void Multiply(int A[][20], int B[][20], int C[][20],int N, int L, int M)
{
  for(int R=0;R<N;R++)
   for(int C=0;C<M;C++)
   {
      C[R][C]=0;
      for(int T=0;T<L;T++)
        C[R][C]+=A[R][T]*B[T][C];
    }
}
Function to find & display sum of rows & sum of cols. of a 2 dim. array A
void SumRowCol(int A[][20], int N, int M)
{
  for(int R=0;R<N;R++)
  {
     int SumR=0;
     for(int C=0;C<M;C++)
       SumR+=A[R][C];
     cout<<"Row("<<R<<")="<<SumR<<endl;
   }
  for(int R=0;R<N;R++)
  {
    int SumR=0;
    for(int C=0;C<M;C++)
      SumR+=A[R][C];
    cout<<"Row("<<R<<")="<<SumR<<endl;
   }
}
Function to find sum of diagonal elements of a square matrix A
void Diagonal(int A[][20], int N, int &Rdiag, int &LDiag)
{
  for(int I=0,Rdiag=0;I<N;I++)
    Rdiag+=A[I][I];
  for(int I=0,Ldiag=0;I<N;I++)
    Ldiag+=A[N-I-1][I];
}
Function to find out transpose of a two dimensional array A
void Transpose(int A[][20], int B[][20],int N, int M)
{
  for(int R=0;R<N;R++)
    for(int C=0;C<M;C++)
       B[R][C]=A[C][R];


Array

Array
An array is a collection of data elements of same data type. It is described by a single name and each element of an array is referenced by using array name and its subscript no.
Declaration of Array
Type arrayName[numberOfElements];
For example,
int Age[5] ;
float cost[30];
Initialization of One Dimensional Array
An array can be initialized along with declaration. For array initialization it is required to place the elements separated by commas enclosed within braces.
int A[5] = {11,2,23,4,15};
It is possible to leave the array size open. The compiler will count the array size.
int B[] = {6,7,8,9,15,12};
Referring to Array Elements
In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:
name[index]

Examples:
cout<<age[4];      //print an array element
age[4]=55;         // assign value to an array element
cin>>age[4];       //input element 4
Using Loop to input an Array from user
int age [10], i ;
for (i=0 ; i<10; i++)
{
  cin>>age[i];
}
Arrays as Parameters
At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address.
For example, the following function:
void print(int A[])
accepts a parameter of type "array of int" called A.
In order to pass to this function an array declared as:
int arr[20];
we need to write a call like this:
print(arr);

Here is a complete example: 
#include <iostream>
using namespace std;
 
void print(int A[], int length)
{
  for (int n=0; n<length; n++)
    cout << A[n] << " ";
  cout << "\n";
}
int main ()
{
  int arr[] = {5, 10, 15};
  print(arr,3);
  return 0;
}
Basic Operation on One Dimensional Array
Function to traverse the array A
void display(int A[], int n)
{
       cout<<"The elements of the array are:\n";
       for(int i=0;i<n;i++)
              cout<<A[i];
}
Function to Read elements of the array A
Void Input (int A[], int n)
{
 
      cout<<"Enter the elements:";
      for(int i=0;i<n;i++)
            cin>>A[i];
}
Function to Search for an element from A by Linear Search
void lsearch(int A[], int n, int data)
{
      int i;
 
      for(i=0; i<n; i++)
      {
            if(A[i]==data)
            {
                  cout<<"Data Found at : "<<i;
                  return;
            }
      }
      cout<<"Data Not Found in the array"<<endl;
}
Function to Search for an element from Array A by Binary Search
int BsearchAsc(int A[], int n, int data)
{
       int Mid,Lbound=0,Ubound=n-1,Found=0;
       while((Lbound<=Ubound) && !(Found))
       {
              Mid=(Lbound+Ubound)/2;        //Searching The Item
              if(data>A[Mid])
                     Lbound=Mid+1;
              else if(data<A[Mid])
                     Ubound=Mid-1;
              else
                     Found++;
       }
       if(Found)
              return(Mid+1);        //returning 1ocation, if present
       else
              return(-1);        //returning -1,if not present
}
Function to Sort the array A by Bubble Sort
void BSort(int A[], int n)
{
    int I,J,Temp;
    for(I=0;I<n-1;I++) //sorting
   {
       for(J=0;J<(n-1-I);J++)
            if(A[J]>A[J+1])
           {
               Temp=A[J]; //swapping
               A[J]=A[J+1];
               A[J+1]=Temp;
           }
    }
}
Function to Sort the array ARR by Insertion Sort
void ISort(int A[], int n)
{
       int I,J,Temp;
       for(I=1;I<n;I++) //sorting
       {
           Temp=A[I];
           J=I-1;
           while((Temp<A[J]) && (J>=0))
           {
               A[J+1]=A[J];
               J--;
           }
           A[J+1]=Temp;
       }
}
Function to Sort the array by Selection Sort
void SSort(int A[], int n)
{
    int I,J,Temp,Small;
    for(I=0;I<n-1;I++)
    {
         Small=I;
         for(J=I+1;J<n;J++) //finding the smallest element
         if(A[J]<A[Small])
              Small=J;
         if(Small!=I)
        {
            Temp=A[I]; //Swapping
            A[I]=A[Small];
            A[Small]=Temp;
        }
     }
}
Function to merge A and B arrays of lenghts N and M
void Merge(int A[], int B[], int C[], int N, int M, int &K)
{
      int I=0, J=0;
      K=0;             //Initialisation of counters for A, B, and C
      while (I<N && J<M)
      {
            if (A[I]<B[J])
                  C[K++]=A[I++];
            else if (A[I]>B[J])
                  C[K++]=B[J++];
            else
            {
                  C[K++]=A[I++];
                  J++;
            }
      }
      for (int T=I;T<N;T++)
            C[K++]=A[T];
      for (T=J;T<M;T++)
            C[K++]=B[T];
}