0% found this document useful (0 votes)
8 views46 pages

C Programming Functions and Recursion Guide

The document outlines the syllabus and grading structure for a C programming course, detailing topics such as C fundamentals, arrays, functions, and pointers. It emphasizes the importance of user-defined functions and provides examples of function declarations, definitions, and calls. Additionally, it discusses different aspects of function calling and parameter passing methods, including call by value and call by reference.

Uploaded by

b2356939
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)
8 views46 pages

C Programming Functions and Recursion Guide

The document outlines the syllabus and grading structure for a C programming course, detailing topics such as C fundamentals, arrays, functions, and pointers. It emphasizes the importance of user-defined functions and provides examples of function declarations, definitions, and calls. Additionally, it discusses different aspects of function calling and parameter passing methods, including call by value and call by reference.

Uploaded by

b2356939
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

CSE 1215 -

Computer
Programming
Slide 05

Tasnim Ahmed, Lecturer, BME, KUET


2

Remember !

Content Percentage Marks

Attendance, Assignments 10% 30

Class Test, Spot Test 20% 60

Term Final Examination 70% 210


3

Syllabus

C fundamentals: The C character set, Identifiers and keywords, Data types, Constants, Variables,
Arrays, Declaration, Expressions, Statements, Symbolic constants, Operators & Expressions,
Arithmetic operators, Unary operators, Relational & logical operators, Assignment operator,
Conditional operators, Library functions, Data input & output functions.

Arrays: Defining an array, Processing array, Passing an array to a function, Multi-dimensional array,
Array & strings.

Functions: Defining a function, Accessing a function, Passing arguments to functions, Specifying


arguments data types, Function prototypes, Storage classes, auto, Static, Extern and register
variables.

Pointers: Declarations, Pointers to a function, Pointer and one-dimensional array, Operating a


pointer, Pointers and multi-dimensional arrays, Arrays of pointers, Passing functions to other
functions.
4

05
Function & Recursion
Defining a function, Accessing a function, Passing arguments to functions, Specifying arguments
data types, Function prototypes, Storage classes, auto, Static, Extern and register variables.
5

C Function
C Function : A function is a block of code that performs a specific task. A C program must
have main( ) function. Without main( ) function, there is technically no C program.

Types of C Functions: #include<stdio.h>


✔ Standard Library Function
int main()
✔ User Defined Function
{
int a,b,c,average;
float s;
scanf(“%d%d%d”,&a, &b, &c);
average=(a+b+c)/3;
s = sqrt( average );
printf("Result=%f", s);

}
6

Library Function
Library Function: The standard library functions are built-in functions in C programming.
These functions are defined in header files.
#include<stdio.h>

Library Function Header File int main()


{
scanf(), printf() stdio.h int a,b,c,average;
Input/output functions float s;
scanf(“%d%d%d”,&a, &b, &c);
sin(x), cos(x), sqrt(x) math.h
average=(a+b+c)/3;
Mathematical functions
s = sqrt( average );
printf("Result=%f", s);

}
7

User Defined Function


User Defined Function: As the name suggests, a user-defined function is a function
written by the user to write any program code and execute specific actions. These user-defined
functions can be modified and execute according to the requirement of the programmer. A
programmer can change the user-defined function, but these functions are not defined in the C
header files.

A user-defined function is made up using


❑ Function prototype or function declaration,
❑ Function definition or function body
❑ Function call.

Dividing a complex problem into smaller chunks makes our program easy to understand and
reuse.
8

User Defined Function Ingredient Ratio in


(Milk + Coco
Powder + Nut)

Dark 2 : 10 : 0
Chocolate

White 10 : 1 : 0
Chocolate

Nutty 5:5:2
Chocolate
Chocolate Factory
9

User Defined Function


Write a C program to make these three different chocolates where summation of ingredients will be the
price of the chocolates. In this code, variables (milk, coco and nut) are
initialized multiple times to execute the operation. It
int main()
will be very hectic to write complex codes where
{
int milk, coco, nut; multiple operations will be done using same variable
int Dark, White, Nutty; but different value. Likewise if you use single
machine to make these 3 different chocolates, you will
milk=2; coco=10; have to add ingredients in multiple combination each
Dark= milk + coco; time for specific chocolate, which will make the work
tiring and painful. One solution to this problem is the
milk=10; coco = 1;
White=milk + coco; use of function in C program to execute specific tasks
( Dark, White, Nutty). For example, if you use 3
milk=5; coco=5; nut=2; different machine to make these chocolates, you just
Nutty=milk + coco + nut; have to set the ingredient ratio ones and each machine
will produce target chocolate without any extra work
printf("Price of Dark Chocolate = %d",Dark );
and you will never have to change the input (ingredient
printf("Price of White Chocolate = %d", White);
printf("Price of Nutty Chocolate = %d", Nutty); ratio) to make different chocolates. Dark machine will
} produce dark chocolate, white will produce white
chocolate and Nutty will give us Nutty chocolate.
10

User Defined Function

Lets make 3 different function for each chocolate


A user-defined function is made up using
❑ Function prototype or function declaration,
❑ Function definition or function body
❑ Function call.
11

Function Declaration
User Defined Function Declaration: A function prototype is also known as a function
declaration which specifies the function’s name, function parameters, and return type. The function
prototype does not contain the body of the function. It is basically used to inform the compiler about the
existence of the user-defined function which can be used in the later part of the program.

Syntax:

Return_type Function_name ( data_type_1 parameter_1, data_type_2 parameter_2, data_type_n parameter_n)

Return Type: Return type represents the function that can return any defined data type values. The return type value can be int,
float, char, double, etc., where the function_name represents the name of a function that contains more than one argument in it. If
function doesn’t return any value to main ( ) function, then return type is void.

Parameter: The data that will be passed to function from main function are known as parameter or argument.
12

Function Definition / Body


User Defined Function Definition: The function definition defines the actual body of
the function that perform some specific tasks in a program. All the statements of the function
definition are enclosed within { } braces.

Syntax:
Return_type Function_name ( data_type_1 parameter_1, data_type_2 parameter_2, data_type_n parameter_n)

{
Statements to be executed;
Return value if any;
}
13

Function Call
User Defined Function Call: Function can be called from anywhere in the program. A
function gets called when the function name is followed by a semicolon.

Syntax:

Function_name (Parameter List);


14

User Defined Function


Write a C program to make these three different chocolates where summation of ingredients will be the
price of the chocolates (using funtion.) int main(){
int milk, coco, nut;
Dark(2,10,0);
Function Call White(10,1,0);
Nutty(5,5,2);
}
Function Declaration/ prototype void Dark(int a, int b, int c){
int dark = a+b+c;
Function Body/Definition printf("Dark Chocolate Price=%d\n", dark);
}

Function Declaration/ prototype void White(int a, int b, int c){


int white = a+b+c;
Function Body/Definition
printf("White Chocolate Price=%d\n", white);
}

Function Declaration/ prototype void Nutty(int a, int b, int c){


int nutty = a+b+c;
Function Body/Definition
printf("Nutty Chocolate Price=%d", nutty);
}
15

User Defined Function


Write a C program to make these three different chocolates where summation of ingredients will be the
price of the chocolates (using funtion.) void Dark(int a, int b, int c){
int Dark = a+b+c;
printf("Dark Chocolate Price=%d\n", Dark);
}

You can use main ( ) function after user void White(int a, int b, int c){
defined functions. The program will still int White = a+b+c;
start from the main ( ) function regardless printf("White Chocolate Price=%d\n", White);
}
of the position. Because main ( ) is the
starting point of any C program. void Nutty(int a, int b, int c){
int Nutty = a+b+c;
printf("Nutty Chocolate Price=%d", Nutty);
}
int main(){
int milk, coco, nut;
Dark(2,10,0);
White(10,1,0);
Nutty(5,5,2);
}
16

User Defined Function


int Dark(int a, int b, int c){
return a+b+c;
In previous example, return type of user }
int White(int a, int b, int c){
defined functions were void because these
return a+b+c;
functions were not returning any value to the }
main function. They were printing the result int Nutty(int a, int b, int c){
(price) by themselves. return a+b+c;
}
But in this example, results are being printed
in main ( ) function. Hence for printing the int main( ){
results, value must be returned from the user int milk, coco, nut, dark, white, nutty ;
dark = Dark(2,10,0);
defined functions to main ( ) function.
printf(“Dark Chocolate Price=%d", dark);
Otherwise, we can’t show any result. Hence white= White(10,1,0);
the return type is int here, as integer value printf(“White Chocolate Price=%d", white);
is returned to the main function. nutty = Nutty(5,5,2);
printf("Nutty Chocolate Price=%d", nutty);
}
17

User Defined Function Flow Diagram

int Dark(int a, int b, int c){


return a+b+c;
}

int main( ){
Second Step First Step
int milk, coco, nut, dark;
dark = Dark(2,10,0);
printf(“Dark Chocolate Price=%d", dark);
}
18

Different Aspect of Function Calling


Function may or may not accept any argument. It may or may not return any value. Based on
these facts, There are four different aspects of function calls. Thus a function can be
categorized depending on argument and return type:

❑ function without arguments and without return value


❑ function without arguments and with return value
❑ function with arguments and without return value
❑ function with arguments and with return value
19

Different Aspect of Function Calling


1. Function without arguments/parameters and without return value:
You only want to print the name of the chocolate factory using function. In that case, you don’t
need to pass any parameter from main function to user defined function, as no calculation is
required to print a name. As the printing will be done in user defined function, we don’t
need to return any value to main function. Hence the function return type is void here.

int main ()
{
Output:
Name( );
}
void Name( )
{
printf("Kinder Joy");
}
20

Different Aspect of Function Calling


1. Function without arguments/parameters and without return value:
Say you want to calculate sum of two numbers using user defined function. In that case, you
can add the numbers without importing any parameter from main function. You can simply
declare and initialize variable within your defined function. As the printing will be done in
user defined function, you don’t need to return any value to main function. Hence the
function return type is void here. int main()
{
printf("Going to calculate the sum of two numbers:\n");
sum( );
}

Output: void sum( )


{
int a=5,b=9;
printf("%d + %d = %d",a,b,a+b);
}
21

Different Aspect of Function Calling


2. Function without arguments/parameters and with return value:
Say you want to calculate sum of two numbers using user defined function like previous
example but here you want to print the sum in main function. In this case, you will have to
return the result value to main function.
Hence the function return type is int here.
int main()
{
int result;
printf("Going to calculate the sum of two numbers:\n");
result = sum();
printf("result = %d", result);
Output: }
int sum() Value returned
{ to main function
int a=5,b=9;
return a+b;
}
22

Different Aspect of Function Calling


3. Function with arguments/parameters and without return value:
Say you want to calculate sum of two numbers by importing parameters from main function.
So you have to pass the parameters (a and b in this example) to sum( ). As the printing will be
done in user defined function, you don’t need to return any value to main function. Hence the
function return type is void here.
int main()
{
int a=5,b=9;
printf("Going to calculate the sum of two numbers:\n");
sum(a,b);
}
void sum(int a, int b)
Output: {
int result = a+b;
printf("result = %d", result);
}
23

Different Aspect of Function Calling


4. Function with arguments/parameters and with return value:
Say you want to calculate sum of two numbers by importing parameters from main function.
So you have to pass the parameters (a and b in this example) to sum( ). Also you want to print
the sum in main function. In this case, you will have to return the result value to main
function. Hence the function return type is int here.
int main()
{
int a=5,b=9;
printf("Going to calculate the sum of two numbers:\n");
int result = sum(a,b);
printf("result = %d", result);
}
Output: int sum(int a, int b)
{
return a+b;
}
24

Parameter Passing in Function


The parameters of functions can be passed in two ways:
❑ Call by value: A copy of the variable is passed to the function. (all of the previous
examples where parameters were passed in user defined function are done by call by
value)
❑ Call by reference: An address of the variable is passed to the function.

Call by reference is preferred when we have to return more than one variable, like in C programming where
we can only return one variable at a time. Call by reference can be achieved via pointers.

Call by reference via pointer is discussed in detail


in pointer slide.
Page (17-20)
25

Passing Array to Function


❑ Array elements can be passed to a function by calling the function by value, or by reference
❑ In the call by value we pass values of array elements to the function
❑ In the call by reference we pass addresses of array elements to the function
❑ As we did not see call by reference yet, we will see that later
26

Passing Array to Function


❑ Consider the following syntax to pass an array to the function.
function_name(arrayname);

❑ 3 ways to declare a function that receives an array as an argument


• return_type function_name(data_type arrayname[])
Declaring blank subscript notation [] is the widely used technique.

• return_type function_name(data_type arrayname[SIZE])


Optionally, we can define size in subscript notation [].

• return_type function_name(data_type *arrayname)


You can also use the concept of a pointer.
27

Passing Array to Function


#include<stdio.h>
int main(){
int i=0,min=0;
int numbers[]={4,5,7,3,8,9}; //declaration of array
min=min_array(numbers, 6); //passing array with size. Then arr[ ] will receive numbers in the min_array.
printf("minimum number is %d \n",min);
return 0;
}
Determining minimum value in an array
int min_array(int arr[ ],int size){ using user defined function. The function here
int min=arr[0];
int i=0; is called by reference (address).
for(i=1;i<size;i++){ Note: The array name itself is the address of first element of that
if(min>arr[i]){ array. For example if array name is number then you can say
min=arr[i]; that number is equivalent to the &number[0].
}
}
return min;
}
28

Passing Array to Function


#include <stdio.h>
void disp( char ch)
{ The function here is called by value.
printf("%c ", ch); First, the ch receives arr[0] and the value of arr[0] will be
} printed. Then ch will receive arr[1] and will print it. This
process will be repeated till arr[9].
int main()
{
char arr[ ] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int i=0; i<10; i++)
{ Output
disp (arr[i]);
}

return 0;
}
29

Passing Array to Function using Pointer

Please Go to Pointer Slide- Page 30.


30

Advantages of User Defined Function

• User defined functions helps to decompose the large program into small segments which
makes programmer easy to understand, maintain and debug.

• If repeated code occurs in a program. Function can be used to include those codes and
execute when needed by calling that function.

• Programmer working on large project can divide the workload by making different
functions.
31

Recursion
Recursion: Recursion is the process of calling a function itself repeatedly until a particular
condition is met. A function that calls itself directly or indirectly is called a recursive function
and such kind of function calls are called recursive calls. Syntax:

void recursion()
{ recursion(); /* function calls itself */
}
int main()
{
recursion(); /* function call */
}

Note: while using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
32

Recursion
#include <stdio.h> int fact(int n)
#include <stdlib.h> {
if (n==0)
{
int main() return 0;
{ }
int n,f; else if ( n == 1)
printf("Enter the number whose factorial {
you want to calculate: "); return 1;
scanf("%d",&n); }
else
f = fact(n); {
printf("factorial = %d",f); return n*fact(n-1);
} }
}
33

Recursion
34

Recursion

5*factorial(4)
5*(4*factorial(3))
5*(4*(3*factorial(2)))
5*(4*(3*(2*factorial(1))))
5*4*3*2 = 120
35

Storage Classes in C
Every variable in C programming has two properties: type and storage class. Type refers to the
data type of a variable. And, storage class determines the scope, visibility and lifetime of a
variable.

There are 4 types of storage class:


▪ Automatic or local
▪ external
▪ static
▪ register
36

Automatic or Local variable


Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist only inside
the block in which it is declared.

#include <stdio.h>

int main( ) {
Here a, b, c and sum
int a=5, b=6, c=7; are automatic or local
int sum = a+b+c; variable.
printf("Summation=%d", sum);
return 0;
}
37

Automatic or Local variable


Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist only inside
the block in which it is declared.

#include <stdio.h>

int main( ) {
for (i = 0; i < 5; i++) {
printf("C programming\n");
} Here i is not declared in the main function. That is why We
return 0; cannot get result of this code and get a error mentioned above
} in red colour.
38

Automatic or Local variable


Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist
only inside the block in which it is declared.

#include <stdio.h>

int main( ) {
for (int i = 0; i < 5; i++) {
printf("C programming\n");
}
return 0; • Here, i is declared in for loop.
} • Hence value of i can be used to execute the body
of for loop.
39

Automatic or Local variable


Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist
only inside the block in which it is declared.

#include <stdio.h>

int main( ) {
for (int i = 0; i < 5; i++) {
printf("C programming\n");
• Though i is declared in the program, it will still
}
show error message.
printf("i=%d", i);
• Because i is declared inside for loop. Outside the
return 0;
block, it is undeclared.
}
• That means, here i is local variable for the for
loop block only, i can not be accessed outside
the for loop block.
40

Automatic or Local variable


Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist
only inside the block in which it is declared.

#include <stdio.h>

int main( ) {
int i;
for ( i = 0; i < 5; i++) {
printf("C programming\n"); • Here i is declared inside the main function.
} • Hence i can be accessed in any part of the code
printf("i=%d", i); within main function.
return 0;
}
41

Automatic or Local variable


Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist
only inside the block in which it is declared.

#include <stdio.h>

int main( ) {
int i;
for ( i = 0; i < 5; i++) {
printf("C programming\n");
} • Here i is declared inside the main function.
printf("i=%d", i); • Hence i can be accessed in any part of the code
return 0; within main function.
}
42

Automatic or Local variable


Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist
only inside the block in which it is declared.

int main() {
int a=5, b=5;
printf("Summation = %d", sum);
}

void func() {
int sum;
sum = a + b; • Here a and b are local variable for main function.
} Hence a and b can not be accessed outside the main
function.
• sum is local variable of func( ). Hence sum can not
be accessed outside of this user defined function
43

Automatic or Local variable


Local Variable
The variables declared inside a block are automatic or local variables. The local variables exist
only inside the block in which it is declared.

int main() {
int a=5, b=5, result;
result = func(a,b);
printf("Summation = %d", result);
}
• To solve the previous problem, we can pass the
void func(int a, int b) { variables from main function to user defined function
int sum; by calling the function.
sum = a + b; • Note: a and b in main ( ) are different than a and b in
return sum; func ( ). Each of these variable might hold same
} name but they are local to only their residence
function.
44

External or Global variable


Global Variable
Variables that are declared outside of all functions are known as external or global variables.
They are accessible from any function inside the program.

int a=5;
int main() {
a++;
func();
}
• Here a is declared outside of all functions [ main ( )
void func() { and func ( ) ]. Hence a can be accessed anywhere in
int result; the code. Here a is global variable.
result = ++a;
printf("a = %d", result);
}
45

Static variable
Static Variable
A static variable is declared by using the static keyword. The value of a static variable persists
until the end of the program. Syntax: static datatype variable_name;

int main()
{
display();
display();
}
void display() • During the first function call, the value of c is
{ initialized to 1. Its value is increased by 5. Now, the
static int c = 1; value of c is 6, which is printed on the screen.
c += 5; • During the second function call, c is not initialized
printf("c=%d\n",c); to 1 again. It's because c is a static variable. The
} value c is increased by 5. Now, its value will be 11,
which is printed on the screen.
46

Register variable
The register Storage Class

• The register storage class is used to define local variables that should be stored in a
register instead of RAM.

• This makes the use of register variables to be much faster than that of the variables stored
in the memory during the runtime of the program.

• Syntax: register datatype variable_name;

• Usually, a few variables which are to be accessed very frequently in a program are declared
with the register keyword which improves the running time of the program.

• An important and interesting point to be noted here is that we cannot obtain the address of
a register variable using pointers.

You might also like