Function Examples (Pass and Return)

PASS AND RETURN

In Pass and Return, value(s) is/are passed from the calling function to the called function and a value is returned back from the called function to the calling function.

 Note:

* A function can return a maximum of one value.

* There can be any number of return statements in a function but as soon as anyone of return the statement gets executed the control goes back to the calling function.

Question:1
Write a function C language to calculate and print square of a number?
Sol:

#include <stdio.h>

//function definition
int square(int n)
{
int s;
s=n*n;
return(s);
//or
//return(n*n);
}
int main()
{
int a,b;
printf("Enter any no ");
scanf("%d",&a);
b=square(a);
printf("square = %d",b);
return 0;
}

Question:2
Write a function C language to take input for two numbers calculate and print their sum?
Sol:

#include <stdio.h>

//function definition
int sum(int n1,int n2)
{
int s;
s=n1+n2;
return(s);
//or
//return(n1+n2);
}
int main()
{
int a,b,c;
printf("Enter 2 nos ");
scanf("%d %d",&a,&b);
c=sum(a,b);
printf("sum = %d",c);
return 0;
}

C Language Programming Tutorial

C Language Tutorial Home     Introduction to C Language     Tokens     If Condition      goto statement and Labelname     Switch Statements     For loop     While Loop     Do while loop     break and continue     Functions     Recursion     Inbuild Functions     Storage Classes     Preprocessor     Arrays     Pointers     Structures and Unions     File Handling     Projects