0% found this document useful (0 votes)
36 views63 pages

Important - Topics SLOW LEARNERS

The document outlines important topics for the CS3251 Programming in C course, structured into five units covering fundamental concepts such as program structure, decision-making statements, string operations, pointers, structures, file handling, and looping statements. Each unit includes specific topics and examples to aid understanding. The document serves as a study guide for slow learners preparing for university examinations.

Uploaded by

jamila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views63 pages

Important - Topics SLOW LEARNERS

The document outlines important topics for the CS3251 Programming in C course, structured into five units covering fundamental concepts such as program structure, decision-making statements, string operations, pointers, structures, file handling, and looping statements. Each unit includes specific topics and examples to aid understanding. The document serves as a study guide for slow learners preparing for university examinations.

Uploaded by

jamila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

CS3251: PROGRAMMING IN C

Important topics to be covered for University Examination (Don’t skip any of these topics)

Note: This is only for slow learners.

UNIT I

 Structure of C program
 Decision making statements
 Switch statement
 Looping statements
 Precedence and Associativity
 Preprocessor directives

UNIT II

 String operations like string length, compare, concatenate and copy


 Selection sort
 Linear search
 binary search

UNIT III

 Binary Search using recursive functions


 Pointers and Pointer operators
 Pointer arithmetic
 Arrays and pointers & Array of pointers
 Parameter passing: Pass by value, Pass by reference.

UNIT IV

 Structures or (UNION)
 Nested structures
 Self-referential structures or (singly linked list)
 Dynamic memory allocation

UNIT V

 Sequential access file


 Random access file
 Command line arguments
UNIT I
 Structure of C program
The structure of C program includes the following sections:

i.Documentation section
The documentation section consists of a set of comment lines giving:
 The name of the program,
 The author and
 Other details, which the programmer would like to use later.
Example:
//Factorial Program
//Written by Siva

ii.Link section (Preprocessor statement)


The link section provides instructions to the compiler to link functions from the system library
such as using the #include directive.
Example: #include<stdio.h>
#include<conio.h>

iii.Definition section
The definition section defines all symbolic constants such using the #define directive.
Example: #define pi 3.14

iv.Global declaration section:


There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section
that is outside of all the functions.
This section also declares all the user-defined functions.
Example:
float num = 2.54;
int a = 5;
char ch ='z‘ ;
v.main () function section
Every C program must have one main function section.
We can also use int or main with the main ().
The void main() specifies that the program will not return any value.
The int main() specifies that the program can return integer type data.
This section contains two parts declaration part and executable part
i. Declaration part:
The declaration part declares all the variables used in the executable part.
ii. Executable part:
There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces.
The program execution begins at the opening brace and ends at the closing brace.
The closing brace of the main function is the logical end of the program.
All statements in the declaration and executable part end with a semicolon.
vi.Subprogram section
If the program is a multi-function program then the subprogram section contains all
the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main () function,
although they may appear in any order.
Example:
int add(int a, int b)
{
return (a+b);
}
 Decision making statements
Decision making statements in a programming language help the programmer to transfer the
control from one part to other part of the program. Program control is transferred from one
point to another based on the result of some condition.
Decision making statements are also called as conditional statements in C.
Conditional Statements in C are:
1. if statement
2. if-else statement
3. Nested if-else statement
4. If … else if ladder
1. if Statement
if - statement is used to test a condition or Boolean expression(logical expression Eg:- ( x>y),
(x==y), (x!=y)). If the condition is true then the if block statements will be executed.
The if statement contains a logical expression using which data is compared and a decision is
made based on the result of comparison
if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statement is executed otherwise not.
Syntax:

Example-1 (program to find out the greater number)


#include<stdio.h>
void main()
,
int a, b;
a=30;
b=90;
if(b > a)
printf("b is greater than a");
if(a> b)
printf("a is greater than b");
-

Output
b is greater than a
2. If…else Statement
The if…else statement evaluates test expression and will execute body of if only when test
condition is True. If the condition is False, body of else is executed. Finally come to the X-
statement which immediately follows the if…else block.

Example-1 (program to check whether the given number is odd or even)


#include <stdio.h>
void main()
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if(num % 2 == 0)
{
printf("%d is even.", num);
}
else
{
printf("%d is odd.", num);
}
}
Output
Enter an integer: 27
27 is odd.

3. Nested if-else statement


We can have a if...else statement inside another if…else statement. This is called nesting in
computer programming.
Example (program to find the largest among three numbers)
#include <stdio.h>
int main()
,
int n1, n2, n3;
printf("Enter three numbers\n");
scanf("%d %d %d", &n1, &n2, &n3);
if (n1 >= n2)
,
if (n1 >= n3)
printf("%d is the greatest number", n1);
else
printf("%d is the greatest number.", n3);
-
else
,
if (n2 >= n3)
printf("%d is the greatest number.", n2);
else
printf("%d is the greatest number.", n3);
-
-

Output
Enter three numbers
25
90
45
90 is the greatest number.

4. If … else if ladder
This is used to check multiple conditions
If condition-1 is false, then it checks the condition-2 of the else if block, if this is also false then
it checks the condition-3 of the next else if block and so on. If all the given conditions are false
then it execute the else block.
Among the several if…else if block only one block is executed accordingly to the condition.
The chained conditional (if…else if ...else ) block can have only one else block, but it can have
multiple else if blocks.

Example:- Program to print the grade of a student


#include <stdio.h>
int main()
,
int s1,s2,s3,s4,s5,t,p;
printf("Enter marks of 5 subjects each out of 100 ");
scanf("%d %d %d %d %d ",&s1, &s2, &s3, &s4, &s5);
t=s1+s2+s3+s4+s5;
p=t/5;
if(p>=90)
printf("\n\n Your Grade : O");
else if(p>=80)
printf("\n\n Your Grade : A+");
else if(p>=70)
printf("\n\n Your Grade : A");
else if(p>=60)
printf("\n\n Your Grade : B");
else if(p>=50)
printf("\n\n Your grade : C");
else
printf("\n R - Fail");
-

Output
Enter marks of 5 subjects each out of 100
Maths = 75
Science = 85
English = 90
History = 95
Geography = 92
Your Grade : A+
 Switch statement
Switch statements are similar to if-else-if statements.
Switch statement in C tests the value of a variable and compares it with multiple cases. Once
the case match is found, a block of statements associated with that particular case is executed.
Each case in a block of a switch has a different name/number which is referred to as an
identifier. The value provided by the user is compared with all the cases inside the switch block
until the match is found.
The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.
The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.

Rules to be followed on switch statement:


 Cases cannot be duplicate.
 Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
 Break statement may be included which terminates the switch block when the condition is
satisfied. If omitted, execution will continue on into the next case.

Syntax of Switch statement:


switch (expression)
,
case constant1:
<statements >
break;
case constant2:
<statements >
break;
.
.
.
default:
<default statements >
-

Example Program:
C program to design a menu-based calculator to perform various basic arithmetic operations
like addition, subtraction, multiplication and division
#include<stdio.h>
#include <stdlib.h>
void main()
{
int ch,a,b,c;
printf("Enter the choice\n");
printf("1) Addition\n 2) Subtraction\n 3) Multiplication\n 4) Division\n 5) Square\n 0)Exit\n");
scanf("%d",&ch);
switch(ch)
,
case 1:
printf("Enter two numbers to be added:");
scanf("%d %d",&a,&b);
c=a+b;
printf("The sum of two numbers %d and %d is:%d",a,b,c);
break;
case 2:
printf("Enter two numbers to be subtracted:");
scanf("%d %d",&a,&b);
c=a-b;
printf("The difference of two numbers %d and %d is:%d",a,b,c);
break;
case 3:
printf("Enter two numbers to be multiplied:");
scanf("%d %d",&a,&b);
c=a*b;
printf("The product of two numbers %d and %d is:%d",a,b,c);
break;
case 4:
printf("Enter two numbers to be divided:");
scanf("%d %d",&a,&b);
c=a/b;
printf("The division of two numbers %d and %d is:%d",a,b,c);
break;
case 0:
exit(0);
default:
printf("Invalid option");
-
-
Output
Enter the choice
1) Addition
2) Subtraction
3) Multiplication
4) Division
0) Exit
3
Enter two numbers to be multiplied:5 8
The product of two numbers 5 and 8 is 40
 Looping statements
Different types of looping statements in C are:
1. For
2. While
3. Do While

1. For
A for loop is used for iterating over a sequence of statements
To iterate over a series of statements for loop uses three parameters like initial value of the
iterating variable, Condition for exit of loop and increment or decrement statement.

Syntax: for (initialization ; expression; increment/Decrement)


{
// statements inside the body of loop
}

Example:
for (i = 1; i < 11; i++)
{
printf("%d ", i);
}

Execution of for loop:


The initialization statement is executed only once.
Then, the test expression /condition is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
However, if the test expression is evaluated to true, statements inside the body of the for loop
are executed, and the expression is updated by executing the increment/decrement statement.
Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the
loop terminates.

Example: Program to calculate the sum of first n natural numbers.


#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
}
Output
Enter a positive integer: 10
Sum = 55

2. While Loop
A while loop statement in Python programming language repeatedly executes one or more
target statements as long as a given condition is true.

The syntax of the while loop is: while (testExpression)


,
Statements // the body of the loop
-
Example:
while (i <= 5)
{
printf("%d\n", i);
i++;
}

Execution of while loop:


The while loop evaluates the testExpression inside the parentheses ().
If testExpression is true, statements inside the body of while loop are executed. Then,
testExpression is evaluated again.
The process goes on until testExpression is evaluated to false.
If testExpression is false, the loop terminates.

Example:
Program to print ODD numbers from 1 to N using while loop.
#include <stdio.h>
int main()
{
int number;
int n;
number=1;
printf("Enter the value of N: ");
scanf("%d",&n);
printf("Odd Numbers from 1 to %d:\n",n);
while(number<=n)
{
if(number%2 != 0)
printf("%d ",number);
number++;
}
}

Output
Enter the value of N: 10
Odd Numbers from 1 to 10:
13579

3. do...while loop
The do..while loop is similar to the while loop with one important difference. The body of
do...while loop is executed at least once. Only then, the test expression is evaluated.
It is a type of exit control loop statement.
The syntax of the do...while loop is:
do
,
Statement(s) // the body of the loop
-
while (testExpression);
Execution of do...while loop:
The body of do...while loop is executed once. Only then, the testExpression is evaluated.
If testExpression is true, the body of the loop is executed again and testExpression is evaluated
once more.
This process goes on until testExpression becomes false.
If testExpression is false, the loop ends.

Example:
Program to add numbers until the user enters zero
#include <stdio.h>
void main() {
int number, sum = 0;
do {
printf("Enter a number: ");
scanf("%d", &number);
sum += number;
} while(number != 0);
printf("Sum = %d",sum);
}

Output
Enter a number: 25
Enter a number: 15
Enter a number: 20
Enter a number: 30
Enter a number: 0
Sum = 90
 Precedence and Associativity
Operator precedence:
The operator precedence determines the order in which the C compiler evaluates the operators
in an expression.
Even though an expression may contain lot of operators, the operations on the operands are
carried out according to the priority known as precedence of operators.
The operator having highest priority is evaluated first, and then the operator having the next
highest priority is evaluated and so on.
Precedence rule:
Parentheses ‘( )’ have the highest precedence and can be used to force an expression to
evaluate in the order as required. So parentheses can be used to change the order of
evaluation.
Example:
Since expressions in parentheses are evaluated first.
2 * (3 - 1) = 4
(1 + 1) ** (5 - 2) = 8
We can also use parentheses to make an expression easier to read.
Example:
(minute * 100) / 60
This expression is easier and clear to read, even with out using parenthesis it doesn’t change
the result.
Exponentiation has the next highest precedence, so 2 *3**2 is 18, not 36.
Unary operators are evaluated next.
Multiplication and Division have higher precedence than Addition and Subtraction.
Therefore 2 * 3 - 1 = 5, not 4, and 6 + 4 / 2 = 8, not 5.
Addition and Subtraction are evaluated before assignment.

The order of evaluation depends on the priority of operators

Associativity in Precedence
When the expression contains operators with equal precedence, then associativity decides
which operations is to be performed first.
It implies the direction of execution.
 Left to Right (Left associative)
 Right to Left (Right associative)
Operators with the same precedence are left associative, so they are evaluated from left to
right (except exponentiation and assignment operators).
Left associative (Left to Right )
In this type, the evaluation is from left to right.

Thus Z = 20
Exponentiation and assignment operators are right associative, so they are evaluated from
right to left.

Right associative (Right to Left)


In this type, the evaluation is from right to left.
Example 1:
a = b = c = 25
Here the value 25 will be assigned to the variable c first then it is assigned to the variable b
and then to variable a.

Finally assign the value 53 to Z.


 Preprocessor directives
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Preprocessor programs provide preprocessors directives which tell the compiler to preprocess
the source code before compiling. Commands used in preprocessor are called preprocessor
directives. All of these preprocessor directives begin with a ‘#’ (hash) symbol.
Examples of some preprocessor directives are: #include, #define, #ifndef etc.
This # symbol only provides a path that it will go to the preprocessor, and command such as
include is processed by preprocessor program. For example, include will include extra code to
your program. We can place these preprocessor directives anywhere in our program.

There are 4 main types of preprocessor directives:


1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives

1. Macros:
Macros are a piece of code in a program which is given some name. Whenever this name is
encountered by the compiler the compiler replaces the name with the actual piece of code.
The ‘#define’ directive is used to define a macro.
These macro definitions allow constant values to be declared for use throughout your code.
Macro definitions are not variables and cannot be changed by your program code like
variables. You generally use this syntax when creating constants that represent numbers,
strings or expressions.
Output
Enter the radius r: 5
The area of circle of radius 5 is 78.500000
Enter the radius r: 7
The area of circle of radius 7 is 153.860001

In the above program, when the compiler executes the word Pi it replaces it with 3.14
The word ‘Pi’ in the macro definition is called a macro template and ‘3.14’ is macro expansion.

2. File Inclusion:
This type of preprocessor directive tells the compiler to include a file in the source code
program.
There are two types of files which can be included by the user in the program, they are header
files and user defined files.

header files
When a program becomes very large, it is good practice to divide it into smaller files and
include whenever needed. These types of files are user defined files. These files can be included
as:
#include"filename“
Example:
:
These files contains definition of pre-defined functions like printf(), scanf() etc. These files must
be included for the proper working with these functions.
Different function are declared in different header files. For example standard I/O functions
are in ‘stdio.h’ file whereas functions which perform string operations are in ‘string.h’ file.
Syntax:
#include< file_name >
Example:
#include< stdio.h >
#include< string.h >

user defined files


When a program becomes very large, it is good practice to divide it into smaller files and
include whenever needed. These types of files are user defined files. These files can be included
as:
#include"filename“
Example:
myfile.c myprog.c

int add(int a, int b) #include<stdio.h>


{
#include"myfile.c"
int ans;
ans = a+b; void main()
return ans; {
}
int a1, b1, sum, product;
int mult(int a, int b)
{ a1=10;
int ans; b1=5;
ans = a*b; sum = add(a1,b1);
return ans;
} product= mult(a1,b1);
printf("The sum is %d \nThe product is %d",sum, product);
Output }
The sum is 15
The product is 50

3. Conditional Compilation:
Conditional Compilation directives are type of directives which helps to compile a specific
portion of the program or to skip compilation of some specific part of the program based on
some conditions. This can be done with the help of two preprocessing commands ‘ifdef‘ and
‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif

Other Conditional Compilation directives: #ifdef, #endif, #if, #else, #ifndef


Set of commands are included or excluded in source program before compilation with respect
to the condition.

Example -1
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}

Output
RAJU is defined. So, this line will be added in this C file

4. Other directives:
The other directives used in C are #undef, #pragma etc.
Syntax: #undef, #pragma
 #undef is used to undefine a defined macro variable.
 #Pragma is used to call a function before and after main function in a C program.

i. Example program for #undef


#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
printf("value of height after undef \& redefine:%d",height);
}

Output
First defined value for height : 100
value of height after undef & redefine : 600
UNIT II
 String operations like string length, compare, concatenate
and copy
The group of characters, digits, & symbols enclosed within double quotes is called as Strings.
Every string is terminated with the NULL (‘\0’) character.
E.g. “INDIA” is a string. Each character of string occupies 1 byte of memory. The last character
is always ‘\0’.
Declaration:
String is always declared as character arrays.
Syntax: char stringname*size+;
E.g. char a*20+;

Initialization:
1. We can use 2 ways for initializing.
By using string constant
E.g. char str*6+= “Hello”;
2.By using initialisation list
E.g. char str*6+=,‘H’, ‘e’, ‘l’, ;l’, ;o’, ‘\0’-;

String Operations or String Functions


There are many important string functions defined in "string.h" library.
Functions Descriptions

strlen() Determines the length of a String

strcpy() Copies a String from source to destination

strcmp() Compares two strings

strlwr() Converts uppercase characters to lowercase

strupr() Converts lowercase characters to uppercase

strcat() Appends source string to destination string

strrev() Reverses all characters of a string

strstr() Determines the first occurrence of a given String in another string

1. strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not counted.
Syntax: variable = strlen(string_name);

E.g.
s= “welcome”;
strlen(s)
-> returns the length of string s as 7.
2. strcpy() function
It copies the source string to the destination string
Syntax : strcpy ( destination, source);
E.g.
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); -> s2 is copied to s1. i.e. s1=welcome

3. strcat() function
It concatenates a second string to the end of the first string.
Syntax: strcat( firststring, secondstring );
E.g.
s1=“good ”;
s2= “ evening”;
strcat(s1,s2); -> s2 is joined with s1. Now s1 is good evening.

Example Program:
#include <stdio.h>
#include <string.h>
void main ()
,
char str1*20+ = "Hello";
char str2*20+ = "World";
char str3*20+;
int len ;
strcpy(str3, str1);
printf("Copied String: %s\n", str3 );
strcat( str1, str2);
printf("Concatenated String is: %s\n", str1 );
len = strlen(str1);
printf("Length of string str1 is %d\n", len );
return 0;
-

Output
Copied String: Hello
Concatenated String is: HelloWorld
Length of string str1 is 10

4. strcmp() function
It is used to compare 2 strings.
Syntax: varaible=strcmp(string1,string2);
 If the first string is greater than the second string a positive number is returned.
 If the first string is less than the second string a negative number is returned.
 If the first and the second string are equal 0 is returned.
Example: String Comparison
#include<stdio.h>
#include<string.h>
void main()
,
char s1*20+,s2*20+;
int val;
printf(“Enter String 1\n”);
gets(s1);
printf(“Enter String 2\n”);
gets (s2);
val=strcmp(s1,s2);
if (val==0)
printf(“Two Strings are equal”);
else
printf(“Two Strings are not equal”);
-

Output
Enter String 1
Computer
Enter String 2
Programming
Two Strings are not equal

5. strlwr() function:
It changes all the characters of the string to lower case.
Syntax : strlwr(string variable_name);
It shall convert the whole string stored in the variable name*+ to lowercase.

6. strupr() function:
It changes all the characters of the string to upper case. Syntax: strupr(string variable_name);
It shall convert the whole string stored in the variable name*+ to uppercase.

Example:
#include<stdio.h>
#include <string.h>
int main(),
char str*20+;
printf("Enter string: ");
gets(str);
printf("String is: %s",str);
printf("\nLower case String is: %s", strlwr(str));
printf("\nUpper case String is: %s", strupr(str));
return 0;
-

Output
Enter string: Welcome You All
String is: Welcome You All
Lower case String is: welcome you all
Upper case String is: WELCOME YOU ALL

7. strrev() function:
strrev( ) function reverses a given string in C language.
Syntax for strrev( ) function: strrev(string name)
Exapmle:
char name*20+;
strrev(name)

Example program:
#include<stdio.h>
#include<string.h>
void main()
,
char name*30+ = "Hello";

printf("String before strrev( ) : %s\n",name);

printf("String after strrev( ) : %s",strrev(name));


-

Output
String before reversing : Hello
String after reversing : olleH
 Selection sort
Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in
each iteration and places that element at the beginning of the unsorted list.
Lets consider an example: arr*+ = ,20, 12, 10, 15, 2-
Iteration-1:
1. Set the first element as minimum.

2. Compare minimum with the second element. If the second element is smaller than minimum,
assign the second element as minimum. Compare minimum with the third element. Again, if
the third element is smaller, then assign third element as minimum otherwise do nothing. The
process goes on until the last element.

After each iteration, minimum is placed in the front of the unsorted list. By swapping the
particular position element with the minimum.

For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated
until all the elements are placed at their correct positions.

Iteration-2:
Iteration-3:

Iteration-4:

Selection Sort Algorithm:

selectionSort(array, size)
repeat (size - 1) times
set the first unsorted element as the minimum
for each of the unsorted elements
if element < currentMinimum
set element as new minimum
swap minimum with first unsorted position
end selectionSort

Program:
#include <stdio.h>
void selectionSort(int array*+, int size)
,
int temp;
for (int i = 0; i < size - 1; i++)
,
int minindx = i;
for (int j = i + 1; j < size; j++)
,
if (array*j+ < array*minindx+)
minindx = j;
-
temp = array*minindx+;
array*minindx+ = array*i+;
array*i+ = temp;
-
-
void main()
,
int data*+ = ,20, 12, 10, 15, 2-;
int size = sizeof(data)/sizeof(data*0+);
printf("Array before sorting:\n");
for (int i = 0; i < size; ++i)
,
printf("%d ", data*i+);
-
printf("\nArray After sorting:\n");
selectionSort(data, size);
for (int i = 0; i < size; ++i)
,
printf("%d ", data*i+);
-
-

Output
Array before sorting:
20 12 10 15 2
Array After sorting:
2 10 12 15 20
 Linear search
Searching is an operation in which a given list is searched for a particular value. If the value is
found its position is returned.
Types of searching:
i. Linear Search
ii. Binary Search

1. Linear Search
The search is linear. The search starts from the first element & continues in a sequential
fashion till the end of the list is reached.
It is slower method.
Linear search is also called as sequential search algorithm.
It is the simplest searching algorithm.
In Linear search, we simply traverse the list completely and match each element of the list with
the item whose location is to be found. If the match is found, then the location of the item is
returned; otherwise, the algorithm returns NULL.

Algorithm for implementing linear search:


Step 1: First, read the search element (Target element) in the array.
Step 2: In the second step compare the search element with the first element in the array.
Step 3: If both are matched, display "Target element is found" and terminate the Linear Search
function.
Step 4: If both are not matched, compare the search element with the next element in the array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target) element is compared with the
last element of the array.
Step 6: If the last element in the list does not match, the Linear Search function will be terminated,
and the message "Element is not found" will be displayed.

Program:
#include<stdio.h>
#include<conio.h>
void main()
,
int a*10+,i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++)
scanf("%d",&a*i+);
printf("Enter the number to be searched: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++)
,
if(a*i+==m)
,
printf("Element is in the position %d\n",i+1);
c=1;
break;
-
-
if(c==0)
printf("The number is not in the list");
-

Output
Enter the size of an array: 5
Enter the elements of the array:
25
15
20
35
40
Enter the number to be searched: 35
Element is in the position 4
 binary search
Searching is an operation in which a given list is searched for a particular value. If the value is
found its position is returned.
Types of searching:
1. Linear Search
2. Binary Search
2. Binary Search
If a list is already sorted then we can easily find the element using binary search.
It uses divide and conquer technique.
Binary search follows the divide and conquer approach in which the list is divided into two
halves, and the item is compared with the middle element of the list. If the match is found
then, the location of the middle element is returned. Else, if searching element is less than
middle element, search the left half else search the right half. Repeat these processes again.
Binary search is faster than the linear search. Its time complexity is O(log(n)), while that of the
linear search is O(n). However, the list should be in ascending/descending order.

Algorithm:
Step 1: START.
Step 2: Accept the sorted array
Step 3: Accept key to be searched.
Step 4: first=0.
Step 5: last=n-1.
Step 6: mid= (first + last) / 2.
Step 7: If k(mid)==key then Display “Record found at position mid” then go to step 10.
Step 8: If key<k(mid) then bottom=mid-1 else, top=mid+1.
Step 9: If top<=bottom then go to step 5.
Step 10: Display “Record not found”.
Step 11: STOP.

Program
#include<stdio.h>
void main()
,
int i, first, last, middle, n, s_elemet, array*100+;
printf("Enter number of elements: ");
scanf("%d",&n);
printf("Enter %d numbers:\n", n);
for (i = 0; i < n; i++)
scanf("%d",&array*i+);
printf("Enter the value to find: ");
scanf("%d", &s_elemet);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
,
if (array*middle+ < s_elemet)
first = middle + 1;
else if (array*middle+ == s_elemet)
,
printf("%d is present at index %d.\n", s_elemet, middle+1);
break;
-
else
last = middle - 1;
middle = (first + last)/2;
-
if (first > last)
printf("Not found! %d is not present in the list.\n", s_elemet);
-

Output
Enter number of elements:5
Enter 5 numbers:
25
15
35
40
10
Enter the value to find: 40
40 is present at index 4
UNIT III
 Binary Search using recursive functions Or (Explain about
Recursion)
Recursion is a common programming concept. It means that a function calls itself.
This has the benefit of meaning that you can loop through data to reach a result.
Recursive function: A function is said to be a recursive function if it calls itself.

There are two types of Recursion:


i. Direct Recursion
ii. Indirect Recursion

Problem Solution:
1. We will be having an array of numbers, we just need to find out the whether the element is
present in an array or not.
2. It can be done using Binary Search by recursion or iteration methods. Here in this problem
we will do it using recursion.
3. The basic idea behind Binary Search is that the array in which it is applied upon should be
sorted. It divides the whole array into two halves and proceeds to look for the key in
suitable part of divided array.
4. Worst case time complexity of Binary Search it is O(log n). The Best case time complexity
of Binary Search is O(1). The only condition for implementing Binary Search is that the
array should be sorted.

Binary Search program using recursive functions:


#include <stdio.h>
void binary_search(int [], int, int, int);
int main()
{
int key, n, i;
int list[25];
printf("Enter size of a list: ");
scanf("%d", &n);
printf("Enter elements in sorted order\n");
for(i = 0; i < n; i++)
{
scanf("%d",&list[i]);
}
printf("\n");
printf("Enter key to search: ");
scanf("%d", &key);
binary_search(list, 0, n, key);
}
void binary_search(int list[], int lo, int hi, int key)
{
int mid;
if (lo > hi)
{
printf("Number not found\n");
return;
}
mid = (lo + hi) / 2;
if (list[mid] == key)
{
printf("Key found in position %d\n",mid+1);
}
else if (list[mid] > key)
{
binary_search(list, lo, mid - 1, key);
}
else if (list[mid] < key)
{
binary_search(list, mid + 1, hi, key);
}
}

Output
Enter size of a list: 5
Enter elements in sorted order
10
40
90
110
150
Enter key to search: 90
Key found in position 3
 Pointers and Pointer operators
The Pointer is a variable that stores address of another variable. A pointer can also be used
to refer to another pointer function.
A pointer can be incremented/decremented, i.e., to point to the next/ previous memory
location.
The purpose of pointer is to save memory space and achieve faster execution time.
The general form of a pointer variable declaration is

Data_type *pointer_var_name;
Example: int *p1;
Here, Data_type is the pointer's base data 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.
Example:
int *ip; //pointer to an integer
double *dp; // pointer to a double
float *fp; //pointer to a float
char *ch //pointer to a character

Example program:
#include<stdio.h>
void main()
{
int x, y, z;
int *p1, *p2;
x=10;
y=20;
p1=&x;
p2=&y;
z= *p1 + *p2
printf(“%d “, z);
printf(“%d “, p1);
printf(“%d “,*p1);
printf(“%d “,&p2);
}

Operators in pointers

1. Referencing operator: A pointer variable is made to refer to an object. Reference


operator(&) is used for this. Reference operator is also known as address of (&) operator.
Example:
float a=12.5;
float *p;
p=&a;
printf(“%u”,p);
Here p will be assigned with address of variable a.
2. Dereferencing operator
The object referenced by a pointer can be indirectly accessed by dereferencing the pointer.
Dereferencing operator (*) is used for this .This operator is also known as indirection operator
or value- at-address
Example:
int b;
int a=12;
int *p;
p=&a;
b=*p;
printf(“%u”,p);
printf(“%d”,*p);
printf(“%d”,b);

Output
1000411
12
12

Example program
#include<stdio.h>
void main()
{
int a=12;
int *p;
int **pptr;
p=&a;
pptr=&p;
printf(“a value=%d”,a);
printf(“value by dereferencing p is %d \n”,*p);
printf(“value referencing p is %d \n”,&p);
printf(“value by dereferencing pptr is %d \n”,**pptr);
printf(“value of p is %u \n”,p);
printf(“value of pptr is %u\n”,pptr);
}

Output
a value=12
value by dereferencing p is 12
value referencing p is 100041
value by dereferencing pptr is 12
value of p is 1000
value of pptr is 2000
 Pointer arithmetic
Arithmetic operations on pointer variables are also possible.
Following arithmetic operations are possible on the pointer in C language
i. Increment
ii. Decrement
iii. Addition
iv. Subtraction
v. Comparison

1. Incrementing Pointer:
If we increment a pointer by 1, the pointer will start pointing to the immediate next location.
This is somewhat different from the general arithmetic since the value of the pointer will get
increased by the size of the data type to which the pointer is pointing.
The Rule to increment the pointer is given below:
new_address= current_address + i * size_of(data type)
Where i is the number by which the pointer get increased.

Example program:
#include <stdio.h>
void main() {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[0];

for ( i = 0; i < 3; i++)


{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++;
}
}

Output
Address of var[0] = 22FE30
Value of var[0] = 10
Address of var[1] = 22FE34
Value of var[1] = 100
Address of var[2] = 22FE38
Value of var[2] = 200

2. Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type.
The Rule to increment the pointer is given below:
new_address= current_address - i * size_of(data type)
Where i is the number by which the pointer get increased.
Example program:
#include <stdio.h>
void main ()
{
int var[] = {10, 100, 200};
int i, n, *ptr;
n=3;
ptr = &var[n-1];
for (i=n; i > 0; i--)
{
printf("Address of var[%d] = %x\n", i-1, ptr );
printf("Value of var[%d] = %d\n", i-1, *ptr );
ptr--;
}
}

Output
Address of var[2] = 22FE38
Value of var[2] = 200
Address of var[1] = 22FE34
Value of var[1] = 100
Address of var[0] = 22FE30
Value of var[0] = 10

3. Comparison in pointer:
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2
point to variables that are related to each other.
#include <stdio.h>
void main()
{
int var[] = {10, 100, 200};
int i, n, *ptr;
n=3;
ptr = var;
i = 0;
while ( ptr <= &var[n-1] )
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++;
i++;
}
}

Output
Address of var[0] = 22fe30
Value of var[0] = 10
Address of var[1] = 22fe34
Value of var[1] = 100
Address of var[2] = 22fe38
Value of var[2] = 200

4 .Pointer Addition:
When a pointer is added with a value, the value is first multiplied by the size of data type and
then added to the pointer.
Example:
#include<stdio.h>
void main(){
double num = 50.3;
char a = 'u';
double *ptr;
char *ptr1;
ptr = &num;
ptr1 = &a;
printf("\n The address which the pointer ptr holds is %u",ptr);
printf("\n The address which the pointer ptr1 holds is %u",ptr1);
ptr = ptr + 4;
ptr1 = ptr1 + 4;
printf("\n Now the address which the pointer ptr holds is %u",ptr);
printf("\n Now the address which the pointer ptr1 holds is %u",ptr1);
}

Output
The address which the pointer ptr holds is 2293304
The address which the pointer ptr1 holds is 2293303
Now the address which the pointer ptr holds is 2293336
Now the address which the pointer ptr1 holds is 2293307

5. Pointer Subtraction:
When a pointer is subtracted with a value, the value is first multiplied by the size of the data
type and then subtracted from the pointer.
Example:
#include<stdio.h>
void main(){
double num = 50.3;
char a = 'u';
double *ptr;
char *ptr1;
ptr = &num;
ptr1 = &a;
printf("\n The address which the pointer ptr holds is %u",ptr);
printf("\n The address which the pointer ptr1 holds is %u",ptr1);
ptr = ptr - 4;
ptr1 = ptr1 - 4;
printf("\n Now the address which the pointer ptr holds is %u",ptr);
printf("\n Now the address which the pointer ptr1 holds is %u",ptr1);
}

Output
The address which the pointer ptr holds is 2293304
The address which the pointer ptr1 holds is 2293303
Now the address which the pointer ptr holds is 2293272
Now the address which the pointer ptr1 holds is 2293299
 Arrays and pointers & Array of pointers
In C language, pointers and arrays are so closely related.
i) An array name itself is an address or pointer. It points to the address of first element (0th
element) of an array.
Example:
#include<stdio.h>
void main()
{
int a[3]={10,15,20};
printf("First element of array is at %u\n", a);
printf("2nd element of array is at %u\n", a+1);
printf("3nd element of array is at %u\n", a+2);
}

Output
First element of array is at 2293312
2nd element of array is at 2293316
3nd element of array is at 2293320

ii. Any operation that involves array subscripting is done by using pointers in c language.
Example:
E1[E2]=>*(E1+E2)
#include<stdio.h>
void main()
{
int a[3]={10,15,20};
printf("Elements are %d %d %d\n", a[0],a[1],a[2]);
printf("Elements are %d %d %d\n", *(a+0),*(a+1),*(a+2));
}

Output
Elements are 10 15 20
Elements are 10 15 20

Array of pointers

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.
An array of pointers is a collection of addresses. Pointers in an array must be the same type.
Example:
int a=10,b=20,c=30;
int *b[3];
B[3]={&a,&b,&c};
Example program:
Program to store the address of three individual arrays in the array of pointers:
#include<stdio.h>
void main()
{
int arr1[]={1,2,3,4,5};
int arr2[]={0,2,4,6,8};
int arr3[]={1,3,5,7,9};
int *parr[3] = {arr1, arr2, arr3};
int i;
for(i=0;i<3;i++)
printf("%d\t", *parr[i]);
}

Output
1 0 1
 Parameter passing: Pass by value, Pass by reference.
There are different ways in which parameter data can be passed into functions.
Let us assume that a function B() is called from another function A().
In this case A is called the “calling function (caller)” and B is called the “called
function(callee)”. Also, the arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
Important ways of Parameter Passing are
i. Pass By Value
ii. Pass by reference

i. Pass By Value:
C always uses 'pass by value' to pass arguments to functions (another term is 'call by value’).
Pass by value means that a copy of the actual parameter’s value is made in memory, i.e. the
caller and callee have two independent variables with the same value. If the callee modifies
the parameter value, the effect is not visible to the caller.
Features:
 Passes an argument by value.
 Callee does not have any access to the underlying element in the calling code.
 A copy of the data is sent to the callee.
 Changes made to the passed variable do not affect the actual value.

Example:
#include<stdio.h>
void incrementcount(int count)//pass by value
{
count=count+1;
printf("\nvalue of count in callee function: %d",count);
}
void main()
{
int count=0;
printf("Pass by value\n");
incrementcount(count);
printf("\nvalue of count in caller function: %d",count);
}
Output
Pass by value
value of count in callee function: 1
value of count in caller function: 0

ii. Pass by reference:


Pass by reference (also called pass by address) means to pass the reference of an argument in
the calling function to the corresponding formal parameter of the called function so that a
copy of the address of the actual parameter is made in memory, i.e. the caller and the callee
use the same variable for the parameter. If the callee modifies the parameter variable, the
effect is visible to the caller’s variable.
Features
 Passes the argument by reference (address).
 The memory address of the stored data (reference) is passed to the callee
 Changes to the value have an effect on the original data.

Example:
#include<stdio.h>
void incrementCount(int *count)//pass by value
{
*count=*count+1;
printf("\nvalue of count in callee function: %d",*count);
}
void main()
{
int count=0;
printf("Pass by reference\n");
incrementCount(&count);
printf("\nvalue of count in caller function: %d",count);
}

Output
Pass by reference
value of count in callee function: 1
value of count in caller function: 1
UNIT IV
 Structures or (Explain about UNION)
Structure is a user defined data type available in C that allows to combine data items of
different types. Here, all the individual components or elements of structures are known as a
member.
Structures are used to represent a record. It is widely used to store student information,
employee information, book information, product information etc.
Suppose we want to keep track of employee details in a organisation. we might want to track
the following attributes about each book:
i. Emp_name
ii. Emp_Id
iii. Salary
iv. Department

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 Syntax of the struct statement is as follows.
Syntax:
struct structureName
,
dataType member1;
dataType member2;
.
.
.
-;

Example:
struct empdetails
,
char empname*50+;
int empNo;
char dept*50+;
float salary;
-;
Here struct is the keyword, empdetails is the structure name, empname, empNo, dept,salary
are the members.

Declaration of structure variables:


A structure variable can either be declared with structure declaration or as a separate
declaration within the main() function.
Syntax: Approach-1 Example
struct structureName struct empdetails
, ,
dataType member1; char empname*50+;
dataType member2; int empNo;
. char dept*50+;
. float salary;
. -e1,e2,e3;
-variable1,variable2, . . .;

Syntax: Approach-2
struct structureName
,
dataType member1;
dataType member2;
.
.
.
-;

void main()
,
struct structureName variable1,variable2, . . ;
-

Example:

struct empdetails
,
char empname*50+;
int empNo;
char dept*50+;
float salary;
-;
void main()
,
struct empdetails e1,e2,e3;
-

Access Members of a Structure


There are two ways for accessing members of a structure.
i. By using . (Member operator or Dot operator)
ii. By using -> (Structure pointer operator)
i. By using . (Member operator or Dot operator)

Syntax: variablename . membername

Ex:-
e1.empname
e1.empNo

Example program:
#include <stdio.h>
struct empdetails
{
char empname[50];
int empNo;
char dept[50];
float salary;
}e1,e2;
int main()
{
printf(“Enter the employee name: ");
scanf("%s",&e1.empname);
printf(“Enter the employee number: ");
scanf("%d",&e1.empNo);
printf(“Enter the department: ");
scanf("%s",&e1.dept);
printf(“Enter the salary: ");
scanf("%f",&e1.salary);
printf("Name: %s\n",e1.empname);
printf("Number: %d\n",e1.empNo);
printf("Department: %s\n",e1.dept);
printf("Salary: %f\n",e1.salary);
return 0;
}

Output
Enter the employee name: SIVA
Enter the employee number: 1001
Enter the department: Production
Enter the salary: 50000
Name: SIVA
EmployeeNumber: 1001
Department: Production
Salary: 50000.000000

ii. By using -> (Structure pointer operator)


we can have pointer to a structure. If we have a pointer to structure, members are accessed
using arrow ( -> ) operator.
Syntax:
variablename -> membername
Example:
e1 -> empname
e1 -> empNo

Example program:
#include<stdio.h>
struct Point
{
int x, y;
};
void main()
{
struct Point p1;
p1.x = 10;
p1.y = 20;
struct Point *p2 = &p1;
printf("%d %d", p2->x, p2->y);
}

Output
10 20
 Nested structures
A nested structure in C is a structure within structure. One structure can be declared inside
another structure in the same way structure members are declared inside a structure.
There are two ways to define nested structure in C
i. By separate structure
ii. By embedded structure

i. By separate structure :
Here we can create 2 structures, but depended structure should be used inside the main
structure as a member.
Example
Syntax:
struct name1
{
member_1;
member_2;
member_n;
};
struct name2
{
member_1;
member_2;
struct name1 var1;
} var2;

Example:
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address addr;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s", & emp.name, & emp.addr.city, &emp.addr.pin,& emp.addr.phone);
printf("Printing the employee information....\n");
printf("name: %s\n City: %s\n Pincode: %d\n Phone: %s", emp.name, emp.addr.city,
emp.addr.pin, emp.addr.phone);
}

Output
Enter employee information?
Siva
Nagercoil
629001
9294565701
Printing the employee information....
name: Siva
City: Nagercoil
Pincode: 629001
Phone: 9294565701

ii. By embedded structure


The embedded structure enables us to declare the structure inside the structure. Hence, it
requires less line of codes but it cannot be used in multiple data structures.
Syntax:
struct name1
,
member_1;
member_2;
struct name2
,
member_1;
member_2;
. Member_3
.
member_n;
- var1;
member_n;
- var2;

Example:
#include<stdio.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
};
void main ()
{
struct Employee emp1;
printf("Enter employee information?\n");
scanf("%d %s %d %d %d",&emp1.id, &emp1.name, &emp1.doj.dd, &emp1.doj.mm,
&emp1.doj.yyyy);
printf("Printing the employee information....\n");
printf(" Employee Id: %d\n Name: %s\n Dob: %d %d %d",emp1.id,emp1.name, emp1.doj.dd,
emp1.doj.mm,emp1.doj.yyyy);
}

Output
Enter employee information?
1001
Siva
10
04
1988
Printing the employee information....
Employee Id: 1001
Name: Siva
Dob: 10 4 1988
 Self-referential structures or (singly linked list)
Self Referential structures are those structures that have one or more pointers which point to
the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-referential in nature.
For example: consider the structure given below.

Here the structure node will contain three types of data an integer, character and link which is
a pointer to the same structure named node.
Self referential structure is the foundation of other data structures.
Self-referential structure plays a very important role in creating other data structures like
Linked list.

Types of Self Referential Structures


There are two types of Self Referential Structures, They are
i. Self Referential Structure with Single Link
ii. Self Referential Structure with Multiple Links

i. Self Referential Structure with Single Link:


These structures can have only one self-pointer as their member. The following example will
show us how to connect the objects of a self-referential structure with the single link and
access the corresponding data members.

Example:
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
void main()
{
struct node ob1;
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2;
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

ob1.link = &ob2;
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
}

Output
30 40

ii. Self Referential Structure with Multiple Links:


Self referential structures with multiple links can have more than one self-pointers. Many
complicated data structures can be easily constructed using these structures. Such structures
can easily connect to more than one nodes at a time.

Example:
#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
void main()
{
struct node ob1;
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;

struct node ob2;


ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;
struct node ob3;
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;
// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;
// Accessing data of ob1, ob2 and ob3 by ob1
printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob2
printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob3
printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
}

Output
10 20 30
10 20 30
10 20 30
 Dynamic memory allocation
 Dynamic memory allocation refers to the process of manual memory management (allocation
and deallocation).
 Sometimes the size of the array you declared may be insufficient. To solve this issue, you can
allocate memory manually during run-time. This is known as dynamic memory allocation in C
programming.
 Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.

1. malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it
returns a pointer of void which can be casted into pointers of any form.
Syntax of malloc() : ptr = (castType*) malloc(size);
Example: ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes.
And, the pointer ptr holds the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.

Example program:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using malloc.\n");
}
}
2. calloc()
The name "calloc" stands for contiguous allocation.
The calloc() function allocates multiple blocks of requested memory.
The malloc() function allocates memory and leaves the memory uninitialized, whereas the
calloc() function allocates memory and initializes all bits to zero.

Syntax of malloc(): ptr = (castType*)calloc(n, size);


Example: ptr = (float*) calloc(5, sizeof(float));
In the above statement, we are allocating an float array of size 5 at run-time and assigning it
to an integer pointer ptr, ptr will store the address of the very first element of the allocated
array.
Example program:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
}
}

Difference between malloc() and calloc()

3. realloc()
If the dynamically allocated memory using malloc() or calloc() is not sufficient, we can
reallocate the memory by realloc() function.

Syntax of realloc(): ptr = realloc(ptr, newSize);

Example: ptr1=realloc(ptr1,5,size(int))

Here, ptr is reallocated with a new size of 20 bytes.

Example program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
}
}

4. free()
The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.

Syntax of free(): free( pointer );


free() takes one argument and it is the pointer containing the address of the memory block
that is to be freed or deallocated.
Example : free(ptr1);
In the above statement, we are deallocating memory block(s) pointed by a pointer ptr1 in the
memory.
Example program:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *ptr, *ptr1;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL
{
printf("Memory not allocated.\n");
}
else
{
printf("Memory successfully allocated using malloc.\n");
free(ptr);
printf("Memory successfully freed.\n");
}
}
UNIT V
 Sequential access file
There are two main ways a file can be processed:
 Sequential Access
 Random Access

Sequential Access
In this type of file, the data are kept sequentially. To read last record of the file, it is expected to
read all the records before that particular record. It takes more time for accessing the records.
A Sequential file is characterized by the fact that individual data items are arranged serially in a
sequence, one after another.
They can only be processed in serial order from the beginning.
In other words, the records can be accessed in the same manner in which they have been stored.
It is not possible to start reading or writing a sequential file from anywhere except at the
beginning.

Reading Sequential Access file


Data is stored in files so that the data can be retrieved for processing when needed
Example:
clients.dat file contents

100 Jones 9023.00


200 Frank 234.00
300 Mano 29023.00
400 Bala 2344.00

// Reading and printing a sequential file


#include <stdio.h>
#include <stdlib.h>
void main()
{
int account;
char name[30];
double balance;
FILE *cfPtr;
cfPtr = fopen("E:\\clients.txt", "r");
if (cfPtr == NULL)
{
printf("File could not be opened");
exit(0);
}
printf("%-10s%-10s%s\n", "Account", "Name", "Balance");
fscanf(cfPtr, "%d %s %lf", &account, &name, &balance);
while (!feof(cfPtr))
{
printf("%-10d%-10s%.2f\n", account, name, balance);
fscanf(cfPtr, "%d %s %lf", &account, name, &balance);
}
fclose(cfPtr);
}

Output
Account Name Balance
100 Jones 9023.00
200 Frank 234.00
300 Mano 29023.00
400 Bala 2344.00
 Random access file
In this type of file, the data can be read and modified randomly. If it is desired to read the last
record of a file, directly the same record can be read.
Due to random access of data, it takes less access time as compared to the sequential file.
The second and better method of arranging records of a file is called direct access or random
access. In this arrangement one can have access to any record which is situated at the middle or
anywhere of the file without reading or passing through other records in the file.

Advantages:
Access individual records without searching through other records
Give Instant access to records in a file
Data can be inserted without destroying other data.
Data previously stored can be updated or deleted without overwriting.
Implemented using fixed length records whereas Sequential files do not have fixed length
records.

Functions For Selecting A Record Randomly


The functions used to randomly access a record stored in a file are

1. fseek()

2. ftell()

3. rewind()

1. fseek() :

It is used to reposition a data stream.

The syntax: fseek( file pointer, offset value , position);


fseek() is used to set the file position pointer for the given stream.
Offset value is an integer value that gives the number of bytes to move forward or backward in
the file. Offset may be positive or negative, provided it makes sense.
For example, you cannot specify a negative offset if you are starting at the beginning of the file.
The position value should have one of the following values (defined in stdio.h):
i. SEEK_SET : to perform input or output on offset bytes from start of the file
ii. SEEK_CUR : to perform input or output on offset bytes from the current position in the
file
iii. SEEK_END : to perform input or output on offset bytes from the end of the file
SEEK_SET, SEEK_CUR and SEEK_END are defined constants with value 0, 1 and 2 respectively.
On successful operation, fseek() returns zero and in case of failure, it returns a non-zero value.
For example, if you try to perform a seek operation on a file that is not opened in binary mode
then a non-zero value will be returned. fseek() can be used to move the file pointer beyond a file,
but not before the beginning.
Example: fseek(fp, 5, 0);
fseek(fp, -5, 2);

2. ftell()
The ftell function is used to know the current position of file pointer. It is at this position at which
the next I/O will be performed. The ftell() is defined in stdio.h
Syntax: ftell (file pointer);
Example:
long int x;
x=ftell(fp);
On successful, ftell() function returns the current curser position (in bytes) in the file.
However, in case of error, ftell() returns -1.
When using ftell(), error can occur either because of the following reasons:
when the position is larger than that can be represented in a long integer. This will usually
happen when dealing with very large files

3. rewind()
rewind() is used to adjust the position of file pointer so that the next I/O operation will take place
at the beginning of the file.
Syntax: rewind(file pointer);
Example:
rewind( fp);
rewind() is equivalent to calling fseek() with following parameters:
fseek(fp, 0, SEEK_SET);

Example program for random access of file:


#include<stdio.h>
void main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","w+");
fputs("This is our class room", fp);
fseek( fp, 12, 0 );
fputs("C programming LAB ", fp);
printf("The current position of the file pointer is: %ld\n", ftell(fp));
rewind(fp);
printf("The current position of the file pointer is: %ld\n", ftell(fp));
while(!feof(fp))
{
c = fgetc(fp);
printf("%c", c);
}
fclose(fp);
}

Output
The current position of the file pointer is: 30
The current position of the file pointer is: 0
This is our C programming LAB
 Command line arguments
It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments.
To support command line argument, you need to change the structure of main() function as
given below.
The command line arguments are handled using main() function arguments.
 where Here, argc counts the number of arguments. It counts the file name as the first
argument.
 argv[] is a pointer array which points to each argument passed to the program. It
should be noted that argv[0] holds the name of the program itself.
 argv[1] is a pointer to the first command line argument supplied,
 argv[2] is a pointer to the second command line argument supplied, and so on.
 If no arguments are supplied, argc will be one, and if you pass one argument then
argc is set at 2.
We can pass all the command line arguments separated by a space, but if argument itself
has a space then you can pass such arguments by putting them inside double quotes "" or
single quotes ''.

Example 1:
#include <stdio.h>
#include <conio.h>
void main(int argc, char *argv[])
{
int i;
if( argc >= 1 )
{
printf("The arguments supplied are:\n");

for(i = 0; i < argc; i++)


{
printf("The argument number [%d] is %s\n", i+1,argv[i]);
}
}
}

Run this program from command line by following the bellow steps:
Step-1: compile the program
Step-2: Type cmd in the windows run prompt.
Step-3: Open the directory where the c program is stored
Step-4: Enter the name of the program as the first argument and followed by remaining
arguments one by one separated by space.
Example:
E:\>program_name hello 100 200
Output
The arguments supplied are:
The argument number [1] is program_name
The argument number [2] is hello
The argument number [3] is 100
The argument number [4] is 200

Example 2:
Program to add 2 numbers using command line arguments:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int x, y, z;
x = atoi(argv[1]);
y = atoi(argv[2]);
z = x + y;
printf("The name of the program is %s",argv[0]);
printf("\nThe sum is %d",z);
}
Here: The atoi() function that converts a character string to an integer value which is
defined in the stdlib.h header file.
Output
E:\>add 25 35
The name of the program is add
The sum of 25 and 35 is 60

Example 3:
Program to find the sum of N integer numbers using command line arguments in C
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a,b,sum;
int i;
sum=0;
for(i=1; i<argc; i++)
{
printf("%d %d\n",i,atoi(argv[i]));
sum = sum + atoi(argv[i]);
}
printf("SUM of all %d values= %d\n",i-1,sum);
return 0;
}

Output
E:\>program_sum 10 20 30 40 50
1 10
2 20
3 30
4 40
5 50
SUM of all 5 values= 150

You might also like