Wednesday 31 July 2013

Programs List

  1. Write a C++ program to find the sum of individual digits of a positive integer.
  2. A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and1.Subsequent terms are found by adding the preceding two terms in the sequence.Write a C++program to generate the first n terms of the sequence.
  3. Write a C++ program to generate all the prime numbers between 1 and n ,where n is a value supplied by the user.
  4. Write C++ programs that use both recursive and non-recursive functions
    a) To find the factorial of a given integer.
    b) To find the GCD of two given integers.
    c) To find the nth Fibonacci number.
  5. Write a C++ program that uses a recursive function for solving Towers of Hanoi problem.
  6. Write a C++ program that uses functions
    a) To swap two integers.
    b) To swap two characters.
    c) To swap two reals.
    Note: Use overloaded functions.
  7. Write a C++ program to find both the largest and smallest number in a list of integers.
  8. Write a C++ program to sort a list of numbers in ascending order.
  9. Write a C++ program that uses function templates to solve problems-7&8.
  10. Write a C++ program to sort a list of names in ascending order.
  11. Write a C++ program to implement the matrix ADT using a class. The operations supported by this ADT are:
    a) Reading a matrix.                        c) Addition of two matrices.
    b)Printing a matrix.                         d)Multiplication of two matrices.
  12. Implement the matrix ADT presented in the problem-11 using overloaded operators (<<, >>, +, *) and templates.
  13. Implement the complex number ADT in C++ using a class. The complex ADT is used to represent complex numbers of the form c=a+ib, where a and b are real numbers.
    The operations supported by this ADT are:
          a) Reading a complex number.
          b) Writing a complex number.
          c) Addition of two complex numbers.
          d) Multiplication of two complex numbers.
  14. Write a C++ program that overloads the + operator and relational operators (suitable) to perform the following operations:      a) Concatenation of two strings.      b)Comparison of two strings.
  15. Implement the complex number ADT in C++ using a class. The complex ADT is used to represent complex numbers of the form c=a+ib, where a and b are real numbers.
    The operations supported by this ADT are:
          a) Reading a complex number.
          b) Writing a complex number.
          c) Addition of two complex numbers.
          d) Multiplication of two complex numbers.
    Note:      1. overload << and >> operators in part a) and part b).
          2. overload +, * operators in parts c) and d).
  16. Write a template based C++ program that determines if a particular value occurs in an array of values.
  17. Write a C++ program that uses functions to perform the following operations:
        a) Insert a sub-string into the given main string from a given position.
        b) Delete n characters from a given position in a given string.
  18. Write a C++ program that uses a function to reverse the given character string in place, without any duplication of characters.
  19. Write a C++ program to make the frequency count of letters in a given text.
  20. Write a C++ program to count the lines, words and characters in a given text.
  21. Write a C++ program to determine if the given string is a palindrome or not.
  22. Write a C++ program to make frequency count of words in a given text.
  23. Write a C++ program that displays the position or index in the string S where the string t begins , or –1 if S doesn’t contain t.
  24. 2’s complement of a number is obtained by scanning it from right to left and complementing all the bits after the first appearance of a 1. Thus 2’s complement of 11100 is 00100. Write a C++ program
    to find the 2’s complement of a binary number.
  25. Write a C++ program that counts the number of 1 bits in a given integer.
  26. Write a C++ program to generate Pascal’s triangle.
  27. Write a C++ program to construct of pyramid of numbers.
  28. Write a C++ program to compute the Sine series.
  29. Write a C++ program that converts Roman numeral into an Arabic integer.
  30. Write a C++ program which converts a positive Arabic integer into its
    corresponding Roman Numeral.
  31. Write a C++ program to display the contents of a text file.
  32. Write a C++ program which copies one file to another.
  33. Write a C++ program to that counts the characters, lines and words in the text file.
  34. Write a C++ program to change a specific character in a file.
    Note: Filename , number of the byte in the file to be changed and the new character are specified on the command line.
  35. Write a C++ program to reverse the first n characters in a file.
  36. Write a C++ program that uses a function to delete all duplicate characters in the given string.
  37. Write a C++ program that uses a function to convert a number to a character string.
  38. Write a C++ program that uses a recursive function to find the binary equivalent of a given non- negative integer n.
  39. Write a C++ program to generate prime numbers up to n using Sieve of Eratosthenes method.
  40. Write a C++ program
         a) To write an object to a file.
         b) To read an object from the file.
  41. Write C++ programs that illustrate how the following forms of inheritance are supported:
         a) Single inheritance
         b) Multiple inheritance
         c) Multi level inheritance
         d) Hierarchical inheritance
  42. Write a C++ program that illustrates the order of execution of constructors and destructors when new class is derived from more than one base class.
  43. Write a C++ program that illustrates how run time polymorphism is achieved using virtual functions.
  44. Write a C++ program that illustrates the role of virtual base class in building class hierarchy.
  45. Write a C++ program that illustrates the role of abstract class in building class hierarchy.

Saturday 20 July 2013

39. Write a C++ program to generate prime numbers up to n using Sieve of Eratosthenes method.

 Sieve of Eratosthenes:
Sieve of Eratosthenes

#include<iostream.h>
#define SIZE 100
int main()
{
int i,j,n,a[SIZE];
cout<<"Please enter the max limit to check whether prime or not :"<<endl;
cin>>n;
    for(i=2;i<=n;++i)
         a[i-2]=i;               //Storing the elements into Array Ex: a[5]=7
    for(i=2;i<=n;++i)    //value ie used to check it's multiples in Array
     {
        if(a[i-2]==0)         //value '0' indicates that it is divisible (not prime)
            continue;
        cout<<a[i-2]<<" is prime"<<endl;
        for(j=i+1;j<=n;++j)       //eliminating prime multiples
        {
              if(j%i==0)
              a[j-2]=0;
         }
     }
     return 0;
}

28. Write a C++ program to compute the Sine series.






SIne series:





\begin{align}
\sin x & = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots \\[8pt]
& = \sum_{n=0}^\infty \frac{(-1)^n}{(2n+1)!}x^{2n+1} \\[8pt]
\end{align}


#include<iostream.h>
#define PI 3.1415926
void sin(float f,int n);
long fact(int n)
{
   long f=1;
   for(int i=1;i<=n;++i)
   f =f*i;
   return f;
}

double power(float b,int p)
{
    double k=1;
    for(int i=1;i<=p;++i)
    k=k*b;
    return k;
}

long power(int b,int p)
{
    long k=1;
    for(int i=1;i<=p;++i)
    k=k*b;
    return k;
}

int main()
{
        float x;
        int m ;
        cout<<"\n enter x value ";
        cin>>x;
        cout<<"\n enter n value ";
        cin>>m;
        while(m<0)
        {
             cout<<"\n enter n value ";
             cin>>m;
        }
        x=x*(PI/180);
        sin(x,m);
        return 0;
}

void sin(float x,int num)
{
int n,m;
long a,c;
double b,Result=0;
for(n=0;n<=num;++n)
{  
        a= power(-1,n) ;           //a =(-1)^n
        m=(2*n)+1;                   
        b=power(x,m);             //b=x^((2*n)+1)
        c=fact(m);                    //c=((2*n)+1)!
        Result=Result+((a*b)/c);
}
cout<<"sin value for "<<x<<" is : "<<Result;
}

22. Write a C++ program to make frequency count of words in a given text.


#include<string.h>
#include<iostream>
#include<cstdio>
#define SIZE 50
using namespace std;

struct freq
{
    int n;
    char *s;
};

void display(char text[][SIZE],int num)
{
    for(int i=0;i<=num;++i)
    {
        puts(text[i]);
        //cout<<endl;
    }
}

int main()
{
    char text[SIZE][SIZE],ch;
    int i=0,j=0,k=-1,a;
    bool flg=true;
    freq words[120];
    cout<<"Please enter text trucated by $"<<endl;
    while((ch=getchar())!='$')
      {
        if(ch==' '&&flg==true)
             continue;
        else if(ch==' '||ch=='\n')
        {
            flg=true;
            ++i;
            j=0;
        }
        else
        {
            flg=false;
          text[i][j++]=ch;
          text[i][j]='\0';
        }
      }
      cout<<"given text is :"<<endl;
      display(text,i);
      for(j=0;j<=i;++j)
      {
        if(strcmp(text[j],"#")!=0)
        {
            words[++k].s=text[j];
            words[k].n=1;
            for(a=j+1;a<=i;++a)
            {
                if(strcmp(text[j],text[a])==0)
                {
                    ++words[k].n;
                    strcpy(text[a],"#");
                }
            }
        }
        else
            continue;
      }
      for(j=0;j<=k;++j)
      {
        cout<<words[j].s<<"\t is repeated "<<words[j].n<< "times"<<endl;
      }
    return 0;
}

17. Write a C++ program that uses functions to perform Insert a sub-string into the given main string from a given position and Delete n characters from a given position in a given string.

#include<iostream.h>
#include<string.h>
void del(char s[],int r,int c);
void substring(char s[],char m[],int n)
{
        char ans[100];
        int i,u,t;
        if(n>strlen(s))
        {
          cout<<"Position is Out of the String bound \n Insert failed"<<endl;
          return ;
        }
        for(i=0;i<n;++i)                 //copy the string upto the starting position
        {
                ans[i]=s[i];
        }
        for(i=0;i<strlen(m);++i)   //now copy the sub string into temp array
        {
                t=n+i;
                ans[t]=m[i];
        }
        u=n+strlen(m);
        for(i=n;i<strlen(s);++i)    //finally copy the remaining main string
        {
                ans[u]=s[i];
                ++u;
        }
        ans[strlen(s)+strlen(m)]='\0';  //Adding Null terminator to temp array
        cout<<"New string is :";
        puts(ans);
}

int main()
{
        char s[100],m[50],ch;
        int r,c,i,n;
        cout<<"\nenter a string"<<endl;   //Reading main String
        cin>>s;
        cout<<"enter 'd' for deletion\n\t 'i' for insertion : ";
        cin>>ch;                                            //Reading choice
        switch(ch)
        {
        case 'd':
        cout<<"\nenter the starting position for deletion";
        cin>>r;
        cout<<"\nenter the number of char want to del";
        cin>>c;
        del(s,r,c);                                              //calling del function
        break;
        case 'i':
        cout<<"enter the string m";         //reading Sub string
        cin>>m;
        cout<<"enter the position ";         //Reading starting position
        cin>>n;
        substring(s,m,n);                         //calling sub string function
        break;
        default:
        cout<<"Invalid choice";
        }
        return 0;
}

void del(char s[],int r,int c)
{       char a[100];
        int i,l;
        for(l=0;s[l]!='\0';l++);          //finding the size of main string
        if((r+c)>l)
        cout<<"deletion  is running out of given string\nso deletion impossible";
        else
        {
                for(i=0;i<r;++i)
                a[i]=s[i];
                for(i=(r+c);i<l;++i,++r)
                a[r]=s[i];
                a[l-c]='\0';
        }
        cout<<"string after deletion :"<<a;
}

14. Write a C++ program that overloads the + operator and relational operators (suitable) to perform Concatenation of two strings and Comparison of two strings.

 Need for Class :
                Inorder to achieve the operator overloading.we must have to pass one object implicitly to overloading function.

Concatenation:

                default concatenation doesn't include space between arguments.
            Ex: Rama+Krishna=RamaKrishna      //but not "Rama Krishna"


Comparison:
                returns '0', if both the strings are "equal"
                returns '1' or +ve value, if the first string is greater than second
                returns '-1' or -ve value, if the second string is greater than first


#include<iostream.h>
class String
{
        private:
                char s[100];
        public:
                void input();
                void output();
                int operator<(String);
                void operator+(String);
};
int String::operator<(String a)
{
    int l1,l2,i;
    for(l1=0;s[l1]!='\0';++l1);         //length of first string
    for(l2=0;a.s[l2]!='\0';++l2);     //length of second string
    if(l1>l2)
    {   
        for(i=0;s[i]!='\0';++i)
        {
                if(a.s[i]!='\0'&&s[i]==a.s[i])
                        continue;
                else if(a.s[i]=='\0')     
                        return 1;
                return s[i]-a.s[i];
        }
        if(a.s[i]!='\0')
        return -1;
   }
   if(l1<=l2)
   {  
        for(i=0;a.s[i]!='\0';++i)
        {
                     if(s[i]!='\0'&&s[i]==a.s[i])
                        continue;
                else if(s[i]=='\0')
                        return -1;
                return s[i]-a.s[i];
        }
        if(a.s[i]!='\0')
        return 1;
   }
return 0;
}

void String::operator+(String a)
{
        int i,j;
        for( i=0;s[i]!='\0';++i);             //traversing first string upto the Null
        for( j=0;a.s[j]!='\0';++j,++i)     //Appending second string to first
        {
                s[i]=a.s[j];
        }
}

void String::input()
{
        cout<<"Please enter a string :"<<endl;
        cin>>s;
}

void String::output()
{
        cout<<"the string is :";
        cout<<s<<endl;
}
int main()
{
        String s1,s2;
        int c;
        cout<<"Reading first string .....";
        s1.input();
        cout<<"Reading second string .....";
        s2.input();
          c=s1<s2;
       if(c==0)
       cout<<"\nboth strings are equall";
       else if(c>0)
       cout<<"\nfirst string is larger than second";
       else
       cout<<"\nsecond string is larger than first";
       cout<<"\nAfter concatenation.......";
       s1+s2;
       s1.output();
       return 0;
}

10. Write a C++ program to sort a list of names in ascending order.

Basic Concept:
                   Name is an Array of Characters and to sort an array of names and to store them in a List, we require a Double Dimensional Array of Characters . Where first index used to represents List of Names and the second index used to store List of Characters in Name

#include<iostream.h>
#include<string.h>
#define SIZE 30
void swap(char one[SIZE],char two[SIZE])       //to swap two name (STRINGS)
{
     char tmp[SIZE];
     strcpy(tmp,one);
     strcpy(one,two);
     strcpy(two,tmp);
}

void sort(char array[][SIZE],int num)               //Function to Sort the ARRAY of Names
                                                                            //In Called function first index of array must be empty
{
    for(int i=0;i<num;++i)
    {
         for(int j=i+1;j<num;++j)
         {
              if(strcmp(array[i],array[j])>0)          //if the name is greater than it's subsequent call swap
              {
                   swap(array[i],array[j]);
              }
         }
    }
}

int main()
{
    char names[SIZE][SIZE];
    int n;
    cout<<"Please enter number of names :"<<endl;
    cin>>n;                                                          //Reading number of names
    cout<<"Please enter the names separated By 'White Space' or 'Newline ( ENTER )' : "<<endl;
    for(int i=0;i<n;++i)
    {
         cin>>names[i];                                         //Reading the names into array
    }
    cout<<"Given names before sorting are :"<<endl;
    for(int i=0;i<n;++i)
    {
         cout<<names[i]<<endl;                           //Verifying array list and order of names
    }
    sort(names,n);                                               //calling Sort Function
    cout<<"Given names in ascending order are :"<<endl;
    for(int i=0;i<n;++i)                                      //Displaying Sorted array of names
    {
         cout<<names[i]<<endl;
    }
    return 0;
}

9. Write a C++ program that uses function templates to sort a list in ascending order and to find both the largest and smallest value in a list

#include<iostream.h>
template
<class T>                    //Template declaration
void maxmin(T a[],int n)           //Function Template
{
   int i;
   T temp;
   for(i=0;i<n;i++)
        for(int j=i+1;j<n;j++)
        {
            if(a[i]>a[j])
           {
                temp=a[i];
               a[i]=a[j];
               a[j]=temp;
           }
        }                 
   cout<<"max="<<a[n-1]<<"\n"<<"min="<<a[0]<<"\n";
      /*After sorting an Array starting index consists of Small element and Final index consists of Largest element */
   cout<<"sorted list is: \n";
   for(i=0;i<n;i++)
       cout<<a[i]<<" ";
}

int main()
{
   int a[50],i,ch,n;
   double d[50];
   float f[50];
   char c[50];
   cout<<"1.integer"<<endl;
   cout<<"2.characters"<<endl;
   cout<<" 3.float numbers"<<endl;
   cout<<" 4.double numbers"<<endl;
   cout<<"enter corresponding Index Example : enter '1' for integers"<<endl;

   cin>>ch;                   //Reading Choice from User
   cout<<"enter the n value\n";
   cin>>n;                     //Number of elements is independent of DATA TYPE
   switch(ch)
  {
      case 1:                   //for operations over Integer Array
                 cout<<"enter integers\n";
                 for(i=0;i<n;i++)
                     cin>>a[i];
                 maxmin(a,n);
            break; 

      case 2:                    //for operations over Character Array
                 cout<<"enter characters\n";
                 for(i=0;i<n;i++)
                      cin>>c[i];
                 maxmin(c,n);
            break;
 

      case 3:                    //for operations over Floating Array
                 cout<<"enter floatnumbers\n";
                 for(i=0;i<n;i++)
                      cin>>f[i];
                 maxmin(f,n);
            break;
 

      case 4:                    //for operations over Double
                  cout<<"enter doublenumbers\n";
                  for(i=0;i<n;i++)
                       cin>>d[i];
                  maxmin(d,n);
           break;
  

     default:
                   cout<<"Invalid choice entered...";
   }
   return 0; }

Friday 19 July 2013

08. Write a C++ program to sort a list of numbers in ascending order.

Description about sorting technique: (Bubble Sort)
          Compare each element with remaining elements in the list
          During comparison if the preceding element is small then we will swap
          So that the Biggest element will reach to higher bound of array
          Repeat this process excluding higher most boundary

#include<iostream>
#define SIZE 50      /*Macro used to modify the size of array Based on requirement 

Mechanism of Sorting

                                 No need to traverse or Disturb the program */

using namespace
std;
void
sort(int a[SIZE],int n)
{
    int i,pass,t;   
    for(pass=1;pass<n;++pass)
    {
        for(i=0;i<n-pass;++i)
        {
            if(a[i]>a[i+1])        //swap the two numbers
            {
                t=a[i];
                a[i]=a[i+1];
                a[i+1]=t;
            }
        }
    }
}

int main()
{
    int a[SIZE],n,i;
    cout<<"enter n value";
    cin>>n;
    cout<<"\nenter array values";
    for(i=0;i<n;++i)
        cin>>a[i];           
    cout<<"\narray before sorting : \n";
    for(i=0;i<n;++i)
        cout<<"\n"<<a[i];
    sort(a,n);                 //Array itself is the address of the storage location ( no need of referencing )
    cout<<"\narray after sorting: \n";
    for(i=0;i<n;++i)
        cout<<"\n"<<a[i];
    return 0;
}

07. Write a C++ program to find both the largest and smallest number in a list of integers.

#include<iostream>
using namespace std;

void minmax(int a[],int n,int &min,int &max)    //Call by Reference mechanism to get back the modified result
{
int i;
for(i=0;i<n;++i)       //we are scanning each and every element of array to measure Min and Max
{
if(a[i]<min)             //any element less than min is saved as min (over writing old with new )
         min=a[i];
else if(a[i]>max)     //any element greater than max will be max
         max=a[i];
}
}

int main()
{
    int a[50];
    int n,i,min=a[0],max=a[0];    //Assuming that the first element is Min and Max for comparison
    cout<<"enter the number of integers in list";
    cin>>n;                                //Number of element we want to store in array.......
    cout<<"\nenter the values in list";
    for(i=0;i<n;++i)
        cin>>a[i];                          //Reading each element into array
    cout<<"\ngiven values in list";
    for(i=0;i<n;++i)
        cout<<"\n"<<a[i];               //Displaying the element in the Array (Verification)

    minmax(a,n,min,max);             //Function that evaluate Min and Max values
    cout<<"\nminimum value is : "<<min<<"\nmaximum value is : "<<max;
    return 0;
}

06. Write a C++ program that uses overloaded functions to swap

#include<iostream>
using namespace std;
void swap(int &,int&);                           /*we are passing the address of the variables to functions
                                                             so that the modified values will take effect on the main method*/
void swap(char&,char&);                     //else the a,b values seems never swap(a=a; b=b)
void swap(float&,float&);
int main()
{
    int ch;
cout<<"\nenter '1' to swap two integers ";
cout<<"\nenter '2' to swap two charecters";
cout<<"\nenter '3' to swap two real values";
ch:                                                      //label "ch" I have used for the successful execution of the program
cin>>ch;                                             //variable to read the choice from user
switch(ch)
{
case 1:
    int a,b;
    cout<<"enter a,b values";
    cin>>a>>b;
    cout<<"a,b values before swaping: "<<a<<" , "<<b<<endl;
    swap(a,b);
    cout<<"a,b values after swaping are : "<<a<<" , "<<b<<endl;
    break;                               //Break have used to skip the execution of remaining cases
case 2:
    char c,d;
    cout<<"enter a,b values";
    cin>>c>>d;
    cout<<"a,b values before swaping: "<<c<<" , "<<d<<endl;
    swap(c,d);
    cout<<"a,b values after swaping are : "<<c<<" , "<<d<<endl;
    break;
case 3:
    float e,f;
    cout<<"enter a,b values";
    cin>>e>>f;
    cout<<"a,b values before swaping: "<<e<<" , "<<f<<endl;
    swap(e,f);
    cout<<"a,b values after swaping are : "<<e<<" , "<<f<<endl;
    break;

default:

    cout<<"enter a valid choice: ";
    goto ch;                                  /*be cautious while using labels. It will transfer control          
                                                    Dynamically(excluding sequence or the order of execution)*/
}

return 0;
}

void swap(int &a,int &b)           /*Function overloading take place by having same name 
                                                   with same number of parameters but different data type*/
{
int t;
t=a;
a=b;
b=t;
}

void swap(float &a,float &b)
{
float t;
t=a;
a=b;
b=t;
}

void swap(char &a,char &b)
{
char t;
t=a;
a=b;
b=t;
}

05. Write a C++ program that uses a recursive function for solving Towers of Hanoi problem.

What is Towers of Hanoi Problem:
             Towers of Hanoi Problem is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  1. Only one disk may be moved at a time.
  2. Each move consists of taking the disk from one of the stacks and placing it on top of another stack.
  3. No disk may be placed on top of a smaller disk. (-Source from WIKIPEDIA)

                                                             A               C               B
Let 'A', 'B', 'C' are three rods and; 'n' is the number of disks on the starting rod,
         The minimum number of moves required to solve a Tower of Hanoi puzzle is count = 2n - 1.

Solution
#include<iostream>
int count1;                            //Global variables are by default initialized to '0' for int type
void hanoi(char A,char B, char C, int n)
{
    if(n>1)
    {
        hanoi(A,C,B,n-1);
        hanoi(A,B,C,1);
        hanoi(C,B,A,n-1);
    }
    else
    {
    cout<<"\n disc moved from '"<<A<<"' to '"<<B";
    count1++;
    }
}
int main()
{
    int n;
    cout<<"enter stack height :";
    cin>>n;
    hanoi('A','B','C',n);                 //we assume that 'A' is the starting rod consisting of rod of disks
    cout<<"\n number of changes done are : "<<count1;
    return 0;
}

04. Write C++ programs to find Fibonacci number in both recursive and non-recursive functions

((((((Don't copy and paste it. Please Practice . These programs are provided to create interest in Students))))))))

/* Fibonacci series is Staring with 0, 1 remaining series is obtained by adding previous two numbers */
/*in general fibonacci series starts from 0, but they have given instruction as it is starting with 1, 1
so I have followed the instructions from Authority */

#include<iostream>
using namespace std;

void fibnr(int );

int fibr(int n)
{
        if(n<=2)                          //logic similar to factorial in case of recursion
                 return 1;
        else
                 return (fibr(n-1))+(fibr(n-2));
}
int main()
{
        int n,fibo;
        char ch;
        cout<<"\nenter n value";
        cin>>n;
        while(n<1)                     //validating n value to strictly +ve integer
        {
                cout<<"\nPlease enter a valid +ve integer"<<endl;
                cin>>n;
        }
        cout<<"Enter 'r' to find using recursive method"<<endl;
        cout<<"Enter 'n' to find using Non- Recursive method"<<endl;
        cout<<"Please enter your choice :";
        cin>>ch;
        switch(ch)
        {
        case 'n':
                fibnr(n);
                break;
        case 'r':
                fibo=fibr(n);
                cout<<"\n"<<n<<"th fibonacci number is : "<<fibo;
                break;
        default:
                cout<<"Invalid choice"<<endl;
        }
        return 0;
}
void fibnr(int n)
{
        int fib1=0,fib2=1,fibo,i;         //Actual fibonacci starts with 0, 1 .though I've neglected '0'.
        for(i=0;i<n;++i)
        {
        fibo=fib1+fib2;
        fib1=fib2;
        fib2=fibo;
        }
        cout<<"\n"<<n<<"th fibonacci number is :"<<fib1;
}

04. Write C++ programsto find GCD by using recursive and non-recursive functions (b). To find the GCD of two given integers.

((((((Don't copy and paste it. Please Practice These programs are provided to create interest in Students))))))))


#include<iostream>  
          //This is actual program executed in gcc compilers like Putty
#include<stdlib.h>              //similar to previous factorial program with switch case without labels
using namespace std;
int gcdr(int,int);                  //Recursive method
int gcdnr(int,int);               //Non-Recursive method
int main()
{
        int m,n,gcd;
        char ch;
        cout<<"enter 'm', 'n' value to find Greatest Common Divisor :: ";
        cin>>m>>n;
        while(n<0||m<0)                 //Validating m, n values for GCD
        {
                cout<<"Please enter valid(only positive) m, n values"<<endl;
                cin>>m>>n;
        }
        if(m==0&&n==0)
         {
               cout<<"GCD not possible. \n terminating program"<<endl;
               exit(0);
         }
        cout<<"\nenter 'r' to implement Recursive method"<<endl;
        cout<<"\nenter 'n' to implement Non-Recursive method"<<endl;
        cin>>ch    ;
        switch(ch)
        {
        case 'r':
                gcd=gcdr(m,n);
                cout<<"Executing Recursive Method"<<endl;
                cout<<"\nGCD of "<<m<<","<<n<<" is: "<<gcd;
                break;
        case 'n':
                gcd=gcdnr(m,n);
                cout<<"\nGCD of "<<m<<","<<n<<" is: "<<gcd;
                break;
        default:
                cout<<"Invalid choice"<<endl;
                cout<<"Terminating the program"<<end;
        }
        return 0;
}
int gcdnr(int m,int n)
{
       int r;
       cout<<"Executing Non-Recursive Method"<<endl;
       if(m==0||n==0)                  //GCD of Any +ve number with 0 is itself the number
       {
           return m+n;
        }
        while(n|=0)
        {
        r=m%n;                              //logic for GCD is divide greater no: by smaller and save remainder
                                                  //divide the smaller value by the above remainder value
                                                  //repeat this process until successful division (one divides another)
        m=n;
        n=r;
        }
        return m;
}
int gcdr(int m,int n)
{
        if(n==0)
                return m;
       if(m==0||n==0)
       {           return m+n;
        }
        else
                return gcdr(n,m%n);
}

04 . Write C++ programs to find factorial by using recursive and non-recursive functions

a ).  To find the factorial of a given integer using Recursion .



#include<iostream.h>   //If you are using gcc compilers like PUTTY, DEV C++, ECLIPSE C++
                                         //kindly use #include<iostream>
                                         //There is no #include<conio.h> header file in gcc
#include<conio.h>           //using namespace std;( recommended if you are using gcc )
int factr(int);                    //finds factorial Using Recursion
int factnr(int);                  //to find factorial Using Non-recursion

int main()
{

    int result,n,res;
    char ch;
    clrscr();                        //gcc does't include this function (it uses conio.h Header)
    cout<<"enter 'n' value to find factorial : ";
    fact:                               //"fact:" is a label to correct -ve values from input ( variable - 'n' ).
                                          //I have implemented this by using goto control structure
    cin>>n;

    if(n>=0)
    {
        cout<<"\nenter 'r' to solve by recursion";
        cout<<"\nenter 'n' to solve by non recursion"<<endl;
        ch:                            //"ch: " is a label to correct your wrong choice of selection (variable- 'ch')
        cin>>ch    ;
    if(ch=='r')
        {
            cout<<"\nRecusive Method is selected for execution"<<endl;
            k=factr(n);
            cout<<"\nfactorial of "<<n<<" is:"<<k<<endl;
        }
    else if(ch=='n')
        {
        k=factnr(n);
        cout<<"\nfactorial of "<<n<<" is:"<<k<<endl;
        }
        else
  
      {
        cout<<"\nmake a valid choice";
        goto ch;                           //CAUTIOUS while using goto in your program                             
                                               //Same result can be achieved by SWITCH contol structure
        }
    }
    else
        {
        cout<<"enter a valid positive integer";
        goto fact;
        }
        getch();                             //gcc does't include this function (it uses conio.h Header)

     return 0;
}
int factnr(int n)                        //Non - Recursive function for factorial
{
  
    int f=1,i;
    cout<<"\nNon recusive Method is selected for execution"<<endl;
    for(i=1;i<=n;++i)
    f=f*i;
    return f;
}
int factr(int n)                         
//Recursive function for factorial                         
{
    if(n==0)
    return 1;
    else
    return n*factr(n-1);
}

output:
enter 'n' value to find factorial -4
enter a valid positive integer-3
enter a valid positive integer3

enter 'r' to solve by recursion
enter 'n' to solve by non recursion
f

make a valid choice
s

make a valid choice
r

Recusive Method is selected for executionfactorial of 3 is:6
//Please write your opinion and comments below

Thursday 11 July 2013

03. Write a program to generate all the Prime numbers between '2' and 'n'

#include<iostream.h>

void prime(int n); 
                 //function declaration

int main()
{
    int n;                                //variable declaration
    cout<<"Please enter a valid 'n' value"<<endl;
    cin>>n;                            //reading 'n' value
    while(n<1)                       //validating 'n' value
    {
        cout<<"You have entered a invalid Number"<<endl;
        cout<<"Please enter a valid Integer"<<endl;
        cin>>n;
    }
    cout<<"serice of prime numbers upto 'n' is :"<<endl;
    prime(n);                          //calling function
    return 0;                           //successful termination
}

/* method 1...............*/

void prime(int n)  
                  //called function
{
    int elem;                                                //to check each element upto 'n' is whether prime or not
    int fact;                                                  //to count the number of factors for each 'elem'
    int i;                                                       //holds the factors of each 'elem' on run time
    for(elem=2;elem<=n;++elem)                 //the possibility of prime number is >= '2'
    {
        fact=0;                                              //to initialize the number of factors for each 'elem'
        for(i=1;i<=elem;++i)                         //to check the factors of each 'elem'
        {
            if(elem%i==0)                              //factor divides the element without remainder
            fact++;                                        //counts the number of factors for each 'elem'
        }
        if(fact==2)                                       //prime number has only '2' factors (1 and 'itself')
        cout<<"\n '"<<elem<<"' is a prime"; //printing the prime number
    }
}

/* Method 2............*/

void prime(int n)
{
        int elem,i;
        bool flag=;
        for(elem=2;elem<=n;++elem)
        {
                i=2;
                flag=false;
                while(!flag&&i<=elem/2)
                {
                        if(elem%i==0)
                                flag=true;
                        ++i;
                }
                if(flag==false)
                cout<<"\n '"<<elem<<"' is a prime";
        }
}

02. Write a program to generate first 'n' terms of sequence using non-recursive function

#include<iostream.h>

void fibonacci(int n);                         //function declaration
int main()

{
    int n;                                             //variable declaration
    cout<<"Please enter a valid 'n' value"<<endl;
    cin>>n;                                        //reading 'n' value
    while(n<1)                                   //validating 'n' value
    {
        cout<<"You have entered a invalid Number"<<endl;
        cout<<"Please enter a valid Integer"<<endl;
        cin>>n;
    }
    cout<<"Fibonacci serice upto 'n'th term is :"<<endl;
    fibonacci(n);                                 //calling function
    return 0;
}

void fibonacci(int n)                          //called function
{
    int f1=0,f2=1,fib,i;                     //variable declaration and Initialization
    for(i=1;i<=n;++i)
    {
        cout<<f1<<endl;                     //to print the series
        fib=f1+f2;
        f1=f2;
        f2=fib;

    }
}

01. Write a CPP program to find the sum of Individual digits of a Positive Integer


#include<iostream.h>

int sumofdigits(int);  
          //function declaration

int main()
{
    int n,sod;
    cout<<"Please enter a valid +ve Integer"<<endl;
    cin>>n;                          //reading Integer
    while(n<0)                     //validating Integer
    {
        cout<<"You have entered a -ve Number"<<endl;
        cout<<"Please enter a valid +ve Integer"<<endl;
        cin>>n;
    }
    sod=sumofdigits(n);        //function calling
    cout<<"Sum of digits of given Integer is :"<<sod;
    return 0;
}

int sumofdigits(int n)            //called function
{
    int sod=0;                       //initializing variable
    while(n!=0)
    {
        sod=sod+n%10;
        n=n/10;

    }
    return sod;
}


How to use Putty for C++ programs(( Only for students ))

PuTTY: the Telnet and SSH client itself
            An SSH client is a software program which uses the secure shell protocol to connect to a remote computer.

            The programs written in putty doesn't store in your System , but stored in external server through internet. So that There is no data lost due to system failure. PuTTY provides security to data access.

How to Download PuTTY

             PuTTY is a freeware . you can easily download from internet.

             Click on this link to directly download PuTTY for any Windows 32 bit Operating System
How to Start with PuTTY
             After downloading putty we can directly use that. No need of Installation and Highly Portable.

            
In this application interface we can customize
it's appearance and a lot can be done.


Before we want to use, first we have to connect
to the server using IP address and SSH protocol
(recommended).

we can use any protocol to access
server but internet connection was must to connect


then click open to use it.


        
then it opens a command prompt asking for log in details in case of no network failure.


Then enter your login details
most of institutions offer your login name as same as your ID number

it prompts for password to authenticate your details and allows you to access server based on accessing permissions


Basic and mandatory commands necessary to use (PuTTY) shell script :

Syntax:            vi <file name along with extension>
Ex:                    vi<space>test.cpp
Functionality:   It is used to open a file. if it was not available or not created before.
                          it creates the file and opens it immediately after pressing "enter" key.

Syntax:            ll
Ex:                    ll
Functionality:   It is used to display the list of files and directories available in the present directory


Syntax:  
          pwd
Ex:                    pwd
Functionality:   To check our present working directory (pwd) or location.


Syntax:
           passwd
Ex:                    passwd
Functionality:   To change the login password of the current user .


Syntax:            mkdir <Directory name>
Ex:                    mkdir<space>cpp
Functionality:  
To create a directory (folder) in the present directory or location.


Syntax:           
cd <Directory name>
Ex:                    cd<space>cpp
Functionality: 
  To open an existing directory. if not exists it will display error


Syntax:
           cp <source file name> <destination file name>
Ex:                    cp<space>test.cpp<space>demo.cpp
Functionality:   It is used to copy the content of source file to destination file
                          If destination file doesn't exist it creates the file and copies the content.


Syntax:  
          rm <file name>
Ex:                    rm<space>test.cpp
Functionality:  It is used to remove the file from file System.


Syntax:
           cd ..
Ex:                    cd<space>..
Functionality:   To come out from the current directory i.e.: to move up from current directory


Syntax:    
        cd /
Ex:                    cd /
Functionality:   To move user to the root directory.

How to Access (Read, Write, Save and Close) the file System

          
when we open a file in VI editor it opens in VI command mode. so that it treats each letter as command

Press 'a', 'i', 'o to open in append mode(though they have different meaning to compiler)

press "Esc" button to leave the append mode and returns to VI command mode (Not returns to shell)
press
         ":wq" or ":x" to save the modifications on the file and returns to shell
         ":q" to close the file without saving the modifications and returns to shell

                      to copy the content select the source using mouse by holding left key
   to paste the content right click on the editor. it appends the buffer (Copied data) to file at the cursor.