Functions in C

 

Functions in C

A function is a self-contained block of program statements that performs a particular task.

The concept of C programming is based on a combination of functions, and program execution begins from the special function main().

Functions such as scanf(), printf(), and main() that have been used in programs are all examples of functions.


Types of Functions in C

1. Library Functions

  • Predefined functions provided by C

  • Example: scanf(), printf(), strlen(), etc.

  • C provides many built-in library functions for common tasks

2. User-Defined Functions

  • Functions written by the programmer

  • Used to perform specific tasks

  • Help in modular programming and code reuse

Functions in C – Working and Importance

Working of Functions

  • When there are multiple functions in a program, each function is given:

    • A different name

    • A list of parameters

  • Whenever a function needs to be used:

    • We call it using the function name with suitable arguments.

    • The program control transfers to that function.

    • The statements inside the function execute.

    • After execution, control returns to the calling function at the same place from where it was called.

  • A function can also:

    • Call another function

    • That function can call yet another, and so on.


Why Functions Are Used

The use of functions provides several benefits:

1. Easy Understanding and Maintenance

  • Functions break programs into small manageable parts.

  • This makes the program easier to read, understand, and maintain.

2. Code Reuse / Code Sharing

  • The same function can be used whenever needed.

  • Avoids writing the same code multiple times.

  • Makes programs smaller and more efficient.

  • A well-written function can be reused in multiple programs.

  • The C standard library is an example of reusable functions.

3. Flexible Debugging

  • Functions make the code:

    • Shorter

    • More readable

  • Errors can be located and fixed more easily.

4. Data Protection

  • Local variables declared inside a function:

    • Are not accessible outside the function.

    • Exist only when the function executes.

  • This improves data security and control.

5. Supports Top-Down Design

  • Functions help in breaking a big task into smaller tasks.

  • Each smaller part is simple and manageable.

  • These parts are combined to achieve the original task.

6. Structured Programming

  • Functions help produce code that is:

    • Elegant

    • Organized

    • Readable


Using Functions in C

The following three components are associated with the use of functions:

1. Function Declaration (Function Prototype)

  • The declaration statement (also called a function prototype) identifies a function by specifying:

    • The function name

    • The list of arguments (parameters)

    • The type of data returned by the function

  • It informs the compiler about the function before it is used in the program.

Function Declaration Syntax in C

Syntax

return_data_type function_name(data_type var1, data_type var2, ...);

Examples

int max(int a, int b);
  • This function max returns the maximum of two integers.

  • a and b are called the arguments (parameters) of the function.

float average(int n, float a[]);
  • This function average finds the average of elements of array a of size n.


Important Notes

  • If a function does not return any value, use void as the return type.

  • The default return type of a function (if not specified) is int.

  • A function declaration is required if the called function is written after main() or later in the program.

  • The function name should not match any built-in library function names.

2. Function Definition

The function definition consists of:

  • A function header that identifies the function

  • Followed by the body of the function, which contains the statements to be executed


General Form of Function Definition

return_type function_name(parameters) { // statements to be executed }

Example of Function Definition

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

Note

  • The function sum returns the sum of a and b.

  • The return statement is used to send a value from the function back to the point where the function was called.

3. Function Calling Statement

The function calling statement is used to invoke (call) a function, either by passing parameters or without passing parameters.

Example of Function Call

add = sum(10, 30); int x = 10, y = 30; add = sum(x, y);
  • Here, x and y are called actual parameters (arguments passed during the function call).

  • The variables a and b in the function definition are called formal parameters.

  • The function sum() adds the given values (10 and 30) and returns the result, which is stored in the variable add.


Note

  • The function name, number of arguments, and data types of arguments must match the function definition.


Formal Parameters and Actual Parameters in C

Formal Parameters

  • The parameters/variables and their data types, as they appear in the function prototype or definition, are called formal parameters.

  • These act as placeholders for the values passed to the function.

  • Example: In the function definition sum(int a, int b), a and b are formal parameters.


Actual Parameters

  • The variables or expressions supplied in the function call that correspond to the formal parameters are called actual parameters.

  • These provide the real values that are passed to the function.

  • Example: In the call sum(x, y), x and y are actual parameters.


Passing Arguments in C

  • In normal C function calls, arguments are passed by value.

  • This means:

    • The function receives local copies of the argument values.

    • Changes made to parameters inside the function do not affect the original variables outside the function.



Example Programs using Functions


Factorial of a number using  a function and computing nCr using the function
#include <stdio.h>
long long int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++) f=f*i;
return(f);
}
int main()
{ int n,r,ncr;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the value of r\n");
scanf("%d",&r);
ncr=fact(n)/(fact(r)*fact(n-r));
printf("%dC%d=%d",n,r,ncr);
return 0;
}

Sample program to find power x^k using a function
#include <stdio.h>
int power(int x, int k)
{
int r=1,i;
for (i=1;i<=k;i++)
     r=r*x
return r;
}
int main()
{
Int x,k,p;
printf(“Enter x and k \n”);
scanf(“%d%d”,&x,&k);
p=power(x,k);
printf(“%d power %d= %d”,x,k,p);
}
Note: The variables used in calling the function are called actual arguments and the variables used in function header are called formal arguments.

Binary to decimal conversion using function(university question)
#include <stdio.h>
#include <math.h>
int convert(long long n)
 {
    int dec = 0, i = 0, rem;
    while (n != 0) {
        rem = n % 10;
        n /= 10;
        dec += rem * pow(2, i);
        ++i;
    }
    return dec;
}
int main()
{
    long long n;
    printf("Enter a binary number: ");
    scanf("%lld", &n);
    printf("%lld in binary = %d in decimal\n", n, convert(n));
    return 0;
}

Decimal to Binary conversion using a function  ( University Question)
#include <stdio.h>

void decimalToBinary(int num) {
    int binary[32];
    int i = 0;

    if (num == 0) {
        printf("0");
        return;
    }

    while (num > 0) {
        binary[i] = num % 2;
        num = num / 2;
        i++;
    }

    // Print binary in reverse order
    for (int j = i - 1; j >= 0; j--) {
        printf("%d", binary[j]);
    }
}

int main() {
    int num;

    printf("Enter a decimal number: ");
    scanf("%d", &num);

    printf("Binary equivalent: ");
    decimalToBinary(num);

    return 0;
}

Write a C Program to check if a given number is a strong number or not. A strong number is a number in which the sum of the factorial of the digits is equal to the number itself.
Eg:- 145: 1 !+4 !+5!: l +24+120=145
#include <stdio.h>

// Function to calculate factorial of a digit
int factorial(int n) {
    int fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

int main() {
    int num, temp, sum = 0;
    
    printf("Enter a number: ");
    scanf("%d", &num);

    temp = num;

    while (temp > 0) {
        int digit = temp % 10;
        sum += factorial(digit);
        temp /= 10;
    }

    if (sum == num)
        printf("%d is a Strong Number.\n", num);
    else
        printf("%d is not a Strong Number.\n", num);

    return 0;
}


Passing Arrays as Arguments to a Function in C

  • When an entire array is passed as an argument to a function, only the address of the array is passed, not a copy of the complete array.

  • When the function is called using the array name as an argument, the address of the first element of the array is given to the function.

  • This means that during execution, the function can modify the contents of the original array.

  • This behavior is an exception to the usual rule in C where arguments are passed by value.

  • Therefore, arrays in C are effectively passed by reference (address) to functions.


Example:
The following function modify(a[],i,x) will modify the i th element of the array with a value x.Note that the array element is modified in the main.
#include <stdio.h>
modify(int a[10],int i,int x)
{
  a[i]=x;
}
int main()
{
    int a[10]={10,20,12,11,34,25,67,30,50,70};
    int i;
    modify(a,6,100);
    for(i=0;i<10;i++) printf("%d\t",a[i]);
}
output:
10    20    12    11    34    25    100    30    50    70
Write a C program to find the largest and smallest element in an integer array using function. ( university question )
#include <stdio.h>
void arraysl(int a[],int n)
{
  int l,s,i;
   l=a[0];
   s=a[0];
  for(i=1;i<n;i++)
  {
   if(a[i]>l) l=a[i];
   if(a[i]<s) s=a[i];
   }
  printf("Smallest=%d  largest=%d \n",s,l);
}
int main()
{
 int a[100],n,i;
 printf("Enter the number of elements..:");
 scanf("%d",&n);
 printf("Enter the array elements....\n");
 for(i=0;i<n;i++)
 scanf("%d",&a[i]);
 arraysl(a,n);
}
Write a C program to find sum and average of an array of integers using user defined functions.(university question)
#include <stdio.h>
sum_average(int a[10],int n)
{
    int i;
    float sum,avg;
  for(i=0;i<n;i++)
  sum=sum+a[i];
  avg=sum/n;
  printf("Sum=%f Average =%f\n",sum,avg);
}
int main()
{
    int a[10]={10,20,12,11,34,25,67,30,50,70};
    int i;
    sum_average(a,10);

}

Write a C program that uses a function to sort an array of integers( university question)

#include <stdio.h>

// Function to sort the array
void sortArray(int arr[], int n) {
    int i, j, temp;

    for (i = 0; i < n - 1; i++) {
        for (j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap elements
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[100], n, i;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Call the sort function
    sortArray(arr, n);

    // Print the sorted array
    printf("Sorted array in ascending order:\n");
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

Write a function in C which takes a 2-Dimensional array storing a matrix of numbers and the order of the matrix (number of rows and columns) as arguments and displays the sum of the elements stored in each row. ( university question)
#include <stdio.h>
void sumrow(int a[5][5],int m,int n)
{
    int i,j,sum;
    printf("Sum of the elements in each row\n");
    for(i=0;i<5;i++)
    {sum=0;
      for(j=0;j<5;j++)
        sum=sum+a[i][j];
      printf("Sum of elements in row %d=%d\n",i,sum);
    }
}
int main()
{
    int a[5][5]={{1,2,3,4,5},{2,3,1,1,1},{2,2,2,2,2},{1,1,1,1,1},{2,3,4,1,1}};
    sumrow(a,5,5);
}
Functions help to modularize the program using functions and hence  reduce the code
Matrix multiplication program using functions
#include <stdio.h>
#include <stdlib.h>
void readmatrix(int X[50][50],int m,int n)
{
    int i,j;
    for(i=0;i<m;i++)
    for(j=0;j<n;j++)
    scanf("%d",&X[i][j]);
}
void printmatrix(int X[50][50],int m,int n)
{
    int i,j;
    for(i=0;i<m;i++)
    {
    for(j=0;j<n;j++)
    printf("%5d",X[i][j]);
    
    printf("\n");
    }
}
void multiplymatrix(int A[50][50],int m,int n,int B[50][50],int p,int q,int C[50][50])
{ int i,j,k;
for(i=0;i<m;i++)
    {
      for(j=0;j<q;j++)  
      { C[i][j]=0;
          for(k=0;k<n;k++)
          C[i][j]=C[i][j]+A[i][k]*B[k][j];
      }
    }
}
int main()
{
    int A[50][50],B[50][50],C[50][50],m,n,p,q,i,j,k;
    printf("Enter the dimensions of matrix A \n");
    scanf("%d%d",&m,&n);
    printf("Enter the dimensions of matrix A \n");
    scanf("%d%d",&p,&q);
    if ( n!=p ) { printf("Cannot multiply\n"); exit(0);}
    printf("Enter matrix A\n");
    readmatrix(A,m,n);
    printf("Enter matrix B\n");
    readmatrix(B,p,q);
    multiplymatrix(A,m,n,B,p,q,C);
    printf("The product matrix C\n");
    printmatrix(C,m,q);
    return 0;
}
 
Writing your functions for string handling
 int mystrlen(char str[100])
{
    int i;
    for (i=0;str[i]!='\0';i++);
     
     return(i);
 }
void mystrcpy(char s2[100],char s1[100])// copy from s1 to s2
{
    int i;
    for(i=0;s1[i]!='\0';i++)
        s2[i]=s1[i];
  s2[i]='\0';    
}

void mystrrev(char str[100])
{
    int i,j;
    char rstr[100];
    for(i=0;str[i]!='\0';i++);
    i--;
    for(j=0;i>=0;i--,j++) rstr[j]=str[i];
    rstr[j]='\0';
    
    mystrcpy(str,rstr);
}
 // with out using a temporary array
void mystrrev(char str[100])
{
    int i,j;
    char t;
    for(i=0;str[i]!='\0';i++);
    i--;
    for(j=0;j<i;i--,j++)
    {t=str[i];
    str[i]=str[j];
    str[j]=t;
    }
    
}
void mystrcat(char s1[100],char s2[100]) // concatenate s2 to s1
{
    
    int i,j;
    for(i=0;s1[i]!='\0';i++);
    
    for(j=0;s2[j]!='\0';j++,i++)
    s1[i]=s2[j];
    
    s1[i]='\0';
}
void mystrupper(char str[100])
{
    int i;
    for(i=0;str[i]!='\0';i++)
    if(str[i]>='a' && str[i]<='z') str[i]=str[i]-32;
    
}
 Develop a function that takes the two dates as input and compares them. The function should return 1 if date1 is earlier than date2, return 0 if date1 is later than date2. Write code to display whether date1 is earlier, later, or the same as date2 based on the function’s result.( University Question)
#include <stdio.h>

// Define a structure to store a date
struct Date {
    int day;
    int month;
    int year;
};

// Function to compare two dates
int compareDates(struct Date date1, struct Date date2) {
    if (date1.year < date2.year)
        return 1;
    else if (date1.year > date2.year)
        return 0;

    if (date1.month < date2.month)
        return 1;
    else if (date1.month > date2.month)
        return 0;

    if (date1.day < date2.day)
        return 1;
    else if (date1.day > date2.day)
        return 0;

    return -1; // Dates are equal
}

int main() {
    struct Date d1, d2;
    int result;

    // Input first date
    printf("Enter first date (dd mm yyyy): ");
    scanf("%d %d %d", &d1.day, &d1.month, &d1.year);

    // Input second date
    printf("Enter second date (dd mm yyyy): ");
    scanf("%d %d %d", &d2.day, &d2.month, &d2.year);

    // Compare the dates
    result = compareDates(d1, d2);

    // Display result
    if (result == 1)
        printf("Date1 is earlier than Date2\n");
    else if (result == 0)
        printf("Date1 is later than Date2\n");
    else
        printf("Both dates are the same\n");

    return 0;
}



Try the following programs using functions

1.Converting Fahrenheit to Celsius.
2.Binary to decimal using function.
3.Finding x^k , use x and k as arguments.
4.Function to reverse a number.
5. Çheck whether a given year is leap year or not.( return 0 or 1)
6.Write a function big() to find the biggest of two numbers and use it to find biggest of three numbers.
7.Write a function IsPrime(n) which will return 1 if the number is prime else it will return 0.
8.Sort array of integers( bubble sort-use array and n as arguments)
9.Add a string to the end of another string with out using library function.(concatenation-uq)
10.Copy one string to another with out using library function.(uq)
11.Write a function to reverse a string and use it to check whether the given string is palindrome or not.
12.Modify a char in a particular position of a string. Use position and char as argument.
13.Find maximum value in an array.( use array as arguments)
14.Write a function in C which takes a 2-Dimensional array storing a matrix of numbers and
the order of the matrix (number of rows and columns) as arguments and displays the sum
of the elements stored in each row.(uq)
15.Write matrix addition of 3 matrices A,B and C. write functions for reading and printing matrices.
16.Write functions to convert feet to inches and inches to centimeters. Write a program which will read feet and convert it into centimeters using the two functions.(uq)
17.Factorial of a given number.
18.Use the factorial function to compute nCr.
19.Use the factorial and power function to compute the series 1-x^2/2!+x^4/4!-x^6/6!...n.
20.Write a function to find the decimal equivalent of a binary number.(uq)
21.Write a function in C which takes a 2-Dimensional array storing a matrix of numbers and the order of the matrix (number of rows and columns) as arguments and displays the sum of the elements stored in each row. ( uq).
22.Write an easy to read C program to find the value of a mathematical function
f which is defined as follows. f(n) = n! / (sum of factors of n), if n is not prime and f(n) = n! / (sum of digits of n), if n is prime. 
23.Write a C program to find sum and average of an array of integers using user defined functions.(uq)
24.Generate the series 2,5,12,20,30...etc ( Hint : nth term is n^2 +n ). Write a function which will return the n th term of this series and use this to generate the series.
25.Write a function which will take a string and a character as arguments and return the number of occurrence of the character in the string.


Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays