ACLC College Computer Programming1 C SESSION11
ACLC College Computer Programming1 C SESSION11
(C++)
Gliceria S. Tan
Instructor
Session 11 Topics
➢ Function
➢ Dissection of a function definition
➢ Function call
A function is a subprogram
designed to perform a specific task.
To create a function:
returnType funcName(params){
function body
}
returnType funcName(params){
function body
}
returnType funcName(params){
function body
}
returnType funcName(params){
function body
}
getSum(a,b)
sum=a+b
return sum
void printMsg(){
cout<<”Hello world!”<<endl;
}
printMsg()
return
#include <iostream>
using namespace std;
int getSum(int a, int b);//Function prototype
int main(){
int x,y,sum;
cout<<"Enter values for x and y: ";
cin>>x>>y;
sum=getSum(x,y); //function call
cout<<“The sum is “<<sum;
}
int getSum(int a, int b){
int sum;
sum=a+b;
return sum;
}
Here’s a sample program that uses the getSum() function:
#include <iostream>
using namespace std;
int getSum(int a, int b);//Function prototype
When the program runs, the compiler calls main() first.
int main(){
int x,y,sum;
cout<<"Enter values for x and y: ";
cin>>x>>y; Calls function getSum(). Arguments x and y
sum=getSum(x,y); are copied into parameters a and b of
cout<<“The sum is “<<sum; function getSum().
}
int getSum(int a, int b){
int sum;
Value of sum is returned to main()
sum=a+b;
return sum;
}
Here’s the program flowchart.
START getSum(a,b)
OUTPUT sum
STOP
#include <iostream>
using namespace std;
void printMsg();
int main(){ In main(), the function call printMsg()
causes execution to jump to function
printMsg(); printMsg().
START printMsg()
STOP return