-->





Translate

Showing posts with label functions. Show all posts
Showing posts with label functions. Show all posts

calculator program in c++ using functions

2 comments
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...

Differ pass by value and reference c++ example

Leave a Comment
Pass by value in C++ Programming
In this method we call a function by passing a value. A new copy of value is made and send to functions body. Where operations are applied on new copied value.




Advantages
  • New copy is made of value after passing so if changes go wrong the original data will be save
  • It increase the security of data
Disadvantage
  • If the data is huge making too much copies may cause system over head.

Pass by reference in C++ Programming
In this method we call a function by its reference using address operator. It don't make a copy of data and pass the address of value to the function. Where operations are applied on the reference of value and changes made permanently to data.

Advantages
  • When data is large it reduce the copies of data and creates less system overhead.
Disadvantage
  • Security of data can be weak because the real information is accessible and can be changed 


C++ function example of both ways pass by value and pass by reference
In this example there are two functions one calculates a cube of number with value and other calculates cube of number with reference. With value returns result and with reference not return result.

#include<iostream>
using namespace std;

int pass_Value(int);
void pass_reference(int &);
int main()
{
    int num1,num2;

    cout<<"Enter First Number: ";cin>>num1;
    cout<<"Enter Second Number: ";cin>>num2;

    cout<<"\n\n\n";

    int result=pass_Value(num1);
    cout<<"\t\tPass By Value Result: "<<result<<endl;

    pass_reference(num2);
    cout<<"\t\tPass By Reference Result: "<<num2<<endl;

    return 0;

}

int pass_Value(int number)
{
    return (number*number*number);
}

void pass_reference(int &number)
{
    number=number*number*number;
}


Input Output Example:

see also: Learn Pointers in C++ Programming with Examples


Explanation of functions

  • First function is simple we received a value calculate its cube and return simply the new result.
  • In second function we applies changes using reference of number we sent so no need to return here. As changes are made permanently.



See More Examples Here: C++ Simple Examples
Read More...

Cpp Tutorial Functions in c++ examples

Leave a Comment
This cpp tutorial contains
  • Introduction to functions in c++
  • Different methods to write functions
  • Examples of c++ functions code
  • Types of functions in c++

What are Functions and why they are important in c++ programming Language

A C++ function may have 2 or 3 phases
  1. Prototype
  2. Calling
  3. Definition or body of a function
  •  First one is optional it can be written or not depend upon the code.
  •  The second and third are compulsory to use

The purpose of a function is to do something like in a defining way. Let we want to do 3 different task then we will make 3 different functions and each function name should give us the idea about our function body.
For example we have to calculate prime numbers and detect vowel characters. There should be two functions one will calculate prime and other will check vowels and their name should be like that
calculatePrime();
in the above link there is a prime number program try to do it in a function for practice
CheckVowel();  
or any other name 

 What a function has
  •   return type
  •  It can be any thing like int,  float, or any other data  structure
  •  If we want to that our function not return any thing we use this
  ' void '  means nothing to return from where function has called    If function is not  returning any thing and function name is myfun then we will write it like that
  void myfun(){

}

Function body
  Function body it starts from curly braces and end with curly braces    void myfun(){ // start of function body        cout<<" I AM A Function";          
   }// end of fucntion body

its a function with
Name:        myfun
Return type:   void     

in funtion body we have written
            cout<<" I AM A Function";          

so now its time to use our function How to use the function?
Answer is CALL It
  As program starts from main() function we will use myfun function with in it or simple we can say we will call it within the main().

SO in order to use or call it write its name in main() with curly brackets just like that
#include<iostream> 
using namespace std;
int main()
{  myfun();  return 0; } // here is our function void myfun(){
cout<<"I Am a Function "; }
Lets Run this program Oh.. it will show an error on the compiler
Note: Its a common programming error a beginner can face
 It occurs because our programs run from top to bottom when compiler will reach at
myfun();  // function calling It will not be able to identify the function because compiler does not know what it is
so in order remove this error first we have to tell the compiler what is myfun(); then use it and write function body before the main() in this way compiler will read our function body first and will not show the error..

#include<iostream>
using namespace std;

void myfun(){
cout<<"I Am a Function "; }
int main(){ myfun(); return 0;
}

An alternate method to solve this error is to write function prototype which tells compiler that a function is exist

#include<iostream>
using namespace std;
void myfun();
// it is a prototype int main()
{ myfun();

return 0;
}
void myfun(){
cout<<"I Am a Function "; }

It is always recommend to write prototype when code is large it increase the readability of program because on a look at prototypesit is clear that what a program is about or what it contains.

Function with return type
If a function do some task in its body and want to send or return the result form where it was called then
Identify the data type or result what has to be send or return write this data type before the function name like below
Let this fucntion wants to return an integer
Function body will be look like that

int myfun()
{

  return result; // here result is of integer type
}

if a return type is defined and function is not returning anything then compiler will through an error e.g. "Function myfun must return "

Function with parameters
If we want to send some information in the form of any data type we can send this info at the time of calling it and this function can return the value too.
Let we want a function to which we send to integers it calculates both sum and return the final result

int Sum2Integers(int first, int second)
{
    int result = first+second;
   return result;
// Above to line can be written in one line like that
// return (first+second);

}

To call it form main()
int main()
{
      int myResult;
      myResult=Sum2Integers(5,5); // calling and sending two ints

}
Here cpp tutorial about basics of Cpp functions ends
here are two examples of functions
 more find here C++ simple examples
If you face any problem comment below your problem.
Read More...