Translate

Saturday 2 June 2012

List of strings (2-d array of characters )


         A two dimensional array has to be used to read and process a list of names, where the first index(subscript) specifies the size of the list i.e. the no of names to be processed and the second index indicates the size of each name.
  Example
          char name[10][20];
where the number 10 specifies that a list having 10 names with each size of 20 characters can be accessed.

We can initialise the list also.
          char name [5][20]={“Ashok”, “Neha”, “Dipesh”, “Sarita”, “Shubham”};
Here also we can leave the first index blank.


Q. Write a program to read a list of n-names and display them in alphabetical order.
#include<iostream>
#include<stdio.h>
#include<string.h>
void main()
{
     char name[50][80], temp[80];
     int n, i, j;
     cout<< “How many names: ”;
     cin>>n;
     cout<< “Enter”<< n << “names”;
     for(i=0; i<n; i++)
          gets( name[i] );
     for(i=0; i<n-1; i++)
          for(j=0; j<n-i-1; j++)
               if(strcmpi((name[j], name[j+1] ) >0)
               {
                    strcpy(temp, name[j]);
                    strcpy(name[j], name[j+1]);
                    strcpy(name[j+1], temp);
               }
     cout<< “Arranged list \n”;
     for(i=0; i<n; i++)
     cout<< name[i]<< “\t”;
}

Sunday 27 May 2012

String functions in C++


Unlike single character constants a string constant cannot be assigned directly with a string variable nor compared with an another string.
String functions whose header file is <string.h> have to be used to carry out operation such as comparision, concatenation (combining two strings), assignment operators etc. Some functions are listed below.

strcpy():- This function copies the contents of source string into destination string. Its syntax is
                strcpy(destination string, source string);
Example:
   char sd[10], ss[10]={ “Hi welcome”};
   strcpy(sd,ss);
   cout<<sd;
Output:
   Hi welcome

Thus sd=ss; is invalid statement as arithmetic operation can’t be used two string variable.



strlen():- This function provides the length of the string excluding null character.
Example:
   char ss[10]={ “Welcome”};
   int a= strlen(ss);
   cout<<a;
Output:
   7
The function strlen() counts no of characters used in a string by ignoring null character while the operator sizeof() counts total space allocated if the size is specified with the array name or it counts no of characters including the null characters.
strlen() needs a header file because it is a function whereas sizeof() does not require a header file because it is an operator.



strcat():- This function concatenates(combines) the given strings. Its syntax is
        strcat(s1,s2);
It combines the string s1 with s2 and stores the resultant string with s1.
Example:
   char s1[10]= “Kota”;
   char s2[10]= “Junction”;
   strcat(s1,s2);
   cout<<s1;
Output:
   KotaJunction



strcmp():- It is a function which compares two strings and provides the difference in integer form.
Syntax:
strcmp(s1, s2);
if s1>s2 then it returns +ve value.
if s1<s2 then it returns -ve value.
if s1=s2 then it returns zero.
Example:
1.  s1= “BAT”;
     s2= “CAT”;
     strcmp(s1,s2)=-1

2.  s1= “ARUN”;
     s2= “arun”;
     strcmp(s1,s2)=-32

3.  s1= “Nirmal”;
     s2= “Niranjan”;
     strcmpi(s1,s2)=12

This function is case sensitive i.e. it treats uppercase and lower case of same letter as different. The function strcmpi() can be use to treat the lowercase and uppercase of a letter as identical.
Example:
   s1= “ARUN”;
   s2= “arun”;
   strcmpi(s1,s2)=0


Saturday 26 May 2012

Strings in C++


      A string is a collection of character such as numeric digits alphabets or special characters enclosed within double quotes.
Single character constant can be used in arithmetic expressions whereas string constants cannot be used with arithmetic operations as shown below.
‘A’+3 = ‘D’  or 68   but   “A”+3= Invalid

Declaration:- A string variable is an array variable of type character. It can be declared as shown.
char a[80]

Initialization:- Like integer arrays initialized with some values, an array variable declared as a type of character can be initialized with an aray of characters or string.
char sn[7]= {'a', 'c', 'd', '-', '4', '0', '\0'};
      Thus null character ‘\0’ has to be included when the initialization is carried out with a list of characters. The system assigns a null character when a string variable is initialized with a string constant. Every string is terminated by a null character.

Q. Write a program to read a string and count number of alphabets digits and special characters used in it.
#include <iostream>
void main()
{
    char st[100];
    int i, ca=0, cd=0, csp=0;
    cout<< “Enter a string \n”;
    gets(st);
    for(i=0; st[i]!=‘\0’; i++)
    if (st[i]> ‘a’ && st[i]< ‘z’ || st[i]> ‘A’ && st[i]< ‘Z’)
        ca++;
    else if (st[i]> ‘0’ && st[i]<’9’)
        cd++;
    else
        csp++;
    cout<< “No of alphabets= ”<< ca << endl 
        << “No of digits= ”<< cd<<endl
        <<”No of special characters=”<<csp;
}

Tuesday 22 May 2012

2 - Dimensional array in C++



         This array is used to represent and store data in a tabular form. Such type of array specially used to represent data in a matrix form. It is an array having 2 subscript or indices.
Syntax
               storage class datatype arrayname[s1][s2];
Where ‘s1’ indicates number of rows and ‘s2’ indicates number of column.
      In C++ the subscript of the first array element is always zero. For instance, If a[5][5] is an array then the first element is always (by default) a[0][0].


Example
                int a[4][3];
                int x[m][n];
Where ‘m’ and ‘n’ are constant numbers.


Initialisation:- Like one dimensional array two dimensional array can be initialised with a list of values while declaring the array variable.
        Example
int a[3][2]={1,2,4,6,7,9};
         where
                a[0][0]=1                             a[0][1]=2
    a[1][0]=4                             a[1][1]=6
    a[2][0]=7                             a[2][1]=9
        alternate,
                int a[3][2]={{1,2},{4,6},{7,9}};

The row size is optional when array is initialised with a set of values.


Lets have an example.
Q. Write a program to read a matrix having m X n elements and display the sum of the main diagonal elements.
#include <iostream>
#include <stdlib.h>
void main()
{
   int a[10][10], m, n;
   cout<< “Enter row and column size ”;
   cin>>m>>n;
   if(m!=n)
   {
      cout<< “Diagonal elements don’t exist”;
      exit(1);
   }
   cout<< “Enter”<< m << “X” << n << “elements”;
   for(int i=0; i<m; i++)
      for(int j=0; j<n; j++)
         cin>>a[i][j];
   int s=0;
   for(int i=0; i<m; i++)
      for(int j=0; j<n; j++)
   if( i==j )
      s+=a[i][j];
   cout<< “Sum is ->”<<s;





Q. Write a program to determine product of diagonal element of m X n matrix. 
Q. Write a program to determine sum and product of 2 matrices. 

Saturday 19 May 2012

Selection Sort in C++


        It is a sorting process in which the location is fixed and then value selected from the location is compared with the rest. Swapping values of two locations is carried out if need arises.

Suppose A is an array consisiting of 6 integers as shown
        A[0]= 2,    A[1]= 5,    A[2]= 8,    A[3]=11,    A[4]=14,   A[5]=18
This array has to be arranged in an ascending order using selection sort method. The step and comparison involved while arranging the array are listed below.

STEP 1
2  5  8  11  14  18                 2<5  so swap 2 and 5
5  2  8  11  14  18                 5<8  so swap 5 and 8
8  2  5  11  14  18                 8<11  so swap 8 and 11
11  2  5  8  14  18                 11<14  so swap 11 and 14
14  2  5  8  11  18                 14<18  so swap 14and 18
18  2  5  8  11  14
Now largest value is shifted to first position.

STEP 2
18  2  5  8  11  14                 2<5  so swap 2 and 5
18  5  2  8  11  14                 5<8  so swap 5 and 8
18  8  2  5  11  14                 8<11  so swap 8 and 11
18  11  2  5  8  14                 8<11  so swap 8 and 11
18  14  2  5  8  11                 11<14  so swap 11 and 14
 Now the second largest value is shifted to second position.

STEP 3
18  14  2  5  8  11                 2<5  so swap 2 and 5
18  14  5  2  8  11                 5<8  so swap 5 and 8
18  14  8  2  5  11                 8<11  so swap 8 and 11
18  14  11  2  5  8
Now the third largest value is shifted to third position.

STEP 4
18  14  11  2  5  8                 2<5  so swap 2 and 5
18  14  11  5  2  8                 5<8  so swap 5 and 8
18  14  11  8  2  5                

STEP 5
18  14  11  8  2  5                 2<5  so swap 2 and 5
18  14  11  8  5  2                

Step 1 uses 5 comparisons. Step 2 needs 4 comparisons and so on. The array A requires 5 steps where each step uses 6-step value comparisons. Therefore a list having n values needs n-1 steps with each step using n- step value comparison. So order is O(n2).


Algorithm:- Suppose that an array ‘A’ having n numbers has to be arranged in an descending order. The selection sort algorithm can be used to accomplish the same.

STEP 1:- Repeat step 2   for i=0 to n-2

STEP 2:- Repeat step 3   for j=i+1 to n-1

STEP 3:if (A[i] < A[j] )
                                swap A[j] and A[j+1]
                end of if;
                end of step 2;
    end of step 1;

STEP 4:- STOP


C++ Programme code

#include<iostream>
#include<iomanip.h>
void main()
{
     int a[50], n,i,j;
     cout<< “Enter the size of list ”;
     cin>>n;
     cout<< “Enter”<<n<< “values”;
     for(i=0; i<n; i++)
           cin>> a[i];
     for(i=0; i<n-1; i++)
           for(j=i+1; j<n; j++)
                if(a[i] < a[j])
                {
                     int t = a[i];
                     a[i] = a[j];
                     a[j] = t;
                 }
     cout<< “Arranged list is...”;
     for(i=0; i<n; i++)
           cout<< setw(5) << a[i];
}

Bubble Sort in C++


It is a sorting process in which two nearby values are compared and then exchanged if need arises.

       Suppose A is an array consisting of 5 integers as shown
A[0]= 17,    A[1]= 14,    A[2]= 10,    A[3]=7,    A[4]=3
    This array has to be arranged in an ascending order using bubble sort method. The step and comparison involved while arranging the array are listed below.

STEP 1
17  14  10  7  3                     17>14  so exchange 17 and 14
14  17  10  7  3                     17>10  so exchange 17 and 10
14  10  17  7  3                     17>7  so exchange 17 and 7
14  10  7  17  3                     17>3  so exchange 17 and 3
14  10  7  3  17
Thus after step 1 the largest value is shifted to last position.

STEP 2
14  10  7  3  17                     14>10  so exchange 14 and 10
10  14  7  3  17                     14>7  so exchange 14 and 7
10  7  14  3  17                     14>3  so exchange 14 and 3
10  7  3  14  17
Thus step 2 requires 3 comparisons and the second largest value is shifted to second last position.

STEP 3
10  7  3  14  17                     10>7  so exchange 10 and 7
10  3  14  17                     10>3  so exchange 10 and 3
7  3  10  14  17
Thus after step 3 third largest value is shifted to third last value.

STEP 4
7  3  10  14  17                     7>3  so exchange 7 and 3
3  7  10  14  17


Step 1 uses 4 comparisons. Step 2 needs 3 comparisons and so on. The array A requires 4 steps where each step uses 5-step value comparisons. Therefore a list having n values needs n-1 steps with each step using n- step value comparison. So order is O(n2).


Algorithm:- Suppose that an array ‘A’ having n numbers has to be arranged in an ascending order. The bubble sort algorithm can be used to accomplish the same.

STEP 1:- Repeat step 2   for i=0 to n-2

STEP 2:- Repeat step 3   for j=0 to n-1-i

STEP 3:- if (A[j] > A[j+1] )
                                swap A[j] and A[j+1]
                end of if;
                end of step 2;
end of step 1;

STEP 4:- STOP





C++ Programme code

#include<iostream>
#include<iomanip.h>
void main()
{
     int a[50], n;
     cout<< “Enter the size of list ”;
     cin>>n;
     cout<< “Enter”<<n<< “values”;
     for(int i=0; i<n; i++)
           cin>> a[i];
     for(i=0; i<n-1; i++)
           for(int j=0; j<n-1-i; j++)
                if(a[j] > a[j+1])
                {
                     int t = a[j];
                     a[j] = a[j+1];
                     a[j+1] = t;
                 }
     cout<< “Arranged list is...”;
     for(i=0; i<n; i++)
           cout<< setw(5) << a[i];
}

1 - Dimensional array in C++


     It is an array having array name followed by subscript or index endosed within brackets [ ].
Declaration:- storage class datatype array-name[subscript];
where the storage class specifies the default initialization and the life periodof the array. The datatype indicates the type of list to be assigned with the array. Array name is an identifier. Subscript specifies the size of the array. The subscript should be a constant.
    Example:- int a[10];
                    float f[m];  where m is a constant.

Initialisation of array:- Like an ordinary variable an array variable can be initialized with one or more values.
      Example:- int a[4]={1,2,3,4}
The values are assigned with the array variable as listed below
           a[0]=1,a[1]=2, a[2]=3, a[3]=4
Always remember the first variable of array has subscript 0.
     If the size of an array is ‘n’ and initialised with less than n values then the remaining positions will be filled with 0. For instance an array has the size of 10 and is initialized with 4 values than the last 6 positions are filled with 0.
    When an array is initialised with list of n values the size of the array need not be specified.
           int a []= {1,2,3,4};
The size should be specified when an array is not initialised with a list.


Q. Write a program to display first n terms of Fibonacci series by using array variable where
fn = fn-1 + fn-2
#include<iostream>
#include<iomanip.h>
void main()
{
     int f [50], n;
     cout<< “Enter the size of list”;
     cin>>n;
     for(int i=1;i<n; i++)
     {
           f [i]= i < 2  ?  1  :  f [i-1] + f [i-2];
           cout<<  setw(5) <<  f [i];
     }
}

Q. Correct the error in following program segment.
void main()
{
     int x[ ]=(3, 9, 15, 21);
     for (i=0, i<4, i++)
          cout { x[i];
};

Answer:-
void main()
{
     int x[ ]=3, 9, 15, 21};
     for( int i=0; i<4; i++)
          cout<< x[i];
}


Array in C++


Arrays
An ordinary variable can assign only one value at a time. The variable used with the object cin within a repeated statement (while, do while, for) can assign or can take a list of values however this list of values can’t be used outside the loop. These limitations or drawbacks can be eliminated by using arrays.
                An array is a set of same data item. An array name can be written with 1 or more subscript or indices. An array name with one subscript is known as 1 dimensional array, an array name with two subscript is known as 2 dimensional array and so on.

Wednesday 16 May 2012

Switch statement in C++


switch:- It is a multi branch statement which can be used to select and execute one of the available statements.
                switch(value)
                {
                                case 1:    statement 1;      break;
                                case 2:    statement 2;      break;
                                case n:    statement n;      break;
                                default:    statement d;
                }
Where value can be a variable of type numeric or character. The case label 1 to n can also be written with constant identifiers.
                When the value assigned matches with case label 1 statement 1 is executed. The break statement written after statement 1 transfers the control out of the switch statement. When the value doesn’t match with case label 1 then it checks with case label 2 and so on. When the value assigned doesn’t match with any of the case labels (1 to n) then the default clause is considered and the statement d is executed.
                Default clause is optional like else clause in if-else-if-else statement.


example:
switch(c)
{
case1:     cout<< “north”;      break;
case2:     cout<< “south”;      break;
case3:     cout<< “east”;        break;
case4:     cout<< “west”;       break;
default:   break;
}



Q. Write a program to display the grades as listed below by using switch statement
80-100             Distinction
60-79               Grade A
40-59               Grade B
Otherwise fail

#include<iostream>
void main()
{
int m;
cout<< “Enter marks scored: ”;
cin>> m;
switch( m/10 )                     //marks are divided by 10
{
case 10:
case 9:
case 8:       cout << “Distinction\n”;    break;
case 7:
case 6:       cout << “Grade A\n”;       break;
case 5:
case 4:       cout << “Grade B\n”;       break;
default:       cout << “Fail\n”;              break;
}
}



Q. Write a program to design simple calculator by using switch statement to carry out addition, multiplication, division and subtraction.
Q. Write a program to read a number from 1-7 and print day of week corresponding to that number using switch statement.


Looping in C++


while:- It is a repeated structure statement which repeats a statement given as long as the condition is true.
                        while(condition)
                                     statement1;
                statement1 is executed till the condition is true.
                example:
                        int i = 1;
while (i <= 20)
{
cout<< i << “\t”;
++i;
}

                Output: 1             2              3.........    20



do while:- Like while statement it repeats a statement given as long as the condition is satisfied unlike in while statement the condition is checked at the end of the structure.
                                do
                                {
                                                statement1;
                                }
                                while(condition);
statement1 is executed till the condition is true. Here while statement contains a semicolon.
example:
                         int i = 1;
do
{
cout<< i << “\t”;
++i;
} while(i <= 20);

           Output: 1             2              3.........    20



for:- It is a repeated structure which can repeat a statement as long as the given condition is satisfied.
                         for(statement1; condition; statement2)
                                    statement3;
                where statement1 initialises control variable, condition is used to check whether statement written after loop can be repeated or not , statement2 is used to modify the control variable. Statement3 is a simple statement (having only one statement) or compound statement (a set of statements written within braces {} ) which can be repeated as long as condition is true or satisfied.
example:
                         for(i = 1; i <= 20; i++)
{
cout<< i << “\t”;
++i;
}

           Output: 1             2              3.........    20


Nested loop:- When one repeated structure is written within one or more such repeated structures then the entire structure is known as nested loop.
        example:
            int i = 1;
           while(i <= 3)
           {
            int j = 1; 
            while(j <= 2)
            {
          cout<< i << “;” << j << “  ”;
          j++;
            }
            i++;
            }             

Output: 1;1  1;2   2;1  2;2  3;1  3;2



Lets have some examples.
Q. Write a program to read two positive integers and check whether they are coprime or not.
#include<iostream>
void main()
{
            int a, b, p, q;
            cout<< “Enter two numbers”;
            cin>> a >> b;
p = a;
q = b;
while (b != 0)
{
int r = a % b;
a = b;
b = r;
}
if(a == 1)
                        cout<< p << “ and ”<< q << “are coprime”;
else
                        cout<< p << “ and ”<< q << “are not coprime”;
}


Q.Write a program to read a list of numbers terminated by -1 and determine positive average of positive numbers.
#include<iostream>
void main()
{
                int a, s = 0, i = 0;
                cout<< “Enter a list of numbers terminated by -1”;
                do          
                {
                                cin>> a;
                                if(a < 0)
                                                continue;
                                s = s + a;
                                ++i;
                }while(a != -1);
                cout<< “No of +ve numbers read”<< i << endl << “Avg=”<< s/float(i);
}


Q. Write a program to display odd factors of a positive integer.
#include<iostream>
#include<iomanip.h>
void main()
{
                int a, n;
                cout<< “Enter the value of a”;
                cin>> a;
                for(i = 1; i <= n; i += 2)
                                if(a % i == 0)
                                                cout<<setw(5)<<i;
}


Q. Write a program to print following pattern.

54321
5432
543
54
5

#include<iostream>
#include<iomanip.h>
void main()
{
int i, j;
for (i = 1;i <= 5;i++)
{
for (j = 5; j >= i; j--)
cout<< setw(5) << j;
cout<< endl;
}
}



Q. Write a program to display factorial of a given positive integer.

Q. Write a program to read a positive integer and check whether it is prime or not.

Q. Write a program to display binary equivalent of a given decimal no.

Q. Write a program to find sum of the digits and reverse of an n digit number.

Q. Write a program to display followin pattern.
           1
         212
       32123
     4321234
   543212345

Total Pageviews