In: Computer Science
Question 3: What is Function? Explain with examples. Provide at least 2 program examples.
What is function?
Function is a group of statements that performs some operations and returns result. If there is a need to run specific lines of code multiple times for different values than insted of writing same statements multiple times for different values you can declare a function that contains the code and then call that function from your main program for different values. So function basically used to provide reusability into the code.
Example 1:
#include <stdio.h>
// function getMax that calculates the maximum of 2 values
int getMax(int num1, int num2) {
/* local variable declaration */
int result;
//checks if num1 > num2 then max is num1
if (num1 > num2)
result = num1;
//checks if num1 < num2 then max is num2
else
result = num2;
//return the result
return result;
}
int main() {
int max;
//calls getMax method for 20 and 30
max = getMax(20,30);
printf("Max is = %d\n", max );
//calls getMax method for 37 and 21
max = getMax(37,21);
printf("Max is = %d\n", max );
}
Output:
Example 2:
#include <stdio.h>
#include <stdbool.h>
// function checknum checks if number is even or odd
bool checknum(int num) {
/* modulo operator returns the remainder of integer division
if any number is divisible by 2 then it is an even number otherwise
it is an odd number
*/
//if num is even then return true else returns false
if(num % 2 == 0){
return true;
}
else{
return false;
}
}
int main() {
bool ans;
//call checknum function for value 20 and store the result in ans variable
ans = checknum(20);
//if ans is true then the number is even and prints number is even
if(ans){
printf("Number is even \n");
}
//if ans is false then the number is odd and prints number is odd
else{
printf("Number is odd\n");
}
//call checknum function for value 3 and store the result in ans variable
ans = checknum(3);
//if ans is true then the number is even and prints number is even
if(ans){
printf("Number is even\n");
}
//if ans is false then the number is odd and prints number is odd
else{
printf("Number is odd\n");
}
}
Output: