C Programming
C Programming
Function in C
We refer to a function as a group of various statements that perform a task together. Any C program
that we use has one function at least, that is main(). Then the programs can define multiple additional
functions in a code.
• When we make use of the functions, then we can easily avoid the rewriting of the same code/
logic time and again multiple times in any program.
• The calling of C functions may appear as many numbers of times as we want in any program.
And we can do so from any place in the program that is given to us.
• We can perform the tracking of a large C program pretty easily if we divide it into various
functions.
• One of the primary achievements of the C functions is reusability.
• However, remember that the function calling always acts as an overhead in the case of a C
program.
Defining a Function in C
The function definition, in general, holds this form in the C programming language:
return_type name_of_function( parameter list ) {
function body
}
The function definition in the C programming language contains a function body and a function header.
Let us take a look at all the parts that a function consists of:
• Function Name − It denotes the actual name of any function that we are using in the given
code. The name and parameter of a function constitute a function signature in the code together.
• Function Body − It consists of a collection of all the statements. These provide a definition of
what the function will do in the code.
• Parameters − It is just like a placeholder. Whenever we invoke a function, we pass a value to
the available parameter. We refer to this value as an argument or an actual parameter. We refer
to the parameter list as the number, order, and type of the function in the code. The parameters
may be optional. It means that any function in a code may consist of no parameters at all.
• Return Type − We may get a value in return for a function. The term return type refers to the
data type of the returns that we get from the functions (function returns). Some of the functions
are also capable of performing any desired operation without getting a value in return for it. In
any such case, the keyword used for the return_type will be void.
Function Syntax
Here is the syntax that we use to create a function in the C programming language:
return_type name_of_function(data_type parameter…)
{
// executable code in c
}
Example
Here, we have given a source code below for the function max(). The max() function takes two of the
parameters- namely val1 and val2. It then returns the maximum value that is present between both of
them. Let us take a look:
/* the function returns the max in between two values */
int max(int val1, int val2) {
/* declaration of local variable */
int result;
if (val1 > val2)
result = val1;
else
result = val2;
return result;
}
Types of Functions
The C programming language has functions that are of the following types:
• User-defined Functions – These are the types of functions that we can create using the C
programmer so that we can make use of it multiple times. This function reduces the complexity
of any big program- and thus, optimizes the given code.
• Library Functions – These are the functions whose declaration occurs in the header files of C,
such as floor(), ceil(), outs(), gets(), printf(), scanf(), etc.
Return Value
Any function in the C programming may not return its value from any function. In case we don’t need
to return the value that is available in any function, we can make use of the void in the form of a return
type. Let us look at an example of the C function that does not perform the return of a value from the
available function.
Let us look at an example of a C function that has no return value:
void chocolate()
{
printf(“chocolate c”);
}
In case we want to return a value from an available function, we must make use of any of the data
types, such as char, long, int, etc. Thus, the return type depends totally on the value that needs to return
from the available function. We will look at an example of a C function that will return an int value
from the given function.
Example of a C function with int return value,
int get()
{
return 20;
}
In the example mentioned above, we are trying to return the value 20, and the data type, in this case, is
int. If we are willing to return to the value of the floating-point (example, 64.5, 7,9, 27.61, etc.), then
we must make use of the float in the form of the method’s return type.
float get()
{
return 83.7;
}
Here, we have to call a function so that we get the function’s value.
Example of a function that has arguments and also has a return value,
#include<stdio.h>
int sum(int, int);
void main()
{
int x,y,result;
printf(“\nThe calculation of the sum of two values:”);
printf(“\nThe entering of two values:”);
scanf(“%d %d”,&x,&y);
result = sum(x,y);
printf(“\nThe sum is : %d”,result);
}
int sum(int x, int y)
{
return x+y;
}
The output generated from this program would be:
The calculation of the sum of two values:
The entering of two values: 49
51
The sum is: 100
Declaration of Function
The function definition basically tells a compiler about the name of the function and how one can call
this function. Then we can define the actual body of this function separately.
There are these following parts that exist in a function declaration:
return_type name_of_function(parameter list );
For the defined function above that is max(), the function declaration will occur in the following way:
int max(int val1, int val2);
The parameter names are not that important in the case of function declaration- we only require their
type. Thus, the declaration mentioned below is also going to be valid:
int max(int, int);
We only require the declaration of the function when we define that function in a source file while we
still call that function in a separate file. In any such case, we have to declare that function at the very
top of the file that calls that function.
Calling of a Function
When we create a function in C programming, we basically provide that function with a definition of
what it has to do. But to use this function, we need to call this function for performing its defined task.
When a function gets called by a program, the called function will get the program control transferred
to it. The called function will be performing a defined task. Once we execute the return statement or
when it reaches the closing brace of the function-ending, it is bound to return the program control to
the main program.
For calling a function, we simply have to pass the parameters required for it, along with the name of
the function. Here, if the function happens to return a value, then we can easily keep the returned value
stored with us.
For example −
#include <stdio.h>
/* declaration of function */
int max(int val1, int val2);
int main () {
/* definition of local variable */
int x = 400;
int y = 500;
int ret;
/* function calling for getting a max value */
ret = max(x, y);
printf( “The max value is : %d\n”, ret );
return 0;
}
/* function returns the max in between two values */
int max(int val1, int val2) {
/* declaration of local variable */
int result;
if (val1 > val2)
result = val1;
else
result = val2;
return result;
}
Output
In this case, we have kept the function max() with the function main(). After that, we have performed
the compilation of the source code. Running of the final executable would be producing the result that
follows:
The max value is: 500
Function Arguments
When a function needs to use the arguments, it has to declare those variables that happen to accept the
arguments’ values. Such variables are known as the given function’s formal parameters.
The formal parameters behave just like any other local variables inside our given function. These
parameters get created when they enter into a function. After that, it gets destroyed when it exits.
During the calling of a function, there will be two ways in which we can perform the passing of these
arguments to a given function:
Type of
Description of Call Type
Call
Call By The Call by Reference method creates a copy of the address of the given argument into
Reference the parameter that is formal in nature. Inside this function, the use of address helps in
accessing the actual argument that comes in use in this call. It means that the changes
that appear on the parameter are bound to affect the given argument.
Call By The Call by Value method creates a copy of the actual value of the given argument in
Value the parameter of the function that is formal in nature. Here, the changes that appear on
the parameter (that exists inside the function) create no effect whatsoever on the
available argument.
The C programming, by default, is the Call by Value for passing the arguments. Generally, it means
that we cannot make use of the code that exists within a function for altering the arguments that help
in calling the function.
Library Functions In C
The library functions in the C programming language are the inbuilt functions that are grouped together
and then placed in a common place known as the library. We make use of the library functions to
perform a specific type of operation. For example, the library function printf helps is printing on the
console. The designers of a compiler create the library functions. The defining of all the standard library
functions in C occurs inside multiple header files that are saved using the .h extension.
A user needs to include such header files in their program for utilizing the library functions that exist
in those header files. For instance, if we want to make use of scanf/ printf library functions, then we
have to include the stdio.h header file in our program. This header file consists of all library functions
that relate to standard output/ input.
Here is a list of some of the header files that is mostly utilized in the C programming:
stdio.h It is a standard type of output/ input header file. This header file consists of all the library
functions that are related to standard output/ input.
stdlib.h It is a type of header file that consists of various general library functions, such as exit(),
calloc(), malloc(), etc.
string.h This header file consists of all the library functions that are string-related, such as puts(),
gets(), etc.
time.h It is a type of header file that consists of all the functions that are time-related.
math.h It is a type of header file that consists of all the functions that are related to the math
operations, such as pow(), etc.
stdarg.h We use this header file for defining the variable argument functions.
ctype.h It is a type of header file that consists of the characters that handle the functions.
setjmp.h It is a type of header file that consists of all the functions that are jump functions.
signal.h We use this header file for defining any given signal handling function.
errno.h This type of header file consists of all the error handling functions.
locale.h It is a type of header file that consists of alL the locale functions.
assert.h It is a type of header file that consists of all the diagnostic functions.
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
Difference between Structure and Union in C on the basis of keyword, memory, value altering,
accessing members, and initialization of members.
Structure Union
The keyword union is used to define a The keyword struct is defined as a structure
union.
Union is equal to the size of the largest Greater than or equal to the sum of sizes of
member. its members.
Altering the value of any of the members Altering the value of a member will not
will alter other members’ values. affect other members of the structure.
Only one member can be accessed at a
time
Only the first member of the union can be Several members of a structure can be
initialized. initialized at once.
The employee structure has three members: name, id, and class. The name member is a 20-
element array, and id and class are simple members with int and long types, respectively. The
identifier employee is the structure identifier.
struct name/tag
{
//structure members
} variables;
Example
struct car
{
char name[100];
float price;
} car1;
struct car
{
char name[100];
float price;
};
struct car car1, car2, car3;
Example
#include<stdio.h>
int main()
{
struct car
{
char name[100];
float price;
};
return 0;
Output
Name of car = Benz
Price of car = 987432.500000
Comparing two Structures
Comparing structures in c is not permitted to check or compare directly with logical operators.
Only structure members can be comparable with logical operator.
Like
struc_object_1.age == struc_object_2.age
Program
#include<stdio.h>
#include<conio.h>
struct student {
int rno;
char name[20];
int percentage;
};
void main()
{
clrscr();
//compare structure via members
struct student stu1 = {1001,"Ramesh",87};
struct student stu2 = {1002,"Arun",85};
if (stu1.percentage < stu2.percentage){
printf("%s has higher marks.",stu2.name);
}
else {
printf("%s has higher marks.",stu1.name);
}
}
Output
Ramesh has higher marks.
Array of Structures in C
An array of structures in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities. The array
of structures in C are used to store information about multiple entities of different data
types. The array of structures is also known as the collection of structures.
Example of an array of structures that stores information of 5 students and prints it.
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
C 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.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type in
teger.
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.
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable, i.e., fff4.
The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Let's see the pointer example as explained for the above figure.
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printi
ng p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer the
refore if we print *p, we will get the value stored at the address contained by p.
return 0;
}
Output
Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.
Pointer to a function
Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc.
and used with arrays, structures, and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where the
pointer is used.
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.
Pointer to Array
Use a pointer to an array, and then use that pointer to access the array elements. For example,
#include<stdio.h>
void main()
{
int a[3] = {1, 2, 3};
int *p = a;
for (int i = 0; i < 3; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
Output
123
Syntax:
Array of Pointers in C
When we want to point at multiple variables or memories of the same data type in a C program, we use
an array of pointers.
Let us assume that a total of five employees are working at a cheesecake factory. We can store the
employees’ names in the form of an array. Along with this, we also store the names of employees
working at the office, the library, and the shoe store.
Now, let us assume that once we read all the names of the employees randomly, we want to sort all of
the employees’ names working in the cheesecake factory. Sorting all the employee names requires
reading, swapping, and copying a lot of data. But since we have stored all the employee names in
groups/ arrays, we can directly refer to the array of names of employees working at the cheesecake
factory.
Let us assume that we want to build an enclosed system, and this system uses a different kind of
thermometer for measuring the temperature. Now, in this case, we can use an array for holding the
address of memory for every sensor. This way, manipulation of the sensor status becomes very easy.
Example
The thermo[1] will be holding the 2nd sensor’s address and so on.
Now, since it’s an array, it can interact directly with the thermo pointer indexed in the array. Thus, we
will get the 1st sensor’s status with the thermo[0], the second one using the thermo[1], and so on ahead.
An array of pointers can be declared just like we declare the arrays of char, float, int, etc. The syntax
for declaring an array of pointers would be:
int *ary[55]
This one is an array of a total of 55 pointers. In simple words, this array is capable of holding the
addresses a total of 55 integer variables. Think of it like this- the ary[0] will hold the address of one
integer variable, then the ary[1] will hold the address of the other integer variable, and so on.
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
m = 10
n = 20
After Swapping:
m = 20
n = 10
A function can also return a pointer to the calling function. In this case you must be careful, because
local variables of function don’t live outside the function. They have scope only inside the function.
Hence if you return a pointer connected to a local variable, that pointer will be pointing to nothing
when the function ends.
File Management
What is File Handling in C?
File handling refers to the method of storing data in the C program in the form of an output or input that might have
been generated while running a C program in a data file, i.e., a binary file or a text file for future analysis and
reference in that very program.
What is a File in C?
A file refers to a source in which a program stores the information/data in the form of bytes of sequence on a disk
(permanently). The content available on a file isn’t volatile like the compiler memory in C. But the program can
perform various operations, such as creating, opening, reading a file, or even manipulating the data present inside
the file. This process is known as file handling in C.
• Reusability: File handling allows us to preserve the information/data generated after we run the program.
• Saves Time: Some programs might require a large amount of input from their users. In such cases, file
handling allows you to easily access a part of a code using individual commands.
• Commendable storage capacity: When storing data in files, you can leave behind the worry of storing all
the info in bulk in any program.
• Portability: The contents available in any file can be transferred to another one without any data loss in the
computer system. This saves a lot of effort and minimises the risk of flawed coding.
• Text Files
• Binary Files
Text Files
The text files are the most basic/simplest types of files that a user can create in a C program. We create the text files
using an extension .txt with the help of a simple text editor. In general, we can use notepads for the creation of .txt
files. These files store info internally in ASCII character format, but when we open these files, the content/text
opens in a human-readable form.
Text files are, thus, very easy to access as well as use. But there’s one major disadvantage; it lacks security. Since a
.txt file can be accessed easily, information isn’t very secure in it. Added to this, text files consume a very large
space in storage.
To solve these problems, we have a different type of file in C programs, known as binary files.
Binary Files
The binary files store info and data in the binary format of 0’s and 1’s (the binary number system). Thus, the files
occupy comparatively lesser space in the storage. In simpler words, the binary files store data and info the same
way a computer holds the info in its memory. Thus, it can be accessed very easily as compared to a text file.
The binary files are created with the extension .bin in a program, and it overcomes the drawback of the text files in
a program since humans can’t read it; only machines can. Thus, the information becomes much more secure. Thus,
binary files are safest in terms of storing data files in a C program.
used to set the file pointer to the intended file position fseek()
Note: It is important to know that we must declare a file-type pointer when we are working with various files in a
program. This helps establish direct communication between a program and the files.
Here is how you can do it:
FILE *fpointer;
Out of all the operations/functions mentioned above, let us discuss some of the basic operations that we perform in
the C language.
• Here, if we suppose that the file – recentprogram.txt doesn’t really exist in the E:\\myprogram location.
Here, we have used the mode “w”. Thus, the first function will create a new file with the name
recentprogram.txt and then open it for writing (since we have used the “w” mode).
• The “w” here refers to writing mode. It allows a programmer to overwrite/edit and create the contents in a
program file.
• Now, let us take a look at the second binary previousprogram.bin file that is present in the E:\\myprogram
location. Thus, the second function here will open the file (that already exists) for reading in the “rb”
binary mode.
• The “rb” refers to the reading mode. It only allows you to read a file, but not overwrite it. Thus, it will only
read this available file in the program.
Let us take a look at a few more opening modes used in the C programs:
r Open a file for reading the content. In case the file doesn’t exist in the
location, then fopen() will return NULL.
rb Open a file for reading the content in binary In case the file doesn’t exist in the
mode. location, then fopen() will return NULL.
w Open a file for writing the content. In case the file exists, its contents are
overwritten.
In case the file doesn’t exist in the
location, then it will create a new file.
wb Open a file for writing the content in binary In case the file exists, then its contents
mode. will get overwritten.
In case the file doesn’t exist in the
location, then it will create a new file.
a Open a file for appending the content. In case the file doesn’t exist in the
location, then it will create a new file.
Meaning, the data of the program is added to
the file’s end in a program.
ab Open a file for appending the content in binary In case the file doesn’t exist in the
mode. location, then it will create a new file.
Meaning, the data of the program is added to
the file’s end in a program in a binary mode.
r+ Open a file for both writing and reading the In case the file doesn’t exist in the
content. location, then fopen() will return NULL.
rb+ Open a file for both writing and reading the In case the file doesn’t exist in the
content in binary mode. location, then fopen() will return NULL.
w+ Open a file for both writing and reading. In case the file exists, its contents are
overwritten.
In case the file doesn’t exist in the
location, then it will create a new file.
wb+ Open a file for both writing and reading the In case the file exists, its contents are
content in binary mode. overwritten.
In case the file doesn’t exist in the
location, then it will create a new file.
a+ Open a file for both appending and reading the In case the file doesn’t exist in the
content. location, then it will create a new file.
ab+ Open a file for both appending and reading the In case the file doesn’t exist in the
content in binary mode. location, then it will create a new file.
Questions