C Language
C Language
C Language
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 procedure or subroutine in other programming languages.
*Advantage of functions in C*
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.
*Types of Functions*
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.
*Function Aspects*
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.
*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.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h all the general library functions like malloc(), calloc(), exit(), etc.
9 signal.h All the signal handling functions are defined in this header file.
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.
Actual Parameters
Formal Parameters
The actual parameters are the parameters that are specified 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
*Call by Value*
In call by value parameter passing method, the copy of actual parameter values are
copied to formal parameters and these formal parameters are used in called
function. The changes made on the formal parameters does not effect the values
of actual parameters. That means, after the execution control comes back to the
calling function, the actual parameter values remains same.
*Call by Reference*
In Call by Reference parameter passing method, the memory location address of the
actual parameters is copied to formal parameters. This address is used to access the
memory locations of the actual parameters in called function. In this method of
parameter passing, the formal parameters must be pointer variables.
That means in call by reference parameter passing method, the address of the actual
parameters is passed to the called function and is recieved by the formal parameters
(pointers). Whenever we use these formal parameters in called function, they directly
access the memory locations of actual parameters. So the changes made on the
formal parameters effects the values of actual parameters.
Example
Now, consider the following function, which takes an array as an argument along with
another argument and based on the passed arguments, it returns the average of the
numbers passed through the array as follows −
double getAverage(int arr[], int size) {
int i;
double avg;
double sum = 0;
UNIT 6 *RECURSION*
Recursion is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function, then it is
called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
*Number Factorial*
The following example calculates the factorial of a given number using a recursive
function −
Live Demo
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
*Fibonacci Series*
The following example generates the Fibonacci series for a given number using a
recursive function −
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
return 0;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
*Ackermann Function*
In computability theory, the Ackermann function, named after Wilhelm Ackermann, is
one of the simplest and earliest-discovered examples of a total computable function that
is not primitive recursive. All primitive recursive functions are total and computable, but
the Ackermann function illustrates that not all total computable functions are primitive
recursive.
#include <stdio.h>
int ack(int m, int n)
{
if (m == 0){
return n+1;
}
else if((m > 0) && (n == 0)){
return ack(m-1, 1);
}
else if((m > 0) && (n > 0)){
return ack(m-1, ack(m, n-1));
}
}
int main(){
int A;
A = ack(1, 2);
printf("%d", A);
return 0;
}
Output
4
*QUICK SORT*
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions
the given array around the picked pivot. There are many different versions of quickSort
that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
/* C implementation QuickSort */
#include<stdio.h>
Output:
SORTED ARRAY
1 5 7 8 9 10
*MERGE SORT *
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge()
function is used for merging two halves. The merge(arr, l, m, r) is key process that
assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays
into one.
merge(arr, l, m, r);
}
}
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
UNIT 7 *STRUCTURE*
A structure is a user defined data type in C/C++. A structure creates a data type that
can be used to group items of possibly different types into a single type.
Arrays allow to define type of variables that can hold several data items of the same
kind. Similarly structure is another user defined data type available in C that allows to
combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
*Defining a Structure*
To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member. The format of the struct statement is as
follows −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end of the
structure's definition, before the final semicolon, you can specify one or more structure
variables but it is optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
**What is an array of structures?
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
Output:
10 20
UNIT 8 *POINTERS*
A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a
pointer before using it to store any variable address.
*Declaration*
The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is
the name of the pointer variable. The asterisk * used to declare a pointer is the same
asterisk used for multiplication. However, in this statement the asterisk is being used to
designate a variable as a pointer.
Take a look at some of the valid pointer declarations −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address.
The only difference between pointers of different data types is the data type of the
variable or constant that the pointer points to.
There are a few important operations, which we will do with the help of pointers very
frequently.
(a) We define a pointer variable,
(b) assign the address of a variable to a pointer and
(c) finally access the value at the address available in the pointer variable. This is done
by using unary operator * that returns the value of the variable located at the address
specified by its operand. The following example makes use of these operations −
#include <stdio.h>
int main () {
Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
UNIT 9 *FILE HANDLING*
A file is nothing but a source of storing information permanently in the form of a
sequence of bytes on a disk. The contents of a file are not volatile like the C compiler
memory. The various operations available like creating a file, opening a file, reading a
file or manipulating data inside a file is referred to as file handling
*Need for File Handling in C*
There is a time when the output generated by compiling and running the program does
not serve the purpose. If we want to check the output of the program several times, it
becomes a tedious task to compile and run the same program multiple times. This is
where file handling comes into play. Here are some of the following reasons behind the
popularity of file handling:
Text files
These are the simplest files a user can create when dealing with file handling in C. It is
created with a .txt extension using any simple text editor. Generally, we use notepads
to create text files. A text file stores information in the form of ASCII characters
internally, but when you open the text file, you would find the content of the text
readable to humans.
Hence, it is safe to say that text files are simple to use and access. But, along with
advantages comes disadvantages as well. Since it is easily readable, it does not
provide any security of information. Moreover, it consumes large storage space. Hence,
there is a different type of file available called binary files which helps us solve this
problem.
Binary files
A binary file stores information in the form of the binary number system (0’s and 1’s)
and hence occupies less storage space. In simple words, it stores information in the
same way as the information is held in computer memory. Therefore, it proves to be
much easier to access.
It is created with a .bin extension. It overcomes the drawback offered by text files. Since
it is not readable to humans, the information is more secure. Hence, it is safe to say that
binary files prove to be the best way to store information in a data file.
*C File Handling Operations*
The C programming offers various operations associated with file handling. They are:
*fpointer is the pointer to the file that establishes a connection between the file and the
program.
Input
Output
Input / Output
The input/output operations in a file help you read and write in a file.
The simplest functions used while performing operations on reading and writing
characters in a file are getc() and putc() respectively..
Working with binary files is a bit more complicated than working with text files as the
syntax involves the use of more arguments.