Credits

Monday, February 23, 2009

Learn Functions More-Part 2

Sometimes, functions must return and/or pass a value. So, the function type will be based on the data type of the value returned. Check the sample programs below.



[+/-] show/hide




#include stdio.h /*enclose this in <> */
int compute(int len, int wid);

main()
{
clrscr();
printf("\nEnter a dimension for length of the rectangle : ");
scanf("%d",&length);
printf("\nEnter a dimension for width of the rectangle : ");
scanf("%d",&width);
printf("The area of the rectangle is %d ",compute(length,width)); /*inside your function compute, we call these the actual parameters whose values are passed to the formal parameters*/
getche();
}

int compute(int len, int wid) /* these are your formal parameters */
{
return len * wid; /* the product of length and width is returned back to main function. The data type of this returned value shall define the function datatype. */
}

In Bloodshed C++:

#include iostream /*enclose this in <> */
using namespace std;
int compute(int len, int wid);

main()
{
cout<<"Enter a dimension for length of the rectangle : ";
cin>>length;
cout<<
"Enter a dimension for width of the rectangle : ";
/* add endl for the newline before the text */
cin>>width;
cin.ignore();
cout<<
"The area of the rectangle is %d "+compute(length,width); /*inside your function compute, we call these the actual parameters whose values are passed to the formal parameters*/
cin.get();
}

int compute(int len, int wid) /* these are your formal parameters */
{
return len * wid; /* the product of length and width is returned back to main function. The data type of this returned value shall define the function datatype. */
}

AddThis