Lecture 18 – Functions (continued)


Let’s see how we can write a function which takes an argument but does not return a value.

Type 3 – Functions that take argument and returns nothing

Let’s work with another type in which

1.       Main function will take input from the user

2.       Pass that value to the called function

3.       The called function will calculate its square

4.       The called function will display the calculated value on screen

 

#include <stdio.h>

#include <conio.h>

 

void square(int number)

{


Output

Please enter a number: 5

The square is 25





number = number * number;

printf(”\nThe square  is %d ”,number);

}

void main()

{

int result, input_value;

clrscr();                                                 // Function Call

printf(“\nPlease enter a number :”);

scanf(“%d”, &input_value);

square(input_value);                     //Function Call to my function Square, and passing an argument

getch();                                                                // Function Call

}

Example 35 - Function that takes a parameter and returns nothing

 

Local and Global Variable

In above example you can see that there are three variables i.e. number, result and input_value. The variable number is local to the function named square. Its access is limited to this function only. Similarly the other two variables are limited to the main function only.

Local variable is a variable whose access is limited to a block or a function. On the other hand a global variable is a kind of a variable which is accessible by every block or a function.

Type 4 – Functions that take argument and returns a value

 

Now it’s time to see how we can write a function which takes an argument but and returns a value.

In this example

1.       Main function will take input from the user

2.       Pass that value to the called function

3.       The called function will calculate its square

4.       The called function will return the value to the caller

5.       The main function will display the calculated value on screen

 

#include <stdio.h>

#include <conio.h>

 

void square(int number)

{


Output

Please enter a number: 5

The square is 25



number = number * number;

return number;

}

 

void main()

{

int result, number;

clrscr();                                                 // Function Call

printf(“\nPlease enter a number :”);

scanf(“%d”, &number);

result = square(number);                             //Function Call to my function Square, and capturing the result

printf(“\nThe square of  %d  is  %d”, number, result);

getch();                                                                // Function Call

}

Comments

Popular posts from this blog

Lecture 17 – Functions (continued)

Lecture 6 – Operators in C (continued)

Lecture 10 – Decisions (if-else-if)