Wednesday, December 3, 2014

Add two complex & prime numbers in c++



C++ program to add two complex numbers

#include 
#include 
class complex
{
   public :
      int real, img;
};
 
int main()
{
   complex a, b, c;
 
   cout << "Enter a and b where a + ib is the first complex number.";
   cout << "\na = ";
   cin >> a.real;
   cout << "b = ";
   cin >> a.img;
   cout << "Enter c and d where c + id is the second complex number.";
   cout << "\nc = ";
   cin >> b.real;
   cout << "d = ";
   cin >> b.img;
 
   c.real = a.real + b.real;
   c.img = a.img + b.img;
 
   if ( c.img >= 0 )
      cout << "Sum of two complex numbers = " << c.real << " + " << c.img << "i";
   else
      cout << "Sum of two complex numbers = " << c.real << " " << c.img << "i";
 
   return 0;
}

C++ program for prime numbers

#include
#include
#include 
int main()
{
   int n, status = 1, num = 3, count, c;
 
   cout << "Enter the number of prime numbers to print\n";
   cin >> n;
 
   if ( n >= 1 )
   {
      cout << "First " << n <<" prime numbers are :-" << endl;
      cout << 2 << endl;
   }
 
   for ( count = 2 ; count <=n ;  )
   {
      for ( c = 2 ; c <= (int)sqrt(num) ; c++ )
      {
         if ( num%c == 0 )
         {
            status = 0;
            break;
         }
      }
      if ( status != 0 )
      {
         cout << num << endl;
         count++;
      }
      status = 1;
      num++;
   }         
 
   return 0;
}

c++ program to generate Fibonacci series

#include
#include
 
using namespace std;
 
main()
{
   int n, c, first = 0, second = 1, next;
 
   cout << "Enter the number of terms of Fibonacci series you want" << endl;
   cin >> n;
 
   cout << "First " << n << " terms of Fibonacci series are :- " << endl;
 
   for ( c = 0 ; c < n ; c++ )
   {
      if ( c <= 1 )
         next = c;
      else
      {
         next = first + second;
         first = second;
         second = next;
      }
      cout << next << endl;
   }
 
   return 0;
}

No comments:

Post a Comment