C Function
C Function
need it.
Parts of Function
1. Function Prototype (function declaration)
2. Function Definition
3. Function Call
1. Function Prototype
Syntax:
dataType functionName (Parameter List)
Example:
int addition();
2. Function Definition
Syntax:
returnType functionName(Function arguments){
}
Example:
int addition()
3. Calling a function in C
int main()
return 0;
return num1+num2;
Program Output:
The addition of the two numbers is: 15
While calling a function, the arguments can be passed to a function in two ways, Call by value and call by reference.
Type Description
Call by Value
Example:
#include<stdio.h>
int main()
int num2 = 5;
return 0;
return a + b;
Program Output:
The addition of two numbers is: 15
Call by Reference
Example:
#include<stdio.h>
int main()
int num2 = 5;
return 0;
/* function returning the addition of two numbers */int addition(int *a,int *b)
return *a + *b;
Program Output:
The addition of two numbers is: 15
The C library functions are provided by the system and stored in the library. The C library function is also called an
#include<ctype.h>
#include<math.h>
void main()
int i = -10, e = 2, d = 10; /* Variables Defining and Assign values */ float rad =
1.43;
printf("%d\n", abs(i));
printf("%f\n", sin(rad));
printf("%f\n", cos(rad));
printf("%f\n", exp(e));
printf("%d\n", log(d));
Program Output:
A scope is a region of the program, and the scope of variables refers to the area of the program
where the variables can be accessed after its declaration.
In
where
that
In C
Cregion.
every
a variable
variable
programming, hasdefined
its existence;
variable in scope.
moreover,
declared You canathat
within define
variable
scope
function cannot
as the be
is differentsection
useda or
from or region
accessed
variable of beyond
a program
declared
outside of a function. The variable can be declared in three places. These are:
Position Type
int main ()
y = 30;
z = x + y;
printf ("value of x = %d, y = %d and z = %d\n", x, y, z);
return 0;
Global Variables
Variables
called global
thatvariables.
are declared outside of a function block and can be accessed inside the function is
Global Scope
Global variables are defined outside a function or any specific block, in most of the case, on the
top of the C program. These variables hold their values all through the end of the program and
are accessible within any of the functions defined in your program.
Any function can access variables defined within the global scope, i.e., its availability stays for
the entire program after being declared.
Example:
#include <stdio.h>
int main ()
y = 30;
z = x + y;
return 0;
}
Global Variable Initialization
After defining a local variable, the system or the compiler won't be initializing any value to it.
You have to initialize it by yourself. It is considered good programming practice to initialize
variables before using. Whereas in contrast, global variables get initialized automatically by the
compiler as and when defined. Here's how based on datatype; global variables are defined.
datatype Initial Default Value
int 0
char '\0'
float 0
double 0
pointer NULL
C is a powerful programming language having capabilities like an iteration of a set of statements 'n' number of times.
The same concepts can be done using functions also. In this chapter, you will be learning about recursion concept
What is Recursion
can beand
Recursion
again
programtermed
lets
again,
canyou
be
asand
call
recursion,
defined
that
the process
specific
asand
the the
technique
function
continues
function
from
oftill
inreplicating
specific
inside
which makes
that
condition
orfunction,
doing
thisreaches.
possible
again
thenan
this
In
isactivity
called
the
concept
world
inrecursive
aofof
self-similar
calling
programming,
function.
theway
function
calling
whenfrom
your
itself
itself
Here's an example of how recursion works in a program:
Example Syntax:
void rec_prog(void) {
int main(void) {
rec_prog();
return 0;
C program
this
function,
recursion
or allows
else
concept,
it you
will continue
toyou
dohave
such
toto
calling
anbeinfinite
cautious
of function
loop,
in so
defining
within
makeanother
an
sure
exit
that
or
function,
the
terminating
condition
i.e., recursion.
condition
is set within
from
But your
when
this program.
recursive
you implement
Factorial Program
Example:
#include<stdio.h>
#include<conio.h>
int fact(int f) {
if (f & lt; = 1) {
printf("Calculated Factorial");
return 1;
int main(void) {
int f = 12;
clrscr();
getch();
return 0;
Fibonacci Program
Example:
#include<stdio.h>
#include<conio.h>
int fibo(int g) {
if (g == 0) {
return 0;
}
if (g == 1) {
return 1;
int main(void) {
int g;
clrscr();
getch();
return 0;
Storage Classes are associated with variables for describing the features of any variable or
function in the C program. These storage classes deal with features such as scope, lifetime and
visibility which helps programmers to define a particular variable during the program's runtime.
These storage classes are preceded by the data type which they had to modify.
There are four storage classes types in C:
auto
register
static
extern
The above
only be implemented
example has
with
a variable
the localname
variables.
roll with auto as a storage class. This storage class can
register Storage Class
This storage class is implemented for classifying local variables whose value needs to be saved
in a register in place of RAM (Random Access Memory). This is implemented when you want
your variable the maximum size equivalent to the size of the register. It uses the
keyword register.
Syntax:
register int counter;
Register variables are used when implementing looping in counter variables to make program
execution fast. Register variables work faster than variables stored in RAM (primary memory).
Example:
for(register int counter=0; counter<=9; counter++)
// loop body
int val;
val = 10;
funcExtern();
Another example:
Example:
#include <stdio.h>
extern int val; // now the variable val can be accessed and used from anywhere
void funcExtern()
The preprocessor is a program invoked by the compiler that modifies the source code before the
actual composition takes place.
To use any preprocessor directives, first, we have to prefix them with pound symbol #.
The following section lists all preprocessor directives:
Category Directive Description
Compiler control division #line Set line number, Abort compilation, Set compiler option
#error
#pragma
C Preprocessors Examples
Syntax:
#include <stdio.h>
#define LIMIT 10
int main()
int counter;
printf("%d\n",counter);
return 0;
In the above
#include example for loop will run ten times.
<stdio.h>
#include "header.h"
#include <stdio.h> tell the compiler to add stdio.h file from System Libraries to the current
source file, and #include "header.h" tells the compiler to get header.h from the local directory.
#undef LIMIT
#define LIMIT 20
This tells the compiler to undefine existing LIMIT and set it as 20.
#ifndef LIMIT
#define LIMIT 50
#endif
This tellsLIMIT
#ifdef the compiler to define LIMIT, only if LIMIT isn't already defined.
/* Your statements here */#endif
This tells the compiler to do the process the statements enclosed if LIMIT is defined.
C language is famous for its different libraries and the predefined functions pre-written within it. These make
programmer's effort a lot easier. In this tutorial, you will be learning about C header files and how these header files
can be included in your C program and how it works within your C language.
while programming in C or C++ programs is that you can keep every macro, global variables, constants, and other
function prototypes in the header files. The basic syntax of using these header files is:
Syntax:
#include <file>
or
#include "file"
This kind of file inclusion is implemented for including system oriented header files. This technique (with angular
braces) searches for your file-name in the standard list of system directories or within the compiler's directory of
header files. Whereas, the second kind of header file is used for user-defined header files or other external files for
your program. This technique is used to search for the file(s) within the directory that contains the current file.
specific file like that of input before abiding by the rest of your existing source file. Let us take an example where you
may think of having a header file karl.h having the following statement:
Example:
char *example (void);
Example:
then, you have a main C source program which seems something like this:
#include<stdio.h>
int x;
#include "karl.h"
int main ()
printf("Program done");
return 0;
So, the compiler will see the entire C program and token stream as:
Example:
#include<stdio.h>
int x;
int main ()
printf("Program done");
return 0;
within your program, your compiler will be going to process the contents inside it - twice which will eventually lead to
an error in your program. So to eliminate this, you have to use conditional preprocessor directives. Here's the syntax:
Syntax:
#ifndef HEADER_FILE_NAME
#define HEADER_FILE_NAME
#endif
Again, sometimes it's essential for selecting several diverse header files based on some requirement to be
incorporated into your program. For this also multiple conditional preprocessors can be used like this:
Syntax:
#if FIRST_SYSTEM
#include "sys.h"
#elif SEC_SYSTEM
#include "sys2.h"
#elif THRID_SYSTEM
....
#endif
You can create your custom header files in C; it helps you to manage user-defined methods, global variables, and
#include"swap.h"
void main()
int a=20;
int b=30;
swap (&a,&b);
printf ("b=%d\n",b);
Swap method is defined in swap.h file, which is used to swap two numbers by using a temporary variable.
Example:
void swap (int* a, int* b)
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
Note:
header file name must have a .h file extension.
In this example, I have named swap.h header file.
Instead of writing <swap.h> use this terminology swap.h for include custom header file.
Both files swap.h and main.c must be in the same folder.
The array is a data structure in C programming, which can store a fixed-size sequential collection
of elements of the same data type.
For
instead
example,
In the Cofprogramming
defining
if youten
want
variables.
to storean
language, tenarray
numbers,
can beit One-Dimensional,
is easier to define anTwo-
array of 10 lengths,
Define an Array in C
Syntax:
type arrayName [ size ];
Example:
Thismust
size is called
be an
a one-dimensional
integer constant greater
array. An
than
array
zero.type can be any valid C data types, and array
double amount[5];
Initialize an Array in C
Arrays can be initialized at declaration time:
int age[5]={22,25,30,32,35};
int n = 0;
for(n=0;n<sizeof(myArray)/sizeof(myArray[0]);n++)
myArray[n] = n;
int n = 0;
for(n=0;n<sizeof(myArray)/sizeof(myArray[0]);n++)
myArray[n] = n;
In C programming, the one-dimensional array of characters are called strings, which is terminated by a null character
'\0'.
Strings Declaration in C
Example:
There are two ways to declare a string in C programming:
Through
char pointers.
*name;
Strings Initialization in C
Example:
char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};
or
char name[] = "Cloud";
Example:
#include<stdio.h>
int main ()
printf("Tutorials%s\n", name );
return 0;
Program Output:
TutorialsCloud
Pointer Definition in C
Syntax:
type *variable_name;
Example:
int *width;
char *letter;
int main ()
{
/* access the value using the pointer */ printf("Value of *pntr variable: %d\n",
*pntr );
return 0;
C language provides many functions that come in header files to deal with the allocation and management of
memories. In this tutorial, you will find brief information about managing memory in your program using some
# Management of Memory
Management of Memory
writing codes.
Almost
precise
program).
all
memory
Therefore,
computer
space
languages
managing
along with
can
memory
the
handle
program
utmost
system
itself,
care
memory.
which
is oneneeds
of
Allthe
thesome
major
variables
memory
tasksused
a programmer
forinstoring
your program
itself
must(i.e.,
keep
occupies
itsin
own
mind
a while
When a variable gets assigned in a memory in one program, that memory location cannot be used by another
variable or another program. So, C language gives us a technique of allocating memory to different variables and
programs.
There are two types used for allocating memory. These are:
throughout the entire run of your program. Neither any changes will be there in the amount of memory nor any
has the facility to increase/decrease the memory quantity allocated and can also release or free the memory as and
when not required or used. Reallocation of memory can also be done when required. So, it is more advantageous,
malloc, calloc, or realloc are the three functions used to manipulate memory. These commonly used functions are
available through the stdlib library so you must include this library to use them.
Table of Contents
# malloc function
# calloc function
# realloc function
# free function
malloc function
malloc function is used to allocate space in memory during the execution of the program.
malloc function does not initialize the memory allocated during execution. It carries garbage value.
malloc function returns null pointer if it couldn't able to allocate requested amount of memory.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
char *mem_alloc;
if(mem_alloc== NULL )
else
strcpy( mem_alloc,"google.in");
free(mem_alloc);
Program Output:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
char *mem_alloc;
else
strcpy( mem_alloc,"google.in");
free(mem_alloc);
Program Output:
free function
free function frees the allocated memory by malloc (), calloc (), realloc () functions.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
char *mem_alloc;
else
strcpy( mem_alloc,"google.in");
mem_alloc=realloc(mem_alloc,100*sizeof(char));
if( mem_alloc == NULL )
else
free(mem_alloc);
Program Output:
The structure is something similar to an array; the only difference is array is used to store the same data types.
struct keyword is used to declare the structure in C.
Variables inside the structure are called members of the structure.
Table of Contents
# Defining a Structure in C
Defining a Structure in C
Syntax:
struct structureName
//member definitions
};
Example:
struct Courses
char WebSite[50];
char Subject[50];
int Price;
};
#include<stdio.h>
#include<string.h>
struct Courses
char WebSite[50];
char Subject[50];
int Price;
};
void main( )
struct Courses C;
//Initialization
C.Price = 0;
//Print
printf( "WebSite : %s\n", C.WebSite);
Program Output:
WebSite : google.in
Book Price : 0
Unions are user-defined data type in C, which is used to store a collection of different kinds of data, just like a
structure. However, with unions, you can only store information in one field at any one time.
Defining a Union in C
Syntax:
union unionName
//member definitions
};
Example:
union Courses
char WebSite[50];
char Subject[50];
int Price;
};
Accessing Union Members in C
Example:
#include<stdio.h>
#include<string.h>
union Courses
char WebSite[50];
char Subject[50];
int Price;
};
void main( )
union Courses C;
C.Price = 0;
Program Output:
WebSite : google.in
slongtype.
data
your program
Example:in the
Now
statement
for
thedefining
thing
as mentioned
isany
thissigned
'slong',
above
long
which
is
variable
used
is anfor
user-defined
type
a defining
within your
identifier
a signed
C program.
qualified
can be This
implemented
long
means:
kind ofin
slong g, d;
will allow you to create two variables name 'g' and 'd' which will be of type signed long and this
quality of signed long is getting detected from the slong (typedef), which already defined the
meaning of slong in your program.
typedef struct
type first_member;
type sec_member;
type thrid_member;
} nameOfType;
HerebenameOfType
can implemented
nameOfType type1,correspond
by declaring
type2; to the
a variable
definition
of this
of structure
structureallied
type. with it. Now, this nameOfType
#include<stdio.h>
#include<string.h>
char p_name[50];
int p_sal;
} prof;
void main(void)
prof pf;
The binding of pointer (*) is done to the right here. With this kind of statement declaration, you
are in fact declaring an as a pointer of type int (integer).
typedef int* pntr;
pntr g, h, i;