Problem Solving using C Language

0 of 77 lessons complete (0%)

Functions

Functions

A function is a self-contained block of statements that perform a coherent task of some kind. If you have a task that is always performed in the same way than instead of putting the same functionality at every point, we should make function and can call by just declaring function name.

Syntax of a Function in C:

return_type function_name(parameters) {
    // Function body (code to perform the task)
    return value;  // Optional, based on the return type
}
  • Return Type: Specifies the type of value the function will return (e.g., int, void, char).
  • Function Name: The name you use to call the function.
  • Parameters (Arguments): The inputs the function needs to perform its task (optional).
  • Body: The block of code that performs the task.

Definition of Function

  • Function Definition
  • Function name
  • Function type
  • List of parameters
  • Local variable declaration
  • Function statement
  • A return statement

Key Features of Functions:

  1. Modularity: Functions allow you to divide your code into smaller parts, each handling a specific task.
  2. Reusability: Once a function is written, it can be reused multiple times in a program without rewriting the code.
  3. Abstraction: A function encapsulates the logic it performs, so you can use it without needing to know its internal workings.
  4. Maintainability: Functions make it easier to manage and debug a program since you can test and fix individual parts separately.

Example 1:

#include<stdio.h>

void func1()
{
	printf("\nthis is func1");
}

int main()
{
	func1();
	printf("\nthis is first program with funtion");
	return 0;
}

Output:
This is func1
This is the first program with function

Example: Adding two number

#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main() {
    int x = 5, y = 10;
    int result = add(x, y);
    printf("Sum: %d\n", result);
    return 0;
}

Explanation:

  • int add(int a, int b): This defines a function named add that takes two integers (a and b) as parameters and returns an integer (int).
  • return a + b;: The function returns the sum of a and b.
  • add(x, y): This is how you call the function, passing x and y as arguments.

Function Types in C:

  1. Library Functions: Predefined functions provided by C’s standard library (e.g., printf(), scanf(), strlen()).
  2. User-Defined Functions: Functions you define yourself to perform specific tasks.

Important points about function

  •  A function gets called when the function name is followed by a semincolon.
  • A function is defined when function name is followed by a pair of braces in which one or more statements may be present.
  • Any function can be called from any other function. Even main can be called from other function.
  • A function calls itself such process known as recursion.