Showing posts with label Cplusplus. Show all posts
Showing posts with label Cplusplus. Show all posts

Friday, 22 May 2015

Program In C++ to Print Fibonacci Numbers

print Fibonacci numbers in c++
Problem: Write a program in c++ that will print the fibonacci numbers to a limit.

Description: This is another best program in c++ which prints the fibonacci numbers. You have to enter the number till where you want to print the series.



#include<iostream>
#include<cmath>

using namespace std;

int main()
{
   unsigned long a=0,b=1,num;
   unsigned long c=0;
   cout << "Enter the number till where you want fibonacci series...... : ";
   cin >> num;
   cout << endl;
   cout << a << ", ";
   while (c<=num)
   {
      cout << b << ", ";
      c=a+b;
      a=b;  
      b=c;  
   }
   cout << endl << endl;
   system("pause");
   return 0;
}

Write a Program In C++ That Will Convert Roman Number Into Decimal Number

convert roman numbers into decimal numbers
Problem: Write a c++ program that will convert roman numbers into its equivalent decimal numbers.

This program takes a roman number as input and converts into decimal number. please make sure to keep the caps lock on. Run this program in devc++


#include <iostream>
#include <string>

using namespace std;
class RomanNumber
{
private:
        string romanNumber;
        int sum; 

public:

  RomanNumber( string input)
                {
                      romanNumber = input;
                }
  int convert()
                {
                      int length = romanNumber.length();

                      int previous = 0;
                      bool error = false;
                      int nIndex = 0;
                      sum = 0;
                      while( (error == false) && (nIndex < length) )
               {
              switch(romanNumber[nIndex])
              {
                    case 'M':
                             sum += 1000;
                   if(previous < 1000)
                   {
                sum -= 2 * previous;
                   }
                   previous = 1000;
                   break;
                  case 'D':
                   sum += 500;
                   if(previous < 500)
                   {
                 sum -= 2 * previous;
                   }
                   previous = 500;
                   break;
                  case 'C':
                   sum += 100;
                   if(previous < 100)
                   {
                  sum -= 2 * previous;
                   }
                   previous = 100;
                   break;
                 case 'L':
                   sum += 50;
                   if(previous < 50)
                   {
                 sum -= 2 * previous;
                   }
                   previous = 50;
                   break;
                 case 'X':
                   sum += 10;
                   if(previous < 10)
                   {
                   sum -= 2 * previous;
                   }
                   previous = 10;
                   break;
                 case 'V':
                   sum += 5;
                   if(previous < 5)
                   {
                 sum -= 2 * previous;
                   }
                          previous = 5;
                   break;
                 case 'I':
                   sum += 1;
                   if(previous < 1)
                   {
                  sum -= 2 * previous;
                   }
                   previous = 1;
                   break;
                       default:
                            cout << romanNumber[nIndex] << " is not a Roman Numeral!" << endl;
                            error = true;
                            sum = 0;
                 } // switch
                               nIndex++;
                      } // while
                      return sum;
         } 
};

int main()
{
       system("color 1F");
       string myInput;
       cout<<"\n\n\t\t....ROMAN NUMBER TO DECIMAL CONVERTER....\n\n";
       cout<<"\n\n\tEnter your input in Roman Number(Plz Keep Caps Lock On): ";
       cin>>myInput;

       RomanNumber myRomanNumber(myInput);

       int value=myRomanNumber.convert();

       cout << "\n\n\t\tRoman Number " << myInput << " is equals to Decimal " << value <<endl<<endl;

       system("pause");
       return 0; 
}

Wednesday, 20 May 2015

How To Implement Queue In C++ Full Code

Implement Queue In C++
This code is an example of queue in C++. As queue works on first come first out(FIFO) basis. Inserting an element into queue is known as enqueue and deleting an element is known as dequeue. Copy and paste the below code into your DevC++ editor and run the program.





#include<iostream>

using namespace std;

const int LIMIT=20;

class Queue

{

     int contents[LIMIT];

     int head,tail;

     bool becomeFull;

 public:

     Queue();

     bool isFull();

     bool isEmpty();

     void Enqueue(int x);    // Insert data... 

     int Dequeue();          // delete/remove data...

};

/*****************************************/

int main()

{

  Queue q1;

  q1.Enqueue(2); 

  q1.Enqueue(6); 

  q1.Enqueue(9);

  cout<<q1.Dequeue()<<endl; 

  cout<<q1.Dequeue()<<endl;

  cout<<q1.Dequeue()<<endl;

  system("pause");   

}



/*****************************************/

/*****************************************/

Queue::Queue()

{

    head=0;

    tail=0;

    becomeFull=false;             

}

/*****************************************/

bool Queue::isFull()

{

  if(tail==LIMIT)

    return (true);

  else

    return false;          

}

/*****************************************/

bool Queue::isEmpty()

{

   if(head==tail)

      return true;

   else

    return false;              

}

/*****************************************/

void Queue::Enqueue(int x)

{

    if(!isFull())

    {

       contents[tail]=x;

       tail++;

       becomeFull=true;

       if(tail==LIMIT)

          tail=0;            

    }           

}

/*****************************************/

int Queue::Dequeue()

{

   if(!isEmpty())

   {

      int x=contents[head];

      //contents[head]=0;

      head++;

      becomeFull=false;

      if(head==LIMIT)

         head=0;

      return x;            

   }            

}

/*****************************************/

/*****************************************/

How To Create a Calculator Using Switch Statement

Create a calculator in C++
This is a simple c++ program to show how switch statement is used and how can we make a calculator using switch. This simple calculator can work with only four operations i.e addition,subtraction,multiplication and division.
select any one operation and enter the two values to calculate.



#include<iostream>
#include<math.h>

using namespace std;
int main ()
{
    int choice;
    float a,b,c;

    cout<<"\t\t\t**SELECT CHOICE** \n '1' for addition\n '2' for subtraction\n '3' for multiplication\n '4' for division" <<endl<<endl<<endl;
    cout<<"Enter your Choice : ";
    cin>>choice;
    cout<<"\n\nEnter first number : ";
    cin>>a;
    cout<<"Enter second number :";
    cin>>b;
    cout<<endl<<endl;
  switch (choice)

   {
            case 1:
                 c=a+b;
                 cout<<"Addition is : "<<c <<endl;
                 break;
            case 2:
                 c=a-b;
                 cout<<"Subtraction is : "<<c <<endl;
                 break;
            case 3:
                 c=a*b;
                 cout<<"Multiplication is : "<<c <<endl;
                 break;
            case 4:
                 if(b==0)
                 cout<<"Undefined";
                 else
                 {
                 c=a/b;
                 cout<<"Division is : "<<c <<endl<<endl;
                 }
                 break;
                 }
            system("pause");
            return 0;
      }

Tuesday, 19 May 2015

Program Using Pointers In C++

pointers in c++
#include<iostream>
using namespace std;

int main ()

             int *x;
             int *p,*q;
             int c=100,a;
             x=&c;

             p=x+2;
             q=x-2;
            a=p-q;
            cout << "The address of x : " << x << endl;
            cout << "The address of p after incrementing x by 2 : " << p << endl;
            cout << "The address of q after derementing  x by 2 : " << q << endl; 
            cout << " The no of elements between p and q :" << a << endl;

            system("pause");
            return(0);

}

Break Array Into Two Arrays Using C++

divide array in c++
Problem Description: Write a code in C++ that will break the array into two arrays.

In this program we created an array of size 10 by giving values and break this array into two arrays of size 5.



#include<iostream>
using namespace std;
int main()
{int n=10;
    int arr[]={2,4,6,7,4,3,9,0,1,5};
    int arr1[n/2],arr2[n/2];
    cout<<"Original Array of size 10 \n\n";
    for(int i=0;i<n;i++)
        cout<<arr[i]<<"\t";    
    cout<<endl<<endl;
    for(int i=0,j=(n/2);i<n/2;i++,j++)
    {
       arr1[i]=arr[i];
       arr2[i]=arr[j];  
    }
    cout<<"\tnew Array1 of size 5 \n\n";
    for(int i=0;i<n/2;i++)
        cout<<arr1[i]<<"\t";
     cout<<endl<<endl;
     cout<<"\tnew Array2 of size 5 \n\n";
     for(int i=0;i<n/2;i++)
        cout<<arr2[i]<<"\t";    
     
     cout<<endl<<endl;
     system("pause");    
}

Array Program To Add and Subtract Two Matrices

Add Two Matrices in C++
Problem Description: Write a program in c++ that will add and subtract two matrices.

This program adds two matrices by using arrays in c++. The program will ask you to enter the number of rows and columns and then to enter the value of each row and column. After that this will add or subtract by your choice.

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

int main()
{
    int rows,cols;
    int choice;
string ch;    
    do{
    cout<<"Enter number of rows ::)) "; cin>>rows;
    cout<<"Enter number of columns :: )) "; cin>>cols;
    
    int matrix1[rows][cols],matrix2[rows][cols],matrixsum[rows][cols],matrixsub[rows][cols],i,j;    
    cout<<"\t\t***YOU HAVE TO ENTER THE DATA OF 2 MATRICES ***\n\n";
    cout<<"\tEnter matrix 1 data \n";
    for(i=0;i<rows;i++)
    {
     for(j=0;j<cols;j++)
     {
      // cout<<"[ "<<i+1<<"]"<<"["<<j+1"]=";
       cout<<"Enter row "<<i+1<<"column "<<j+1<<" =)) ";
       cin>>matrix1[i][j];
       }
       }
     cout<<"\tEnter matrix 2 data \n";
     for(i=0;i<rows;i++)
    {
     for(j=0;j<cols;j++)
     {
      // cout<<"[ "<<i+1<<"]"<<"["<<j+1"]=";
       cout<<"Enter row "<<i+1<<"column "<<j+1<<" =)) ";
       cin>>matrix2[i][j];
       }
       } 
    do{
    cout<<"\n\t\t\t*** CHOICE ***\n";
    cout<<"\tSelect 1 for (2matrices) addition \n\t"
    <<"Select 2 for (2 matrices) subtraction\n "; 
    cout<<"\tEnter your choice ::))"; cin>>choice;
    switch(choice)
    {  
      case 1:
       for(i=0;i<rows;i++)
       {
         for(j=0;j<cols;j++)
         {
            matrixsum[i][j]=matrix1[i][j]+matrix2[i][j];
            cout<<matrixsum[i][j]<<"\t";
         }
            cout<<"\n";
         }
         break;
       case 2:
          for(i=0;i<rows;i++)
           {
            for(j=0;j<cols;j++)
            {
            matrixsub[i][j]=matrix1[i][j]-matrix2[i][j];
            
            cout<<matrixsub[i][j]<<"\t";
            }
            cout<<"\n";
            }
          
           break;
           }
            cout<<"DO U WANT TO DO NEXT OPERATION"; cin>>ch;
       }while(!(ch=="no"||ch=="NO"));
       
            cout<<"DO U WANT TO DO AN OTHER OPERATION ::))) "; cin>>ch;
            }
            while(!(ch=="no"||ch=="NO"));
            system("cls");
    system("pause");
    return 0;
    }

Tuesday, 5 May 2015

C++ Program to Print Equilateral Star Triangle

Print Equilateral Star Triangle in C++


Problem Description: This program prints equilateral Star triangle using for loops in C++.


Note: Run this program using DevC++




#include<iostream>

using namespace std;





int main()

{

     int lines,space,stars;

     for(lines=20;lines>=1;lines--)

     {

     for(space=20-lines;space>=0;space--)

     {

     cout << " " ;                                  

     }           

     for(stars=1;stars<=(2*lines-1);stars++)

     {

     cout << "*" ;                                      

     }                 

     cout << endl;

     }

    

     system("pause");

     return 0;   

}



Write a C++ Code To Print Diamond Shape

Print diamond in c++
Problem Description: This program will simply print out diamond shape using C++.If you like to print a kite shape please remove the comments and run the program it will print a kite.

Note: Run this program using DevC++




#include<iostream>

using namespace std;





int main()

{

     int lines,space,stars;

     for(lines=1;lines<=10;lines++)

     {

     for(space=10-lines;space>=0;space--)

     {

     cout << " " ;                                 

     }           

     for(stars=1;stars<=(2*lines-1);stars++)

     {

     cout << "*" ;                                     

     }

     cout << endl;

     }                 

     for(lines=9;lines>=1;lines--)

     {

     for(space=10-lines;space>=0;space--)

     {

     cout << " " ;                                 

     }           

     for(stars=1;stars<=(2*lines-1);stars++)

     {

     cout << "*" ;                                     

     }       

     cout << endl;

     }

  /*   // Till Here it is Diamond Code.........After this the code is for a kite

     for(int i=1;i<=3;i++)

     {

     for(int j=1;j<=10;j++)

     {

     cout << " ";       

     }

     for(int k=1;k<=1;k++)

     {

     cout << "*";       

     }

     cout << endl;

     }*/

     system("pause");

     return 0;   

}


Write a Program In C Plus Plus For Currency Converter

Currency Converter in C++
Problem Description: Write a program in c++ which will convert the pound into its equivalent decimal number and convert it into euro. The program will ask you to enter pounds, shillings and pence and then it will convert in into decimal and Euro.




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


int main()
{
   int pound,shilling,pence;
   char ch;
   do
   {
   cout << "Enter the amounts of pounds,shillings and pence" << endl << endl;
   cout << "Pound(s) : ";
   cin >> pound;
   cout << "Shilling(s) : ";
   cin >> shilling;
   cout << "Pence : ";
   cin >> pence;
   cout << endl;
   
   float tpenny = (static_cast<float>(shilling * 12) + pence)/240;
   float final = (pound) + tpenny;
   
   cout << "In Decimal Pounds" <<'\n'<<'\x9c'<<pound<<"."<<shilling<<"."<<pence<<" = "<<'\x9c'<<final << endl << endl;
   cout << "To end the Program Press 'X or x' and To continue Press any 'Y or y' " << endl;
   cin >> ch;
   }  
   while(ch!='x');
   
   
   system("pause");
   return 0;
   }

Tuesday, 28 April 2015

Count the occurence of each word from given sentence string using LinkList & OOP concepts.


Problem Description:
Given a string sentence, separate the each word from given string and count the occurrence of each word in string sentence.

P.S. The program coded using Link List data structure & OOP concepts.

The Sample Input & Output of program:
Input: dil dil pakistan jaan jaan pakistan dil dil pakistan jaan jaan pakistan

Output:
      dil: 4
      pakistan: 4
      jaan: 4  

Code:
#include 
#include

using namespace std;

class node{
 public:
  node* next;
  string data;
 public:
  node(string str){
   data=str;
   next=NULL;
  }
};class list{
 node* head;
 public:
 list()
 {
  head=NULL;
 }
 void insert(string str)
 {
  if(head==NULL)
   head=new node(str);
  else
  {
   node* temp=new node(str);
   temp->next=head;
   head=temp;
  }
 }
 void print(){
  node* temp=head;
  while(temp!=NULL)
  {
   cout<data<next;
  }
 }
 bool exist(string str)
 {
  node* temp=head;
  while(temp!=NULL)
  {
   if(temp->data==str) return true;
   temp=temp->next;
  }
  return false;
 }
 int count(string str)
 {
  int counter=0;
  node* temp=head;
  while(temp!=NULL)
  {
   if(temp->data==str) counter++;
   temp=temp->next;
  }
  return counter;
 }
};
int main()
{
 string str="dil dil pakistan jaan jaan pakistan dil dil pakistan jaan jaan pakistan";
 list visited;
 string array[10];
 int i=0;
 string temp;
 list l;
 stringstream ssin(str);
 while (ssin.good() && i < str.length()){
  ssin>>temp;
  l.insert(temp);
  ++i;
 };
 //string temp2;
 stringstream ssin2(str);
 i=0;
 while (ssin2.good() && i < str.length()){
  ssin2>>temp;
  if(!visited.exist(temp))
   cout<

C++ Flip a Coin Problem: Program to Flip a Coin (until you get 3 "heads" in a row)

Flip a coin


The same problem is also called "The consecutive heads problem"

Problem Overview: Write a program that simulates flipping a coin repeatedly and continues until three consecutive heads are tossed.
At that point, your program should display the total number of coin flips that were made.

The following is one possible sample run of the program:
Heads..
Tails..
Tails..
Heads..
Heads..
Heads..
It took 6 tosses to get 3 consecutive heads.
Press any key to continue . . .

Note: In the below code the output will always be changed because of random number generator function i.e., rand() .

Code: FileName: "FlipTheCoin.cpp"

#include <iostream>
#include <string>
using namespace std;
enum { Head, Tail };
int flip();
string label(int);
int flip()
{
    return rand()%2 == 0 ? Head : Tail;
}
string label(int value)
{
    return (value == Head ? "Head.." : "Tail..");
}
   int main (int argc, const char * argv[])
{
    // seed PRNG
    srand( (unsigned int)time(NULL) );   
    // declare variables
    int headCount = 0, tossCount = 0;
    int flipValue = -1;



    // run loop
    while ( headCount < 3 )
    {
        flipValue = flip();    
        headCount = (flipValue == Head) ? (headCount + 1) : 0;
        ++tossCount;
        cout << label(flipValue) << endl;
    }
    // print answers
    cout << "It took " << tossCount << " tosses to get " << headCount << " consecutive heads." << endl;
    system("pause");
    return 0;
}


Sunday, 19 April 2015

C++ Program To Check Palindrome Number

// Palindrome Problem.

#include<iostream>
using namespace std;
int main()
{
  long num;
  int arr[10],n=1,mod,c=0,j;
  cout<<"\n\t\t\tIS NUMBER PALINDROME\n";
  cout<<"Enter any Number :\t";cin>>num;

  while(num!=0)
  {
     mod=num%10;
     num/=10;
     arr[n]=mod;
     n++;
  }
  for(int i=1,j=n-1;i<=(n)/2;i++)
  {
     if(arr[i]==arr[j])
        j--;
     else
        c++;
  }
  if(c!=0)
      cout<<"\n\t\t....Not Palindrome....\n\n";
  else
      cout<<"\n\t\t....Palindrome....\n";
  cout<<"\n\n";
  system("pause");
  return 0;
}



C++ Program To Print ASCII Codes

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
    int ASCII;
    char ch;
    cout << "\t.....ASCII codes of Capital Letters....." << endl;
    for(ch='A';ch<='Z';ch++)
    {
      ASCII = static_cast<int>(ch);
      cout << "\t\t" << ch << setw(15) << setfill('.') << ASCII;
      cout << endl;                     
    }
    cout << "\n\t.....ASCII Codes of Small Letters....." << endl;
    for(ch='a';ch<='z';ch++)
    {
      ASCII = static_cast<int>(ch);
      cout << "\t\t" << ch << setw(15) << setfill('.') << ASCII;
      cout << endl;                                           
    }

   

   

system("pause");

return 0;   

}

Tuesday, 14 April 2015

Print Tribonacci Series Using C++

#include<stdio.h>
#include<iostream>
using namespace std;
int fabi(int);
int main()
{
      int num,i,num1=0,num2=0,num3=1,nex;
      cout<<"enter the number: ";
      cin>>num;
      for(i=0;i<=num;i++)
      {
         if ( i <= 1 )
           nex = i;
         else
         {
           nex  =  num1 + num2 + num3;
           num1= num2;
           num2 =  num3;
           num3  =  nex;  
         }
      cout << nex;
      cout<<",";
      }
      cout<<endl;
      system("pause");
      return 0;
}

Print Fabbinocci Series Using C++

#include<stdio.h>
#include<iostream>
using namespace std;
int fabi(int);
main()
{
      int num,i,num1=0,num2=1,nex;
      cout<<"enter the number: ";
      cin>>num;
      for(i=0;i<=num;i++)
      {
         if ( i <= 1 )
         nex = i;
         else
         {
           nex = num1 + num2;
           num1 = num2;
           num2 = nex;
      }
      cout << nex;
      cout<<",";
     }
      cout<<endl;
      system("pause");
      return 0;
      }

Thursday, 2 April 2015

C++ Project For a Cable Billing Company

Program: Cable Company Billing
This program calculates and prints a customer's bill for a local cable company.
The program processes two types of
customers: residential and business.

#include <iostream>
#include <iomanip>
using namespace std;
//Named constants – residential customers
const double RES_BILL_PROC_FEES = 4.50;
const double RES_BASIC_SERV_COST = 20.50;
const double RES_COST_PREM_CHANNEL = 7.50;
//named constants – business customers
const double BUS_BILL_PROC_FEES = 15.00;
const double BUS_BASIC_SERV_COST = 75.00;
const double BUS_BASIC_CONN_COST = 5.00;
const double BUS_COST_PREM_CHANNEL = 50.00;
int main()
{
//Variable declaration
int accountNumber;
char customerType;
int numOfPremChannels;
int numOfBasicServConn;
double amountDue;
cout << fixed << showpoint; //Step 1
cout << setprecision(2); //Step 1
cout << "This program computes a cable "
<< "bill." << endl;
cout << "Enter account number ( an integer): "; //Step 2
cin >> accountNumber; //Step 3
cout << endl;
cout << "Enter customer type: "
<< "R or r (Residential), "
<< "B or b ( Business): "; //Step 4
cin >> customerType; //Step 5
cout << endl;
switch (customerType)
{
case 'r': //Step 6
case 'R':
cout << "Enter the number"
<< " of premium channels: "; //Step 6a
cin >> numOfPremChannels; //Step 6b
cout << endl;
amountDue = RES_BILL_PROC_FEES //Step 6c
+ RES_BASIC_SERV_COST
+ numOfPremChannels *
RES_COST_PREM_CHANNEL;
cout << "Account number : "
<< accountNumber
<< endl; //Step 6d
cout << "Amount due: $"
<< amountDue
<< endl; //Step 6d
break ;
case 'b': //Step 7
case 'B':
cout << "Enter the number of ba sic "
<< "service connections: "; //Step 7a
cin >> numOfBasicServConn; //Step 7b
cout << endl;
cout << "Enter the number"
<< " of premium ch annels: "; //Step 7c
cin >> numOfPremChannels; //Step 7d
cout << endl;
if (numOfBasicServConn<= 10) //Step 7e
amountDue = BUS_BILL_PROC_FEES
+ BUS_BASIC_SERV_COST
+ numOfPremChannels *
BUS_COST_PREM_CHANNEL;
else
amountDue = BUS_BILL_PROC_FEES
+ BUS_BASIC_SERV_COST
+ (numOfBasicServConn - 10) *
BUS_BASIC_CONN_COST
+ numOfPremChannels *
BUS_COST_PREM_CHANNEL;
cout << "Account number: "
<< accountNumber << endl; //Step 7f
cout << "Amount due: $" << amountDue
<< endl; //Step 7f
break ;
default:
cout << "Invalid customer type." << endl; //Step 8
}//end switch
system("pause");
return 0;
}

How To Print The Absolute Number In C++

Q:Write a c++ code to print the absolute number

#include <iostream>
using namespace std;
int main()
{
int number,temp;
cout << " Enter an integer: ";
cin >> number;
cout << endl;
temp = number;
if (number < 0)
number = -number;
cout << " The absolute value of "
<< temp << " is " << number << endl;
system("pause");
return 0;
}

run this code using devc++

Saturday, 28 March 2015

How to Print Factorial Number in C++


// Problem : Calculate factorial of a given number using C++

#include<iostream>
using namespace std;
int main()
{
   long num;
   int j=1;
   long fact=1;
   cout << "Enter the number for Factorial......... : ";
   cin >> num;
   cout << endl;
   if(num==0)
   {
   cout << j;         
   }   
   else
   {
     for(int i=num;i>0;i--)
     {
       fact *= i;                 
     } 
     cout << num << "! = " << fact << endl;
   }
   cout << endl;
   system("pause");
   return 0;
}

C++ program to print the ASCII characters

Q: How to print ASCII characters using two for loops in C++

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
    int ASCII;
    char ch;
    cout << "\t.....ASCII codes of Capital Letters....." << endl;
    for(ch='A';ch<='Z';ch++)
    {
      ASCII = static_cast<int>(ch);
      cout << "\t\t" << ch << setw(15) << setfill('.') << ASCII;
      cout << endl;                     
    }
    cout << "\n\t.....ASCII Codes of Small Letters....." << endl;
    for(ch='a';ch<='z';ch++)
    {
      ASCII = static_cast<int>(ch);
      cout << "\t\t" << ch << setw(15) << setfill('.') << ASCII;
      cout << endl;                                           
    }
system("pause");
return 0;   
}