0% found this document useful (0 votes)
9 views11 pages

Functions

The document provides an overview of functions in C programming, detailing their types, components, and usage, including user-defined and library functions. It explains function declarations, definitions, calls, parameters, arguments, and return values, along with examples for each concept. Additionally, it covers the benefits of using library functions and lists common functions categorized by their header files.

Uploaded by

hbodded1
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)
9 views11 pages

Functions

The document provides an overview of functions in C programming, detailing their types, components, and usage, including user-defined and library functions. It explains function declarations, definitions, calls, parameters, arguments, and return values, along with examples for each concept. Additionally, it covers the benefits of using library functions and lists common functions categorized by their header files.

Uploaded by

hbodded1
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

Functions in C:

A function is a self-contained block of code that performs a specific task.


There are two types of functions in C:

User-defined Functions → created by the programmer.

1.​ Function Declaration (Prototype)


A function declaration tells the compiler:
●​ The function’s name
●​ Its return type
●​ The number and type of parameters
It helps the compiler check that function calls are made correctly.
Example
#include <stdio.h>

// Function Declaration
float areaOfCircle(float radius);

int main() {
float r = 5.0;
float area = areaOfCircle(r); // Function Call
printf("Area = %.2f\n", area);
return 0;
}

// Function Definition
float areaOfCircle(float radius) {
return 3.14 * radius * radius;
}

✅floatHere,​
areaOfCircle(float radius); → is a function declaration.​
It informs the compiler before main() that a function with that signature exists.

2.​ Function Definition


A function definition provides the actual body (code) that performs the work.​
It includes statements, logic, and (optionally) a return statement.

Example
#include <stdio.h>
// Function Definition
void displayMessage() {
printf("Hello! Welcome to the world of C functions.\n");
}
int main() {
displayMessage(); // Function Call
return 0;
}

✅voidHere,​
displayMessage() { ... } is the function definition —​
it tells the compiler what the function does.

3.​ Function Call

💻 A function call tells the program to execute the code inside a function.
Example
#include <stdio.h>

void greetUser() {
printf("Good Morning, User!\n");
}

int main() {
greetUser(); // Function Call
greetUser(); // Can be called multiple times
return 0;
}

✅theEach time you call greetUser();,​


control jumps to that function and executes it.

4.​ Calling Function and Called Function

●​ Calling Function → The function that invokes another function.


●​ Called Function → The function that is executed when called.​

💻 Example
#include <stdio.h>
// Called Function
void displaySquare(int n) {
printf("Square of %d = %d\n", n, n * n);
}
int main() {
// Calling Function
displaySquare(6);
return 0;
}
✅✅main() → Calling Function​
displaySquare() → Called Function

5.​ Parameters (Formal Parameters)


Parameters are variables listed in the function definition that receive values from
the calling function.

Example
#include <stdio.h>
void printSum(int a, int b) { // Parameters: a, b
printf("Sum = %d\n", a + b);
}
int main() {
printSum(10, 20); // Function Call with Arguments
return 0;
}
Here,​
a and b → parameters (formal arguments) used within the function.

6.​ Arguments (Actual Parameters)


Arguments are actual values passed to a function during a call.​
They are copied into the function’s parameters.

Example
#include <stdio.h>
void multiply(int x, int y) {
printf("Product = %d\n", x * y);
}
int main() {
multiply(4, 5); // Arguments: 4, 5
multiply(7, 3); // Arguments: 7, 3
return 0;
}

Here,​
4, 5 and 7, 3 → arguments passed to multiply() function.

7.​ Return Value


A return value is the result a function sends back to the calling function using the
return statement.
Example
#include <stdio.h>

// Function returning a value


int findMax(int a, int b) {
if (a > b)
return a;
else
return b;
}

int main() {
int m = findMax(25, 40);
printf("Maximum = %d\n", m);
return 0;
}

Here,
findMax() returns an integer to main(), which is printed.

Types of functions:

1. Function with No Arguments and No Return Value


●​ Doesn’t take any input from the user.
●​ Doesn’t return any output to the calling function.​
Used for performing fixed operations.​

Example:
#include <stdio.h>
void greet() {
printf("Hello! Welcome to C programming.\n");
}
int main() {
greet(); // Function call
return 0;
}
Output:
Hello! Welcome to C programming.

2. Function with Arguments but No Return Value


●​ Takes inputs (parameters) but does not return a value.
●​ Commonly used for displaying or processing data.​

Example:
#include <stdio.h>
void add(int a, int b) {
int sum = a + b;
printf("Sum = %d\n", sum);
}
int main() {
add(5, 10); // Passing arguments
return 0;
}
Output:
Sum = 15

3. Function with No Arguments but Returns a Value


●​ Takes no input but returns a result.
●​ Used when values are obtained inside the function (e.g., user input).​

Example:
#include <stdio.h>
int getNumber() {
int x;
printf("Enter a number: ");
scanf("%d", &x);
return x; // returns value to main
}

int main() {
int num = getNumber();
printf("You entered: %d\n", num);
return 0;
}

Output:
Enter a number: 25
You entered: 25

4. Function with Arguments and Return Value


●​ Takes inputs and returns a result.
●​ Most commonly used logic in real applications.​

Example:
#include <stdio.h>

int multiply(int a, int b) {


return a * b;
}

int main() {
int x = 6, y = 7;
int result = multiply(x, y);
printf("Product = %d\n", result);
return 0;
}

Output:
Product = 42

Components of a Function
Term Description Example

Function Tells the compiler about function name, int add(int, int);
Declaration return type, and parameters before its use.
(Prototype)

Function Definition Contains the actual code (body) of the int add(int a, int b) {
function. return a + b; }

Function Call Invokes the function to perform its task. sum = add(10, 20);

Calling Function The function that calls another function. main() calls add()

Called Function The function being called. add()

Parameter Variable declared in the function int add(int a, int b) → a, b


definition to receive values. are parameters

Argument Actual values passed during a function add(10, 20) → 10, 20 are
call. arguments

Return Value The value that a function gives back to return a + b;


the calling function.
Library Functions in C:
A library function is a predefined function provided by the C standard library (stdlib).​
These functions are already compiled, tested, and stored in the C libraries —​
we just use them in our programs by including the proper header file.

✅we Weonlydon’t write the code for these functions —​


call them when needed.

Examples:
Function Header File Purpose

printf() <stdio.h> Prints output on the screen

scanf() <stdio.h> Reads input from the user

sqrt() <math.h> Returns square root

strlen() <string.h> Finds length of a string

strcpy() <string.h> Copies one string into another

toupper() <ctype.h> Converts character to uppercase

malloc() <stdlib.h> Allocates memory dynamically

exit() <stdlib.h> Terminates program execution

time() <time.h> Returns current time

rand() <stdlib.h> Generates a random number

⚙️ 2️⃣ Why Use Library Functions?


✅✅Saves time (no need to write code from scratch)​

✅ Reliable and tested by experts​

✅ Portable across all systems​


Helps maintain code readability

🧩 3️⃣ How to Use Library Functions


To use a library function:
1.​ Include its header file using #include.​

2.​ Call the function by its name with required arguments.​

💻 Example 1: Using sqrt() from <math.h>


#include <stdio.h>
#include <math.h>

int main() {
double num = 25.0;
double result = sqrt(num); // Library function
printf("Square root of %.2f = %.2f\n", num, result);
return 0;
}

🧾 Output:
Square root of 25.00 = 5.00

📌WhenNote:​compiling, link the math library:​


gcc example.c -o example -lm

🔢 4️⃣ Categories of Library Functions


Category Header Examples
File

Input / Output <stdio.h> printf(), scanf(), gets(), puts(), fopen(), fclose()

String Handling <string.h> strlen(), strcpy(), strcmp(), strcat(), strrev()

Mathematical <math.h> sqrt(), pow(), ceil(), floor(), fabs()

Character Handling <ctype.h> toupper(), tolower(), isalpha(), isdigit()

Memory <stdlib.h> malloc(), calloc(), realloc(), free()


Management

General Utilities <stdlib.h> exit(), rand(), abs(), atoi()

Date and Time <time.h> time(), clock(), difftime(), ctime()


File Handling <stdio.h> fopen(), fprintf(), fscanf(), fclose()

💻 5️⃣ Example 2: String Library Functions


#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello";
char str2[20] = "World";

printf("Length of str1 = %zu\n", strlen(str1));


strcpy(str2, str1);
printf("After copying, str2 = %s\n", str2);

strcat(str1, " C");


printf("After concatenation, str1 = %s\n", str1);

return 0;
}

🧾 Output:
Length of str1 = 5
After copying, str2 = Hello
After concatenation, str1 = Hello C

💻 6️⃣ Example 3: Character Library Functions


#include <stdio.h>
#include <ctype.h>

int main() {
char ch = 'a';

if (isalpha(ch))
printf("%c is an alphabet\n", ch);
printf("Uppercase: %c\n", toupper(ch));
printf("Lowercase: %c\n", tolower('G'));

return 0;
}
🧾 Output:
a is an alphabet
Uppercase: A
Lowercase: g

💻 7️⃣ Example 4: Memory & Random Number Functions


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
srand(time(0)); // seed for random
int randomNum = rand() % 100; // random 0–99
printf("Random number: %d\n", randomNum);

int *ptr = (int*)malloc(5 * sizeof(int));


if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
} else {
printf("Memory allocated successfully!\n");
free(ptr);
}

return 0;
}

🧾 Output:
Random number: 47
Memory allocated successfully!

Example 5: Date and Time Library Functions


#include <stdio.h>
#include <time.h>

int main() {
time_t currentTime;
time(&currentTime); // get current time
printf("Current local time: %s", ctime(&currentTime));
return 0;
}

🧾 Output (example):
Current local time: Wed Oct 15 [Link] 2025

Summary Table
Category Header File Common Functions

Input/Output <stdio.h> printf(), scanf()

String <string.h> strlen(), strcpy(), strcmp()

Math <math.h> sqrt(), pow(), ceil(), floor()

Character <ctype.h> isalpha(), isdigit(), toupper()

General Utilities <stdlib.h> malloc(), rand(), exit()

Time <time.h> time(), ctime()

✅ In short:
Library functions are the ready-made tools in C that make programming easier,
faster, and more reliable.

You might also like