C++ | Introduction to functions

Introduction

This is tutorial of c++ of functions. The first program find the sum of two numbers using functions. The second one also does so. There is a little difference in the method of these programs but output is same. The program can be extended. Look at the extending it section. Go enjoy the program. Lets begin……………

Program to find sum of two numbers using function (method 1).

#include<iostream.h>
#include<conio.h>
//global variables int
int a,b,c;
//function prototype
void sum(void);
//main function
void main()
{
//clear the screen.
clrscr();
//Input the two numbers save them in ‘a’ and ‘b’
cout<<“Enter the no.”<<endl;
cin>>a>>b;
//calculate sum using sum function.
sum();
//get character
getch();
}

//function
void sum(void)
{
c=a+b;
cout<<“Sum of “<<a<<” & “<<b<<” is “<<c;
}

Output

Enter the no.
1
2
Sum of 1 & 2 is 3

Program to find sum of two numbers using function (method 2).

#include<iostream.h>
#include<conio.h>
//function prototype
int sum(int,int);
//main function
void main()
{
//clear the screen.
clrscr();
//declare variables as int.
int a,b,c;
//Input the two numbers save them in ‘a’ and ‘b’
cout<<“Enter the no.”<<endl;
cin>>a>>b;
//calculate sum using sum function.
c=sum(a,b);
//print sum
cout<<“Sum of “<<a<<” & “<<b<<” is “<<c;
//get character
getch();
}

//function
int sum(int x,int y)
{
int z;
z=x+y;
return(z);
}

Output

Enter the no.
1
2
Sum of 1 & 2 is 3

How does it work

  1. You enter the number.
  2. The function calculates sum.
  3. The sum is printed.

Extending it

The program can be extended by using more numbers or look here :-

  • Subtraction of two numbers using function.
  • Multiplication of two numbers using function.
  • Division of two numbers using function.

Go extend it…..

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Declare global variables if required.
  3. Declare the function prototype.
  4. Add void main.
  5. Start program by first clearing the screen.
  6. Declare the variables as int (name them as you want.)
  7. Add the cout and cin of numbers.
  8. Call the function.
  9. Add the function definition outside the void main().

At the end

You learnt creating the C++ program of Sum of two numbers using function. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s