CS8251 C Prog
CS8251 C Prog
COLLEGE OF ENGINEERING
POTTAPALAYAM – 630 612 (11 KM from Madurai City)
SIVGANGAI DISTRICT, TAMILNADU, INDIA
(Sponsored by K.L.N. Sourashtra College of Engineering Council)
Approved by AICTE, New Delhi
All UG Courses are permanently Affiliated to Anna University, Chennai
Included under 2(f) and 12(B) status of UGC Act of 1956
Approved as Nodal Centre for Quality Improvement Cell by Anna University, Chennai
Approved Research Centres for MECH, EEE, ECE & CSE by Anna University, Chennai
An ISO 9001:2015 Certified Institution – A Sourashtra Linguistic Minority Institution
Accredited by NBA, New Delhi fro BE – MECH, EEE, ECE CSE & B. Tech – IT
for Three Academic Years, 2019 – 2020 to 2021 – 2022 (i.e.) upto 30.06.2022
Ph : 0452 – 6562171 &2, 0452 – 2090971 & 2 , Fax : 0452 – 2090970, Email – [email protected]
(R2017)
CS8251
PROGRAMMING IN C
MONOGRAPH
PREPARED BY,
MISSION
To Develop and Make Students Competent Professional in the Dynamic Environment in the
field of Engineering, Technology and Management by emphasizing Research, Social Concern and
Ethical Values through Quality Education System.
Ability to apply good analytical, design and implementation skills to formulate and solve
PSO1 scientific and business applications pertaining to Algorithms, Computer Systems, Networks,
Security, Data Analytics and Artificial Intelligence.
Ability to update knowledge continuously in the tools like Rational Rose, MS VISIO, NS,
PSO2 VMware workstation, Mobile Application Development tools and technologies like storage,
Computing, communication to meet the industry requirements.
3003
OBJECTIVES:
To develop C Programs using basic programming constructs
To develop C programs using arrays and strings
To develop applications in C using functions , pointers and structures
To do input/output and file handling in C
UNIT IV STRUCTURES 9
Structure -Nested structures –Pointer and Structures –Array of structures –Example Program using
structures and pointers –Self referential structures –Dynamic memory allocation -Singly linked list -
typedef
OUTCOMES:
Upon completion of the course, the students will be able to
Develop simple applications in C using basic constructs
Design and implement applications using arrays and strings
Develop and implement applications in C using functions and pointers.
Develop applications in C using structures.
Design applications using sequential and random access file processing.
CO- PO MAPPING
Subject: Programming in C
Subject Code: CS8251(Reg2017)
POs
COs
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
C114.1 3 1 - - - - - 1 1 - - 1
C114.2 3 2 1 1 - - - 1 1 - - 1
C114.3 3 2 2 1 - - - 1 1 - - 2
C114.4 3 2 2 1 - - - 1 1 - - 2
C114.5 3 2 2 2 - - - 1 2 - - 2
To understand and develop the C program using various concepts of arrays, strings, functions,
pointers, structures and files.
OBJECTIVE :
17. 2
1
concatenate, copy
18. 2
2
Selection sort
19. Linear and binary search
20. Revision
TEXT BOOKS
T2 The C Programming language Kernighan, B.W and Second Edition, Pearson Education, 2006
Ritchie,D.M
WEB REFERENCES
1. https://www.tutorialspoint.com/cprogramming/
2. http://phy.ntnu.edu.tw/~cchen/pdf/ctutor.pdf
3. http://nptel.ac.in/courses/106105085/2
4. http://nptel.ac.in/courses/106105085/9
5. http://students.iitk.ac.in/programmingclub/course/
Q5: Write a program to find whether the given year is leap year or not.
#include <stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("Enter a year: ");
scanf("%d",&year);
if(year%4 == 0)
{
if( year%100 == 0)
{
if ( year%400 == 0)
printf("%d is a leap year.", year);
else
Assignment 2
Q1: Write a simple program to Change the Value Pointed by Pointers.
Solution: int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc);
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Q2: write the program for writing data to the file "credit.dat". (It uses the combination of fseek and
fwrite to store data at specific locations in the file Function fseek sets the file position pointer to a specific
position in the file, then fwrite writes the data)
Solution:
// Writing data randomly to a random-access file
#include <stdio.h>
// clientData structure definition
struct clientData {
unsigned int acctNum; // account number
char lastName[ 15 ]; // account last name
char firstName[ 10 ]; // account first name
double balance; // account balance
}; // end structure clientData
Q3: write a C Program to populate an array with height of persons and find how many persons
are above the average height.
Solution:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,sum=0,count=0,height[100];
float avg;
clrscr();
printf("Enter the Number of Persons : ");
scanf("%d",&n);
printf("\n Enter the Height of each person in centimeter\n");
for(i=0;i<n;i++)
{
scanf("%d",&height[i]);
sum = sum + height[i];
}
avg = (float)sum/n;
//Counting
for(i=0;i<n;i++)
if(height[i]>avg)
Q5: write a C Program to Sort the list of numbers using pass by reference
Solution:
#include <stdio.h>
#include <conio.h>
void main()
{
int n,a[100],i;
void sortarray(int*,int);
clrscr();
printf("\nEnter the Number of Elements in an array : ");
scanf("%d",&n);
printf("\nEnter the Array elements\n");
STRUCTURE OF A C PROGRAM
In general, a C program is composed of the following sections:
Section 1: Pre-processor directives
Section 2: Global declarations
Section 3: Functions
Section 1 and 2 are optional, Section 3 is compulsory.
Documentation Section
Pre-processor directives
Definition Section and Global declarations
void main()
{
Declaration part
Executable part
}
Sub Program Section
{
Body of the Sub
}
Structure of a C Program
Comments:
Comments are used to convey a message and used to increase the readability of a
program.
They are not processed by the compiler.
There are two types of comments:
1. Single line comment
2. Multi line comment
Single line comment
A single line comment starts with two forward slashes (//) and is automatically terminated with
the end of the line.
E.g. //First C program
Multi-line comment
Line1 is a comment; Line 2 is a preprocessor directive. Line3 is a header of the function main. Line 4,
5, 6 form the body of main function.
Example Program:
4 Double 8 1.7*10-308 to
1.7*10308
5 Unsigned char 1 0 to 255
Type qualifier
A type qualifier is used to indicate the special properties of data within an object. It never
affects the range of values & the arithmetic properties of the declared object.
Two type qualifiers available in C are:
Symbolic constants
Symbolic constants are created with the help of the define preprocessor directive. For ex
#define PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each symbolic constant is
replaced by its actual value during the pre-processing stage.
Enumeration Constants:
An enumeration is a user-defined data type or constant. Enumeration is achieved by using the
keyword enum.
The enumeration type is an integral data type.
const1,
const2,
...
constN
};
Example:
#include <stdio.h>
main()
{
enum Day{ Monday =1, Tuesday, Wednesday, Thursday};
enum { A= 3, B , C , Z = 400, X, Y };
printf("Wednesday = %d\n", Wednesday);
printf("B = %d \t C = %d\n", B,C);
printf("X = %d \t Y = %d\n", X,Y);
printf("Thursday/Tuesday = %d\n", Thursday/Tuesday);
}
Output:
Wednesday=3
B=4 C=5
X=401 Y=402
Thursday/Tuesday=2
When you create an enumerated type, only blueprint for the variable is created. Here's how you
can create variables of enum type.
Another syntax:
enum boolean
} check;
#include <stdio.h>
int main()
today = wednesday;
printf("Day %d",today+1);
return 0;
Output
Day 4
Operands
An operand specifies an entity on which an operation is to be performed. It can be a variable
name, a constant, a function call.
E.g: a=2+3 Here a, 2 & 3 are operands
Operator
An operator is a symbol that is used to perform specific mathematical or logical manipulations.
For e.g, a=2+3 Here = & + are the operators
Precedence of operators
The precedence rule is used to determine the order of application of operators in
evaluating sub expressions.
Each operator in C has a precedence associated with it.
Classification of Operators
The operators in C are classified on the basis of
1) The number of operands on which an operator operates. 2)The role of an operator
Operator Meaning
- Minus
2. Binary Operator: A binary operator operates on two operands. Some of the binary operators
are,
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
Division
&& Logical AND
3. Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is the ternary
operator.
Increment operator
The operator ++ adds one to its operand.
++a or a++ is equivalent to a=a+1
Prefix increment (++a) operator will increment the variable BEFORE the expression is
evaluated.
Postfix increment operator (a++) will increment AFTER the expression evaluation.
E.g.
1. c=++a. Assume a=2 so c=3 because the value of a is incremented and then it is
assigned to c.
2. d=b++ Assume b=2 so d=2 because the value of b is assigned to d before it is
incremented.
Decrement operator
The operator – subtracts one from its operand.
--a or a-- is equivalent to a=a+1
Prefix decrement (--a) operator will decrement the variable BEFORE the expression is
evaluated.
Postfix decrement operator (a--) will decrement AFTER the expression evaluation.
E.g.
1. c=--a. Assume a=2 so c=1 because the value of a is decremented and then it is
assigned to c.
2. d=b-- Assume b=2 so d=2 because the value of b is assigned to d before it is
decremented.
2. Relational Operators
Relational operators are used to compare two operands. There are 6 relational operators
in C, they are
If the relation is true, it returns value 1 and if the relation is false, it returns
value 0.
Meaning of
Operator Operator Example Description
4. Bitwise Operators
C language provides 6 operators for bit manipulation. Bitwise operator operates on the
individual bits of the operands. They are used for bit manipulation.
Truth tables
5. Assignment Operators
To assign a value to the variable assignment operator is used.
Operators Example Explanation
Simple assignment operator = sum=10 10 is assigned to variable sum
+= sum+=10 This is same as sum=sum+10
-= sum-=10 sum = sum-10
Compound assignment operators *= sum*=10 sum = sum*10
Or /+ sum/=10 sum = sum/10
Shorthand assignment operators %= sum%=10 sum = sum%10
&= sum&=10 sum = sum&10
^= sum^=10 sum = sum^10
E.g.
var=5 //5 is assigned to var
a=c; //value of c is assigned to a
6. Miscellaneous Operators
Other operators available in C are
c) Conditional Operator
It is the only ternary operator available in C.
Conditional operator takes three operands and consists of two symbols ? and : .
Conditional operators are used for decision making in C.
Syntax :
(Condition? true_value: false_value);
For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
d) Address-of Operator
It is used to find the address of a data object.
Syntax
&operand
E.g.
&a will give address of a.
Managing Input and Output operations
The I/O functions are classified into two types:
Formatted Functions
Unformatted functions
printf() getch()
getche()
scanf() getchar()
gets()
putch()
putchar()
puts()
Unformatted Functions:
They are used when I/P & O/P is not required in a specific format.
C has 3 types I/O functions.
a) Character I/O
b) String I/O
c) File I/O
a) Character I/O:
1. getchar() This function reads a single character data from the standard input.
(E.g. Keyboard)
Syntax :
variable_name=getchar();
eg:
char c;
c=getchar();
Example Program
void main()
{
char ch[30];
clrscr();
printf(“Enter the String : “);
gets(ch);
puts(“\n Entered String : %s”,ch);
puts(ch);
}
Output:
Enter the String : WELCOME
Width Modifier: It specifies the total number of characters used to display the value.
Precision: It specifies the number of characters used after the decimal point.
E.g: printf(“ Number=%7.2\n”,5.4321);
Width=7
Precesion=2
Output: Number = 5.43(3 spaces added in front of 5)
Flag: It is used to specify one or more print modifications.
Flag Meaning
- Left justify the display
+ Display +Ve or –Ve sign of value
E.g: Space Display space if there is no sign
0 Pad with leading 0s
printf(“Number=%07.2\n”,5.4321)
Output: Number=0005.43
#include <stdio.h>
void main( )
{
int num1, num2, sum;
printf("Enter two integers: ");
scanf("%d %d",&num1,&num2);
sum=num1+num2;
printf("Sum: %d",sum);
}
Output
Enter two integers: 12 11
Sum: 23
Decision making statements in a programming language help the programmer to transfer the
control from one part to other part of the program.
1.Branching
Jump-unconditional Branching
2.Iteration statements
Branching statements
Branching statements are used to transfer program control from one point to another.
2 types
a) Conditional Branching:- Program control is transferred from one point to another based on
the result of some condition
Eg) if, if-else, switch
b) Unconditional Branching:- Pprogram control is transferred from one point to another without
checking any condition
Eg) goto, break, continue, return
a) Conditional Branching : Selection statements
Statements available in c are
The if statement
The if-else statement
The switch case statement
(i)The if statement
C uses the keyword if to execute a statement or set of statements when the logical condition is
true.
Syntax:
if (test expression)
F
Statement; Test
expres
sion
T
Statement
Example:
#include <stdio.h>
void main()
{
int n;
clrscr();
(Or)
This nesting can be done up to any level.
Syntax:
if (test expression) if (test expression1)
if (test expression) { {
if (test expression) statement; …..
if (test expression) if (test expression2)
…. {
statement; ….
} if (test expression3)
else {
….
Statement F;
if (test expression n)
}}}
v) Switch statement
It is a multi way branch statement.
It provides an easy & organized way to select among multiple operations depending upon some
condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets executed.
4. If no match occurs, then all the statements after the default statement get executed.
Switch ,case, break and default are keywords
Break statement is used to exit from the current case structure
Flowchart
switch(expression)
case : break
statement
constant 1
default
statement break
Syntax
Example1
void main()
{
char ch;
printf(“Enter a character\n”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘A’:
printf(“you entered an A\n”);
break;
case ‘B’:
printf(“you entered a B\n”);
break;
default:
Example2
void main()
{
int n;
printf(“Enter a number\n”);
scanf(“%d”,&n);
switch(n%2)
{
case 0:printf(“EVEN\n”);
break;
case 1:printf(“ODD\n”);
break;
}
getch();
}
Output:
Enter a number
5
ODD
Output : 1 2
Example :2
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
break;
printf(“ %d”,i);
}
}
Output :1 2 3 4
iii) continue statement
A continue statement can appear only inside a loop.
A continue statement terminates the current iteration of the nearest enclosing loop.
Syntax:
Output :1 2 3 4 6 7 8 9 10
return;
(or)
return expression;
2. while statement
They are also known as Entry controlled loops because here the condition is checked before the
execution of loop body.
Syntax:
while (expression)
{
statements;
}
3. do while statement
They are also known as Exit controlled loops because here the condition is checked after the
execution of loop body.
Syntax:
do
{
statements;
}
while(expression);
The body of do-while is executed once, even when the condition is initially false.
Nested loops
If the body of a loop contains another iteration statement, then we say that the loops are nested.
Loops within a loop are known as nested loop.
Syntax
while(condition)
{ while(condition)
{
Statements;
}
Statements;
}
Preprocessors Directives
Directive Description
Preprocessors Examples
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use
#definefor constants to increase readability.
These directives tell the CPP to get stdio.h from System Libraries and add the text to the
current source file. The next line tells CPP to get myheader.h from the local directory and add the
content to the current source file.
#undef FILE_SIZE
#ifndef MESSAGE
1 3 5 2 a(integer array)
char b[5]={‘A’.’r’,’r’};
Computing Median:
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,temp,n,a[20],sum=0;
float median;
printf("enter n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter %d number:",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
A 2D array is an array of 1-D arrays and can be visualized as a plane that has rows and
columns.
The elements can be accessed by using two subscripts, row subscript (row no), column
subscript(column no).
It is also known as matrix.
E.g,
1 2 3 6 7
a[3][5] 9 10 5 0 4
3 1 2 1 6
Declaration
Initialization
1. By using an initialization list, 2D array can be initialized.
e.g. int a[2][3] = {1,4,6,2}
1 4 6
a
2 0 0
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j;
long determinant;
clrscr();
printf("Enter the 4 elements of matrix: ");
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
long determinant;
1 2
3 4
Transpose of given matrix:
1 3
2 4
char stringname[size];
strcat(firststring, secondstring);
E.g.
s1=“hai ”;
s2= “welcome”;
strcat(s1,s2); -> s2 is joined with s1. Now s1 is hai welcome.
E.g. 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 str1is 10
4. strcmp() function
It is used to compare 2 strings.
Syntax
temp_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.
5. strlwr() function
strlwr(string_name);
E.g.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output: hello
6. strupr() function
It converts all the lowercase characters in that string to uppe rcase characters.
Syntax
strupr(string_name);
E.g.
str[10]= “HEllo”;
strupr(str);
puts(str);
Output: HELLO
7. strrev() function
It is used to reverse the string.
Syntax
strrev(string_name);
E.g.
str[10]= “HELLO”;
strrev(str);
puts(str);
Output: OLLEH
String functions
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
strdup() Duplicates a String
strstr() Determines the first occurrence of a given String in another string
strcat() Appends source string to destination string
strrev() Reverses all characters of a string
Declaration
char arrayname[rowsize][colsize];
E.g.
char s[2][30];
Here, s can store 2 strings of maximum 30 characters each.
Initialization
2 ways
1. Using string constants
char s[2][20]={“Ram”, “Sam”};
2. Using initialization list.
char s[2][20]={ {‘R’, ‘a’, ‘m’, ‘\0’},
{‘S’, ‘a’, ‘m’, ‘\0’}};
E.g. Program
#include<stdio.h>
void main()
{
int i;
char s[3][20];
printf(“Enter Names\n”);
for(i=0;i<3;i++)
scanf(“%s”, s[i]);
printf(“Student Names\n”);
for(i=0;i<3;i++)
printf(“%s”, s[i]);
}
2.7 Searching
Output:
Enter the size of an array: 4
Enter the elements of the array: 4 3 5 1
Enter the number to be search: 5
Element is in the position 3
2. Binary Search
If a list is already sorted then we can easily find the element using binary serach.
It uses divide and conquer technique.
Steps:
1. The middle element is tested with searching element. If found, its position is returned.
2. Else, if searching element is less than middle element, search the left half else search the
right half.
3. Repeat step 1 & 2.
#include<stdio.h>
int main()
{
int a[10][10],b[10][10],sum[10][10],i,j,r,c;
printf("Enter the Numbers of Row : ");
scanf("%d",&r);
printf("\nEnter the Number of Coloumn : ");
scanf("%d",&c);
printf("\nEnter the Element of First Matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\tEnter the Element [%d] [%d] : ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Element of Second Matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\tEnter the Element [%d] [%d] : ",i,j);
scanf("%d",&b[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
sum[i][j]=a[i][j]+b[i][j];
}
printf("\n\n");
return 0;
}
#include<stdio.h>
int main()
{
int a[10][10],i,j,r,c;
printf("Enter the Numbers of Row : ");
scanf("%d",&r);
printf("\nEnter the Number of Coloumn : ");
scanf("%d",&c);
printf("\nEnter the Element of Matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\tEnter the Element [%d] [%d] : ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\n\nElement in the Matrix are :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("\t%d",a[i][j]);
printf("\n");
}
printf("\n\nTranspose of a Matrix :\n");
#include<stdio.h>
int main()
{
int a[10][10],b[10][10],mul[10][10],i,j,k,r,c,sum;
printf("Enter the Numbers of Row : ");
scanf("%d",&r);
printf("\nEnter the Number of Coloumn : ");
scanf("%d",&c);
printf("\nEnter the Element of First Matrix :\n");
for(i=0;i<r;i++)
{
}
printf("\n\nEnter the Element of Second Matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\nEnter the Element [%d] [%d] : ",i,j);
scanf("%d",&b[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum=0;
for (k=0;k<r;k++)
printf("\n\n");
return 0;
}
#include<stdio.h>
int main()
{
int a[20],i,n,ele,pos;
}
printf("\nArray After Inserting element :\n");
for(i=1;i<=n+1;i++)
printf("%d\t",a[i]);
printf("\n\n");
return 0;
}
#include<stdio.h>
int main()
{
int a[25],b[25],sum[50],i,j,k=1,n,m,s,temp;
printf("Enter the number of element in first array :");
scanf("%d",&n);
printf("\nEnter the element of array :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\nEnter the number of element in second array :");
scanf("%d",&m);
printf("\nEnter the element of array :\n");
for(i=1;i<=m;i++)
scanf("%d",&b[i]);
s=m+n;
for(i=1;i<=s;i++)
{
if(i<=n)
{
sum[i]=a[i];
}
else
{
sum[i]=b[k];
k=k+1;
}
4.1 Functions
A function is a subprogram of one or more statements that performs a specific task when
called.
Advantages of Functions:
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
Based on who develops the function
Based on the number of arguments a function accepts
1. Based on who develops the function
There are two types.
1. Library functions
2. User-defined functions
1. Library functions [Built-in functions]
Library functions are predefined functions. These functions are already developed by someone
and are available to the user for use. Ex. printf( ), scanf( ).
2. User-defined functions
User-defined functions are defined by the user at the time of writing a program. Ex. sum( ),
square( )
statements;
return (value);
Calling function – The function that calls a function is known as a calling function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual arguments.
Formal arguments – The arguments of called function are called as formal arguments.
#include<stdio.h>
void main()
{
void show( );
show( );
} No arguments are passed.
No values are sent back.
Output:
Hai
void show(int x)
{
printf(“Value =%d”, x);
}
Output:
Enter the value for a
10
Value = 10
1. Pass by value
In this method the values of actual arguments are copied to formal arguments.
Any change made in the formal arguments does not affect the actual arguments.
Once control, return backs to the calling function the formal parameters are destroyed.
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
OUTPUT:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20
10 20
1000 1002
Swap function
a1 b1
10 20
2000 2002
After swap function
a1 b1
20 10
2000 2002
2. Pass by reference
In this method, the addresses of the actual arguments are passed to formal argument.
Thus formal arguments points to the actual arguments.
So changes made in the arguments are permanent.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
OUTPUT:
Main function
a b
10 20
1000 1002
Swap function
a1 b1
2000 2002
After swap function
a b
20 10
1000 1002
4.5. Built in Functions(String Functions, Math Functions):
Library functions are predefined functions. These functions are already developed by someone
and are available to the user for use.
Declaration:
The declarations of library functions are available in the respective header files. To use a
library function, the corresponding header file must be included.
Library of Mathematical functions.
These are defined in math.h header file.
Example:
1 double cos(double x)- Returns the cosine of a radian angle x
2 double sin(double x)- Returns the sine of a radian angle x.
3 double exp(double x)- Returns the value of e raised to the xth power
double log(double x)
4
Returns the natural logarithm (base-e logarithm) of x.
double sqrt(double x)
5
Returns the square root of x.
double pow(double x, double y)
6
Returns x raised to the power of y.
char stringname[size];
strcat(firststring, secondstring);
E.g.
s1=“hai ”;
s2= “welcome”;
strcat(s1,s2); -> s2 is joined with s1. Now s1 is hai welcome.
E.g. 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 str1is 10
11. strcmp() function
It is used to compare 2 strings.
Syntax
temp_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.
12. strlwr() function
It converts all the uppercase characters in that string to lowercase characters.
Syntax
E.g.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output: hello
strupr(string_name);
E.g.
str[10]= “HEllo”;
strupr(str);
puts(str);
Output: HELLO
14. strrev() function
It is used to reverse the string.
Syntax
strrev(string_name);
E.g.
str[10]= “HELLO”;
strrev(str);
puts(str);
Output: OLLEH
String functions
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
strdup() Duplicates a String
strstr() Determines the first occurrence of a given String in another string
strcat() Appends source string to destination string
strrev() Reverses all characters of a string
Declaration
char arrayname[rowsize][colsize];
E.g.
char s[2][30];
Here, s can store 2 strings of maximum 30 characters each.
Initialization
2 ways
3. Using string constants
char s[2][20]={“Ram”, “Sam”};
4. Using initialization list.
char s[2][20]={ {‘R’, ‘a’, ‘m’, ‘\0’},
{‘S’, ‘a’, ‘m’, ‘\0’}};
E.g. Program
#include<stdio.h>
void main()
{
int i;
char s[3][20];
printf(“Enter Names\n”);
for(i=0;i<3;i++)
scanf(“%s”, s[i]);
printf(“Student Names\n”);
for(i=0;i<3;i++)
printf(“%s”, s[i]);
}
4.5 RECURSION
A function that calls itself is known as a recursive function.
case 3:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x * y;
printf(“\nResult: %f”, result);
break;
case 4:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
int main()
{
int count, element, limit, arr[50], position;
printf("\nEnter the Limit of Elements in Array:\t");
scanf("%d", &limit);
printf("\nEnter %d Elements in Array: \n", limit);
for(count = 0; count < limit; count++)
{
scanf("%d", &arr[count]);
}
printf("\nEnter Element To Search:\t");
scanf("%d", &element);
position = RecursiveBinarySearching(arr, 0, limit - 1, element);
if(position == -1)
{
printf("\nElement %d Not Found\n", element);
}
else
{
printf("\nElement %d Found at Position %d\n", element, position + 1);
}
return 0;
}
Output:
int a=10; p a
int *p=&a;
2000 10
4000 2000
p is an integer pointer & holds the address of an int variable a.
Pointer to pointer
A pointer that holds the address of another pointer variable is known as a pointer to pointer.
E.g.
int **p;
6000 pptr
8000
So **pptr=12
Operations on pointers:
a 12.5
1000
1000
P
2000
2. Dereferencing a pointer
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-operator
Eg) int b;
int a=12;
a 12 int *p;
1000 p=&a;
b=*p; \\value pointed by p(or)value
at 1000=12,
p 1000 so b=12
2000
Example program
#include<stdio.h>
void main() Note
{
int a=12; %p is used for addresses; %u can
int *p; also be used.
int **pptr;
p=&a; *p=value at p
pptr=&p; =value at (1000)=12
printf(“a value=%d”,a);
printf(“value by dereferencing p is %d \n”,*p);
printf(“value by dereferencing pptr is %d \n”,**pptr); *pptr=value at(pptr)
printf(“value of p is %u \n”,p); =value at(value at (2000))
printf(“value of pptr is %u\n”,pptr); =value at (1000)=12
}
Output:
a value=12
value by dereferencing p is 12
value by dereferencing pptr is 12
value of p is 1000
value of pptr is 2000
12
1000 p 1000
2000 pptr 2000
3000
4.8. Initialization
1. Pointer can be assigned or initialized with the address of an object.
Eg) int a=10;
int *p=&a;
2. A pointer to one type cannot be initialized with the address of other type object.
Eg) int a=10;
float *p;
p=&a; //not possible
Because p is a float pointer so it can’t point int data.
1. Addition
(i) An addition of int type can be added to an expression of pointer type. The result
is pointer type.(or)A pointer and an int can be added.
Pre-
increment
Result =
initial value
of pointer +
Eg. post float* - float* ftr=p++ ftr=? ftr=2000 sizeof (T)
increment p=2000 p=2004
Value of ptr
= Value of
ptr
+sizeof(T)
3 - Pointer to int Pointer Result =
type T to type initial value
T of ptr - int
operand *
sizeof (T)
E.g. float* int float* p=p-1 p=2000 1996 2000 – 1 * 4
= 2000-
4=1996
Pre-
decrement
Result =
initial value
of pointer –
sizeof(T)
Eg.pre float* - float* ftr=--p ftr=? ftr=1996
decrement p=2000 p=1996 Value of ptr
= Value of
ptr –
sizeof(T)
10 20 30
Output:
Given array is
0: GeeksforGeeks
Sorted array is
0: CLanguage
1: GeeksQuiz
2: GeeksforGeekss
4.11.PARAMETER PASSING:
Function with input and outputs
More than one value can be indirectly returned to the calling function by making use of
pointers.
E.g. Program:
Call by reference program
4.11.1 Pass by value & Pass by reference
Argument passing methods in ‘C’ are,
3. Pass by value
4. Pass by reference
2. Pass by value
In this method the values of actual arguments are copied to formal arguments.
Any change made in the formal arguments does not affect the actual arguments.
Once control, return backs to the calling function the formal parameters are destroyed.
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int ,int);
a=10;
b=20;
printf("\n Before swapping: a = %d and b = %d",a,b);
swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
OUTPUT:
Main function
a b
10 20
1000 1002
Swap function
a1 b1
10 20
2000 2002
After swap function
a1 b1
20 10
2000 2002
2. Pass by reference
In this method, the addresses of the actual arguments are passed to formal argument.
Thus formal arguments points to the actual arguments.
So changes made in the arguments are permanent.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
Main function
a b
10 20
1000 1002
Swap function
a1 b1
2000 2002
After swap function
a b
20 10
1000 1002
Pass by Value Pass by Reference
Values of the Actual arguments are Passed to the Addresses of the Actual arguments are passed to the
Formal Arguments. Formal Arguments.
Different Memory Locations are Occupied Same memory Locations are Occupied.
There is no Possibility of Wrong Data . There is a Possibility of Wrong Data
Manipulations Manipulations.
In this, you are sending a copy of the data. In this, you are passing the memory address of the
data that is stored.
Changes does not affect the actual value. Changes to the value affect the original data.
OUTPUT:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20
Pass by Reference:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *,int *);
a=10;
b=20;
printf("\n Before swapping: a= %d and b= %d",a,b);
swap(&a,&b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}
void swap(int *a1,int *b1)
{
int t;
t = *a1;
*a1 = *b1;
*b1 = t;
}
OUTPUT:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
UNIT IV STRUCTURES 9
STRUCTURE
INTRODUCTION TO STRUCTURE IN C
1. As we know that Array is collection of the elements of same type, but many time we have to
store the elements of the different data types.
2. Suppose Student record is to be stored, then for storing the record we have to group together all
the information such as Roll name, Percent which may be of different data types.
3. Ideally Structure is collection of different variables under single name.
4. Basically Structure is for storing the complicated data.
5. A structure is a convenient way of grouping several pieces of related information together.
Structure Initialization:
The members of the structure can be initialized to constant valued by enclosing the values to be
assigned within the braces after the structure definition
struct date{
int date;
int month;
int year;
} republic= {26, 1, 1950};
Initializes the member variable data, month, year of republic to 26, 1, 1950 respectively.
2) DEFINITION OF STRUCTURE IN C:
Structure is composition of the different variables of different data types, grouped under same
name.
typedef struct {
char name[64];
char course[128];
int age;
int year; } student;
typedef struct {
char name[64];
char course[128];
book b1;
int year;
} student;
3) STRUCTURE DECLARATION
In C we can group some of the user defined or primitive data types together and form another
compact way of storing complicated information is called as Structure. Let us see how to declare
structure in c programming language -
Structure Alternate Syntax :
Syntax of Structure in C Programming:
struct<structure_name>
structtag
{
{
structure_Element1;
data_type1 member1;
structure_Element2;
data_type2 member2;
...
data_type3 member3;
};
};
int year;
}today;
// 'today' is name of Structure variable
int date;
char month[20];
int year;
};
struct date today;
Where “date” is name of structure and “today” is name of variable.
Arrays of Structures:
Arrays of structures are commonly used in a large number of similar records required to be
processed together. If there were one hundred employees in an organization , this data can be
organized in an array of structures. Consider the following example:
struct emp-data
{
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
for(i=0;i<3;i++)
scanf("%s",&st[i].name);
for(i=0;i<3;i++)
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
return 0;
char name[25];
int sem;
char branch[10];
int mark[3];
}
In the above example there are four members. Out of these four fields, name, branch and mark
are arrays.
Size of structure
Size of structure can be found out using sizeof() operator with structure variable name or tag
name with keyword.
sizeof(struct student); or
sizeof(s2);
Size of structure is different in different machines. So size of whole structure may not be equal to sum
of size of its members.
NESTED STRUCTURES
A structure within structure means nesting of structures. A structure can be declared within
another structure. Consider the following emp-data structure. In this case the structure ‘date’ may be
placed inside the structure.
struct date{
int date,month,year;
};
struct emp-data
{
char name[30];
{“ram”,{16,11,1990}};
When a structure is within another structure, it is called Nested structure. A structure variable
can be a member of another structure and it is represented as
struct student
element 1;
element 2;
………
………
struct student1
member 1;
member 2;
variable 1;
……….
……….
element n;
variable 2;
It is possible to define structure outside & declare its variable inside other structure.
struct date
int date,month;
};
struct student
char nm[20];
int roll;
struct date d;
};
Nested structure may also be initialized at the time of declaration like in above example.
{“ram”,201, {12,11}};
Nesting of structure within itself is not valid. Nesting of structure can be extended to any level.
{ int hr,min;
};
struct day
{ int date,month;
};
struct student
char nm[20];
struct day d;
Nesting of structure within itself is not valid. Nesting of structure can be extended to any level.
struct time
{ int hr,min;
};
struct day
{ int date,month;
};
struct student
char nm[20];
struct day d;
Example
main()
{
struct emp-data raja=,“raja”,,14,8,90--;
printf(“%s”,raja.name);
printf(“%d%d%d”,raja.dob.date,raja.dob.month, raja.dob.year);
}
Syntax:
Function name (Structure variable name)
#include<stdio.h>
struct student
{
int sub1;
int sub2;
int sub3;
};
void main()
{
struct student s[10];
int i,total=0;
clrscr();
for(i=0;i<=2;i++)
{
printf("\nEnter Marks in Three Subjects = ");
scanf("%d%d%d",& s[i].sub1,&s[i].sub2,&s[i].sub3);
total=s[i].sub1+s[i].sub2+s[i].sub3;
printf("\nTotal marks of s[%d] Student= %d",i,total);
}
getch();
}
When a structure is within another structure, it is called Nested structure. A structure variable can be a
member of another structure and it is represented as
struct student
element 1;
element 2;
………
………
struct student1
member 1;
member 2;
variable 1;
……….
……….
element n;
variable 2;
struct date
int date,month;
};
struct student
char nm[20];
int roll;
struct date d;
};
Nested structure may also be initialized at the time of declaration like in above example.
{“ram”,201, {12,11}};
Nesting of structure within itself is not valid. Nesting of structure can be extended to any level.
struct time
{ int hr,min;
};
struct day
{ int date,month;
};
struct student
struct day d;
#include <stdio.h>
struct Distance
int feet;
float inch;
int main()
printf("1st distance\n");
scanf("%d", &dist1.feet);
scanf("%f", &dist1.inch);
printf("2nd distance\n");
scanf("%d", &dist2.feet);
scanf("%f", &dist2.inch);
++sum.feet;
return 0;
Output
1st distance
Enter feet: 12
2nd distance
Enter feet: 2
typedef struct
char name[21];
char city[21];
char phone[21];
char *comment;
} Addr;
Addr s;
char comm[100];
gets(s.name, 20);
gets(s.city, 20);
gets(s.phone, 20);
gets(comm, 100);
s.comment =
(char *)malloc(sizeof(char[strlen(comm)+1]));
strcpy(s.comment, comm);
Writing struct structure_name variable_name; to declare a structure variable isn't intuitive as to what it
signifies, and takes some considerable amount of development time.
So, developers generally use typedef to name the structure as a whole. For example:
int imag;
float real;
} comp;
int main()
Here, typedef keyword is used in creating a type comp (which is of type as struct complex).
Then, two structure variables comp1 and comp2 are created by this comp type.
#include <stdio.h>
int age;
float weight;
};
int main()
scanf("%d",&(*personPtr).age);
scanf("%f",&(*personPtr).weight);
printf("Displaying: ");
printf("%d%f",(*personPtr).age,(*personPtr).weight);
return 0;
}
ARRYAS OF POINTER
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
C – Array of Structures
As you know, C Structure is collection of different datatypes ( variables ) which are grouped together.
Whereas, array of structures is nothing but collection of structures. This is also called as structure array
in C.
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[30];
float percentage;
};
int i;
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;
record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;
return 0;
OUTPUT:
Records of STUDENT : 1
Id is: 1
Records of STUDENT : 2
Id is: 2
Records of STUDENT : 3
Id is: 3
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[30];
float percentage;
};
int i;
return 0;
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Records of STUDENT2:
Id is: 2
Name is: Mani
Percentage is: 93.500000
struct struct_name
{
datatype datatypename;
struct_name * pointer_name;
};
A self-referential structure is one of the data structures which refer to the pointer to (points) to another
structure of the same type. For example, a linked list is supposed to be a self-referential data structure.
The next node of a node is being pointed, which is of the same struct type. For example,
In the above example, the listnode is a self-referential structure – because the *next is of the type struct
listnode.
6. pictorial representation:
In
Doubly Linked List
1. struct node{
2. int item;
7. pictorial representation:
C program using standard library functions: malloc(), calloc(), free() and realloc()
Dynamic memory management refers to manual memory management. This allows you to obtain more
memory when required and release it when not necessary.
Although C inherently does not have any technique to allocate memory dynamically, there are
4 library functions defined under <stdlib.h> for dynamic memory allocation.
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
C malloc()
The function malloc() reserves a block of memory of specified size and return a pointer of
type void which can be casted into pointer of any form.
Syntax of malloc()
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size
of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.
C calloc()
The only difference between malloc() and calloc() is that, malloc() allocates single block of memory
whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
This statement allocates contiguous space in memory for an array of 25 elements each of size of float,
i.e, 4 bytes.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own.
You must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Write a C program to find sum of n elements entered by user. To perform this program, allocate
memory dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
Write a C program to find sum of n elements entered by user. To perform this program, allocate
memory dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
C realloc()
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
Syntax of realloc()
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
int main()
{
int i, num;
float *data;
if(data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
return 0;
}
LINKED LIST
A linked list is a way to store a collection of elements. Like an array these can be character or integers.
Each element in a linked list is stored in the form of a node.
Node:
Linked List:
A linked list is formed when many such nodes are linked together to form a chain. Each node points to
the next node present in the order. The first node is always used as a reference to traverse the list and is
called HEAD. The last node points to NULL.
struct LinkedList{
int data;
struct LinkedList *next;
};
The above definition is used to create every node in the list. The data field stores the element and
thenext is a pointer to store the address of the next node.
In place of a data type, struct LinkedList is written before next. That's because its a self-referencing
pointer. It means a pointer that points to whatever it is a part of. Here next is a part of a node and it
will point to the next node.
typedef struct LinkedList *node; //Define node as pointer of data type struct LinkedList
node createNode(){
node temp; // declare a node
temp = (node)malloc(sizeof(struct LinkedList)); // allocate memory using malloc()
temp->next = NULL;// make next point to NULL
return temp;//return the new node
}
malloc() is used to dynamically allocate a single block of memory in C, it is available in the header
file stdlib.h.
sizeof() is used to determine size in bytes of an element in C. Here it is used to determine size of each
node and sent as a parameter to malloc.
The above code will create a node with data as value and next pointing to NULL.
Here the new node will always be added after the last node. This is known as inserting a node at the
rear end.
p->next = NULL;
Here -> is used to access next sub element of node p. NULL denotes no node exists after the current
node , i.e. its the end of the list.
The linked list can be traversed in a while loop by using the head node as a starting reference:
node p;
p = head;
while(p != NULL){
p = p->next;
}
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *prev,*head,*p;
int n,i;
printf ("number of elements:");
scanf("%d",&n);
head=NULL;
for(i=0;i<n;i++)
C - typedef
The C programming language provides a keyword called typedef, which you can use to give a type a
new name. Following is an example to define a term BYTE for one-byte numbers −
#include <stdio.h>
#include <string.h>
char author[50];
char subject[100];
int book_id;
} Book;
int main( ) {
Book book;
book.book_id = 6495407;
return 0;
When the above code is compiled and executed, it produces the following result −
typedef is limited to giving symbolic names to types only where as #define can be used to
define alias for values as well, q., you can define 1 as ONE etc.
typedef interpretation is performed by the compiler whereas #define statements are processed
by the pre-processor.
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main( ) {
return 0;
When the above code is compiled and executed, it produces the following result −
Value of TRUE : 1
Value of FALSE : 0
Files – Types of file processing: Sequential access, Random access – Sequential access file - Example
Program: Finding average of numbers stored in sequential access file - Random access file - Example
Program: Transaction processing using random access files – Command line arguments .
A stream is associated with a specific file by performing an open operation. Once a file is opened
information may be exchanged between it and your program. Each file that is opened has a unique file
control structure of type FILE ( which is defined in <stdio.h> along with the prototypes for all I/O
functions and constants such as EOF (-1) ). A file pointer is a pointer to this FILE structure which
identifies a specific file and defines various things about the file including its name, read/write status,
and current position. A file pointer variable is defined as follows
FILE *fptr ;
The fopen() function opens a stream for use and links a file with that stream returning a valid file
pointer which is positioned correctly within the file if all is correct. fopen() has the following prototype
FILE *fopen( const char *filename, const char *mode );
where filename is a pointer to a string of characters which make up the name and path of the required
file, and mode is a pointer to a string which specifies how the file is to be opened. The following table
lists some values for mode.
If fopen( ) cannot open "test.dat " it will a return a NULL pointer which should always be
tested for as follows.
FILE *fp ;
if ( ( fp = fopen( "test.dat", "r" ) ) == NULL )
{
puts( "Cannot open file") ;
exit( 1) ;
}
This will cause the program to be exited immediately if the file cannot be opened.
The fclose() function is used to disassociate a file from a stream and free the stream for use again.
fclose() will automatically flush any data remaining in the data buffers to the file.
Once a file pointer has been linked to a file we can write characters to it using the fputc() function.
fputc( ch, fp ) ;
If successful the function returns the character written otherwise EOF. Characters may be read from a
file using the fgetc() standard library function.
ch = fgetc( fp ) ;
When EOF is reached in the file fgetc( ) returns the EOF character which informs us to stop
reading as there is nothing more left in the file.
#include <stdio.h>
void main()
{
FILE *fin, *fout ;
char dest[30], source[30], ch ;
This is quite similar to working with characters except that we use the functions fgets() and
fputs() whose prototypes are as follows :-
For Example : Program to read lines of text from the keyboard, write them to a file and then read them
back again.
#include <stdio.h>
void main()
{
char file[80], string[80] ;
FILE *fp ;
fclose( fp ) ;
fclose( fp ) ;
}
Formatted I/O
For Example :- Program to read in a string and an integer from the keyboard, write them to a disk file
and then read and display the file contents on screen.
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fp ;
char s[80] ;
int t ;
fclose( fp ) ;
}
Note : There are several I/O streams opened automatically at the start of every C program.
It is through these streams that the console functions we normally use operate. For example in reality a
normal printf call such as
is in fact interpreted as
These two functions are used to read and write blocks of data of any type. Their prototypes are as
follows where size_t is equivalent to unsigned.
where buffer is a pointer to the region in memory from which the data is to be read or written
respectively, num_bytes is the number of bytes in each item to be read or written, and count is the
total number of items ( each num_bytes long ) to be read/written. The functions return the number of
items successfully read or written.
For Example :-
#include <stdio.h>
#include <stdlib.h>
struct tag {
float balance ;
char name[ 80 ] ;
} customer = { 123.232, "John" } ;
void main()
{
FILE *fp ;
double d = 12.34 ;
int i[4] = {10 , 20, 30, 40 } ;
fclose( fp ) ;
}
NB : Unlike all the other functions we have encountered so far fread and fwrite read and write binary
data in the same format as it is stored in memory so if we try to edit one these files it will appear
completely garbled. Functions like fprintf, fgets, etc. read and write displayable data. fprintf will write
a double as a series of digits while fwrite will transfer the contents of the 8 bytes of memory where the
double is stored directly.
The fseek() function is used in C to perform random access I/O and has the following prototype.
where origin specifies one of the following positions as the origin in the operation
and where num_bytes is the offset in bytes to the required position in the file. fseek() returns zero
when successful, otherwise a non-zero value.
For Example if we had opened a file which stored an array of integers and we wish to read the 50 th
value we might do the following
Low level file input and output in C does not perform any formatting or buffering of data whatsoever,
transferring blocks of anonymous data instead by making use of the underlying operating system's
capabilities.
As in the case of stream I/O a number of standard files are opened automatically :-
The following table lists some of the more common low level I/O functions, whose prototypes are
given in <io.h> and some associated constants are contained in <fcntl.h> and <sys\stat.h>.
The open function has the following prototype and returns -1 if the open operation fails.
where filename is the name of the file to be opened, oflag specifies the type of operations that are to be
allowed on the file, and pmode specifies how a file is to be created if it does not exist.
oflag may be any logical combination of the following constants which are just bit flags combined
using the bitwise OR operator.
pmode is only used when O_CREAT is specified as part of oflag and may be one of the following
values
S_IWRITE
S_IREAD
S_IREAD | S_IWRITE
where handle refers to a specific file opened with open(), buffer is the storage location for the data ( of
any type ) and count is the maximum number of bytes to be read in the case of read() or the maximum
number of bytes written in the case of write(). The function returns the number of bytes actually read
or written or -1 if an error occurred during the operation.
Example : Program to read the first 1000 characters from a file and copy them to another.
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
void main()
{
char buff[1000] ;
int handle ;
close( handle ) ;
handle = open("test.bak",
O_BINARY|O_CREAT|O_WRONLY| O_TRUNC,
S_IREAD | S_IWRITE ) ;
close( handle ) ;
}
Low level file I/O also provides a seek function lseek with the following prototype.
_lseek uses the same origin etc. as fseek() but unlike fseek() returns the offset, in bytes, of the new file
position from the beginning of the file or -1 if an error occurs.
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>
void main()
{
int handle ;
long length ;
char name[80] ;
close( handle ) ;
1. Write a program that determines the following statistics pertaining to a text file.
i. Total number of characters
ii. Number of alphabetic characters
iii. Number of words
iv. Number of non alphabetic characters
v. Tabulates the usage of each letter of the alphabet.
2. Write a program that computes the value of Sin( x ) for x in the range 0 to 2 in steps of 0.01
radians and stores them in a binary file. This look-up table is commonly used to improve program
Write a simple database program which stores and manages information of the type contained in the
following structure by making use of a dynamically allocated array / list of structures of this type as
described below.
The list structure defined above contains three data items. <numrecords> is the total number of records
in the list at present, <selrecord> is the current record selected, and <data_items> is a pointer to a
pointer to type DETAILS, i.e. a doubly indirected pointer to the actual data.
The data is arranged as illustrated below in the case of a list with two records.
The list structure tells us that there are two records in the list, the current being the first in the list. The
pointer mylist->data_items, of type DETAILS **, has been allocated memory to store two addresses,
of type DETAILS *, i.e. the addresses for each individual record. Each of these individual pointers, i.e.
*(mylist->data_items + i), has been allocated sufficient memory to store an individual record.
Q1: For the given 3 integers as input. The inputs may or may not be different from each other.
You have to output 1 if all three inputs are different from each other, and 0 if any input is
repeated more than once.
Input
-----
Three integers on three lines.
Output
------
1 if the three inputs are different from each other , 0 if some input is repeated more than once.
Solution:
#include <stdio.h>
int main()
{
int a;
int b;
int c;
scanf("%d", &a);
scanf("%d", &b);
scanf("%d", &c);
return 0;
}
Q2: For the given an NxN matrix. You have to determine whether the matrix is a triangular
matrix. The diagonal of the matrix M of size NxN is the set of entries M(0,0), M(1,1), M(2,2), ...,
M(N,N). A matrix is upper triangular if every entry below the diagonal is 0. For example,
111
Input
First, you will be given N, which is the size of the matrix.
Then you will be given N rows of integers, where each row consists of
N integers separated by spaces.
Output
If the input matrix is triangular, then print yes. Otherwise, print
no.
Solution: #include<stdio.h>
int main()
{
int i,x,p,q,n,counter,z;
p=0;
q=0;
scanf("%d",&n);
for(i=1;i<n+1;i++)
{
counter =1;
for(;counter<i;)
{
scanf("%d",&z);
counter++;
if(z==0);
else
p=1;
}
if(counter==i)
{
scanf("%d",&x);
counter++;
}
}
if(p==1&&q==1)
printf("no");
else
printf("yes");
return 0;
}
Q3: You are given a sorted (either in the increasing or in the decreasing order) sequence of
numbers, ending with a -1. You can assume that are at least two numbers before the ending -
1.Let us call the sequence x0 x1 ... xn -1.You have to output the number of distinct elements in
the sorted sequence. Kindly do not use arrays in the code.
Solution:
#include <stdio.h>
int main()
{
int curr=0; /* current value being read */
int prev; /* previous value read */
int num_distinct=0; /* number of distinct values read */
prev = curr;
scanf ( "%d",&curr );
num_distinct = 1;
while ( curr != -1 ) {
prev = curr;
scanf ( "%d", &curr );
if ( prev != curr && curr != -1){
num_distinct = num_distinct + 1;
}
}
printf("%d\n", num_distinct);
return 0;
}
Input
You are given the input in two lines:
The first line contains a positive integer k. In the second line, you will be given a sequence of
numbers. You have to find the kth occurrence of n in the sequence below.
The second line consists of a sequence of non-negative integers, terminated with a -1. The -1 is not
part of the sequence.
Output
If there are k even numbers in the sequence, then output the kth occurrence of even in the sequence.
Otherwise, output a -1.
Sample Input
2
1 1 3 2 3 4 -1
Sample Output
4
scanf("%d",&curr);
while ( curr != -1 ){
if ( curr % 2 == 0 ){
even_count = even_count+1;
if ( even_count == k ){
printf ( "%d\n", curr );
return ;
}
}
scanf ( "%d", &curr );
}
printf ( "-1\n" );
scanf("%d",&k);
find_even(k);
return 0;
}
Q5: Given two arrays of integers output the smallest number in the first array not present in the
second one.
Input Specification:
The first line contains the size N1 of the first array.
Next line give the contents of the first array.
Next line contains the size N2 of the second array.
Next line give the contents of the second array.
Output Format:
Output must be a single number which is the smallest number occurring
in the first array that does not occur in the second. In case there is
no such number, output NO.
Variable Constraints:
The sizes of the arrays are smaller than 20.
Each array entry is an integer which fits an int data type.
Example:
Input:
3
234
4
1357
Output: 2
Input
1
1
2
12
Output: NO
Solution: #include<stdio.h>
#define MAX 20
return n;
}
int main() {
int arr1[MAX], n1;
int arr2[MAX], n2;
n1 = read_array(arr1);
n2 = read_array(arr2);
int i, small_np = 0, flag = 0;
for (i = 0; i < n1; i++) {
if (!present(arr2, n2, arr1[i])) {
if (!flag || (small_np > arr1[i]) ) {
flag = 1;
small_np = arr1[i];
}
}
}
if (flag) {
printf("%d", small_np);
} else {
printf("NO");
}
return 0;
}
Q6: Find the number of distinct numbers in a given sequence. The sequence need not be sorted.
Input
The input consists of two lines.
The first line consists of a positive number N. N is at most 1000.
The second line consists of N numbers separated by spaces.
Sample Input
4
1231
Sample Output
3
Solution: #include <stdio.h>
int main()
{
int arr[SIZE];
int i;
int j;
int count=0;
int n;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
/* O(n^2) solution */
for(i=0;i<n;i++){
int found=0;
printf("%d\n",count);
return 0;
Q7: Create a database of students using structures, where in each entry of the database will have
the following fields:
a name, which is a string with at most 128 characters
their marks in physics which is an int between 0 and 100
their marks in chemistry which is an int number between 0 and 100
their marks in mathematics which is an int number between 0 and 100
You have to output a list of students in the following order.
if a student 'A' has lower marks in physics than a student 'B', then A's data is listed before B.
If A and B have the same physics marks and A has lower chemistry marks than B, then A is
listed before B.
If A and B have the same marks in physics and chemistry, and A has lower marks in
mathematics than B, then A is listed before B.
If all marks are equal and A's name precedes B's name in the dictionary order, then A is listed
before B.
.
Input Format :
First line contains the number of students n, where 1<=n<=100.
In following n lines each line contains(space separated) a name and their respective marks in
physics, chemistry, maths, where 0<=marks<=100.
Output Format :
Sorted database of n lines.
Solution: #include<stdio.h>
#include<stdlib.h>
struct student{
char name[20];
int phy,che,math;
};
typedef struct student student;
int main(){
int i,n;
scanf("%d",&n);
student *student_info= (student *)malloc(sizeof(student)*n);
for(i=0;i<n;i++){
scanf("%s",student_info[i].name);
scanf("%d",&student_info[i].phy);
scanf("%d",&student_info[i].che);
scanf("%d",&student_info[i].math);
}
qsort((void *)student_info,n,sizeof(student),comparator);
print(student_info,n);
return 0;
}
Q8: For the given a sequence of integers terminated with a -1. The -1 is not part of the input sequence.
Next, you are given a positive number N.
You have to create a linked list with the input sequence of integers
as entries. You can use the following structure.
struct node{
int data;
struct node *next;
};
Now, you have to delete all but the last N elements from the linked
list, and print the resulting list. (i.e. The resulting list will
consist of only the last N elements from the list.)
If N is longer than the length of the linked list, you must print -1.
Sample Output
-------------
6
struct node {
int data;
struct node *next;
};
int list_length;
return head;
}
/* Delete the first num nodes from the list */
struct node *delete_first ( int num, struct node *head )
int main()
{
int number;
int pruned_length=0;
struct node *head;
Answer 31
Answer 26
Answer B
PO2:Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
PO5:Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6:The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO8:Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice..
PO9:Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO12:Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.