[go: up one dir, main page]

0% found this document useful (0 votes)
91 views19 pages

C Language

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

UNIT – 5 *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 procedure or subroutine in 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.

*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.
*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.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {function body;}

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

return_type function_name(data_type parameter...){


//code to be executed
}

*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.

SN Header file Description

1 stdio.h This is a standard input/output header file.

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 all the general library functions like malloc(), calloc(), exit(), etc.

5 math.h 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.h This file contains all the jump functions.

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.


*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

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.

*Passing Arrays as Function Arguments in C*

If you want to pass a single-dimension array as an argument in a function, you would


have to declare a formal parameter in one of following three ways and all three
declaration methods produce similar results because each tells the compiler that an
integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays
as formal 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;

for (i = 0; i < size; ++i) {


sum += arr[i];
}

avg = sum / size;


return avg;
}

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>

unsigned long long int factorial(unsigned int i) {

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;

for (i = 0; i < 10; i++) {


printf("%d\t\n", fibonacci(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.

// C program to illustrate Ackermann function

#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>

// A utility function to swap two elements


void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j <= high- 1; j++)


{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}

// Driver program to test above functions


int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}

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.

/* C program for Merge Sort */


#include<stdlib.h>
#include<stdio.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */


int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays back into arr[l..r]*/


i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

while (j < n2)


{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m+1, r);

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");
}

/* Driver program to test above functions */


int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}

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?

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.

Like other primitive data types, we can create an array of structures.

#include<stdio.h>

struct Point
{
int x, y;
};

int main()
{
// Create an array of structures
struct Point arr[10];

// Access array members


arr[0].x = 10;
arr[0].y = 20;

printf("%d %d", arr[0].x, arr[0].y);


return 0;
}

Output:
10 20

UNIT 8 *POINTERS*

**What are 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.

**How to Use Pointers?

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 () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );
return 0;
}
When the above code is compiled and executed, it produces the following result
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

*Self Referential Structures*


Self Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.

Types of Self Referential Structures


1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links

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:

 Reusability: It helps in preserving the data or information generated after running


the program.
 Large storage capacity: Using files, you need not worry about the problem of
storing data in bulk.
 Saves time: There are certain programs that require a lot of input from the user.
You can easily access any part of the code with the help of certain commands.
 Portability: You can easily transfer the contents of a file from one computer system
to another without having to worry about the loss of data.

*Different Types of Files in C*


When talking about files with reference to file handling, we generally refer it to as data
files. There are basically 2 distinct types of data files available in the C programming
language:

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:

 Creating a new file: fopen()


 Opening an existing file in your system: fopen()
 Closing a file: fclose()
 Reading characters from a line: getc()
 Writing characters in a file: putc()
 Reading a set of data from a file: fscanf()
 Writing a set of data in a file: fprintf()
 Reading an integral value from a file: getw()
 Writing an integral value in a file: putw()
 Setting a desired position in the file: fseek()
 Getting the current position in the file: ftell()
 Setting the position at the beginning point: rewind()

*Opening a Text File in C*


We use the fopen() function to create or open a file as mentioned earlier. It is pretty
obvious that creating or opening a file is the first step in file handling. Once the file has
been created, it can be opened, modified or deleted.

The basic syntax of opening a file is:


1. *fpointer = FILE *fopen(const char *file_name, const char *mode);
Here,

*fpointer is the pointer to the file that establishes a connection between the file and the
program.

*file_name is the name of the file.

*mode is the mode in which we want to open our file

*Closing a Text File in C*


We use the fclose() function to close a file that is already open. It is pretty obvious that
the file needs to be opened so that the operation to close a file can be performed.
int fclose( FILE *fpointer);
Here, the fpointer is the pointer associated with closing the file. This function is
responsible for returning the value 0 if the file is closed successfully. Otherwise, EOF
(end of file) in case of any error while closing the file.

*Reading and Writing a Text File in C*


After discussing how to open and close a file, it is important to note that there are 3
types of streams (sequence of bytes) in a file:

 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..

*Reading and Writing a Binary File in C*


We use the fread() and fwrite() function to read and write data from a binary file
respectively.

Working with binary files is a bit more complicated than working with text files as the
syntax involves the use of more arguments.

The function fread() and fwrite() both take 4 arguments to work.

The basic syntax for reading a binary file in C is:


fread(data_address, data_size, number_of_data_items, file_pointer);

The basic syntax for writing in a binary file in C is:


fwrite(data_address, data_size, number_of_data_items,file_pointer);

You might also like