0% found this document useful (0 votes)
5 views

C Functions Unit 6

The document provides an overview of functions in C programming, explaining their advantages, aspects, and types, including library functions and user-defined functions. It details the syntax for function declaration, calling, and definition, along with examples of various string handling functions from the string.h library. Additionally, it covers string manipulation operations, such as concatenation, comparison, and length calculation, using specific C functions.

Uploaded by

dinesh22.b4u
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C Functions Unit 6

The document provides an overview of functions in C programming, explaining their advantages, aspects, and types, including library functions and user-defined functions. It details the syntax for function declaration, calling, and definition, along with examples of various string handling functions from the string.h library. Additionally, it covers string manipulation operations, such as concatenation, comparison, and length calculation, using specific C functions.

Uploaded by

dinesh22.b4u
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

C Functions

In c, we can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed
by {}. A function can be called multiple times to provide reusability and
modularity to the C program. In other words, we can say that the collection
of functions creates a program. The function is also known
as procedureor subroutinein other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and


again in a program.
o We can call C functions any number of times in a program and from
any place in a program.
o We can track a large C program easily when it is divided into multiple
functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Function Aspects

There are three aspects of a C function.

o Function declaration A function must be declared globally in a c


program to tell the compiler about the function name, function
parameters, and return type.

o Function call Function can be called from anywhere in the program.


The parameter list must not differ in function calling and function
declaration. We must pass the same number of functions as it is
declared in the function declaration.
o Function definition It contains the actual statements which are to be
executed. It is the most important aspect to which the control comes
when the function is called. Here, we must notice that only one value
can be returned from the function.

S C function Syntax
N aspects

1 Function return_type function_name


declaration (argument list);

2 Function call function_name (argument_list)

3 Function return_type function_name


definition (argument list) {function body;}

The syntax of creating function in c language is given below:

1. return_type function_name(data_type parameter...){


2. //code to be executed
3. }

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C


header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimizes the code.
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value


Example 1
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
Learn more

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34
program to calculate the average of five numbers.
#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}
Output
Going to calculate the average of five numbers:
Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

C Library Functions

Library functions are the inbuilt function in C that are grouped and placed at
a common place called the library. Such functions are used to perform some
specific operations. For example, printf is a library function used to print on
the console. The library functions are created by the designers of compilers.
All C standard library functions are defined inside the different header files
saved with the extension .h. We need to include these header files in our
program to make use of the library functions defined in such header files. For
example, To use the library functions such as printf/scanf we need to include
stdio.h in our program which is a header file that contains all the library
functions regarding standard input/output.

The list of mostly used header files is given in the following table.

S Heade Description
N r file

1 stdio.h This is a standard input/output header file. It contains all the


library functions regarding standard input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(),


puts(),etc.

4 stdlib.h This header file contains all the general library functions like
malloc(), calloc(), exit(), etc.

5 math.h This header file contains all the math operations related
functions like sqrt(), pow(), etc.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.

9 signal.h All the signal handling functions are defined in this header file.

10 setjmp. This file contains all the jump functions.


h

11 locale.h This file contains locale functions.

12 errno.h This file contains error handling functions.

13 assert.h This file contains diagnostics functions.

C – Strings and String functions with examples

String is an array of characters. In this guide, we learn how to declare


strings, how to work with strings in C programming and how to use the pre-
defined string handling functions.

We will see how to compare two strings, concatenate strings, copy one string
to another & perform various string manipulation operations. We can
perform such operations using the pre-defined functions of “string.h” header
file. In order to use these string functions you must include string.h file in
your C program.

String Declaration
Method 1:

char address[]={'T', 'E', 'X', 'A', 'S', '\0'};


Method 2: The above string can also be defined as –

char address[]="TEXAS";
In the above declaration NULL character (\0) will automatically be inserted at
the end of the string.

What is NULL Char “\0”?


'\0' represents the end of the string. It is also referred as String terminator &
Null Character.

String I/O in C programming


Read & write Strings in C using Printf() and Scanf() functions

#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");

/* I am reading the input string and storing it in nickname


* Array name alone works as a base address of array so
* we can use nickname instead of &nickname here
*/
scanf("%s", nickname);

/*Displaying String*/
printf("%s",nickname);

return 0;
}
Output:

Enter your Nick name:Negan


Negan
Note: %s format specifier is used for strings input/output

Read & Write Strings in C using gets() and puts() functions

#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

/* Console display using puts */


puts("Enter your Nick name:");

/*Input using gets*/


gets(nickname);

puts(nickname);
return 0;
}
C – String functions

C String function – strlen

Syntax:

size_t strlen(const char *str)


size_t represents unsigned short
It returns the length of the string without including end
character (terminating char ‘\0’).

Example of strlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:

Length of string str1: 13


strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof
returns the total allocated size assigned to the array. So if I consider the
above example again then the following statements would return the below
values.

strlen(str1) returned value 13.


sizeof(str1) would return value 20 as the array size is 20 (see the first
statement in main function).

C String function – strnlen

Syntax:

size_t strnlen(const char *str, size_t maxlen)


size_t represents unsigned short
It returns length of the string if it is less than the value specified for maxlen
(maximum length) otherwise it returns maxlen value.

Example of strnlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the
string length was 13 it returned only 10 because the maxlen was 10.
C String function – strcmp

int strcmp(const char *str1, const char *str2)


It compares the two strings and returns an integer value. If both the strings
are same (equal) then this function would return 0 otherwise it may return a
negative or positive value based on the comparison.

If string1 < string2 OR string1 is a substring of string2 then it would


result in a negative value. If string1 > string2 then it would return positive
value.
If string1 == string2 then you would get 0(zero) when you use this
function for compare strings.

Example of strcmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string 1 and 2 are different


C String function – strncmp

int strncmp(const char *str1, const char *str2, size_t n)


size_t is for unassigned short
It compares both the string till n characters or in other words it compares
first n characters of both the strings.

Example of strncmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string1 and string 2 are equal


C String function – strcat

char *strcat(char *str1, char *str2)


It concatenates two strings and returns the concatenated string.

Example of strcat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:

Output string after concatenation: HelloWorld


C String function – strncat

char *strncat(char *str1, char *str2, int n)


It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will
always be appended at the end of the concatenated string.

Example of strncat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:

Concatenation using strncat: HelloWor


C String function – strcpy

char *strcpy( char *str1, char *str2)


It copies the string str2 into string str1, including the end character
(terminator char ‘\0’).

Example of strcpy:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m gonna copied into s1


C String function – strncpy

char *strncpy( char *str1, char *str2, size_t n)


size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into
str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1
and appends several terminator chars(‘\0’) to accumulate the length of str1
to make it n.
Example of strncpy:

#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m


C String function – strchr

char *strchr(char *str, int ch)


It searches string str for character ch (you may be wondering that in above
definition I have given data type of ch as int, don’t worry I didn’t make any
mistake it should be int only. The thing is when we give any character while
using strchr then it internally gets converted into integer for better
searching.

Example of strchr:

#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:

f function strchr
C String function – Strrchr

char *strrchr(char *str, int ch)


It is similar to the function strchr, the only difference is that it searches the
string in reverse order, now you would have understood why we have extra r
in strrchr, yes you guessed it correct, it is for reverse only.
Now let’s take the same above example:

#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:

function strchr
Why output is different than strchr? It is because it started searching
from the end of the string and found the first ‘f’ in function instead of ‘of’.

C String function – strstr

char *strstr(char *str, char *srch_term)


It is similar to strchr, except that it searches for string srch_term instead of a
single char.

Example of strstr:

#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return 0;
}
Output:

Output string is: BeginnersBook.COM


You can also use this function in place of strchr as you are allowed to give
single char also in place of search_term string.

C Math

C Programming allows us to perform mathematical operations through the


functions defined in <math.h> header file. The <math.h> header file
contains various methods for performing mathematical operations such as
sqrt(), pow(), ceil(), floor() etc.

C Math Functions

There are various methods in math.h header file. The commonly used
functions of math.h header file are given below.

No Function Description
.

1) ceil(number) rounds up the given number. It returns the integer value which
is greater than or equal to given number.

2) floor(number) rounds down the given number. It returns the integer value
which is less than or equal to given number.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.

C Math Example

Let's see a simple example of math functions found in math.h header file.

#include<stdio.h>

#include <math.h>

int main(){

printf("\n%f",ceil(3.6));

printf("\n%f",ceil(3.3));

printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));

printf("\n%f",sqrt(16));

printf("\n%f",sqrt(7));

printf("\n%f",pow(2,4));

printf("\n%f",pow(3,3));

printf("\n%d",abs(-12));

return 0;

Output:

4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
Call by value and Call by reference in C
There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.

Let's understand call by value and call by reference in c language one by one.

Call by value in C
o In call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable is
used in the function call in the call by value method.

o In call by value method, we can not modify the value of the actual parameter by
the formal parameter.

o In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.

o The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.

Let's try to understand the concept of call by value in c language by the example given
below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by Value Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the val
ue of a and b in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual p
arameters do not change by changing the formal parameters in call by value, a = 10, b
= 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameter
s, a = 20, b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C
o In call by reference, the address of the variable is passed into the function call as
the actual parameter.

o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.

o In call by reference, the memory allocation is similar for both formal parameters
and actual parameters. All the operations in the function are performed on the
value stored at the address of the actual parameters, and the modified value
gets stored at the same address.

Consider the following example for the call by reference.

1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the val
ue of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual
parameters do change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal paramet
ers, a = 20, b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference


in c
No. Call by value Call by reference

1 A copy of the value is passed into the An address of value is passed into the
function function

2 Changes made inside the function is limited Changes made inside the function validate
to the function only. The values of the actual outside of the function also. The values of the
parameters do not change by changing the actual parameters do change by changing the
formal parameters. formal parameters.

3 Actual and formal arguments are created at Actual and formal arguments are created at
the different memory location the same memory location

You might also like