2. ⢠A function is a block of statements that performs a specific task. Letâs say
you are writing a C program and you need to perform a same task in that
program more than once. In such case you have two options:
⢠a) Use the same set of statements every time you want to perform the
task
b) Create a function to perform that task, and just call it every time you
need to perform that task.
⢠Using option (b) is a good practice and a good programmer always uses
functions while writing code in C.
⢠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.
3. Advantage of functions in C
There are the following advantages of C functions.
⢠By using functions, we can avoid rewriting same
logic/code again and again in a program.
⢠We can call C functions any number of times in a
program and from any place in a program.
⢠We can track a large C program easily when it is
divided into multiple functions.
⢠Reusability is the main achievement of C functions.
⢠However, Function calling is always a overhead in a C
program.
4. Types of functions
1) Predefined standard library functions
⢠Standard library functions are also known as built-in
functions. Functions such as puts(), gets(), printf(), scanf() etc
are standard library functions. These functions are already
defined in header files (files with .h extensions are called
header files such as stdio.h), so we just call them whenever
there is a need to use them.
⢠For example, printf() function is defined in <stdio.h> header
file so in order to use the printf() function, we need to include
the <stdio.h> header file in our program using #include
<stdio.h>.
5. 2) User Defined functions
⢠The functions that we create in a program are known
as user defined functions or in other words you can say
that a function created by user is known as user
defined function.
⢠C programming functions are divided into three
activities such as,
⢠Function declaration
⢠Function definition
⢠Function call
6. Syntax of a function
return_type function_name (argument list)
{
Set of statements â Block of code
}
return_type: Return type can be of any data type such as int, double, char,
void, short etc.
function_name: It can be anything, however it is advised to have a
meaningful name for the functions so that it would be easy to understand the
purpose of function just by seeing itâs name.
argument list: Argument list contains variables names along with their data
types. These arguments are kind of inputs for the function. For example â A
function which is used to add two integer variables, will be having two integer
argument.
Block of code: Set of C statements, which will be executed whenever a call
will be made to the function.
7. return_type addition(argument list)
return_type addition(int num1, int num2)
int addition(int num1, int num2);
⢠Function Declaration
⢠The function declaration tells the compiler about function name, the data
type of the return value and parameters. The function declaration is also
called a function prototype. The function declaration is performed before
the main function
Function declaration syntax -
returnType functionName(parametersList);
⢠In the above syntax, returnType specifies the data type of the value which
is sent as a return value from the function definition. The functionName is
a user-defined name used to identify the function uniquely in the
program. The parametersList is the data values that are sent to the
function definition.
9. Function Definition
⢠The function definition provides the actual code of that function. The function
definition is also known as the body of the function. The actual task of the function is
implemented in the function definition. That means the actual instructions to be
performed by a function are written in function definition. The actual instructions of a
function are written inside the braces "{ }".
Function definition syntax -
returnType functionName(parametersList)
{
Actual code...
}
11. Function Call
⢠The function call tells the compiler when to execute the function
definition. When a function call is executed, the execution control jumps
to the function definition where the actual code gets executed and returns
to the same functions call once the execution completes. The function call
is performed inside the main function or any other function or inside the
function itself.
⢠Function call syntax -
functionName(parameters);
Function call
result = add(4,5);
12. #include <stdio.h>
int add(int a, int b); //function declaration
int main()
{
int a=10,b=20;
int c=add(10,20); //function call
printf("Addition:%dn",c);
getch();
}
int add(int a,int b) //function body
{
int c;
c=a+b;
return c;
}
Addition:30
13. TYPES OF USER DEFINED FUNCTIONS
⢠A function may or may not accept any argument. It
may or may not return any value. Based on these
facts, There are four different aspects of function
calls.
⢠function without arguments and without return
value
⢠function without arguments and with return value
⢠function with arguments and without return value
⢠function with arguments and with return value
14. function without arguments and without return value
#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);
}
OUTPUT:
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
15. Function without argument and with return value
#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:
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
16. Function with argument and without return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("nGoing to calculate the sum of
two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("nThe sum is %d",a+b);
}
OUTPUT:
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
17. Function with argument and with return value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("nGoing to calculate the sum of two numbers:");
printf("nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30
18. In the concept of functions, the function call is known as "Calling Function" and
the function definition is known as "Called Function".
Parameter Passing in C
When a function gets executed in the program, the execution control is
transferred from calling-function to called function and executes function
definition, and finally comes back to the calling function. When the execution
control is transferred from calling-function to called-function it may carry one
or number of data values. These data values are called as parameters.
Parameters are the data values that are passed from calling function to called
function.
In C, there are two types of parameters and they are as follows...
Actual Parameters
Formal Parameters
19. ⢠The actual parameters are the parameters that are
speficified in calling function. The formal parameters are
the parameters that are declared at called function.
When a function gets executed, the copy of actual
parameter values are copied into formal parameters.
⢠In C Programming Language, there are two methods to
pass parameters from calling function to called function
and they are as follows...
⢠Call by Value
⢠Call by Reference
20. #include<stdio.h>
#include<conio.h>
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
printf("nValue of a: %d",a);
printf("nValue of b: %d",b);
getch();
}
Value of a: 200
Value of b: 100
Call by Value
21. #include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
printf("nValue of a: %d",a);
printf("nValue of b: %d",b);
getch();
}
Value of a: 200
Value of b: 100
Call by reference
22. C Recursion
A function that calls itself is known as a recursive function. And, this technique
is known as recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
23. Storage allocation
⢠Dynamic Memory Allocation in C Programming Language - C
language provides features to manual management of memory, by
using this feature we can manage memory at run time, whenever
we require memory allocation or reallocation at run time by
using Dynamic Memory Allocation functions we can create amount
of required memory.
⢠Dynamic memory allocation in c language is possible by 4 functions
of stdlib.h header file.
⢠malloc()
⢠calloc()
⢠realloc()
⢠free()
24. static memory allocation dynamic memory allocation
memory is allocated at compile
time.
memory is allocated at run time.
memory can't be increased while
executing program.
memory can be increased while
executing program.
used in array. used in linked list.
25. malloc() method
âmallocâ or âmemory allocationâ method in C is used to dynamically allocate a single
large block of memory with the specified size. It returns a pointer of type void which
can be cast into a pointer of any form. It initializes each block with default garbage
value.
Syntax:
ptr = (cast-type*) malloc(byte-size)
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory
If space is insufficient,
allocation fails and
returns a NULL
pointer
26. calloc() method
callocâ or âcontiguous allocationâ method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. It initializes each block
with a default value â0â.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the
size of the float.
27. free() method
âfreeâ method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own.
Hence the free() method is used, whenever the dynamic memory allocation takes
place. It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
28. realloc() method
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'
29. Storage Classes in C
⢠storage classes in C are used to determine the
lifetime, visibility, memory location, and initial value
of a variable. There are four types of storage classes
in C
⢠Automatic
⢠External
⢠Static
⢠Register
30. Automatic
ďąAutomatic variables are allocated memory automatically at runtime.
ďąThe visibility of the automatic variables is limited to the block in which they
are defined.
ďąThe automatic variables are initialized to garbage by default.
ďąThe memory assigned to automatic variables gets freed upon exiting from
the block.
ďąThe keyword used for defining automatic variables is auto.
ďąEvery local variable is automatic in C by default.
Static
Default initial value of the static integral variable is 0 otherwise null.
The visibility of the static global variable is limited to the file in which it has
declared.
The keyword used to define static variable is static.
31. Register
ď§The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
ď§We can not dereference the register variables, i.e., we can not use
&operator for the register variable.
ď§The access time of the register variables is faster than the automatic
variables.
ď§The initial default value of the register local variables is 0.
External
The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
We can only initialize the extern variable globally, i.e., we can not initialize
the external variable within any block or method.
32. Storage
Classes
Storage
Place
Default
Value
Scope Lifetime
auto RAM Garbage
Value
Local Within function
extern RAM Zero Global Till the end of the main
program Maybe declared
anywhere in the program
static RAM Zero Local Till the end of the main
program, Retains value
between multiple
functions call
register Register Garbage
Value
Local Within the function
33. Strings
⢠The string can be defined as the one-dimensional array of
characters terminated by a null ('0').
⢠The character array or the string is used to manipulate text
such as word or sentences.
⢠Each character in the array occupies one byte of memory, and
the last character must always be 0.
⢠The termination character ('0') is important in a string since it
is the only way to identify where the string ends.
⢠When we define a string as char s[10], the character s[10] is
implicitly initialized with the null in the memory.
34. There are two ways to declare a string in c language.
By char array
By string literal
36. String Example
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};
char ch2[11]="javatpoint";
printf("Char Array Value is: %sn", ch);
printf("String Literal Value is: %sn", ch2);
return 0;
}
Char Array Value is: javatpoint
String Literal Value is: javatpoint
37. String Handling Functions
ďśC programming language provides a set of pre-defined
functions called string handling functions to work with string
values.
ďśThe string handling functions are defined in a header file
called string.h.
ďś Whenever we want to use any string handling function we
must include the header file called string.h.
38. No. Function Description
1) strlen(string_name) returns the length of string
name.
2) strcpy(destination, source) copies the contents of source
string to destination string.
3) strcat(first_string, second_string) concats or joins first string
with second string. The result
of the string is stored in first
string.
4) strcmp(first_string, second_string) compares the first string with
second string. If both strings
are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in
lowercase.
7) strupr(string) returns string characters in
uppercase.
39. strlen() function
The strlen() function returns the length of the given string. It doesn't count
null character '0'.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output:
Length of string is: 10
40. strcpy()
The strcpy(destination, source) function copies the source string in destination.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: javatpoint
42. strlwr()
The strlwr(string) function returns string characters in lowercase
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("nLower String is: %s",strlwr(str));
return 0;
}
Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint
43. strupr()
The strupr(string) function returns string characters in uppercase.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("nUpper String is: %s",strupr(str));
return 0;
}
Output:
Enter string: javatpoint
String is: javatpoint
Upper String is: JAVATPOINT
44. structures
⢠In C, there are cases where we need to store multiple
attributes of an entity.
⢠It is not necessary that an entity has all the
information of one type only.
⢠It can have different attributes of different data
types.
⢠For example, an entity Student may have its name
(string), roll number (int), marks (float).
45. ďąStructure in c is a user-defined data type that enables us to store the
collection of different data types.
ďąEach element of a structure is called a member.
ďąThe ,struct keyword is used to define the structure. Let's see the syntax to
define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define a structure for an entity employee in c.
struct employee
{ int id;
char name[20];
float salary;
};
46.
47. Declaring structure variable
We can declare a variable for the structure so that we can access the member
of the structure easily. There are two ways to declare structure variable:
â˘By struct keyword within main() function
â˘By declaring a variable at the time of defining the structure.
48. Accessing members of the structure
There are two ways to access structure members:
ďąBy . (member or dot operator)
ďąBy -> (structure pointer operator)
49. Unions
ďąLike structure, Union in c language is a user-defined data type that is
used to store the different type of elements.
ďąAt once, only one member of the union can occupy the memory. In
other words, we can say that the size of the union in any instance is equal
to the size of its largest element.
Advantage of union over structure
It occupies less memory because it occupies the size of the largest
member only.
50.
51. Command Line Arguments
ďąThe arguments passed from command line are called command line
arguments. These arguments are handled by main() function.
ďąTo support command line argument, you need to change the structure of
main() function as given below.
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first
argument.
The argv[] contains the total number of arguments. The first argument is the file
name always.
ď§The command line arguments are supperated with SPACE.
ď§Always the first command line argument is file path.
ď§Only string values can be passed as command line arguments.
ď§All the command line arguments are stored in a character pointer array called argv[ ].
ď§Total count of command line arguments including file path argument is stored in a
integer parameter called argc.
52. Pointers
ďąThe pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-
bit architecture the size of a pointer is 2 byte.
ďąConsider the following example to define a pointer which stores the
address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the a
ddress of the variable n of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known
as indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
56. Double Pointer (Pointer to Pointer)
ďąAs we know that, a pointer is used to store the address of a variable in
C. Pointer reduces the access time of a variable.
ďąHowever, In C, we can also define a pointer to store the address of
another pointer. Such pointer is known as a double pointer (pointer to
pointer).
ďąThe first pointer is used to store the address of a variable whereas the
second pointer is used to store the address of the first pointer. Let's
understand it by the diagram given below.
The syntax of declaring a double pointer is given below.
int **p; // pointer to a pointer which is pointing to an integer.