functions_in_c_step_by_step presentation with code
fizzamansoor3
2 views
28 slides
Oct 31, 2025
Slide 1 of 28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
About This Presentation
functions_in_c_step_by_step presentation with code
Size: 386.15 KB
Language: en
Added: Oct 31, 2025
Slides: 28 pages
Slide Content
Functions in C — Step by Step
Outline What is a function ? Uses of Function Advantages of Function Function declaration vs definition vs call Function syntax and types of parameters/returns Pass-by-value vs pass-by-reference (pointers) Recursion and examples Scope, storage, and linkage Step-by-step example: write → compile → run Common errors and best practices Exercises
What is a function? A self-contained block of code that performs a specific task. Helps organize code, improve reuse and readability. Example roles: calculation, input/output wrapper, helper routines.
4 In short: A function is a group of statements that together perform a task. C functions are basic building blocks in a program. Long Answer: 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. Actually, Collection of these functions creates a C program
Classification Of Function Library function User define function - main() - printf () - scanf () - sqrt () - getchar () 5 A large program in c can be divided to many subprogram The subprogram posses a self contain components and have well define purpose . The subprogram is called as a function Basically a job of function is to do something C program contain at least one function which is main(). 2. Types of C functions
6 Standard Library Functions: Library functions in C language are inbuilt functions which are grouped together and placed in a common place called library. Each library function in C performs specific operation. The standard library functions are built-in functions in C programming to handle tasks such as mathematical computations, I/O processing, string handling etc . These functions are defined in the header file. When you include the header file, these functions are available for use. For example: ➤ The printf () is a standard library function to send formatted output to the screen (display output on the screen). This function is defined in " stdio.h " header file. ➤ There are other numerous library functions defined under " stdio.h ", such as scanf (), printf (), getchar () etc. Once you include " stdio.h " in your program, all these functions are available for use. User-defined Functions: As mentioned earlier, C allow programmers to define functions. Such functions created by the user are called user-defined functions. Depending upon the complexity and requirement of the program, you can create as many user-defined functions as you want.
7 C functions are used to avoid rewriting same logic/code again and again in a program . There is no limit in calling C functions to make use of same functionality wherever required . We can call functions any number of times in a program and from any place in a program . A large C program can easily be tracked when it is divided into functions . The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs. 3. Uses of C functions:
4. Advantages of function It is much easier to write a structured program where a large program can be divided into a smaller, simpler task. Allowing the code to be called many times Easier to read and update It is easier to debug a structured program where there error is easy to find and fix 8
9 C functions aspects syntax function definition Return_type function_name (arguments list) { Body of function; } function call function_name (arguments list); function declaration return_type function_name (argument list); There are 3 aspects in each C function. They are, Function declaration or prototype – this informs compiler about the function name, function parameters and return value’s data type. Function call - this calls the actual function Function definition – this contains all the statements to be executed. 5. C function declaration, function call and function definition:
10 As you know, functions should be declared and defined before calling in a C program. In the below program, function “square” is called from main function. The value of “m” is passed as argument to the function “square”. This value is multiplied by itself in this function and multiplied value “p” is returned to main function from function “square”. 6. Simple Example Program for C Function: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include< stdio.h > // function prototype, also called function declaration float square ( float x ); // main function, program starts from here int main( ) { float m, n ; printf ( "\ nEnter some number for finding square \n"); scanf ( "%f", &m ) ; // function call n = square ( m ) ; printf ( "\ nSquare of the given number %f is %f", m,n ); } float square ( float x ) // function definition { float p ; p = x * x ; return ( p ) ; } Enter some number for finding square 2 Square of the given number 2.000000 is 4.000000 Output: Enter some number for finding square 4 Square of the given number 4.000000 is 16.000000
11 #include < stdio.h > /* function declaration */ int max( int num1, int num2); int main () { /* local variable definition */ int a = 200; int b = 800; int ret; /* calling a function to get max value */ ret = max(a, b); printf ( "Max value is : %d\n", ret ); return 0; } /* function returning the max between two numbers */ int max( int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } We have kept max() along with main() and compiled the source code. While running the final executable, it would produce the following result − Max value is : 800 Output : Example 2
Example 3 1: #include < stdio.h > 2: 3: long cube(long x); /* Function prototype*/ 4: 5: long input, answer; 6: 7: int main( void ) 8: { 9: printf (“Enter an integer value: “); 10: scanf (“%d”, &input); 11: answer = cube(input); /* calling function*/ 12: printf (“\ nThe cube of % ld is %ld.\ n”, input, answer); 13: 14: return 0; 15: } 16: 17: long cube(long x) /* Function definition*/ 18: { 19: long x_cubed ; 20: 21: x_cubed = x * x * x; 22: return x_cubed ; 23: } Function names is cube Variable that are requires is long The variable to be passed on is X(has single arguments)—value can be passed to function so it can perform the specific task. It is called Output Enter an integer value : 4 The cube of 4 is 64. Return data type Arguments/formal parameter Actual parameters arguments 12
13 7. How To Call C Functions In A Program? There are two ways that a C function can be called from a program. They are , Call by value Call by reference 1. Call By Value: In call by value method, the value of the variable is passed to the function as parameter. The value of the actual parameter can not be modified by formal parameter. Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.
14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include< stdio.h > // function prototype, also called function declaration void swap( int a, int b); int main() { int m = 22, n = 44; // calling swap function by value printf (" values before swap m = %d \ nand n = %d", m, n); swap(m, n); } void swap( int a, int b) { int tmp ; tmp = a; a = b; b = tmp ; printf (" \ nvalues after swap m = %d\n and n = %d", a, b); } values before swap m = 22 and n = 44 values after swap m = 44 and n = 22 In this program, the values of the variables “m” and “n” are passed to the function “swap”. These values are copied to formal parameters “a” and “b” in swap function and used. Example Program For C Function (Using Call By Value):
15 2 . Call by reference: In call by reference method, the address of the variable is passed to the function as parameter. The value of the actual parameter can be modified by formal parameter. Same memory is used for both actual and formal parameters since only address is used by both parameters 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #include< stdio.h > // function prototype, also called function declaration void swap( int *a, int *b); int main() { int m = 22, n = 44; // calling swap function by reference printf ("values before swap m = %d \n and n = %d", m,n ); swap(&m, &n); } void swap( int *a, int *b) { int tmp ; tmp = *a; *a = *b; *b = tmp ; printf ("\n values after swap a = %d \ nand b = %d", *a, *b); } Example Program For C Function (Using Call By Reference): In this program, the address of the variables “m” and “n” are passed to the function “swap”. These values are not copied to formal parameters “a” and “b” in swap function. Because, they are just holding the address of those variables. This address is used to access and change the values of the variables. values before swap m = 22 and n = 44 values after swap a = 44 and b = 22 Output:
16 Overview C functions are basic building blocks in every C program . There are 2 types of functions in C. They are, 1. Library functions 2. User defined functions Key points to remember while writing functions in C language: All C programs contain main() function which is mandatory. main() function is the function from where every C program is started to execute. Name of the function is unique in a C program. C Functions can be invoked from anywhere within a C program. There can any number of functions be created in a program. There is no limit on this. There is no limit in calling C functions in a program. All functions are called in sequence manner specified in main() function. One function can be called within another function. C functions can be called with or without arguments/parameters. These arguments are nothing but inputs to the functions.
17 C functions may or may not return values to calling functions. These values are nothing but output of the functions. When a function completes its task, program control is returned to the function from where it is called. There can be functions within functions. Before calling and defining a function, we have to declare function prototype in order to inform the compiler about the function name, function parameters and return value type. C function can return only one value to the calling function. When return data type of a function is “void”, then, it won’t return any values When return data type of a function is other than void such as “ int , float, double”, it returns value to the calling function. main() program comes to an end when there is no functions or commands to execute .
Declaration vs Definition vs Call Declaration (prototype): tells the compiler about function signature. Definition: the actual body/implementation of the function. Call: invoking the function from another place in code. Example: Declaration: int add(int a, int b); Definition: int add(int a,int b){ return a+b; } Call: int s = add(3,4);
Function syntax & return types General form: return_type function_name(parameter_list) { /* body */ } Return types can be any valid C type or void for no return. Parameter list can be empty or include typed parameters. Examples: void printHello(void); float area(float r); int *buildArray(int n); // returns pointer
Pass-by-value (default in C) C passes arguments by value — copies of values are passed. Modifying a parameter inside function doesn't change caller variable. Use pointers when you need to modify caller's data.
Pass-by-reference using pointers (example) // swap using pointers #include < stdio.h > void swap( int *a, int *b) { int tmp = *a; *a = *b; *b = tmp ; } int main() { int x = 5, y = 10; swap(&x, &y); // x becomes 10, y becomes 5 printf ("x=%d y=%d\n", x, y); return 0; }
Recursion Function that calls itself — useful for divide-and-conquer and tree algorithms. Must have a base case to stop recursion. Example: factorial
Factorial (recursive) #include < stdio.h > int fact( int n) { if (n <= 1) return 1; return n * fact(n-1); } int main() { printf ("5! = %d\n", fact(5)); return 0; }
Scope, storage and linkage Local variables: declared inside function — automatic storage (stack). Static variables: persist across calls, file-level if declared static. Global variables: accessible across functions (avoid if possible). Linkage: extern for cross-file access; static to limit linkage.
Full example: calculator functions #include < stdio.h > int add( int a,int b) { return a+b ; } int sub( int a,int b) { return a-b; } int mul ( int a,int b) { return a*b; } float divide( int a,int b) { return b==0 ? 0.0f : (float)a/b; } int main() { int x=10,y=3; printf ("add=%d sub=%d mul =%d div=%.2f\n", add( x,y ), sub( x,y ), mul ( x,y ), divide( x,y )); return 0; }
Common errors & debugging tips Missing prototype when function used before definition. Add prototypes. Type mismatch in parameters/return — enable compiler warnings. Uninitialized local variables. Segfaults from invalid pointer use. Use printf debugging or gdb for step-through.
Best practices Keep functions short and single-purpose. Use clear, descriptive names. Prefer const for read-only parameters where possible. Use prototypes in header files for modular code. Document behavior, side-effects, and ownership (who frees memory).
Exercises (try these) 1) Write a function to check if a number is prime. 2) Implement Fibonacci: iterative and recursive versions; compare performance. 3) Write a function that returns dynamically allocated array of first n squares. 4) Implement string reversal using pointers.