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

Strings

Posted by Tayyab


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.hIt 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.hIt 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;
}



<< Previous                                                                                                                 Next >>    

0 comments:

Post a Comment

Arrays

Posted by Tayyab


One Dimensional 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];
array c++

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.h>
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

int 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];
}

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];
array two dimensional

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.h>
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];
}



<< Previous                                                                                                                 Next >>    

0 comments:

Post a Comment

Numbers

Posted by Tayyab


Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types.

Defining Numbers in C++:

You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++:
#include <constream.h>
 
int main ()
{
   // number definition:
   short  s;
   int    i;
   long   l;
   float  f;
   double d;
   
   // number assignments;
   s = 10;      
   i = 1000;    
   l = 1000000; 
   f = 230.47;  
   d = 30949.374;
   
   // number printing;
   cout << "short  s :" << s << endl;
   cout << "int    i :" << i << endl;
   cout << "long   l :" << l << endl;
   cout << "float  f :" << f << endl;
   cout << "double d :" << d << endl;
 
   return 0;
}
When the above code is compiled and executed, it produces the following result:
short  s :10
int    i :1000
long   l :1000000
float  f :230.47
double d :30949.4

Math Operations in C++:

In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use.
C++ has a rich set of mathematical operations, which can be performed on various numbers. Following table lists down some useful built-in mathematical functions available in C++.
To utilize these functions you need to include the math header file <cmath>.
S.N.Function & Purpose
1double cos(double);
This function takes an angle (as a double) and returns the cosine.
2double sin(double);
This function takes an angle (as a double) and returns the sine.
3double tan(double);
This function takes an angle (as a double) and returns the tangent.
4double log(double);
This function takes a number and returns the natural log of that number.
5double pow(double, double);
The first is a number you wish to raise and the second is the power you wish to raise it to.
6double hypot(double, double);
If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse.
7double sqrt(double);
You pass this function a number and it gives you this square root.
8int abs(int);
This function returns the absolute value of an integer that is passed to it.
9double fabs(double);
This function returns the absolute value of any decimal number passed to it.
10double floor(double);
Finds the integer which is less than or equal to the argument passed to it.
Following a simple example to show few of the mathematical operations:
#include <constream.h>
#include <math.h>
 
int main ()
{
   // number definition:
   short  s = 10;
   int    i = -1000;
   long   l = 100000;
   float  f = 230.47;
   double d = 200.374;

   // mathematical operations;
   cout << "sin(d) :" << sin(d) << endl;
   cout << "abs(i)  :" << abs(i) << endl;
   cout << "floor(d) :" << floor(d) << endl;
   cout << "sqrt(f) :" << sqrt(f) << endl;
   cout << "pow( d, 2) :" << pow(d, 2) << endl;
 
   return 0;
}
When the above code is compiled and executed, it produces the following result:
sign(d) :-0.634939
abs(i)  :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7

Random Numbers in C++:

There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function.
Following is a simple example to generate few random numbers. This example makes use of time()function to get the number of seconds on your system time, to randomly seed the rand() function:
#include <iostream.h>
#include <time.h>
#include <stdlib.h>

 
int main ()
{
   int i,j;
 
   // set the seed
   srand( (unsigned)time( NULL ) );

   /* generate 10  random numbers. */
   for( i = 0; i < 10; i++ )
   {
      // generate actual random number
      j= rand();
      cout <<" Random Number : " << j << endl;
   }

   return 0;
}
When the above code is compiled and executed, it produces the following result:
 Random Number : 1748144778
 Random Number : 630873888
 Random Number : 2134540646
 Random Number : 219404170
 Random Number : 902129458
 Random Number : 920445370
 Random Number : 1319072661
 Random Number : 257938873
 Random Number : 1256201101
 Random Number : 580322989



<< Previous                                                                                                                 Next >>    

0 comments:

Post a Comment