Professional Documents
Culture Documents
When we need to solve a large problem, we will divide that large problem into small sub
problems and solved individually to make the program easier.
In C this is concept is implemented using functions.
A function is a self contained block of statements that is used to carry out a particular task in a
program.
Functions are used to divide a large program into smaller entities known as sub programs.
Functions makes the program easy to understand and easy to implement.
Functions increase the readability and execution speed of the program.
Function supports reusability of the existing code.
Every C program must have atleast one function i.e. main() and can have other functions.
In C there are 2 types of functions.
1. Predefined/Library functions: The functions that are already defined in C in header files.
2. User-defined functions: The functions that are defined and used by the programmer himself as per
his requirement are called user-defined functions.
Working with functions:
Working with functions includes 3 steps.
1. Function Declaration (Function Prototype)
2. Function Call
3. Function Definition
Function Declaration: The function declaration tells the interface of the function to the compiler such as
data type of the return value, name of the function, number and type of parameters it receive. The
function declaration is also called as function prototype. The function declaration is a declaration
statement. It can be before main function or inside main function at the beginning point or inside any
other function.
Syntax: returnType functionName( parametersList );
returnType specifies the data type of the value that is sent as return value from the function.
functionName is a name that is used to identify the function uniquely.
parameterList contains number and type of values that are received by the functions as input.
Each parameter will have 2 parts, data type of the parameter and parameter name.
Ex: int sum(int x,int y); Here int --> returnType, sum---> function Name, int x,int y -->
Parameters
Each parameter must be specified individually and separately i.e. int sum(int x,int y);.
Common declaration like int sum(int x,y) is illegal.
In parametersList the parameter name if optional that means you can specify as int sum(int , int
);
Function Call: The function call invokes the definition of the function. It tells the compiler when to
execute the function definition. When a function is called, the execution control jumps to the function
definition where the function statements get executed and returns to the same functions call once the
execution completes. While calling a function we must pass all the necessary values through
parameters. .
Syntax - variable = functionName(parameters);
Ex: int s = sum(10,20); or int s = sum(a,b); Here 10 and 20, a and b are parameters.
Function Definition: The function definition contains a set of statements that are used to implement that
particular function's task. The function definition is also known as body of the function.
Function definition's header is similar to function declaration and includes { } to define the
statements.
In function definition the parameter names are must and they acts like dummy variables.
The parameter names in function declaration and function definition need not to be same.
Usually a function definition terminates with the "return" statement.
Advantages of functions:
Using funcions we can implement modular programming.
Functions makes the program more readable and understandable.
Using functions the program implementation becomes easy.
Once a function is created it can be used many times (code re-usability).
Using functions larger program can be divided into smaller modules.
#include <stdio.h>
#include<conio.h>
int sum(int,int) ; // function declaration
void main()
{
int num1, num2, result ;
clrscr() ; Actual Arguments
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = sum(num1, num2) ; // function call Calling function
printf("SUM = %d", result);
getch() ; Forma Arguments
}
int sum(int a, int b) // function definition
{
int c; Called function
c = a + b;
return(c);
}
In the above example program, the function declaration statement "int sum(int,int)" tells the
compiler that there is a function with name sum which takes two integer values as parameters
and returns an integer value.
The function call statement takes the execution control to the sum() definition along with values
of num1 and num2.
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}
Scope of variables:
Scope of a variable is the portion of the program where a defined variable can be accessed.
The variable scope defines the visibility of variable in the program. Scope of a variable depends on
the position of variable declaration.
Global Declaration (Before the function definition)
Local Declaration (Inside the function or block)
Global Declaration (Global Variables)
Declaring a variable before the function definition (outside the function definition) is called global
declaration. The variable declared using global declaration is called global variable. The global
variable can be accessed by all the functions that are defined in the program.
#include <stdio.h>
#include<conio.h>
int num1, num2 ;
void main(){
void addition() ;
void subtraction() ;
void multiplication() ;
clrscr() ;
Output:
num1 = 10, num2 = 20
addition = 30
subtraction = -10
multiplication = 200
In the above example program, the variables num1 and num2 are declared as global variables. They
are declared before the main() function. So, they can be accessed by function main() and other
functions that are defined after main(). In the above example, the functions main(), addition(),
subtraction() and multiplication() can access the variables num1 and num2.
Local Declaration (Local Variables)
Declaring a variable inside the function or block is called local declaration. The variable declared
using local declaration is called local variable. The local variable can be accessed only by the function
or block in which it is declared. That means the local variable can be accessed only inside the function.
#include <stdio.h>
#include<conio.h>
void main(){
void addition() ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
getch() ;
}
void addition()
{
int sumResult ;
sumResult = num1 + num2 ;
printf("\naddition = %d", sumResult) ;
}
Output:
void func() {
int n1; // n1 is local to func() function
}
In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed when main() exits.
extern storage class:
The variables that are declared with "extern" are external variables. Their life time and scope is entire
program. They are created when the program execution begin and remains until the program
termination. all the global variables are extern variables.
#include <stdio.h>
void display();
extern int n = 5; // global variable
int main()
{
++n; // variable n is not declared in the main() function
display();
return 0;
}
void display()
{
++n; // variable n is not declared in the display() function
printf("n = %d", n);
}
Output
n=7
Register Variable
The register keyword is used to declare register variables. The memory for the register variables are
allocated in register memory location instead of RAM. Register variables were supposed to be faster
than local variables. Using of register variables will make program faster.
A positive value for the offset specifies that the pointer moves forward and a negative value
for the offset specify that the pointer moves backward from the current position. Following are
some of the example usages of the fseekfunction:
#include <stdio.h>
int getSum(int, int);
int getDifference(int, int);
int getProduct(int, int);
int getDivision(int, int);
int main()
{
int (*arrayFp[4])(int, int);
arrayFp[4] = {getSum, getDifference, getProduct, getDivision};
int a = 50, b = 20;
printf("Sum of %d and %d : %d\n", a, b, arrayFp[0](a, b));
printf("Difference of %d and %d : %d\n", a, b, arrayFp[1](a, b));
printf("Product of %d and %d : %d\n", a, b, arrayFp[2](a, b));
printf("Division of %d and %d : %d\n", a, b, arrayFp[3](a, b));
}
int getSum(int x, int y)
{
return x + y;
}
int getDifference(int x, int y)
{
return x - y;
}
int getProduct(int x, int y)
{
return x * y;
}
int getDivision(int x, int y)
{
return x / y;
}
Pointer Arithmetic in C
In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable.
Increment
Decrement
Addition
Subtraction
Comparison
Incrementing Pointer in C
Increment operation depends on the data type of the pointer variable. The formula of incrementing
pointer is
new_address= current_address + i * size_of(data type)
For 32 bit int variable, it will increment to 2 byte.
For 64 bit int variable, it will increment to 4 byte.
Decrementing Pointer in C
We can decrement a pointer variable. The formula of decrementing pointer is given below:
new_address= current_address - i * size_of(data type)
For 32 bit int variable, it will decrement to 2 byte.
For 64 bit int variable, it will decrement to 4 byte.
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
new_address= current_address + (number * size_of(data type))
For 32 bit int variable, it will add 2 * number.
For 64 bit int variable, it will add 4 * number.
C Pointer Subtraction
We can subtract a value from the pointer variable. The formula of subtracting value from pointer
variable is given below:
new_address= current_address - (number * size_of(data type))
For 32 bit int variable, it will subtract 2 * number.
For 64 bit int variable, it will subtract 4 * number.
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of <stdlib.h>
malloc()
free()
Before learning above functions, let's understand the difference between static memory allocation and
dynamic memory allocation.
Static memory allocation Dynamic memory allocation
int main()
{
struct name *ptr;
}
Here, the pointer variable of type struct name is created.
Accessing structure's member through pointer
Structure pointer member can also be accessed using -> operator.
(*personPtr).age is same as personPtr->age
(*personPtr).weight is same as personPtr->weight
Self referential structure:
The structure that represents itself is called as a referential structure. It is done by creating a pointer to
the structure as a member in the same structure and assigning the address of structure variable to that
pointer.
Example:
struct Node
{
int data;
struct Node *link;
}*nOne;
link = &nOne;
Here the link is pointer of struct Node that represent the nOne which is the Node structure's variable.
Union:
Union is also a derived data type that is used to declare variables of different types.
But it occupies common memory for all members of the union.
It occupies in which data type the largest memory is declared as the common memory
It accepts any type of value into that memory.
But when we enter a new value the previous value will be erased.
Enumeration (or enum) in C
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.
enum State {Working = 1, Failed = 0};
The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an example
of enum declaration.
// The name of enumeration is "flag" and the constant
// are the values of the flag. By default, the values
// of the constants are as follows:
// constant1 = 0, constant2 = 1, constant3 = 2 and
// so on.
enum flag{constant1, constant2, constant3, ....... };
// Or
File Handling in C
A file is a collection of information stored on a particular area of the disk. Till now we only work with
internal memory i.e. RAM which can store data temporarily. If we want to store data in the computer
memory permanently, then we use the concept of Files.
File operations include the following:
Creation of a new file / Opening an existing file
Reading from file / Writing to a file
Closing a file
Opening or creating file –
For opening a file, fopen function is used with the required access modes. Some of the commonly used
file access modes are:
“r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. If the file cannot be opened fopen( ) returns
NULL.
“w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open file.
“a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer that points to the last character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.
“r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. Returns NULL, if unable to open the file.
“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new
file is created. Returns NULL, if unable to open file.
“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns
NULL, if unable to open file.
FILE *fp;
So, the file can be opened as
fp = fopen(“fileName.txt”, “w”)
Reading from a file
The file read operations can be performed using functions fscanf() or fgets(). Both the functions
performed the same operations as that of printf() and gets but with an additional parameter, the file
pointer. So, it depends on you if you want to read the file line by line or character by character.
And the code snippet for reading a file is as:
FILE * fp;
fp = fopen(“fileName.txt”, “r”);
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
Writing a file