0% found this document useful (0 votes)
25 views25 pages

Functions 2

The document outlines four types of user-defined functions in C: functions with no arguments and no return value, functions with no arguments and a return value, functions with arguments and no return value, and functions with arguments and a return value. It also discusses function nesting, recursion, and the methods of passing arguments (by value and by reference), along with various exercises to practice these concepts. Additionally, it provides code examples for each type of function and exercise.

Uploaded by

donkengmichael2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views25 pages

Functions 2

The document outlines four types of user-defined functions in C: functions with no arguments and no return value, functions with no arguments and a return value, functions with arguments and no return value, and functions with arguments and a return value. It also discusses function nesting, recursion, and the methods of passing arguments (by value and by reference), along with various exercises to practice these concepts. Additionally, it provides code examples for each type of function and exercise.

Uploaded by

donkengmichael2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

TYPE OF USER-DEFINED FUNCTIONS IN C

There can be 4 different types of user-defined functions, they are:

1. Function with no arguments and no return value

2. Function with no arguments and a return value

3. Function with arguments and no return value

4. Function with arguments and a return value


Below, we will discuss about all these types, along with program examples.

FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUE

Such functions can either be used to display information or they are


completely dependent on user inputs.

Below is an example of a function, which takes 2 numbers as input from


user, and display which is the greater number.

#include<stdio.h>

void greatNum(); // function declaration

int main()

greatNum(); // function call

return 0;
}

void greatNum() // function definition

int i, j;

printf("Enter 2 numbers that you want to compare...");

scanf("%d%d", &i, &j);

if(i > j) {

printf("The greater number is: %d", i);

else {

printf("The greater number is: %d", j);

FUNCTION WITH NO ARGUMENTS AND A RETURN VALUE

We have modified the above example to make the


function greatNum() return the number which is greater amongst the 2
input numbers.
#include<stdio.h>

int greatNum(); // function declaration

int main()

int result;

result = greatNum(); // function call

printf("The greater number is: %d", result);

return 0;

int greatNum() // function definition

int i, j, greaterNum;

printf("Enter 2 numbers that you want to compare...");

scanf("%d%d", &i, &j);

if(i > j) {
greaterNum = i;

else {

greaterNum = j;

// returning the result

return greaterNum;

FUNCTION WITH ARGUMENTS AND NO RETURN VALUE

We are using the same function as in example again and again, to


demonstrate that to solve a problem there can be many different ways.

This time, we have modified the above example to make the


function greatNum() take two int values as arguments, but it will not be
returning anything.

#include<stdio.h>

void greatNum(int a, int b); // function declaration

int main()

{
int i, j;

printf("Enter 2 numbers that you want to compare...");

scanf("%d%d", &i, &j);

greatNum(i, j); // function call

return 0;

void greatNum(int x, int y) // function definition

if(x > y) {

printf("The greater number is: %d", x);

else {

printf("The greater number is: %d", y);

FUNCTION WITH ARGUMENTS AND A RETURN VALUE


This is the best type, as this makes the function completely independent of
inputs and outputs, and only the logic is defined inside the function body.

#include<stdio.h>

int greatNum(int a, int b); // function declaration

int main()

int i, j, result;

printf("Enter 2 numbers that you want to compare...");

scanf("%d%d", &i, &j);

result = greatNum(i, j); // function call

printf("The greater number is: %d", result);

return 0;

int greatNum(int x, int y) // function definition

if(x > y) {
return x;

else {

return y;

NESTING OF FUNCTIONS

C language also allows nesting of functions i.e to use/call one function


inside another function's body. We must be careful while using nested
functions, because it may lead to infinite nesting.

function1()

// function1 body here

function2();

// function1 body here

}
If function2() also has a call for function1() inside it, then in that case, it will
lead to an infinite nesting. They will keep calling each other and the
program will never terminate.

Not able to understand? Let’s consider that inside the main() function,
function1() is called and its execution starts, then inside function1(), we
have a call for function2(), so the control of program will go to the
function2(). But as function2() also has a call to function1() in its body, it
will call function1(), which will again call function2(), and this will go on for
infinite times, until you forcefully exit from program execution.

I. RECURSION
Recursion is the process in which a function repeatedly calls itself to
perform calculations. Typical applications are games and sorting trees and
lists. Recursive algorithms are not mandatory, usually an iterative approach
can be found.

The following function calculates factorials recursively:

int factorial(int n)
{
int result;
if (n<=1)
result=1;
else
result=n*factorial(n-1);
return result;
}

II. FUNCTION ARGUMENTS

If a function is to use arguments, it must declare variables that accept the


values of the arguments. These variables are called the formal parameters
of the function.
The formal parameters behave like other local variables inside the function
and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed
to a function:
IV.1 Function call by value
The call by value method of passing arguments to a function copies the
actual value of an argument into the formal parameter of the function. In
this case, changes made to the parameter inside the function have no
effect on the argument.
By default, C programming language uses call by value method to pass
arguments. In general, this means that code within a function cannot alter
the arguments used to call the function. Now, let us call the function swap()
by passing actual values as in the following example:

#include<stdio.h>
void swap(int x, int y); /* function declaration */
int main ()
{
int a =100;int b =200; /* local variable
definition */
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(a, b); /* calling a function to swap
the values */
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return0;
}
Let us put above code in a single C file, compile and execute it, it will
produce the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

Which shows that there is no change in the values though they had been
changed inside the function.
IV.2 Function call by reference

The call by reference method of passing arguments to a function copies


the address of an argument into the formal parameter. Inside the function,
the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to the
functions just like any other value. So accordingly you need to declare the
function parameters as pointer types as in the following function swap(),
which exchanges the values of the two integer variables pointed to by its
arguments.

void swap(int*x, int*y) /* function definition to swap


the values */
{
int temp;
temp =*x; /* save the value at address x */
*x =*y;/* put y into x */
*y = temp;/* put x into y */
return;
}
Let us call the function swap() by passing values by reference as in the
following example:
#include<stdio.h>
void swap(int*x, int*y); /* function declaration */
int main ()
{
int a =100;int b =200; /* local variable
definition */
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and

* &b indicates pointer to b ie. address of variable b. */

swap(&a,&b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return0;
}

Let us put above code in a single C file, compile and execute it, it will
produce the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Which shows that there is no change in the values though they had been
changed inside the function.

EXERCISE 6
Exercise 6.1: Write a function which take a real number and return its
absolute value. Write a program which use the function
Exercise 6.2: Write two C functions that compute f(x)=2.3*x and g(x,y)=x*y.
Exercise 6.3: Write a function that returns 1 if an integer number is prime, 0
otherwise. Use that function to write a C program which display the list of
prime number below a given integer n.
Exercise 6.4: Write a C function facto that computes the factorial of a
number n (integer). The factorial function is a typical recursive problem.
Rewrite the equation defining the factorial function in a recursive form.
Write the recursive version of the code and call the function facto_rec.
Exercise 6.5: Write the function called pow to calculate xn for any real
number x and integer n. Rewrite it in its recursive form and write the
associate C function that you will call pow_rec.
Exercise 6.6: The Taylor expansion of the exponential function is given by
n
x ∞ x
e = ∑n=0 . Using the previous exercises (function facto and pow), write a C
n!
functions that calculates the exponential for integer values of x. Compare
its results to the results of the C exponential function defined in <math.h>.
Exercise 6.7: Write a program that repeatedly asks the user to enter pairs
of numbers until at least one of the pair is 0. For each pair, the program
should use a function to calculate the harmonic mean of the numbers. The
function should return the answer to main(), which should report the result.
The harmonic mean of the numbers is the inverse of the average of the
inverses and can be calculated as follows: harmonic mean of x and y = 2.0
× x × y / (x + y)
Exercise 6.8: Write a function which generate 50 integers between 1 and
100 randomly and do the follow. It calculates the factorial of each number
divisible by 5 of and the inverse of each number divisible by 6. You must
use two functions facto and inverse to calculate the factorial and the
inverse of any number. Static variables should be used in those functions
to count the number of time each of them has been called.
Exercise 6.9: Write a function that takes three arguments: the name of an
int array, the array size, and an int value. Have the function set each
element of the array to the int value.
Exercise 6.10: Write a program that asks the user to enter up to 10 golf
scores, which are to be stored in an array. You should provide a means for
the user to terminate input prior to entering 10 scores. The program should
display all the scores on one line and report the average score. Handle
input, display, and the average calculation with three separate array-
processing functions.
Exercise 6.11: Write a function that takes three arguments: a pointer to the
first element of a range in an array, a pointer to the element following the
end of a range in an array, and an int value. Have the function set each
element of the array to the int value.
Exercise 6.12: Write a function that takes a double array name and an array
size as arguments and returns the largest value in that array. Note that this
function shouldn’t alter the contents of the array.
Sure! Here’s a concise breakdown of the exercises you provided, along with
the C code implementations for each.

### Exercise 6.1: Absolute Value Function

```c
#include <stdio.h>

double absolute_value(double num) {


return (num < 0) ? -num : num;
}

int main() {
double number;
printf("Enter a real number: ");
scanf("%lf", &number);
printf("Absolute value: %.2f\n", absolute_value(number));
return 0;
}
```

### Exercise 6.2: Simple Functions f(x) and g(x,y)

```c
#include <stdio.h>

double f(double x) {
return 2.3 * x;
}

double g(double x, double y) {


return x * y;
}

int main() {
double x = 4.0, y = 5.0;
printf("f(%.2f) = %.2f\n", x, f(x));
printf("g(%.2f, %.2f) = %.2f\n", x, y, g(x, y));
return 0;
}
```

### Exercise 6.3: Prime Number Checker

```c
#include <stdio.h>

int is_prime(int num) {


if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return 0;
}
return 1;
}

int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
printf("Prime numbers less than %d: ", n);
for (int i = 2; i < n; i++) {
if (is_prime(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
```

### Exercise 6.4: Factorial Function (Recursive)

```c
#include <stdio.h>

int facto_rec(int n) {
if (n == 0) return 1;
return n * facto_rec(n - 1);
}

int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Factorial of %d: %d\n", n, facto_rec(n));
return 0;
}
```
### Exercise 6.5: Power Function (Recursive)

```c
#include <stdio.h>

double pow_rec(double x, int n) {


if (n == 0) return 1;
return x * pow_rec(x, n - 1);
}

int main() {
double x;
int n;
printf("Enter base (x) and exponent (n): ");
scanf("%lf %d", &x, &n);
printf("%.2f^%d = %.2f\n", x, n, pow_rec(x, n));
return 0;
}
```

### Exercise 6.6: Exponential Function using Taylor Expansion

```c
#include <stdio.h>
double facto(int n) {
return (n == 0) ? 1 : n * facto(n - 1);
}

double exp_taylor(int x) {
double sum = 1.0;
for (int n = 1; n < 10; n++) {
sum += pow_rec(x, n) / facto(n);
}
return sum;
}

int main() {
int x;
printf("Enter an integer for e^x: ");
scanf("%d", &x);
printf("Approximation of e^%d: %.5f\n", x, exp_taylor(x));
return 0;
}
```

### Exercise 6.7: Harmonic Mean Function

```c
#include <stdio.h>
double harmonic_mean(double x, double y) {
return (2.0 * x * y) / (x + y);
}

int main() {
double x, y;
while (1) {
printf("Enter two numbers (0 to exit): ");
scanf("%lf %lf", &x, &y);
if (x == 0 || y == 0) break;
printf("Harmonic Mean: %.2f\n", harmonic_mean(x, y));
}
return 0;
}
```

### Exercise 6.8: Factorial and Inverse Calculation

```c
#include <stdio.h>
#include <stdlib.h>

int facto(int n) {
static int count = 0;
count++;
if (n == 0) return 1;
return n * facto(n - 1);
}

double inverse(int n) {
static int count = 0;
count++;
return 1.0 / n;
}

int main() {
int num;
srand(time(NULL));
for (int i = 0; i < 50; i++) {
num = rand() % 100 + 1; // Random number between 1 and 100
if (num % 5 == 0) {
printf("Factorial of %d: %d\n", num, facto(num));
}
if (num % 6 == 0) {
printf("Inverse of %d: %.2f\n", num, inverse(num));
}
}
return 0;
}
```

### Exercise 6.9: Set Array Values

```c
#include <stdio.h>

void set_array(int arr[], int size, int value) {


for (int i = 0; i < size; i++) {
arr[i] = value;
}
}

int main() {
int arr[5];
set_array(arr, 5, 3);
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```

### Exercise 6.10: Golf Scores Program


```c
#include <stdio.h>

void input_scores(int scores[], int *count) {


int score;
while (*count < 10) {
printf("Enter a golf score (or -1 to finish): ");
scanf("%d", &score);
if (score == -1) break;
scores[(*count)++] = score;
}
}

void display_scores(int scores[], int count) {


for (int i = 0; i < count; i++) {
printf("%d ", scores[i]);
}
printf("\n");
}

double average_score(int scores[], int count) {


double sum = 0;
for (int i = 0; i < count; i++) {
sum += scores[i];
}
return (count > 0) ? (sum / count) : 0;
}

int main() {
int scores[10], count = 0;
input_scores(scores, &count);
display_scores(scores, count);
printf("Average score: %.2f\n", average_score(scores, count));
return 0;
}
```

### Exercise 6.11: Set Array Range

```c
#include <stdio.h>

void set_range(int *start, int *end, int value) {


for (int *p = start; p < end; p++) {
*p = value;
}
}

int main() {
int arr[5] = {0};
set_range(arr, arr + 5, 7);
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```

### Exercise 6.12: Largest Value in Array

```c
#include <stdio.h>

double largest_value(double arr[], int size) {


double max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
double arr[] = {1.5, 3.2, 7.4, 2.8, 5.9};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Largest value: %.2f\n", largest_value(arr, size));
return 0;
}
```

### Summary

- Each exercise has its own function or program, demonstrating


fundamental programming concepts in C.
- The code is structured to be straightforward and includes comments for
clarity.

You might also like