Tuesday, 22 January 2013

to convert binary number to decimal equivalent c++


int main()
{ int n,i,sum,rem;
    sum=0,i=0;
    cout<<"enter the binary number   ";
    cin>>n;
  while(n!=0)
  { if((n%10==0) || (n%10==1))
      {rem=n%10;
      sum=sum+(rem*pow(2,i));
      n=n/10;
      ++i;
      }
      else {cout<<"entered number is not binary";goto a;}
  }
    cout<<"the decimal number is:"<<sum;
    a:
    getch();
}

sum of series 1+x+(x^2)/2!+..............+(x^n)/n! c++ program


#include<iostream>
using namespace std;
#include<conio.h>

int fact(int);
#include<math.h>
int main()
{    double sum=1;
int x,i=1,n;
cout<<"1+x+(x^2)/2!+............+(x^n)/n!\n\n\n\n";
cout<<"enter the value of x    ";
cin>>x;
cout<<"enter th value of n      ";  cin>>n;
while(i<=n)
{
sum=sum+(pow(x,i)/fact (i));
i++;
}
double val=(double)sum;        //typecasting
cout<<"sum is "<<val;
getch();
}

int fact(int j)
{
int fact=1,k=1;
while(k<=j)
{
     fact=fact*k;
     k++;
     }
return fact;
}

How the songs are played randomly in a playlist?? This may be one of the algorithm


#include<iostream>
#include<conio.h>
using namespace std;
class Playlist
{public:
        void random(); /*This function initialises the values from 1 to n and swaps the numbers for odd number count*/
               void swap(int &a,int &b);
};  

int main()
{Playlist dev;
dev.random();
getch();
}

void Playlist::random()
{int n,s,i,p;   //present song number p
cout<<"The number of songs in the playlist  :"; cin>>n;
int a[n],j=1;
cout<<"enter the present song number  : ";  cin>>p; s=p;//s  store 
a[0]=p;
     for(i=++p;i<=n;i++,j++)
     {
     a[j]=i;
     if(j%2!=0)
     swap(a[j-1],a[j]);
     }


   if(j!=n)
   {  for(i=1;i<p;i++,j++)
      {a[j]=i;
      if(j%2!=0)
           swap(a[j-1],a[j]);
     }
    }
 cout<<"\nNew  playlist generated \n";
 for(j=0;j<n;j++)
 cout<<a[j]<<"  ";  
}
void Playlist::swap(int &a,int &b)
{int temp=a;
a=b;
b=temp;
}