Function:

In C programming, a function is a block of code that performs a specific task and can be called from other parts of the program. It helps organize code, promote reusability, and improve readability.

In other words function can be defined as function is a block of code that performs a specific task. It allows you to divide a large program into smaller, manageable pieces.

Advantages of Functions

The advantages of functions in C programming are suggested as below

  • Functions make a program easier to read. Big programs are often hard to understand.Dividing the code into small functions helps keep it neat, clear, and easy to use again.
  • A function helps reduce the size of a program because it can be used in many places without writing the same code again.
  • Functions make the code modular, meaning the whole program is split into small parts. Each part does a specific job, which makes it easier to build and fix.
  • In top-down structured programming, dividing a program into functions is more efficient and easier to understand.
  • Multiple programmers can work on different functions of the same program at the same time.

Declaration or Syntax of a function

return_type function_name(parameter_list);

Explanations

  • return_type: The data type of the value the function returns (e.g., int, float, void for no return).
  • function_name: The unique name of the function.
  • parameter_list: The list of parameters with their data types (e.g., int a, float b). Can be empty if no parameters.
  • Semicolon (;) ends the declaration.

Example of a function declaration

#include <stdio.h>
// Function declarations
int add(int a, int b);        // Declares a function returning int, taking two int parameters
void printMessage();          // Declares a function with no return value and no parameters
int main() {
int sum = add(5, 3);           // Function call
printf("Sum: %d\n", sum);
printMessage();               // Function call
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
void printMessage() {
printf("Hello, World!\n");
}

Components of functions 

In C programming, a function is a block of code designed to perform a specific task, and it consists of several components that define its structure and behavior. Since your recent questions focused on functions in C and Dev-C++, I’ll explain the components clearly, with an example tailored to this context. Below are the components of a function in C, including details relevant to function declaration and definition (as per your previous queries).

Components of a Function in C:

  1. Return Type:
    • Specifies the data type of the value the function returns to the caller.
    • Common types: int, float, double, char, void (no return value).
    • If omitted, older C standards default to int, but this is not recommended.
    • Example: In int sum(int a, int b), int is the return type, indicating the function returns an integer.
    • Purpose: Informs the compiler what type of value to expect when the function is called.
  2. Function Name:
    • A unique identifier used to call the function.
    • Follows C naming rules: letters, digits, underscores; cannot start with a digit; case-sensitive.
    • Should be descriptive (e.g., calculateSum instead of cs).
    • Example: In int sum(int a, int b), sum is the function name.
    • Purpose: Allows the function to be referenced and invoked in the program.
  3. Parameter List:
    • Defines the input variables (parameters) the function accepts, including their data types and names.
    • Enclosed in parentheses () after the function name.
    • Can be empty (void or ()) if no parameters are needed.
    • Parameters act as local variables inside the function.
    • Example: In int sum(int a, int b), (int a, int b) specifies two integer parameters.
    • Purpose: Enables the function to process external data dynamically.
  4. Function Body:
    • The block of code enclosed in curly braces {} that contains the function’s logic or operations.
    • Includes statements, calculations, loops, conditionals, or calls to other functions.
    • Defines what the function does when called.
    • Example: In int sum(int a, int b) { return a + b; }, { return a + b; } is the body.
    • Purpose: Executes the task the function is designed.
  5. Return Statement (Optional):
    • Sends a value back to the caller, matching the return type.
    • For void functions, return can be used to exit early, or omitted entirely.
    • Non-void functions must return a value unless they never terminate (e.g., infinite loops).
    • Example: In int sum(int a, int b) { return a + b; }, return a + b; returns the sum.
    • Purpose: Provides the output of the function to the calling code.
  6. Function Declaration/Prototype (Contextual Component):
    • While not part of the function definition itself, a declaration is often associated with functions.
    • Specifies the return type, function name, and parameter types (without the body) before the function is used.
    • Example: int sum(int a, int b); at the top of the code.
    • Purpose: Informs the compiler about the function’s signature if it’s defined later or in another file.

Types of Functions 

In C programming, functions can be classified into different types based on various criteria, such as their purpose, structure, or how they are defined and used.

Based on Who Defines Them. Functions can be categorized into two types these library functions and user-defined functions

  1. Library functions: In C programming, a library function is a predefined function provided by the C standard library or other libraries included with a C compiler. These functions are designed to perform common tasks, such as input/output operations, mathematical computations, string manipulation, memory management, and more. They are part of header files (e.g., stdio.h, math.h, string.h) and can be used by including the appropriate header file in your program.

Common  Library Functions: Library functions are grouped in header files based on their purpose. Here are some key header files and their associated functions:

  • <stdio.h> (Standard Input/Output):
  • printf(): Prints formatted output to the console.
  • scanf(): Reads formatted input from the console.
  • getchar(): Reads a single character.
  • <math.h> (Mathematical Functions):
  • sqrt(): Computes the square root.
  • pow(): Raises a number to a power.
  • sin(), cos(): Trigonometric functions.
  • <string.h> (String Manipulation):
  • strlen(): Returns the length of a string.
  • strcpy(): Copies one string to another.
  • strcmp(): Compares two strings.
  • <stdlib.h> (General Utilities):
  • malloc(), free(): Memory allocation and deallocation.
  • rand(): Generates a random number.
  • exit(): Terminates the program.
  • <time.h> (Date and Time):
  • time(): Returns the current time.
  • localtime(): Converts time to a local time structure.

Example of Library Functions in Dev-C++:

#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
// Using <stdio.h> functions
printf("Library Function Example\n");
// Using <math.h> function
double num = 25.0;
double squareRoot = sqrt(num); // sqrt from math.h
printf("Square root of %.2lf is %.2lf\n", num, squareRoot);
// Using <string.h> functions
char str[] = "Hello, C!";
int length = strlen(str); // strlen from string.h
printf("Length of '%s' is %d\n", str, length);
return 0;
}

    2. User-defined function : 

In C programming, a user-defined function is a function that the programmer creates to do a specific task. It is different from the built-in library functions in C. These functions help make the code more organized, reusable, and easier to manage.

Declaration of user define functions 
return_type function_name(parameter_list) {
// Function body
// Code to perform the task
return value; // Optional, based on return type
}

Example of a User-defined Function:

#include <stdio.h>
// Function Declaration
void greet();
// Main function
int main() {
greet(); // Function call
return 0;
}
// Function Definition
void greet() {
printf("Hello, welcome to C programming!\n");
}

Explanation:

  • Function Declaration (Prototype) →void greet(); tells the compiler that there is a function named greet that returns nothing.
  • Function Definition → The block of code that performs the task (printf(); in this case).
  • Function Call → Executes the function when needed (greet(); in main() ).

3. Recursive function

A recursive function in C is a function that calls itself either directly or indirectly to solve a problem.It is often used when a problem can be broken down into smaller, similar subproblems. Every recursive function must have a base condition (or stopping condition) to prevent infinite calls.

Write a program to find the factorial of a number using a recursive method.

#include <stdio.h>
// Recursive function to calculate factorial
int factorial(int n) {
if (n == 0) // Base condition: factorial of 0 is 1
return 1;
else
return n * factorial(n - 1); // Recursive call
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d is %d\n", num, factorial(num));
}
return 0;
}

Different types of function calls:
In C programming, there are mainly two types of function calls based on how arguments are passed from the calling function to the called function.

1. Function call by value(or passin arguments by value)
2. Function call by reference(pass Arguments by Address)

Function call by value(or passing arguments by value):
A function call by value in C is a method of passing arguments to a function where a copy of the actual value is sent to the function.

  • The function works with this copy, so changes made inside the function do not affect the original variables in the calling function.
  • This method is safe because the original data remains unchanged.
  • Example: Function Call by Value
#include <stdio.h>
// Function that changes the value of x
void changeValue(int x) {
x = x + 10; // only changes the local copy
printf("Inside function: x = %d\n", x);
}
int main() {
int a = 5;
printf("Before function call: a = %d\n", a);
changeValue(a); // call by value
printf("After function call: a = %d\n", a); // original value is unchanged
return 0;
}

Function call by reference(pass Arguments by Address)

A function call by reference in C is a method of passing arguments where the address of the variable is sent to the function.

  • The function works directly with the original variable using its address.
  • Changes made inside the function affect the original variable in the calling function.
  • This method is memory-efficient, but it must be used with care because it can modify the original data.
  • Example: Function Call by Reference
#include <stdio.h>
// Function that changes the value of x using a pointer
void changeValue(int *x) {
*x = *x + 10; // changes the original variable
printf("Inside function: x = %d\n", *x);
}
int main() {
int a = 5;
printf("Before function call: a = %d\n", a);
changeValue(&a); // call by reference (passing address)
printf("After function call: a = %d\n", a); // original value is changed
return 0;
}

WAP to swap the values of the two variables using call by reference.

#include <stdio.h>
// Function to swap values using pointers
void swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a, b;
// Input values
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
// Call by reference
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}

Comparison Between Single-Dimensional and Multidimensional Arrays

Single-Dimensional ArrayMultidimensional Array
Stores data in a single row (linear structure).Stores data in rows, columns, or layers.
Requires one index to access elements.Requires two or more indexes.
Linear (like a list).Tabular (2D), Cubical (3D), or higher.
int arr[5] = {10,20,30,40,50};int matrix[2][3] = {{1,2,3},{4,5,6}};
arr[2] = 30matrix[1][2] = 6
Less memory, simple to manage.More memory, complex to manage.
Easy to declare and use.More complex due to multiple dimensions.
Used for lists, marks, IDs, and simple storage.Used for matrices, tables, images, and simulations.

 Arrays and strings:

In programming, a string is a special type of array of characters.This means a string is basically a collection (sequence) of characters stored together in memory, just like how elements are stored in an array.

In C programming, a string is an array of characters that always ends with a special character called the null character (\0). This null character tells the compiler where the string ends.

 


 
How can strings be initialized?
A string in C can be initialized in different ways, since it is basically an array of characters ending with a null character (\0). The most common method is to assign a string constant directly, for example
 
char str[] = "Hello";
The compiler automatically adds the null character at the end. Another way is to declare a character array with a fixed size, such as
 char str[10] = "Hello";
which stores the word “Hello” followed by \0 and leaves extra unused space. Strings can also be initialized by listing individual characters like
char str[] = {'H','e','l','l','o','\0'};
All these methods create strings, but the most common and easiest way is to use double quotes with an array declaration.
Example
#include <stdio.h>
int main() {
char str[] = "Hello"; // String initialized directly
printf("%s", str); // Output: Hello
return 0;
}
WAP to display string initialization.
#include <stdio.h>
int main() {
char str1[] = "Hello";// Method 1: Direct initialization
char str2[10] = "World";// Method 2: Fixed size array
char str3[] = {'C', 'P', 'R', 'O', 'G', '\0'};// Method 3: Character array with null character
char *str4 = "Programming";// Method 4: Pointer to string literal
printf("String 1: %s\n", str1);// Displaying the strings
printf("String 2: %s\n", str2);// Displaying the strings
printf("String 3: %s\n", str3);// Displaying the strings
printf("String 4: %s\n", str4);// Displaying the strings
return 0;
}
output:
String 1: Hello
String 2: World
String 3: CPROG
String 4: Programming

WAP to read the names of 5 different people using an array of strings and display them.

#include <stdio.h>
int main() {
char names[5][20]; // Array to store 5 names, each up to 19 characters
int i;
// Reading names from the user
printf("Enter the names of 5 people:\n");
for(i = 0; i < 5; i++) {
printf("Name %d: ", i + 1);
scanf("%s", names[i]); // Read string (without spaces)
}
// Displaying the names
printf("\nThe names entered are:\n");
for(i = 0; i < 5; i++) {
printf("%d. %s\n", i + 1, names[i]);
}
return 0;
}
out put of program:
Enter the names of 5 people:
Name 1: Ram
Name 2: Sita
Name 3: Gopal
Name 4: Laxmi
Name 5: Hari
The names entered are:
1. Ram
2. Sita
3. Gopal
4. Laxmi
5. Hari
 
 
 

 

 
 
 

Compiled by: Er. Basant Kumar Yadav

error: Content is protected !!
Scroll to Top