-->




calculator program in c++ using functions

1 comment
Write a program for a simple c++ calculator which have different functions for different operations. Make a menu base selection screen using switch statement. Ever operation should have its own function. This code may also be use as a mini project to start. 
Calculator should have following operations.
  • Addition
  • Subtraction
  • Multiplication
  •  Division
  • Square root
  • Factorial
  • Exponential 

This code has been tested on Code blocks c++ compiler

C++ Source Code:


#include<iostream>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<iomanip>
  char op;
using namespace std;
void sum()
   {
     
    int sum = 0;
    int n;
    int numberitems;
    cout << "Enter number of items: \n";
    cin >> numberitems;

    for(int i=0;i<numberitems;i++)
    {
        cout<< "Enter number "<<i<<":\n\n" ;
        cin>>n; 
        sum+=n;
    }
    cout<<"sum is: "<< sum<<endl<<endl;
    
    }
void diff()
    {
     int diff;
     int n1,n2;
     cout<<"enter two numbers to find their difference:\n\n";
     cout<<"enter first number:";
     cin>>n1;
     cout<<"\nenter second number:";
     cin>>n2;
     diff=n1-n2;
     cout<<"\ndifference is:"<<diff<<endl<<endl;
     }
     
void pro()
    
    {
     int pro=1;
     int n;
     int numberitems;
     cout<<"enter number of items:\n";
     cin>>numberitems;
     for(int i=0;i<=numberitems;i++)
     {
             cout<<"\nenter item "<<i<<":";
             cin>>n;
             pro*=n;
     }
             
     cout<<"product is:"<<pro<<endl<<endl;    
     }
       
 void div()
     {
      int div;
      int n1;
      int n2;
      cout<<"enter 2 numbers to find their quotient\n\n";
      cout<<"enter numerator:";
      cin>>n1;
      cout<<"\nenter denominator:";
      cin>>n2;
      div=n1/n2;
      cout<<"\nquotient is:"<<div<<endl<<endl;
      }      

void power()
     {     
     long int p;
     int res=1,n; 
     cout<<"enter number:";
     cin>>n;
     cout<<"\nenter power:";
     cin>>p;
     for(int i=1;i<=p;i++)
     {
      res=n*res;
     }
      cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
     } 
       
void sq()
     {
     float s;
     int n;
     cout<<"enter number to find its square root:";
     cin>>n;
     s=sqrt(n);
     cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
     }
 void fact()
     {
      long int f=1;
      int c=1,n;
      cout<<"enter number to find its factorial:";
      cin>>n;
      while(c<=n)
      {
                 f=f*c;
                 c+=1;
      }     
                 cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;     
      }
void expo()
     {
          long double res=1,p; 
     double e=2.718281828;     
     cout<<"enter power of exponential function:";
     cin>>p;
     for(int i=1;i<=p;i++)
     {
      res=e*res;
     }
      cout<<" e^ "<<p<<" is :"<<res<<endl;
           
           }
int main()
{   
    
    
    system("cls");
    do
    {
                
    system("pause");              
    system("cls");    
    cout<<"***which operation you want to perform***\n";
    cout<<"press 0 for exit\n";
    cout<<"press 1 for addition \n";
    cout<<"press 2 for subtraction\n";
    cout<<"press 3 for multiplication\n";
    cout<<"press 4 for division\n";
    cout<<"press 5 for power calculation\n";
    cout<<"press 6 for square root \n";
    cout<<"press 7 for factorial calculation\n";
    cout<<"press 8 for exponential calculation\n";
    cout<<"press option:";
    cin>>op;
    switch(op)
    {
              case '1':
              sum();
              
              break;
              case '2':
              diff();
              break;
              case '3':
              pro();
              break;
              case '4':
              div();
              break;
              case '5':
              power();
              break;
              case '6':
              sq();
              break;
              case '7':
              fact();
              break;
              case '8':
              expo();
              break;     
              case '0':
              exit(0);    
              default:
              cout<<"invalid input"  ;
              system("cls");
    } 
    }
                                                                         
    while(op!='0');
                    
                    getch();
                    }



Program output video



Image output
simple calculator source code c++ using while loop functions and switch
output on code blocks console

Find more examples here: C++ simple example source code and explanation with dry run


Read More...

fibonacci series number c++ using while loop example

Leave a Comment
A program can be coded in different ways and this example shows how to find a number which is in Fibonacci series or not using do while loop
To read more visit Wikipedia
For example 5 is in Fibonacci series where 6 is not 
To make it more easy to understand this example shows a dry run in comments at line by line. Hope it will help to understand.
This program covers the concept of while loop and if statement.
Program has tested on code blocks compiler.

C++ source code:

#include <iostream>

using namespace std;

int main()
{
     int n,a,b,next;
     cout<<"Enter a number to check if it is a fibonacci number: ";
     cin>>n;         // 1)let n=9
     if(n==0||n==1)  // 2)check if 9=0 or 9=1 (NOT)
     cout<<n<<" is a fibonacci number\n\n";     //skip
     else
     a=0;b=1;        // 3) a=0 , b=1
     next=a+b;       // 4) next=0+1=1
     while(next<n)   // 5)loop starts from 1 and continues till next is less then 9
     {
        a=b;         // 6) a=1      ,9) a=1   ,12)a=2  ,15) a=3   ,18)a=5
        b=next;      // 7) b=1      ,10)b=2   ,13)b=3  ,16) b=5   ,19)b=8
        next=a+b;    // 8)next=1+1=2   ,11)next=1+2=3   ,14)next=2+3=5   ,17)next=3+5=8
                     // 18)next=5+8=13 (loop ends)
     }
     if(next==n)     // 19)check if 13==9 (NOT)
    cout<<n<<" is a fibonacci number";      //skip
    else
    cout<<n<<" is not a fibonacci number"; // 20)prints that 9 is not a fibonacci number.
    return 0;
}


program image:
source code find Fibonacci number c++
c++ Fibonacci number source code
Program input output:
program input output source code find Fibonacci number c++
input = 5


see also: Fibonacci series in c++ source code with logic explanation



Read More...

stack implementation in c++ using array source code

Leave a Comment
Stack in C++ program
This c++ program has 10 functions. Each function calls on menu based selection using switch statement (functions names may very in source code). Each function and whole code has proper commented to explain the code.  This program has been tested on Visual Studio IDE.

What is a stack?
Stack is know as LIFO(Last in First Out) functionality which means a thing or an object which has been added last time will out first. Like Placing books on one an other the last book we placed will be picked first to collect all books. To now more about stack in c++ read wiki .


List of Stack Functions


  1. void createStack();
  2. void menu();
  3. void display();
  4. void deleteStack();
  5. void clearStack();                     // declaration of functions 
  6. int pop();
  7. void push(int);
  8. void findelement();
  9. int isfull();
  10. int isempty();
  11. void find_by_position();
Program brief introduction


  • Every function will be called on menu based selection
  • An integer pointer has declared for dynamic memory allocation
  • Global variable size and top has declared to track the stack status in whole program

C++ Source Code


#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int top=-1;                         // -1 shows that stack is not created
int size=0;                         // initial size is zero
int *stk;             // initialization of dynamic array of typ int [works as stack]
/////////////////////////////////////////////////////////////////////////////////////
void createstk();
void menu();
void display();
void deletestk();
void clearstk();                     // declaration of functions 
int pop();
void push(int);
void findelement();
int isfull();
int isempty();
int checkIndex=0;
void find_by_position();
 /////////////////////////////////////////////////////////////////////////////////////
void menu()                      
{
     int option;
     system("pause");
     system("cls"); 
     while(option<1||option>10)                             // continue till we select option from 1-10
     {       
     system("cls"); 
     cout<<"press 0 to find element by position\n";
     cout<<"press 1 to create stack\n";
     cout<<"press 2 to display stack\n";
     cout<<"press 3 to clear stack\n";
     cout<<"press 4 to delete stack\n";                    
     cout<<"press 5 to find element in stack\n";        
     cout<<"press 6 to remove element from stack\n" ;
     cout<<"press 7 to add element in stack\n";
     cout<<"press 8 to check whether stack is full\n";
     cout<<"press 9 to check whether stack is empty\n";
     cout<<"press 10 to exit\n";
     cin>>option;
     
     
     switch(option)
     {
      case 0:
      find_by_position();
      break;

     case 1:
     createstk();
     break;
          
     case 2:
     display();
     break;
     
     case 3:
     clearstk();
     break;
          
     case 4:
     deletestk();
     break;    
     
     case 5:
     findelement();
     break;    
     
     case 6:
     {
     if(top<0)
     cout<<"stack not created\n";                  // check to see if stack is created or not
     if(isempty()==1)
     cout<<"stack is empty\n";                     // check to see if stack is empty 
     else 
     pop();                                        // pop element
     }
     menu();
     break;
     
     case 7:
     {
     int a;                 
     if(top<0)
     cout<<"stack not created\n";                   // check to see if stack is created or not
     else 
     if(isfull()==1 )
     cout<<"stack is full\n";                       //check to see if stack is full 
     else 
     cout<<"enter element to push on stack:";       // take element to push on stack if it is not full
     cin>>a;           
     push(a);                         
     }
     menu();
     break;
     
     
     case 8:
     {
     int a;      
     if(top<0)                                        //check to see if stack is created or not
     cout<<"stack not created\n";
     else
     isfull();                                         //calling isfull funtion
     if(a==1)
     cout<<"stack is full\n";                         //if isfull function returns 1 (true) then stack is full
     else
     cout<<"stack is not full\n";                     //else stack is not full
     }
     menu();
     break;
     
     
     case 9:
     {
     int a;
     if(top<0)                                     
     cout<<"stack not created\n";                    //check to see if stack is created or not
     else
     isempty();                                      //calling isempty function
     if(a==1)                                        //if isempty function returns 1(true) then stack is empty
     cout<<"stack is empty\n";
     else
     cout<<"stack is not empty\n";                  //else stack is not empty
     } 
     menu();
     break;
 
          
                       
     case 10:
     exit(0);                                       //calling default built in function to exit program
     break;
     
     
     default:
     cout<<"invalid option";
     break;
     }    
     }
     }
 ///////////////////////////////////////////////////////////////////////////////////////////    
 void createstk()        
 {
      cout<<"enter total size of stack:";
      cin>>size;     
   stk=new int[size];                                        // take total size of stack
     do
     {
           
                         
     cout<<"how many elements do you want to enter?\n";     //take current size of stack that we are going to use yet
     cin>>top;
                         
     }
     while(top<1||top>size);                               //prompt to enter current size till size entered is less then 1
                                                           // or greater then total size
                                                           
     cout<<"enter elements\n";                             
     for(int i=0;i<top;i++)                                //for loop from index 0 to current size (top)
     {
     cin>>stk[i];                                          //input value in stack
     
     }    
     menu();                                               //function call to enter main menu again
     } 
///////////////////////////////////////////////////////////////////////////////////////////
void display()
{
     if(top<0)
     cout<<"stack not created\n";                         //check to see if stack is created
     else
     cout<<"total number of elements in stack are :"<<top;       //displays total number of elements in stack
                                                                //by diplaying current value of top
     
     cout<<"\nand are as follows\n";                           
                                                                                      
                                                                                      
     for(int i=0;i<top;i++)                                 //loop from 0 index to top
     cout<<stk[i]<<endl;                                    //displays value in stack 
     getch();
     menu();                                              //function call to enter main menu again
}

////////////////////////////////////////////////////////////////////////////////////////////
void clearstk()
{
     if(top<0)
     cout<<"stack not created\n";                          //check to see if stack is created or not
     else
     top=0;                                               //if stack is created then make top=0 and clear it
     cout<<"stack is cleared\n";
     menu();
}


////////////////////////////////////////////////////////////////////////////////////////////////
void  deletestk()
{
      if(top<0)
      cout<<"stack not created\n";                       //check to see if stack is created or not
      else
      top=-1;
      cout<<"stack is deleted\n";                        //if stack is created then make top=-1 and delete it
      menu();
}
 ///////////////////////////////////////////////////////////////////////////////////////////////
void findelement()
{
     int item,temp=0;                                 //initialize temp variable from 0 + intializing variable to enter item
                                                        //to be found + intitailaizing counter variable 'i'
     if(top<0)
     cout<<"stack not created\n";                      //check to see if stack is created or not
     else
     {
     
     cout<<"enter item you want to find\n";
     cin>>item;                                        //input item to be found in stack
     for(int m=0;m<top;m++)                                //loop starts from zero index and continue upto top
     {
             if(stk[m]==item)                          //compare each content of stack with value entere
    {
    cout<<"item found at "<<m<<endl;
     temp=1;
             }
                                                //if item found then change value of temp to false the condition
             
             
     
     }
                                                     //control comes out of loop
    if(temp==0)
    {
    
     cout<<"item not found\n";                       //if temp!=1 displays that item not found
}
}
  menu();
     
  }
 /////////////////////////////////////////////////////////////////////////////////////////
 void push(int i)                                   //take arguement
 {
  
    
     stk[top]=i;                                   //places arguement at top
     top++;                                        //increment top to show next available position
  }
 //////////////////////////////////////////////////////////////////////////////////////// 
  int pop()
  {
    
     int i=stk[top];                               //remove element from top
     top--;                                        //decrements top 
  return i;
  }  
 /////////////////////////////////////////////////////////////////////////////////// 
  int isfull()
  {
    
     if( top==size)                              //check if top is equal to total size
     return 1 ;                                  //return true i-e stack is full
     else                                       
     return 0;                                   //else return false tnat stack is not full
     }
 /////////////////////////////////////////////////////////////////////////////////    
     int isempty()
     {
         if(top==0)                             //check if top is zero
         return 1;                              //return true that stack is empty
         else
         return 0;                              //else return false that stack is not empty
     } 
/////////////////////////////////////////////////////////////////////////////////////////   
void find_by_position()
{
     int pos;
     
     if(top<0)
     cout<<"stack not created\n";
     else
     if(top==0)
     cout<<"stack is empty\n";
     else
     {
     do
     {    
     cout<<"enter position to find its content\n";
     cin>>pos;
     }while(pos<0||pos>size); 
     for(int i=0;i<size;i++)
     {
             if(i==pos)
             {
                       cout<<"item at position "<<i<<" is "<<stk[i]<<endl;
                       
              }   //if closed
     }   //for closed
            
     }  //else closed
     menu();
     } //function closed
int main()
     {
         cout<<"welcome to stack application\n";
         menu();                                //funtion call to main menu
         getch();
         }


Program Sample output

create, enter size, select number of elements to enter then enter elements
stack c++ using array output program
Program output
Push element to stack


Output video

Download Source code from Google Drive

Note: It is recommended to dry run all the code for better understanding. There is always more way to code a program. Try to improve it by adding more functions and validations. Hope this mini c++ project help the beginners.

See also: Queue Implementation Using Array C++ Source Code
More C++ projects can be found here

Simple C++ mini projects for beginners 
Read More...

Array based Queue c++ simple project

Leave a Comment
In this c++ tutorial we will discuss  about Array Based Queue C++ project which have 10 functions including main function. User will select an option from main menu function and the respective function will be called. The code is for array based queue implementation. It comprises of various operations that can be performed on array based queue. This code can be used as a project or self-assignment by beginners of data structure. It is recommended to understand the code thoroughly mainly the “logic” then try to create logic for each individual function by yourself. It will surely enhance your coding capability

What is a Queue?
  • List of items arranged on basis of first in and first out principal is called queue.
  • It has 2 ends.
  • Data can be considered as to pass through hollow cylinder.
  • Data enters from one end and leaves from another end.
  • Data only moves in one direction.


Characteristics Of Queue:


  • It works on the FIFO (first in first out) principal.
  • It is ordered list and has elements/data of same type.
  • It doesn’t allow duplication of data.
  •  Enqueue function is used to insert new item in queue.
  • Dequeue function is used to remove any item from queue.
  •  If you want to dequeue any random item from queue, you will have to first dequeuer all items above it. Then remove the item you want. Then enqueue dequeued items accordingly.
cpp queue source code
queue image example 


Real World Examples:


  1. People standing in a queue for submission of their bills in bank. The person who came first will submit bill first. The person who came later will submit bill later.
  2. Cars on one way road. The car that entered first will exists first while the car that entered later will exit later.


Array Based Queue in C++ Data Structures
It is a linear data structure in which insertion of data/element takes places from end (rear) and deletion of data/element takes place from front (head).It allows you to store a data in form of array.

Project Overview:

Below I am going to share with you a c++ source code that is compiled using dev c++ compiler. The code is for array based queue implementation. It comprises of various operations that can be performed on array based queue. This code can be used as a project or self-assignment by beginners of data structure. It is recommended to understand the code thoroughly mainly the “logic” then try to create logic for each individual function by yourself. It will surely enhance your coding capability.

Code:

#include<iostream>     //header files
#include<conio.h> //header files
#include<stdlib.h>      //header files
#include<stdio.h>     //header files
using namespace std;

//////////////////////////////////////////////////////////////////////////////////////
/*declaration of global variables*/
/* front will show first index of array, initiated with -1 that shows that nothing is present at first position in queue*/
int front=-1;   
/* rear will show first last index of array, initiated with -1 that shows that nothing is present at last position in queue*/
int rear=-1;
int index=0;          // index will represent that how long is queue
int *queue=new int[index];      // for dynamical creation of queue
//////////////////////////////////////////////////////////////////////////////////////
/*declaration of functions*/
The functions below are named in such a way that they will clearly reveal what they are meant for
//////////////////////////////////////////////////////////////////////////////////////
void createqueue();
void enqueue(int a);
int dequeue();
void deletequeue();
void clearqueue();
int isfull();
int isempty();
void find();
void display();
void menu();

/////////////////////////////////////////////////////////////////////////////////////
The function below is the first function that would be called when code is executed. It will display a menu having different functionalities. Just select the number corresponding to operation you want to perform and then you will be on your way to go 
////////////////////////////////////////////////////////////////////////////////////
void menu()
{ 
     system("pause");     /*built in function supported by dev c++ to pause a screen until “enter” or any key is entered to proceed further.*/
     system("cls");   /*It will remove any garbage value that may appear on screen*/
     int option;
     cout<<"****welcome to queue application****\n";
     cout<<"press 1 to create queue\n";
     cout<<"press 2 to display queue\n";
     cout<<"press 3 to delete queue\n";
     cout<<"press 4 to clear queue\n";
     cout<<"press 5 to find number in queue\n";
     cout<<"press 6 to enqueue\n";
     cout<<"press 7 to dequeue\n";
     cout<<"press 8 to check if queue is full\n";
     cout<<"press 9 to check if queue is empty\n";
     cout<<"press 0 to exit\n";
     cout<<"enter option\n";
     cin>>option;
//////////////////////////////////////////////////////////////////////////////////////
Below I have used a switch to call various functions. If you are a beginner and don’t have any idea about “switch” you can go ahead with if-else statements but their drawback is they mess up everything, make confusions as code gets lengthy. 
/////////////////////////////////////////////////////////////////////////////////////     
     switch(option)
     {
     case 1:   // this case will simply call create queue function and will create it.
          createqueue();
          menu();
          break;
          
     case 2:   // this case will call display function and will display queue items
          display();
          menu();
          break;
     
     case 3:  // this function will delete whole queue by calling delete queue function
          deletequeue();
          menu();
          break;
     
     case 4:     // it will only clear items in queue but empty queue will still exist
          clearqueue();
          menu();
          break;
     
     case 5:   // it will search for required item in queue
          find();
          menu();
          break;
     
     case 6:    //
          {
          int a;
/*the check below will be used throughout the code to check if queue is created or not. Note the point that whenever front and rear will have negative value it means that array does not exist because array’s index can never be negative*/
          if(front==-1&&rear==-1)
          cout<<"queue not created\n";
          else  
          if(isfull()==1)
          
          cout<<"queue is already full\n";
                     
          else
          {
          cout<<"enter element to enqueue\n";
          cin>>a;
          enqueue(a);
          }
          menu();
          }
          break;
     
     case 7:
          {
          if(front==-1&&rear==-1)
          cout<<"queue not created\n";
          else 
          if(isempty()==1)
          {
          cout<<"queue is already empty\n";
          }
          else
          {
          cout<<"element dequeued is :"<<dequeue();
          cout<<endl;                
          }
          menu();
          } 
          break;
     
     case 8:
          {     
          int a;     
          if(front==-1&&rear==-1)
          cout<<"queue not created\n";
          else   
          isfull();
          if(a==1)
          cout<<"queue is full\n";
          else
          cout<<"queue is not full\n";
          }
          menu();
          break;
     
     case 9:
          {
          int a;     
          if(front==-1&&rear==-1)
          cout<<"queue not created\n";
          else   
          isempty();
          if(a==1)
          cout<<"queue is empty\n";
          else
          {
          cout<<"queue is not empty\n";   
          }
          menu();
          }
          break;
          
     case 0:
          exit(0);
          break;
   
    default:
          cout<<"invalid input\n";
          break;
          }
          }
//////////////////////////////////////////////////////////////
          
void createqueue()
{
/*The loop below will continue till you enter correct size of queue that must be greater than zero*/
     do
     {
     cout<<"enter size of queue:";
     cin>>index;
     }
     while(index<=0);
//////////////////////////////////////////////////////////////////////////////////////
Suppose you entered 10 then, queue will be like that
Front/rear
queue input value
enter queue value = 10
Dequeue/ Enqueue ////////////////////////////////////////////////////////////////////////////////////// /*The loop below will continue till you enter accurate current size that must be positive and less then index value. The “rear” here is pointing last index. */ do { cout<<"enter current size of queue:"; cin>>rear; } while(rear>index||rear<0); ///////////////////////////////////////////////////////////////////////////////// Suppose you entered rear=5 so,
c++ enter input
queue input = 5
////////////////////////////////////////////////////////////////////////////////// front=0; // front always start from zero it could be 1 also. cout<<"enter elements\n"; for(int i=front;i<rear;i++)// loop will start from ‘0’ and continue till “rear” value { cin>>queue[i]; } cout<<"queue is successfully created\n"; }
c++ queue created function
queue created c++
////////////////////////////////////////////////////////////////////////////////////// The function below will be used for display. ////////////////////////////////////////////////////////////////////////////////////// void display() { if(front==-1&&rear==-1) cout<<"queue not created\n"; else if(front<rear) { cout<<"total number of elements in queue are:"; cout<<rear-front<<endl; // rear=5 , front=0 so 5-0=5 elements cout<<"elements are\n"; for(int i=front;i<rear;i++) cout<<queue[i]<<endl; } else { int length; length=(index-front)+rear; cout<<"total number of elements in queue are:"; cout<<length<<endl; cout<<"elements are\n"; for(int i=front;i<index;i++) for(int j=0;j<rear;j++) cout<<queue[1]<<endl; } } ////////////////////////////////////////////////////////////////// void deletequeue() { if(front==-1&&rear==-1) cout<<"queue not created\n"; else front=-1; rear=-1; cout<<"queue is successfully deleted\n"; } ///////////////////////////////////////////////////////////////// void clearqueue() { if(front==-1&&rear==-1) cout<<"queue not created\n"; else front=0; rear=0; cout<<"queue is successfully cleared\n"; } //////////////////////////////////////////////////////////////// void find() { int temp=0; int number; int i; if(front==-1&&rear==-1) cout<<"queue not created\n"; else cout<<"enter number to find in queue\n"; cin>>number; for(i=front;i<rear;i++) { if(queue[i]==number) { cout<<"number found at position"<<i<<endl; temp=1; } } if(temp==0) cout<<"number not found\n"; } ////////////////////////////////////////////////////////////// void enqueue(int a) { queue[rear]=a; rear=(rear+1)%index; cout<<"element is successfully enqueued\n"; } ////////////////////////////////////////////////////////////// int dequeue() { int a=queue[front]; front=(front+1)%index; return a; } //////////////////////////////////////////////////////////// int isfull() { if(rear-front==rear) return 1; else return 0; } /////////////////////////////////////////////////////////// int isempty() { if(front==rear) return 1; else return 0; } /////////////////////////////////////////////////////////////// int main() { menu(); return 0; }
C++ source code output:

Sample input output
queue project menu
menu output selection
if we select option 1 and enter 1, 2, 3 then option 2 we have
queue display c++ project
display queue c++ project
find more projects here: C++ projects source code

Read More...