0% found this document useful (0 votes)
24 views

PPS Unit-04 Notes

Uploaded by

Himanshu Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

PPS Unit-04 Notes

Uploaded by

Himanshu Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Programming for Problem Solving

Syllabus of UNIT IV: Functions

Definition, prototyping, categories, Parameter passing in functions, call by value, call


by reference, Passing arrays to functions (1D & 2D), Recursion: Example programs
(Factorial, Fibonacci, sum of n natural numbers etc.)

Q.1 What is Function. Explain function declaration, calling, definition and Type
of User-defined Functions in C.
Answer:

Function: A function is a block of statements that performs a specific task. All C


programs are written using functions to improve re-usability, understandability and to
keep track on them. A large C program is divided into basic building blocks called C
function. C function contains set of instructions enclosed by “{ }” which performs
specific operation in a C program.

1. Advantage of functions in C

There are the following advantages of C functions.

a) By using functions, we can avoid rewriting same logic/code again and again in a
program.
b) We can call C functions any number of times in a program and from any place in
a program.
c) We can track a large C program easily when it is divided into multiple functions.
d) Reusability is the main achievement of C functions.
e) However, Function calling is always a overhead in a C program.

Prepared by: Shankar Sharan Tripathi Page 1


Programming for Problem Solving

2. Types of Functions

There are two types of functions in C programming:

a) Library Functions: are the functions which are declared in the C header files
such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
b) User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the complexity of
a big program and optimizes the code.

3. Function Aspects

There are three aspects of a C function.

a) Functions declaration: A function must be declared globally in a c program to


tell the compiler about the function name, function parameters, and return type.
b) Function call: Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration. We
must pass the same number of functions as it is declared in the function
declaration.
c) Function definition: it contains the actual statements which are to be executed.
It is the most important aspect to which the control comes when the function is
called. Here, we must notice that only one value can be returned from the
function.

Prepared by: Shankar Sharan Tripathi Page 2


Programming for Problem Solving

4. Type of User-defined Functions in C


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

a) Function with no arguments and no return value


b) Function with no arguments and a return value
c) Function with arguments and no return value
d) Function with arguments and a return value

Example 1: for Function without argument and return value

#include<stdio.h>
void print();
void main ()
{
printf("Hello\n");
print();
}
void print()
{
printf("How are you");
}

Output:

Hello

How are you

Prepared by: Shankar Sharan Tripathi Page 3


Programming for Problem Solving

Example 2: for Function without argument and with return value

#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("The sum of given two number is = %d",result);
}

int sum()
{
int a,b;
printf("\nEnter two integer numbers:\n");
scanf("%d %d",&a,&b);
return a+b;
}
Output:

Going to calculate the sum of two numbers:


Enter two integer numbers:
5
6
The sum of given two number is = 11

Prepared by: Shankar Sharan Tripathi Page 4


Programming for Problem Solving

Example 3: for Function with argument and without return value

#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two integer numbers:\n");
scanf("%d %d",&a,&b);
sum(a,b);
}

void sum(int a, int b)


{
printf("\nThe sum of given two number is = %d",a+b);
}

Output:
Going to calculate the sum of two numbers:
Enter two integer numbers:
5
6
The sum of given two number is = 11

Prepared by: Shankar Sharan Tripathi Page 5


Programming for Problem Solving

Example 4: for Function with argument and with return value

#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two integer numbers:\n");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\The sum of given two number is = %d",result);
}

int sum(int a, int b)


{
return a+b;
}

Output:
Going to calculate the sum of two numbers:
Enter two integer numbers:
5
6
The sum of given two number is = 11

Prepared by: Shankar Sharan Tripathi Page 6


Programming for Problem Solving

Q.2 Explain Standard Library Function in C.

Library functions are the inbuilt function in C that are grouped and placed at a
common place called the library. Such functions are used to perform some specific
operations. For example, printf is a library function used to print on the console. The
library functions are created by the designers of compilers. All C standard library
functions are defined inside the different header files saved with the extension.h.

The list of mostly used header files is given in the following table.

Header
S. No. Description
file
This is a standard input/output header file. It contains all the library
1 stdio.h
functions regarding standard input/output.
2 conio.h This is a console input/output header file.
3 string.h It contains all string related library functions like gets(), puts(),etc.
This header file contains all the general library functions like
4 stdlib.h
malloc(), calloc(), exit(), etc.
This header file contains all the math operations related functions
5 math.h
like sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.
8 stdarg.h Variable argument functions are defined in this header file.
9 signal.h All the signal handling functions are defined in this header file.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
13 assert.h This file contains diagnostics functions.

Prepared by: Shankar Sharan Tripathi Page 7


Programming for Problem Solving

Example 1:

#include <stdio.h>
int main(void)

{ char ch[50];
printf("Enter Name : ");
scanf("%s", ch);
printf("\nWelcome %s\n", ch);
}

Output:
Enter Name : Shankar
Welcome Shankar

Example 2:

#include <stdio.h>
#include <string.h>
int main(void)

{ char fname[20] = "Shankar";


char lname[20] = "Tripathi";
char full_name[40];
strcat(full_name, fname);
strcat(full_name, " " );
strcat(full_name, lname);
printf("%s ", full_name);
}

Output:
Shankar Tripathi

Prepared by: Shankar Sharan Tripathi Page 8


Programming for Problem Solving

Q. 3 Explain call by value and call by reference with the help of suitable
program.

Answer:

Call by value in C

1. In call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable is
used in the function call in the call by value method.
2. In call by value method, we cannot modify the value of the actual parameter by
the formal parameter.
3. In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
4. The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.

Program to swapping the values of the two variables using call by value

#include <stdio.h>
void swap(int , int);
int main()
{ int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}

void swap (int a, int b)


{ int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
}

Prepared by: Shankar Sharan Tripathi Page 9


Programming for Problem Solving

Output:

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C (call by address)

1. In call by reference, the address of the variable is passed into the function call
as the actual parameter.
2. The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
3. In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function are
performed on the value stored at the address of the actual parameters, and
the modified value gets stored at the same address.

Program to swapping the values of the two variables using call by


reference.
#include <stdio.h>
void swap(int *, int *);
int main()
{ int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{ int temp;
temp = *a;
*a=*b;

Prepared by: Shankar Sharan Tripathi Page 10


Programming for Problem Solving

*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference in c

S.
Call by value Call by reference
No.
A copy of the value is passed into the An address of value is passed into the
1
function function
Changes made inside the function
Changes made inside the function are
validate outside of the function also.
limited to the function only. The values of
2 The values of the actual parameters do
the actual parameters do not change by
change by changing the formal
changing the formal parameters.
parameters.
Actual and formal arguments are created Actual and formal arguments are
3
at the different memory location created at the same memory location

Prepared by: Shankar Sharan Tripathi Page 11


Programming for Problem Solving

Q.4 Passing Arrays to Functions (1D & 2D)

1D Arrays: In C, when you pass a 1D array to a function, you are actually passing the
address of the first element. Thus, changes made to the array inside the function will
affect the original array.

Example (1D array):

#include <stdio.h>
void modifyArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
arr[i] = arr[i] + 1; // Modify the original array
}
}

int main()
{
int arr[] = {1, 2, 3, 4, 5};
int size = 5;
modifyArray(arr, size);
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
return 0;
}

Output:

23456

2D Arrays: When passing a 2D array, you need to specify the size of the second
dimension.

Prepared by: Shankar Sharan Tripathi Page 12


Programming for Problem Solving

Example (2D array):

#include <stdio.h>
void modify2DArray(int arr[][3], int rows)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < 3; j++)
{
arr[i][j] = arr[i][j] + 1; // Modify the original 2D array
}
}
}

int main()
{
Int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
modify2DArray(arr, 2);
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}

Output:

234
567

Prepared by: Shankar Sharan Tripathi Page 13


Programming for Problem Solving

Q.6 What is Recursion?

1. Write a Program to print Fibonacci series up to n terms using Recursion.

2. Write a Program to find factorial of a given number using Recursion.

3. Program for Tower of Hanoi using Recursion.

Answer:
Recursion: Recursion can be defined as the technique of replicating or doing again an
activity in a self-similar way calling itself again and again, and the process continues
till specific condition reaches. We must have certain conditions in the function to
break out of the recursion, otherwise recursion will occur infinite times.

Syntax:
function1()
{
...............
function1();
...............
}

1. Program to print Fibonacci series up to n terms using Recursion.


#include<stdio.h>
void Fibo(int ); //declaring the function
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
Fibo(n); //calling the function named Fibo

Prepared by: Shankar Sharan Tripathi Page 14


Programming for Problem Solving

return 0;
}
void Fibo(int n) //defining the function
{
static int n1=-1,n2=1,n3;
if(n>0)
{
n3 = n1 + n2;
printf("%d\n",n3);
n1 = n2;
n2 = n3;
Fibo(n-1); //recursion, since the function calls itself
}
}

Output:
Enter the number of elements: 10
0
1
1
2
3
5
8
13
21
34

Prepared by: Shankar Sharan Tripathi Page 15


Programming for Problem Solving

2. Program to find factorial of a given number using Recursion.

#include<stdio.h>
int fact(int x); //declaring the function
void main()
{
int a, b;
printf("Enter a number:");
scanf("%d", &a);
b = fact(a); //calling the function named factorial
printf("factorial of %d is = %d",a, b);
}

int fact(int x) //defining the function


{
int r = 1;
if(x == 1)
return 1;
else
r = x*fact(x-1); //recursion, since the function calls itself
return r;
}

Output:
Enter a number:5
factorial of 5 is = 120

Prepared by: Shankar Sharan Tripathi Page 16


Programming for Problem Solving

3. program for Tower of Hanoi using Recursion.


#include <stdio.h>
void hanoifun(int n, char fr, char tr, char ar) //fr=from rod,tr =to rod, ar=aux rod
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", fr, tr);
return;
}
hanoifun(n-1, fr, ar, tr);
printf("\n Move disk %d from rod %c to rod %c", n, fr, tr);
hanoifun(n-1, ar, tr, fr);
}

int main()
{
int n = 4; // n immplies the number of discs
hanoifun(n, 'A', 'C', 'B'); // A, B and C are the name of rod
return 0;
}

Output:

Move disk 1 from rod A to rod B


Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Prepared by: Shankar Sharan Tripathi Page 17
Programming for Problem Solving

Move disk 3 from rod B to rod C


Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C

Programs

Wap to find Sum of Natural Numbers using recursion.

#include <stdio.h>
Int sumNN(int n)
{
if (n == 1)
{
return 1;
}
return n + sumNN(n - 1);
}

int main()
{
intnum = 5;
printf("Sum of first %d natural numbers is: %d\n", num, sumNN(num));
return 0;
}

Output:

Sum of first 5 natural numbers is: 15

Prepared by: Shankar Sharan Tripathi Page 18


Programming for Problem Solving

Wap to Swap Two Numbers Using Functions

#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

int main()
{
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}

Output:

Before swap: x = 10, y = 20


After swap: x = 20, y = 10

Prepared by: Shankar Sharan Tripathi Page 19


Programming for Problem Solving

Wap to Find the Largest of Three Numbers using function

#include <stdio.h>
int largest(int a, int b, int c)
{
if (a >= b && a >= c)
{
return a;
}
else if (b >= a && b >= c)
{
return b;
}
else
{
return c;
}
}

int main()
{
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
int result = largest(num1, num2, num3);
printf("The largest number is: %d\n", result);
return 0;
}

Output:

Enter three numbers: 5 9 3


The largest number is: 9

Prepared by: Shankar Sharan Tripathi Page 20


Programming for Problem Solving

Wap to Check Whether a Number is Prime or Not using function.

#include <stdio.h>
int 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 a number: ");
scanf("%d", &n);

if (Prime(n))
{
printf("%d is a prime number.\n", n);
}
else
{
printf("%d is not a prime number.\n", n);
}

Prepared by: Shankar Sharan Tripathi Page 21


Programming for Problem Solving

return 0;
}

Output:

Enter a number: 7
7 is a prime number.

Prepared by: Shankar Sharan Tripathi Page 22


Programming for Problem Solving

Wap to Find the GCD of Two Numbers (Euclidean Algorithm).

#include <stdio.h>
int gcd(int a, int b)
{
if (b == 0)
{
return a;
}
return gcd(b, a % b);
}

int main()
{
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("The GCD of %d and %d is: %d\n", x, y, gcd(x, y));
return 0;
}

Output:

Enter two numbers: 56 98


The GCD of 56 and 98 is: 14

Prepared by: Shankar Sharan Tripathi Page 23


Programming for Problem Solving

Wap to Reverse an Array Using Functions

#include <stdio.h>
void reverseArray(int arr[ ], int size)
{
int start = 0;
int end = size - 1;
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

int main()
{
int arr[ ] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
reverseArray(arr, size);
printf("\nReversed array: ");
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
return 0;

Prepared by: Shankar Sharan Tripathi Page 24


Programming for Problem Solving

Output:

Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1

Prepared by: Shankar Sharan Tripathi Page 25


Programming for Problem Solving

Wap to Calculate Power of a Number Using Recursion

#include <stdio.h>
int power(int base, int expo)
{
if (expo== 0)
{
return 1;
}
return base * power(base, expo- 1);
}

int main()
{
int base, expo;
printf("Enter base and exponent: ");
scanf("%d %d", &base, &expo);
printf("%b to the power %d is: %d\n", base, expo, power(base, expo));
return 0;
}

Output:

Enter base and exponent: 2 5


2 raised to the power 5 is: 32

Prepared by: Shankar Sharan Tripathi Page 26


Programming for Problem Solving

Wap to Find the Length of a String Without Using strlen()

#include <stdio.h>
int stringLength(char str[ ])
{
int length = 0;
while (str[length] != '\0')
{
length++;
}
return length;
}

int main()
{
charstr[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
intlen = stringLength(str);
printf("The length of the string is: %d\n", len);

return 0;
}

Output:

Enter a string: Hello, World!


The length of the string is: 13

Prepared by: Shankar Sharan Tripathi Page 27

You might also like