Lecture 17 – Functions (continued)
Let’s
see how we can write a function which takes no argument but returns a value.
Type
2 – Functions that take NO argument and returns A value
I
would write a function which would
1.
Ask the user to input a number
2.
Calculate its square
3.
Return the calculated value to main function
4.
Main function will display calculated result
#include <stdio.h>
#include <conio.h>
void square()
{
int number;
printf(“\nPlease enter a number :”);
|
Output
There would be no
output as it has a syntax error. The error is LVALUE REQUIRED
|
scanf(“%d”, &number);
number = number * number;
return number;
}
void main()
{
clrscr(); // Function Call
square(); // Function Call to my function Square
getch(); // Function Call
}
Example
33 - Using parameter less function
If
you are using a function which returns a value then you need to have a
placeholder/a variable to receive value from the called function. Consider a
modified example.
#include <stdio.h>
#include <conio.h>
void square()
{
int number;
printf(“\nPlease enter a number :”);
|
Output
Please enter a
number: 5
The square is 25
|
scanf(“%d”, &number);
number = number * number;
return number;
}
void main()
{
int result;
clrscr(); // Function Call
result = square(); //
Function Call to my function Square, and capturing the result
printf(”\nThe square is %d”,
result);
getch(); // Function Call
}
Example
34 - Catching returned value from a
function call
Comments
Post a Comment