0% found this document useful (0 votes)
73 views

CS8251 C Prog

Mr.B.M.Nagarajan AP/CSE Week No. Date Day Topic/Unit 1 16/12/19 Mon Introduction to C Programming, Structure of C Program 2 23/12/19 Mon Data Types, Constants, Operators 3 30/12/19 Mon Input/Output Statements, Decision Making Statements 4 06/01/20 Mon Looping Statements, Preprocessor Directives 5 13/01/20 Mon Arrays: One Dimensional Arrays 6 20/01/20 Mon Arrays: Two Dimensional Arrays, String Operations 7 27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

CS8251 C Prog

Mr.B.M.Nagarajan AP/CSE Week No. Date Day Topic/Unit 1 16/12/19 Mon Introduction to C Programming, Structure of C Program 2 23/12/19 Mon Data Types, Constants, Operators 3 30/12/19 Mon Input/Output Statements, Decision Making Statements 4 06/01/20 Mon Looping Statements, Preprocessor Directives 5 13/01/20 Mon Arrays: One Dimensional Arrays 6 20/01/20 Mon Arrays: Two Dimensional Arrays, String Operations 7 27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

K.L.N.

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]

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

(R2017)

2019-2020 (Even Semester)

CS8251

PROGRAMMING IN C

MONOGRAPH

PREPARED BY,

DR. S. SURESH RAJA, ASP


DR.V.AKILANDESWARI,AP(Sr.Gr)/CSE
MR.B.M.NAGARAJAN AP/CSE

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 1


VISION AND MISSION OF THE COLLEGE
VISION
To become a Premier Institute of National Repute by Providing Quality Education, Successful
Graduation, Potential Employability and Advanced Research & Development through Academic
Excellence.

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.

VISION AND MISSION OF THE DEPARTMENT


VISION
To be a competent Professional in the field of Computer Science & Engineering through
quality education, training and innovative research.
MISSION
• Imparting proficient education through quality teaching –learning process in tune with the
interdisciplinary needs of global work environment.
• Inculcating the attitude of continuous learning through industry institution interaction, consultancy
and research activities.
• Cultivating professionalism, Ethics and integrity of character for positive contributions to society.

Program Educational Objectives(PEO's)

Contribute effectively to the society by applying principles of computer science and


PEO I engineering for analyzing the real world problems to produce Optimal and
acceptable technical solutions.

Sustain as good professionals by pursuing career / advanced studies and practice


PEO II
innovation in emerging technologies through lifelong learning.

Build professionalism, team work, effective communication, ethical values and


PEO III
leadership qualities

Program Specific Outcomes (PSOs)

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 2


CS8251 PROGRAMMING IN C LTPC

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 I BASICS OF C PROGRAMMING 9


Introduction to programming paradigms -Structure of C program -C programming: Data Types –
Storage classes -Constants –Enumeration Constants -Keywords –Operators: Precedence and
Associatively -Expressions -Input/output statements, Assignment statements –Decision making
statements -Switch statement -Looping statements –Pre-processor directives -Compilation process

UNIT II ARRAYS AND STRINGS 9


Introduction to Arrays: Declaration, Initialization –One dimensional array –Example Program:
Computing Mean, Median and Mode -Two dimensional arrays –Example Program: Matrix Operations
(Addition, Scaling, Determinant and Transpose) -String operations: length, compare, concatenate,
copy –Selection sort, linear and binary search

UNIT III FUNCTIONS AND POINTERS 9


Introduction to functions: Function prototype, function definition, function call, Built- in functions
(string functions, math functions) –Recursion –Example Program: Computation of Sine series,
Scientific calculator using built -in functions, Binary Search using recursive functions –Pointers –
Pointer operators –Pointer arithmetic –Arrays and pointers –Array of pointers –Example Program:
Sorting of names –Parameter passing: Pass by value, Pass by reference –Example Program: Swapping
of two numbers and changing the value of a variable using pass by reference

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

UNIT V FILE PROCESSING 9


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

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 3


TEXT BOOKS:
1. Reema Thareja, ―Programming in C‖, Oxford University Press, Second Edition, 2016.
2. Kernighan, B.W and Ritchie,D.M, ―The C Programming language‖, Second Edition, Pearson
Education, 2006.
REFERENCES:
1. Paul Deitel and Harvey Deitel, ―C How to Program‖, Seventh edition, Pearson Publication
2. Juneja, B. L and Anita Seth, ―Programming in C‖, CENGAGE Learning India pvt. Ltd., 2011
3. Pradip Dey, Manas Ghosh, ―Fundamentals of Computing and Programming in C‖, First
Edition, Oxford University Press, 2009.
4. Anita Goel and Ajay Mittal, ―Computer Fundamentals and Programming in C‖, Dorling
Kindersley (India) Pvt. Ltd., Pearson Education in South Asia, 2011.
5. Byron S. Gottfried, "Schaum's Outline of Theory and Problems of Programming with
C",McGraw-HillEducation,1996

CO- PO MAPPING
Subject: Programming in C
Subject Code: CS8251(Reg2017)

C114.1 Develop simple applications in C using basic constructs


C114.2 Design and implement applications using arrays and strings
C114.3 Develop and implement applications in C using functions and pointers.
C114.4 Develop applications in C using structures.
C114.5 Design applications using sequential and random access file processing.

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 4


K.L.N. COLLEGE OF ENGINEERING Format No.:11
Issue No.: 02
Revision No.: 01
LECTURE SCHEDULE Date: 23/06/12

Course/Branch : B.E / CSE Subject: Programming in C


Duration : DEC’2019- May ‘20 Subject Code : CS8251
Semester: II
Regulation : 2017 AUC/AUT/AUM: AUC
AIM

To understand and develop the C program using various concepts of arrays, strings, functions,
pointers, structures and files.

OBJECTIVE :

The student should be made to:


 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

S.No Date Period Topics to be Covered Book No [Page No]


Number
UNIT I BASICS OF C PROGRAMMING Target Periods: 9
1. Introduction to programming paradigms - T1(1-15)
Structure of C program
2. C programming: Data Types
3. Storage classes - Constants T1(19-24) T1(117-
4. 120)
Enumeration Constants - Keywords
5. Operators: Precedence and Associativity T1(32-45)
6. Expressions - Input/Output statements, T1(24-31)
Assignment statements
7. Decision making statements - Switch statement T1(57-68)
8. Looping statements T1(69-89)
9. T1(325-336)
Pre-processor directives - Compilation process
T1(16-18)
10.
Revision
Assignment – I Write a Program using Input/Output statements and Expressions.
Date of announcement: Date of Submission:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 5


UNIT II ARRAYS AND STRINGS Target Hours 9
11. 1 Introduction to Arrays: Declaration, T1(134-153)
3 Initialization
12. 1 One dimensional array
13. 1 Example Program:Computing Mean, Median and Mode
7
14. 1 Two dimensional arrays T1(156-163)
8
15. 1 Example Program: Matrix Operations (Addition,
9 Scaling, Determinant and Transpose)
16. 2 String operations: length, compare, T1(186-196)

17. 2
1
concatenate, copy
18. 2
2
Selection sort
19. Linear and binary search

20. Revision

Self Study Topic-1 Matrix Operations


Date of announcement: Date of Discussion:

UNIT III FUNCTIONS AND POINTERS Target Hours 9


21. Introduction to functions: Function prototype, function T1(101-110)
definition, function call,
22. Recursion – Example Program: Computation T1(120-126)
of Sine series
23. Scientific calculator using built-in functions
24. Binary Search using recursive functions
25. Pointers – Pointer operators – Pointer T1(214-221)
arithmetic
26. T1(223-227)
Arrays and pointers – Array of pointers T1(232-234)
27. Example Program:Sorting of names – T1(111-114)
Parameter passing:Pass by value,Pass by
reference
28. Example Program: Swapping of two numbers Web Ref
and changing the value of a variable using
pass by reference
29. Example Program: Swapping of two numbers and Web Ref
changing the value of a variable using pass by
reference

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 6


30. Revision- CBS
Assignment II - Program using pointers
Date of Announcement : Date of Submission :
Content Beyond: Recursive functions using data structures -
UNIT IV STRUCTURES Target Hours 9
31. Structure T1(259-264)
32. Nested structures T1(265-266)
33. Nested structures
34. Pointer and Structures T1(268-275)
35. Array of structures T1(266-268)
36. Example Program using structures and pointers Wef Ref.
37. Self referential structures T1(276)
38. Dynamic memory allocation T1(240-244)
39. Singly linked list - typedef T1(348,281)
40. Revision
Self Study Topic-1I Dynamic Memory Allocation
Date of announcement: Date of Discussion :
CT – III oct 5 th
UNIT V FILE PROCESSING Target Hours 9
41. T1(290-294)
Files
42. T1(294-300)
Types of file processing: Sequential access files
43. Types of file processing: Random access files T1(316-320)
44. Example Program: Sequential access files
45. Example Program: Randaom Access files Web Ref.
46. Finding average of numbers stored in sequential
Web Ref.
access file
47. Transact Transaction processing using random access files Web Ref.
48. Example Program: Transaction processing using
T1(302-316)
random access files
49. Command line arguments Web Ref.
50. 5 Revision
0
Assignment III - Transaction processing using random access files
Date of Announcement : Date of Submission :

TEXT BOOKS

S.No Title Author Publisher Year


T1 Programming in C Reema Thareja Oxford University Press, Second 2016
Edition,

T2 The C Programming language Kernighan, B.W and Second Edition, Pearson Education, 2006
Ritchie,D.M

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 7


REFERENCE BOOKS

S.no Title Author Publisher Year


Paul Deitel and Harvey Seventh edition,
R1 C How to Program -
Deitel Pearson Publication
CENGAGE Learning
R2 Programming in C Juneja, B. L and Anita Seth 2011
India pvt. Ltd
Fundamentals of Computing and First Edition, Oxford
R3 Pradip Dey, Manas Ghosh 2009.
Programming in C University Press,
Dorling Kindersley
Computer Fundamentals and Programming (India) Pvt. Ltd.,
R4 Anita Goel and Ajay Mittal 2011.
in C Pearson Education in
South Asia,
R5 Schaum's Outline of Theory and Problems . Byron S. Gottfried McGraw-Hill 1996.
of Programming with C Education,

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/

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 8


Assignment – I Write a Program using Input/Output statements and Expressions
Q1: Write a program using values from 0 – 9 are summed up and total “45” is displayed as output.
Assignment operators such as “=” and “+=” are used in this program to assign the values and to sum up
the values.

Solution: # include <stdio.h>


int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Toatal+i
}
printf("Total = %d", Total);
}

Q2: Write a C Program to find area and perimeter of Circle.


#include<stdio.h>
#include<conio.h>
#define pi 3.14
void main()
{
float r,area,perimeter;
clrscr();
printf("\n Enter r value:");
scanf("%f",&r);
area=pi*r*r;
printf(" area%f:",area);
perimeter=2*pi*r;
printf("perimeter%f:",perimeter);
getch();
}

Q3: Write a C Program to find area and perimeter of Circle.


#include<stdio.h>
#include<conio.h>
void main()
{
int age;
char name[50]; // or *name
clrscr();
printf("\n Type the Name of the candidate: ");
gets(name);
printf("\n Enter The Age : ");
scanf("%d",&age);
if(age>=18)
printf("\n %s is Eligible for Vote",name);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 9


else
printf("\n %s is Not Eligible for Vote",name);
getch();
}

Q4: Write a C Program to find area and perimeter of Circle.


#include <stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
int big;
clrscr();
printf("Enter three numbers:");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
big=a;
else if(b>a && b>c)
big=b;
else
big=c;
printf("Largest number is = %d",big);
return 0;
getch();
}

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 10


printf("%d is not a leap year.", year);
}
else
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);
getch();
}

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

Q2: Write a simple program to print the address of the pointer.


#include <stdio.h>
int main()
{
int* pc, c;

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

Q3: Write a simple program to swap a value using call by reference.

Solution: #include <stdio.h>


void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 11


swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Output: num1 = 10
num2 = 5

Q4: Write a program to Pass Pointers to Functions.


Solution: #include <stdio.h>
void addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr
}
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
Q5: Write a Program to calculate the sum of n numbers using malloc() and free().
Solution: #include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));

// if memory cannot be allocated


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);

// deallocating the memory


free(ptr);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 12


return 0;
}

Assignment 3 - Transaction processing using random access files


Q1: Write a program to open a random-access file, define a record format using a struct, write data to
the disk and close the file.
Solution:
// Creating a random-access file sequentially
#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
int main( void ) {
unsigned int i; // counter used to count from 1-100
// create clientData with default information
struct clientData blankClient = { 0, "", "", 0.0 };
FILE *cfPtr; // credit.dat file pointer
// fopen opens the file; exits if file cannot be opened
if ( ( cfPtr = fopen( "credit.dat", "wb" ) ) == NULL ) {
puts( "File could not be opened." );
} // end if
else {
// output 100 blank records to file
for ( i = 1; i <= 100; ++i ) {
fwrite( &blankClient, sizeof( struct clientData ), 1, cfPtr );
} // end for
fclose ( cfPtr ); // fclose closes the file
} // end else
} // end main

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

int main( void ) {


FILE *cfPtr; // credit.dat file pointer
// create clientData with default information
struct clientData client = { 0, "", "", 0.0 };
// fopen opens the file; exits if file cannot be opened
if ( ( cfPtr = fopen( "credit.dat", "rb+" ) ) == NULL ) {

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 13


puts( "File could not be opened." );
} // end if
else {
// require user to specify account number
printf( "%s", "Enter account number"
" ( 1 to 100, 0 to end input )\n? " );
scanf( "%d", &client.acctNum );
// user enters information, which is copied into file
while ( client.acctNum != 0 ) {
// user enters last name, first name and balance
printf( "%s", "Enter lastname, firstname, balance\n? " );
// set record lastName, firstName and balance value
fscanf( stdin, "%14s%9s%lf", client.lastName,
client.firstName, &client.balance );
// seek position in file to user-specified record
fseek( cfPtr, ( client.acctNum - 1 ) *
sizeof( struct clientData ), SEEK_SET );
// write user-specified information in file
fwrite( &client, sizeof( struct clientData ), 1, cfPtr );
// enable user to input another account number
printf( "%s", "Enter account number\n? " );
scanf( "%d", &client.acctNum );
} // end while
fclose( cfPtr ); // fclose closes the file
} // end else
} // end main

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)

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 14


count++;
printf("\n Average Height of %d persons is : %.2f\n",n,avg);
printf("\n The number of persons above average : %d ",count);
getch();
}

Q4: write a C Program to Solve towers of Hanoi using recursion


Solution:
#include <stdio.h>
void towers(int, char, char, char);
void main()
{
int num;
clrscr();
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
getch();
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 15


for(i=0;i<n;i++)
scanf("%d",&a[i]);
sortarray(a,n);
printf("\nAfter Sorting....\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
void sortarray(int* arr,int num)
{
int i,j,temp;
for(i=0;i<num;i++)
for(j=i+1;j<num;j++)
if(arr[i] > arr[j])
{ temp=arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 16


UNIT I BASICS OF C PROGRAMMING
Introduction to programming paradigms - Structure of C program - C programming: Data
Types –Storage classes - Constants – Enumeration Constants - Keywords – Operators:
Precedence and Associativity - Expressions - Input/output statements, Assignment statements –
Decision making statements - Switch statement - Looping statements – Pre-processor directives -
Compilation process

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 17


A multi-line comment starts with /* and terminates with */.A multi-line comment is used when
multiple lines of text are to be commented.
E.g. /* This program is used to find
Area of the Circle */
Section 1.Preprocessor Directive section
 The pre-processor directive section is optional.
 The pre-processor statement begins with # symbol and is also called the pre-processor
directive.
 These statements instruct the compiler to include C pre-processors such as header files
and symbolic constants before compiling the C program.
 The pre-processor directive is terminated with a new line character and not with a
semicolon.
 They are executed before the compiler compiles the source code.
Some of the pre-processor statements are listed below:
(i)Header files

#include<stdio.h> - to be included to use standard I/O functions : prinf(),scanf()


#include<math.h> -to be included to use mathematical functions :eg)sqrt()
(ii)Symbolic constants
#define PI 3.1412
#define TRUE 1

Section 2: Global declaration Section


This section is used to declare a global variable. These variables are declared before the main()
function as well as user defined functions.
Global variables are variables that are used in more than one function.

Section 3: Function Section


This section is compulsory. This section can have one or more functions. Every program
written in C language must contain main () function. The execution of every C program always begins
with the function main ().
Every function consists of 2 parts
1. Header of the function
2. Body of the function
1. Header of the function
The general form of the header of the function is
[return_type] function_name([argument_list])
2. Body of the function
The body of the function consists of a set of statements enclosed within curly brackets
commonly known as braces. The statements are of two types.
1. Non executable statements:
These are declaration statements, which declares the entire variables used. Variable
initialization is also coming under these statements.
2. Executable statements :
Other statements following the declaration statements are used to perform various tasks.
For example printf function call statement.
Non-executable statements are written first and then executable statements are written

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 18


E.g. C Program

Line 1: // First C program


Line2: #include<stdio.h>
Line3: main()
Line4: {
Line5 Printf(“Hello”);
Line6 }

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:

/*Addition of two numbers*/ Documentation Section


#include<stdio.h> Pre-processor directives
#define A 10 Definition Section
int c; Global declarations
int sum(int,int);
main() Main() functions
{
int b;
printf(“Emter the value for B:”);
scanf(“%d”,&b); Execution Part
c=sum(b);
printf(“\n Answer=%d”,c);
getch();
}
int sum(int y)
{
c=A+Y; Sub Program
return(c);
}
PROGRAMMING RULES
1. All statements should be written in lower case letters. Upper case letters are only used for
symbolic constants.
2. Blank spaces cannot be used while declaring a variable, keyword, constant and function.
3. The programmer can write the statement anywhere between the two braces following the
declaration part.
4. The user can also write one or more statements in one line by separating
semicolon (;).Ex:
a=b+c;
d=b*c;
or
a=b+c; d=b*c;
5. The opening and closing braces should be balanced. For example, if opening braces are four,
then closing braces should also be four.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 19


DATA TYPES
Data type determines the possible values that an identifier can have and the valid operations
that can be applied on it.
In C language data types are broadly classified as:
1. Basic data types(Primitive data types)
2. Derived data types
3. User-Defined data types
1. Basic data types:
There are five basic data types:
(i)Character - char
(ii)Integer - int
(iii)Single-Precision floating point - float
(iv)Double Precision floating point - double
(v)No value available - void

Data types and their memory requirements

S.No Data type No of bytes Range


required
1 Char 1 -128 to 127
2 Int 2 -32768 to 32767
3 Float 4 3.4*10-38 to 3.4*10
38

4 Double 8 1.7*10-308 to
1.7*10308
5 Unsigned char 1 0 to 255

Derived data types


These data types are derived from the basic data types. Derived data types available in C are:
1. Array type eg. Char[ ], int [ ]
2. Pointer type eg. Char*, int*
3. Function type eg. int (int,int), float(int)
User-defined data types
The C language provides the flexibility to the user to create new data types. These newly created data
types are called user-defined data types. The user defined data types available in C can be created by
using:
1. Structure
2. Union
3. Enumeration

Type qualifiers and Type Modifiers


The declaration statement can optionally have type qualifiers or type modifiers or both.

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:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 20


Const qualifier: Object value will not be changed during the execution of a
program
Volatile qualifier
Type Modifiers
A type modifier modifies the base type to yield a new type. It modifies the range and the arithmetic
properties of the base type.
Type modifiers and the corresponding keywords available in C are:
 Signed (signed)
 Unsigned (unsigned)
 Short (short)
 Long (long)
Constants
A constant is an entity whose value can’t be changed during the execution of a program.
Constants are classified as:
1. Literal constants
2. Qualified constants
3. Symbolic constants
Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating point
number, character or a string.
Literal constants are of the following types.
1. Integer Literal constant
2. Floating point Literal constant
3. Character Literal constant
4. String Literal constant
Integer Literal constant
Integer Literal constants are integer values like -1, 2, 8 etc. The rules for writing integer literal
constant are:
 An Integer Literal constant must have at least one digit
 It should not have any decimal point
 It can be either positive or negative.
 No special characters and blank spaces are allowed.
 A number without a sign is assumed as positive.
 Octal constants start with 0.
 Hexadecimal constant start with 0x or 0X
Floating point Literal constant
Floating point Literal constants are values like -23.1, 12.8, 4e8 etc.. It can be written in a
fractional form or in an exponential form.
The rules for writing Floating point Literal constants in a fractional form:
 A fractional floating point Literal constant must have at least one digit.
 It should have a decimal point.
 It can be either positive or negative.
 No special characters and blank spaces are allowed.
The rules for writing Floating point Literal constants in an exponential form:
 A Floating point Literal constants in an exponential form has two parts: the
mantissa part and the exponent part. Both are separated by e or E.
 The mantissa part can be either positive or negative. The default sign is
Positive.
 The mantissa part should have at least one digit.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 21


 The mantissa part can have a decimal point.
 The exponent part should have at least one digit
 The exponent part cannot have a decimal point.
 No special characters and blank spaces are allowed.

Character Literal constant


A Character Literal constant can have one or at most two characters enclosed within single
quotes. E.g, ‘A’ , ‘a’ , ‘ n ‘.
It is classified into:
 Printable character literal constant
 Non-Printable character literal constant.
Printable character literal constant
All characters except quotation mark, backslash and new line characters enclosed within single quotes
form a Printable character literal constant. Ex: ‘A’ , ‘#’
Non-Printable character literal constant.
Non-Printable character literal constants are represented with the help of escape sequences. An escape
sequence consists of a backward slash (i.e. \) followed by a character and both enclosed within single
quotes.

String Literal constant


A String Literal constant consist of a sequence of characters enclosed within double quotes.
Each string literal constant is implicitly terminated by a null character.
E.g. “ABC”
Qualified constants:
Qualified constants are created by using const qualifier.
E.g. const char a = ‘A’
The usage of const qualifier places a lock on the variable after placing the value in it. So we can’t
change the value of the variable a

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 22


SYNTAX:
enum enum_name{

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

Enumerated Typr Declarations:

When you create an enumerated type, only blueprint for the variable is created. Here's how you
can create variables of enum type.

enum boolean { false, true };

enum boolean check;

Another syntax:

enum boolean

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 23


false, true

} check;

Example: Enumeration Type

#include <stdio.h>

enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

int main()

enum week today;

today = wednesday;

printf("Day %d",today+1);

return 0;

Output

Day 4

Operators: Precedence and Associativity – Expressions:


An expression is a sequence of operators and operands that specifies computation of a value.
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +

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

Simple Expressions & Compound Expressions


An expression that has only one operator is known as a simple expression.
E.g: a+2
An expression that involves more than one operator is called a compound expression.
E.g: b=2+3*5

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 24


 The operator with the highest precedence is operated first.
Associativity of operators
The associativity rule is applied when two or more operators are having same precedence in the
sub expression.
An operator can be left-to-right associative or right-to-left associative.

Category Operators Associativity Precedence


Unary +, -, !, ~, ++, - -, &, sizeof Right to left Level-1
Multiplicative *, /, % Left to right Level-2
Additive +, - Left to right Level-3
Shift << , >> Left to right Level-4
Relational <, <=, >, >= Left to right Level-5

Rules for evaluation of expression


• First parenthesized sub expressions are evaluated first.
• If parentheses are nested, the evaluation begins with the innermost sub expression.
• The precedence rule is applied to determine the order of application of operators in evaluating
sub expressions.
• The associability rule is applied when two or more operators are having same precedence in
the sub expression.

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

Classification based on Number of Operands


Types:
1. Unary Operator: A unary operator operates on only one operand. Some of the unary operators
are,

Operator Meaning
- Minus

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 25


++ Increment
-- Decrement
& Address- of operator
sizeof sizeof operator

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.

Classification based on role of operands


Based upon their role, operators are classified as,
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Miscellaneous Operators
1. Arithmetic Operators
They are used to perform arithmetic operations like addition, subtraction,
multiplication, division etc.

A=10 & B=20


Operator Description Example
+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

The division operator is used to find the


/ B / A will give 2
quotient.
Modulus operator is used to find the
% B%A will give 0
remainder
+,- Unary plus & minus is used to indicate the +A, -A

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 26


algebraic sign of a value.

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

Operator Meaning of Operator Example

== Equal to 5==3 returns false (0)


> Greater than 5>3 returns true (1)

< Less than 5<3 returns false (0)

!= Not equal to 5!=3 returns true(1)

>= Greater than or equal to 5>=3 returns true (1)

<= Less than or equal to 5<=3 return false (0)

 If the relation is true, it returns value 1 and if the relation is false, it returns
value 0.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 27


 An expression that involves a relational operator is called as a condition. For e.g a<b is
a condition.
3. Logical Operators
 Logical operators are used to logically relate the sub-expressions. There are 3 logical
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

If c=5 and d=2


It returns true when both
Logial then,((c==5) && (d>5))
conditions are true
&& AND returns false.
If c=5 and d=2
It returns true when at-least one
Logical then, ((c==5) || (d>5))
of the condition is true
|| OR returns true.
Logical If c=5 then, !(c==5) It reverses the state of the
! NOT returns false. operand

Truth tables of logical operations


condition 1 condition 2 NOT X X AND Y X OR Y
(e.g., X) (e.g., Y) (~X) ( X && Y ) ( X || Y )
False false true false false
False true true false true
true false false false true
true true false true true

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.

Operators Meaning of operators

& Bitwise AND


| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right

Truth tables

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 28


p Q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
E.g.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)

3 << 2 (Shift Left)


0011
1100=12

3 >> 1 (Shift Right)


0011
0001=1

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 29


a. Function Call Operator(i.e. ( ) )
b. Array subscript Operator(i.e [ ])
c. Member Select Operator
i. Direct member access operator (i.e. . dot operator)
ii. Indirect member access operator (i.e. -> arrow operator)
d. Conditional operator (?:)
e. Comma operator (,)
f. sizeof operator
g. Address-of operator (&)
a) Comma operator
 It is used to join multiple expressions together.
 E.g.
int i , j;
i=(j=10,j+20);
In the above declaration, right hand side consists of two expressions separated by comma.
The first expression is j=10 and second is j+20. These expressions are evaluated from left to right. ie
first the value 10 is assigned to j and then expression j+20 is evaluated so the final value of i will be
30.
b) sizeof Operator
 The sizeof operator returns the size of its operand in bytes.
 Example : size of (char) will give us 1.
 sizeof(a), where a is integer, will return 2.

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 30


Input and Output functions

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

2. putchar() This function prints one character on the screen at a time.


Syntax :
putchar(variable name);
eg
char c=‘C’;
putchar(c);
Example Program
#include <stdio.h>
main()
{
int i;
char ch;
ch = getchar();
putchar(ch);
}
Output:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 31


A
A
3. getch() and getche() : getch() accepts only a single character from keyboard. The character entered
through getch() is not displayed in the screen (monitor).
Syntax
variable_name = getch();
Like getch(), getche() also accepts only single character, but getche() displays the entered character in
the screen.
Syntax
variable_name = getche();
4 putch(): putch displays any alphanumeric characters to the standard output device. It displays only
one character at a time.
Syntax
putch(variable_name);
b) String I/O
1.gets() – This function is used for accepting any string through stdin (keyboard) until enter key is
pressed.
Syntax
gets(variable_name);
2. puts() – This function prints the string or character array.
Syntax
puts(variable_name);
3. cgets()- This function reads string from the console.
Syntax
cgets(char *st);
It requires character pointer as an argument.
4. cputs()- This function displays string on the console.
Syntax
cputs(char *st);

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 32


Entered String : WELCOME

Formatted Input & Output Functions


When I/P & O/P is required in a specified format then the standard library functions scanf( ) &
printf( ) are used.
O/P function printf( )
The printf( ) function is used to print data of different data types on the console in a specified
format.
General Form

printf(“Control String”, var1, var2, …);

Control String may contain


1. Ordinary characters
2. Conversion Specifier Field (or) Format Specifiers
They denoted by %, contains conversion codes like %c, %d etc.
and the optional modifiers width, flag, precision, size.
Conversion Codes
Data type Conversion Symbol
char %c
int %d
float %f
Unsigned octal %o
Pointer %p

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

Size: Size modifiers used in printf are,


Size modifier Converts To
l Long int
h Short int
L Long double
%ld means long int variable

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 33


%hd means short int variable
3. Control Codes
They are also known as Escape Sequences.
E.g:
Control Code Meaning
\n New line
\t Horizontal Tab
\b Back space
Input Function scanf( )
It is used to get data in a specified format. It can accept data of different data types.
Syntax
scanf(“Control String”, var1address, var2address, …);

Format String or Control String is enclosed in quotation marks. It may contain


1. White Space
2. Ordinary characters
3. Conversion Specifier Field
It is denoted by % followed by conversion code and other optional modifiers E.g:
width, size.
Format Specifiers for scanf( )

Data type Conversion Symbol


char %c
int %d
float %f
string %s
E.g Program:

#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 - Switch statement – Looping statements

Decision making statements in a programming language help the programmer to transfer the
control from one part to other part of the program.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 34


Flow of control: The order in which the program statements are executed is known as flow of
control. By default, statements in a c program are executed in a sequential order.
The default flow of control can be altered by using flow control statements. These statements are
of two types.
Selection-Conditional Branching

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

 If test expression evaluates to true, the corresponding statement is executed.


 If the test expression evaluates to false, control goes to next executable statement.
 The statement can be single statement or a block of statements. Block of statements
must be enclosed in curly braces.

Example:
#include <stdio.h>
void main()
{
int n;
clrscr();

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 35


printf(“enter the number:”);
scanf(“%d”,&n);
if(n>0)
printf(“the number is positive”);
getch();
}
Output:
enter the number:50
the number is positive

(ii)The if-else statement


Test
Syntax: expr
essio
if (test expression) n
Statement T; T F
else
Statement F; Stateme Stateme
ntT ntF

 If the test expression is true, statementT will be executed.


 If the test expression is false, statementF will be executed.
 StatementT and StatementF can be a single or block of statements.

Example:1 Program to check whether a given number is even or odd.


#include <stdio.h>
void main()
{
int n,r;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
r=n%2;
if(r==0)
printf(“The number is even”);
else
printf(“The number is odd”);
getch();
}
Output:
Enter a number:15
The number is odd

Example:2 To check whether the two given numbers are equal


void main()
{
int a,b;
clrscr();
printf(“Enter a and b:” );

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 36


scanf(“%d%d”,&a,&b);
if(a==b)
printf(“a and b are equal”);
else
printf(“a and b are not equal”);
getch();
}
Output:
Enter a and b: 2 4
a and b are not equal
(iii) Nested if statement
If the body the if statement contains another if statement, then it is known as nested if statement
Syntax:

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

This is known as if ladder

iv) Nested if-else statement


Here, the if body or else body of an if-else statement contains another if statement or if else
statement
Syntax: ….
if (condition)
{ ….
statement 1;
statement 2; }
}
else
{
statement 3;
if (condition)
statementnest; else
statement 4;
Statement F;
}
Example:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 37


Program for finding greatest of 3 numbers
#include<stdio.h>
void main()
{
int a,b,c;
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“a is greatest”);
}
}
else
{
if(b>c)
{
printf(“b is greatest”);
}
else
{
printf(“C is greatest”);
}
}
}
Output
Enter three numbers 2 4 6
C is greatest

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)

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 38


case: break
statement
constant 0

case : break
statement
constant 1

default
statement break

Syntax

switch(expression) End of switch


{
case value 1:
program statement;
----
break;
case value 2:
program statement;
..…
break;

case value n:
program statement;
……
break;
default:
program statement;
}

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:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 39


printf(“Illegal entry”);
break;
}
getch();
}
Output
Enter a character
A
You entered an A

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

b)Unconditional branching statements


i)The goto Statement
This statement does not require any condition. Here program control is transferred to another
part of the program without testing any condition.
Syntax:
goto label;

 label is the position where the control is to be transferred.


Example:
void main()
{
printf(“www.”);
goto x;
y:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 40


printf(“mail”);
goto z;
x:
printf(“yahoo”);
goto y;
z:
printf(“.com”);
getch();
}
Output: www.yahoomail.com
b)break statement
 A break statement can appear only inside a body of , a switch or a loop
 A break statement terminates the execution of the nearest enclosing loop or switch.
Syntax
break;
break;
Example:1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
break;
printf(“\t %d”,c);
c++;
}
}

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:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 41


continue;
Example :1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
continue;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2 4 5
Example :2
#include<stdio.h>
main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
continue;
printf(“ %d”,i);
}
}

Output :1 2 3 4 6 7 8 9 10

iv) return statement:


A return statement terminates the execution of a function and returns the control to the calling
function.
Syntax:

return;
(or)

return expression;

Iteration Statements (Looping Statements)


Iteration is a process of repeating the same set of statements again and again until the condition
holds true.
Iteration or Looping statements in C are:
1. for
2. while
3. do while
Loops are classified as

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 42


 Counter controlled loops
 Sentinel controlled loops
Counter controlled loops
 The number of iterations is known in advance. They use a control variable called loop
counter.
 Also called as definite repetitions loop.
 E.g: for
Sentinel controlled loops
 The number of iterations is not known in advance. The execution or termination of the loop
depends upon a special value called sentinel value.
 Also called as indefinite repetitions loop.
 E.g: while
1. for loop
It is the most popular looping statement.
Syntax:
for(initialization;condition2;incrementing/updating)
{
Statements;
}

There are three sections in for loop.


a. Initialization section – gives initial value to the loop counter.
b. Condition section – tests the value of loop counter to decide whether to execute the
loop or not.
c. Manipulation section - manipulates the value of loop counter.

Execution of for loop


1. Initialization section is executed only once.
2. Condition is evaluated
a. If it is true, loop body is executed.
b. If it is false, loop is terminated
3. After the execution of loop, the manipulation expression is evaluated.
4. Steps 2 & 3 are repeated until step 2 condition becomes false.

Ex 1: Write a program to print 10 numbers using for loop


void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
printf(“%d”,i);
}
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10
Ex2: To find the sum of n natural number. 1+2+3…+n

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 43


void main()
{
int n, i, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n
4
sum=10

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

Execution of while loop


a. Condition in while is evaluated
i. If it is true, body of the loop is executed.
ii. If it is false, loop is terminated
b. After executing the while body, program control returns back to while header.
c. Steps a & b are repeated until condition evaluates to false.
d. Always remember to initialize the loop counter before while and manipulate loop counter
inside the body of while.

Ex 1: Write a program to print 10 numbers using while loop


void main()
{
int i=1;
clrscr();
while (num<=10)
{
printf (“%d”,i);
i=i+1;
}
getch();
}
Output:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 44


1 2 3 4 5 6 7 8 9 10

Ex2: To find the sum of n natural number. 1+2+3…+n


void main()
{
int n, i=1, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
while(i<=n)
{
sum=sum+i;
i=i+1;
}
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n
4
Sum=10

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

Execution of do while loop


a. Body of do-while is executed.
b. After execution of do-while body, do-while condition is evaluated
i. If it is true, loop body is executed again and step b is repeated.
ii. If it is false, loop is terminated

 The body of do-while is executed once, even when the condition is initially false.

Ex1: Write a program to print 10 numbers using do while loop


void main()
{
int i=1;
clrscr();
do
{
printf (“%d”,i);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 45


i=i+1;
} while (num<=10);
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10

Ex2: To find the sum of n natural number. 1+2+3…+n


void main()
{
int n, i=1, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
do
{
sum=sum+i;
i=i+1;
} while(i<=n);
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n
4
Sum=10

Three main ingredients of counter-controlled looping


1. Initialization of loop counter
2. Condition to decide whether to execute loop or not.
3. Expression that manipulates the value of loop.

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 46


 Preprocessor is a Macro processor program, that processes the code before it passes through the
compiler. It operates under the control of preprocessor command lines and directives.
 It is not part of the compiler, but is a separate step in the compilation process.
 In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to
do required pre-processing before actual compilation.
 All preprocessor commands begin with a pound symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in first column.

Directive Description

#define Substitutes a preprocessor macro

#include Inserts a particular header from another file

#undef Undefines a preprocessor macro

#ifdef Returns true if this macro is defined

#ifndef Returns true if this macro is not defined

#if Tests if a compile time condition is true

#else The alternative for #if

#elif #else an #if in one statement

#endif Ends preprocessor conditional

#error Prints error message on stderr

#pragma Issues special commands to the compiler, using a


standardized method

Preprocessors Examples

Analyze the following examples to understand various directives.

#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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 47


#define FILE_SIZE 42 //tells the CPP to undefine existing FILE_SIZE and define it as 42.

#ifndef MESSAGE

#define MESSAGE "You wish!"

UNIT II ARRAYS AND STRINGS


Introduction to Arrays: Declaration, Initialization – One dimensional array – Example Program:
Computing Mean, Median and Mode - Two dimensional arrays – Example Program: Matrix
Operations (Addition, Scaling, Determinant and Transpose) - String operations: length, compare,
concatenate, copy – Selection sort, linear and binary search

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 48


2.1 Arrays
Definition:
An array is a data structure that is used to store data of the same type. The position of an
element is specified with an integer value known as index or subscript.
E.g.

1 3 5 2 a(integer array)

b(float 1.2 3.5 5.4 2.1 array )

[0] [1] [2] [3]


Characteristics:
i) All the elements of an array share a common name called as array name
ii) The individual elements of an array are referred based on their position.
iii) The array index in c starts with 0.

In general arrays are classified as:


1.Single dimensional array
2.Multi-dimensional array

2.2 Single or one dimensional array


 It is also known as one-dimensional arrays or linear array or vectors
 It consists of fixed number of elements of same type
 Elements can be accessed by using a single subscript. eg) a[2]=9;
Eg)
1 3 5 2
a
[0] [1] [2] [3] subscripts or indices

Declaration of Single Dimensional Array


Syntax:
datatype arrayname [array size];

E.g. int a[4]; // a is an array of 4 integers


char b[6]; //b is an array of 6 characters

Initialization of single dimensional array


Elements of an array can also be initialized.
Rules
a) Elements of an array can be initialized by using an initialization list. An initialization list is a
comma separated list of initializers enclosed within braces.
Eg) int a[3]={1,3,4};
b) If the number of initializers in the list is less than array size, the leading array locations gets
initialized with the given values. The rest of the array locations gets initialized to
0 - for int array
0.0 - for float array

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 49


\0 - for character array

Eg) int a[2]={1};


a 1 0

char b[5]={‘A’.’r’,’r’};

b ‘A’ ‘r’ ‘r’ ‘\0’ ‘\0’

Usage of single dimensional array


The elements of single dimensional array can be accessed by using a subscript operator([]) and
a subscript.

Reading storing and accessing elements:


An iteration statement (i.e loop) is used for storing and reading elements.
Ex:1 Program to calculate the average marks of the class
#include <stdio.h>
void main()
{
int m[5],i,sum=0,n;
float avg;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
avg=(float)sum/n;
printf(“average=%f”,avg);
}
Output:
Enter number of students
5
Enter marks of students
55
60
78
85
90
Average=73.6
2.3 EXAMPLE PROGRAMS:
1.Computing Mean
2.Computing Median
3.Computing Mode

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 50


Computing Mean:
\* C Program to to find the mean of n numbers using array *\
#include <stdio.h>
void main()
{
int m[5],i,sum=0,n;
float mean;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
mean=(float)sum/n;
printf(“Mean=%f”,mean);
}
Output:
Enter number of students
5
Enter marks of students
55
60
78
85
90
Mean=73.6

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])

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 51


{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
{
median=((a[n/2]+a[n/2 -1])/2.0);
}
else
{
median=a[n/2];
}
printf("\n the median value is %f",median);
getch();
}
Output:
Enter N:5
Enter 1 number:11
Enter 2 number:12
Enter 3 number:13
Enter 4 number:14
Enter 5 number:15
The median value is 13.000000
3.Computing Mode:
#include<stdio.h>
#include<conio.h>
void main()
{
int maxvalue = 0, maxCount = 0, i, j,a[20],n,count=0;
clrscr();
printf("enter the N value:");
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;i++)
{
for (j = i+1; j < n;j++)
{
if(a[j] == a[i])
count++;
}
if (count > maxCount)
{

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 52


maxCount = count;
maxvalue = a[i];
printf("\nThe mode value is %d",maxvalue);
}
}
getch();
}
Output:
Enter the N value:5
Enter 1 Number:0
Enter 2 Number:6
Enter 3 Number:7
Enter 4 Number:2
Enter 5 Number:7
The mode value is 7
2.4 Two dimensional arrays

 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

datatype arrayname [row size][column size]

e.g) int a [2][3]; //a is an integer array of 2 rows and 3 columns


number of elements=2*3=6

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

2. The initializers in the list can be braced row wise.


e.g int a[2][3] = {{1,4,6} , {2}};

Example: Matrix Addition


#include<stdio.h>
#include<conio.h>

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 53


main()
{
int a[25][25],b[25][25], c[25][25], i, j m, n;
clrscr();
printf(“\n Enter the rows and columns of two matrices… “);
scanf(“%d %d “, &m, &n)
printf{“\n Enter the elements of A matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf{“\n Enter the elements of B matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j] + b[i][j];
printf(“\n The addition of two matrices”);
for(i=0;i<m;i++)
{
printf(“\n”);
for(j=0;j<n;j++)
{
printf(“\t %d”,c[i][j]);
}
}
getch();
}
Output:
Enter the rows and columns of two matrices…. 3 3
Enter the elements of A matrix… 1 2 3 4 5 6 7 8 9
Enter the elements of B matrix… 1 2 3 4 5 6 7 8 9
The addition of two matrixes
246
8 10 12
14 16 18

Example: Matrix Multiplication


#include <stdio.h>
#include <conio.h>
main()
{
int a[10][10], b[10][10], c[10][10];
int r1, c1, r2, c2;
int i, j, k;
clrscr();
printf("Enter order of matrix A : ");
scanf("%d%d", &r1, &c1);
printf("Enter order of matrix B : ");

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 54


scanf("%d%d", &r2, &c2);
if (c1 != r2)
{
printf("Matrix multiplication not possible");
getch();
exit(0);
}
printf("Enter matrix A elements\n");
for(i=0; i<r1; i++)
for(j=0; j<c1; j++)
scanf("%d", &a[i][j]);
printf("Enter matrix B elements\n");
for(i=0; i<r2; i++)
for(j=0; j<c2; j++)
scanf("%d", &b[i][j]);
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
c[i][j] = 0;
for(k=0; k<c1; k++)
{
c[i][j] =c[i][j]+ a[i][k] * b[k][j];
}
}
}
printf("Product matrix C\n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Output
Enter order of matrix A : 2 3
Enter order of matrix B : 3 2
Enter matrix A elements
111
111
Enter matrix B elements
22
22
22
Product matrix C
66

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 55


66
Example: Matrix Scaling
#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
void main()
{
int graphdriver=DETECT,graphmode,errorcode;
int i;
int x2,y2,x1,y1,x,y;
printf("Enter the 2 line end points:");
printf("x1,y1,x2,y2");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
initgraph(&graphdriver,&graphmode,"c:\\tc\\bgi");
line(x1,y1,x2,y2);
printf("Enter scaling co-ordinates ");
printf("x,y");
scanf("%d%d",&x,&y);
x1=(x1*x);
y1=(y1*y);
x2=(x2*x);
y2=(y2*y);
printf("Line after scaling");
line(x1,y1,x2,y2);
getch();
closegraph();
}

Example: Matrix Determinant


C code for Determinant of 2X2 matrix:

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 56


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("\nThe matrix is\n");
{
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
}
determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\nDeterminant of 2X2 matrix: %ld",determinant);
getch();
}
Output:
Enter the 4 elements of matrix 4 8 3 9
4 8
3 9
Determinant of 2x 2 matrix : 12

C code for Determinant of 3X3 matrix:

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
long determinant;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 57


clrscr();
printf("Enter the 9 elements of matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("\nThe matrix is\n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
determinant = a[0][0]*((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1]*(a[1][0]*a[2][2] -
a[2][0]*a[1][2]) + a[0][2]*(a[1][0]*a[2][1] - a[2][0]*a[1][1]);
printf("\n Determinant of 3X3 matrix: %ld", determinant);
getch();
}
Output:
Enter the 9 elements of matrix: 1 2 3 4 5 6 7 8 9
1 2 3
4 5 6
7 8 9
Determinant of 3X3 matrix:0

Example: Matrix Transpose


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j,m,n;
clrscr();
printf("How many rows");
scanf("%d",&n);
printf("How many columns");
scanf("%d",&m);
printf("\nEnter the matrix:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d",a[i][j]);
printf("\n");
}
printf("\nTranspose of given matrix:\n");

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 58


for(i=0;i<m;++i)
{
for(j=0;j<n;++j)
printf("%d ",a[j][i]);
printf("\n");
}
getch();
}
Output:
How many rows 2
How many columns 2

Enter the matrix: 1 2 3 4

1 2
3 4
Transpose of given matrix:
1 3
2 4

2.5 String Operations:(Length, Compare, Concatenate, Copy):


Definition:
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:
We can use 2 ways for initializing.
1. 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
These functions are defined in string.h header file.
1. strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not counted.
Syntax
temp_variable = strlen(string_name);
E.g.
s= “hai”;
strlen(s)-> returns the length of string s i.e. 3.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 59


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=“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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 60


It converts all the uppercase characters in that string to lowercase characters.
Syntax

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

Example: String Comparison


void main()

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 61


{
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”);
getch();
}
Output:
Enter String 1
Computer
Enter String 2
Programming
Two Strings are not equal
String Arrays
They are used to store multiple strings. 2-D char array is used for string arrays.

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 62


2.6 Sorting
Sorting is the process of arranging elements either in ascending or in descending order.
Sorting Methods
1. Selection Sort
2. Bubble Sort
3. Merge sort
4. Quick sort
1. Selection sort
It finds the smallest element in the list & swaps it with the element present at the head of the
list.
E.g.
25 20 15 10 5
5 20 15 10 25
5 10 15 20 25
2. Bubble Sort
In this method, each data item is compared with its neighbour element. If they are not in order,
elements are exchanged.
With each pass, the largest of the list is "bubbled" to the end of the list.
E.g.
Pass 1:
25 20 15 10 5
20 25 15 10 5
20 15 25 10 5
20 15 10 25 5
20 15 10 5 25
25 is the largest element
Repeat same steps until the list is sorted
3. Merge Sort:
 Merge sort is based on Divide and conquer method.
 It takes the list to be sorted and divide it in half to create two unsorted lists.
 The two unsorted lists are then sorted and merged to get a sorted list.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 63


4. Quick Sort
 This method also uses the technique of ‘divide and conquer’.
 Pivot element is selected from the list, it partitions the rest of the list into two parts – a sub-list
that contains elements less than the pivot and other sub-list containing elements greater than the
pivot.
 The pivot is inserted between the two sub-lists. The algorithm is recursively applied to sort the
elements.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 64


Program:
#include <stdio.h>
void main()
{
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; i++)
printf("%d\n", a[i]);
printf("The numbers arranged in descending order are given below \n");
for(i=n-1;i>=0;i--)
printf("%d\n",a[i]);
}
Output:
Enter the value of N
4
Enter the numbers
10 2 5 3
The numbers arranged in ascending order are given below
2
3
5
10
The numbers arranged in descending order are given below
10
5
3
2

2.7 Searching

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 65


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:
1. Linear Search
2. 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.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,m,c=0;
clrscr();
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");
getch();
}

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 66


Program:
#include<stdio.h>
void main()
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
}
Sample output:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be search: 11
The number is found.
Example:
3 5 7 9 11
Search key=7 middle element=7
Searching element=middle element. So the element is found.
Search key=11
Middle element=7
Searching element>middle
So go to right half: 9 11. Repeat steps until 11 is found or list ends.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 67


Solved Programs

Program: C Program to Add Two Matrix Using Multi-dimensional Arrays.


Programming Code:

#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]);
}

printf("\n\nElement in First Matrix are :\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("\t%d",a[i][j]);
printf("\n");

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 68


}
printf("\n\nElement in Second Matrix are :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("\t%d",b[i][j]);
printf("\n");
}

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
sum[i][j]=a[i][j]+b[i][j];
}

printf("\n\nSum of Two Matrix are :\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("\t%d",sum[i][j]);
printf("\n");
}

printf("\n\n");
return 0;
}

Output of the Program:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 69


Program: C Program to Find Transpose of a Matrix.
Programming Code:

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 70


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("\t%d",a[j][i]);
printf("\n");
}
return 0;
}
Output of the Program:

Program: C Program to Multiply to Matrix Using Multi-dimensional Arrays


Programming Code:

#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++)
{

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 71


for(j=0;j<c;j++)
{
printf("\nEnter the Element [%d] [%d] : ",i,j);
scanf("%d",&a[i][j]);
}

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

printf("\n\nElement in First 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\nElement in Second Matrix are :\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("\t %d",b[i][j]);
printf("\n");
}

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum=0;
for (k=0;k<r;k++)

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 72


{
sum = sum + (a[i][k] * b[k][j]);
}
mul[i][j]=sum;
}
}

printf("\n\nMultiplicaiton of Two Matrix are :\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("\t%d",mul[i][j]);
printf("\n");
}

printf("\n\n");
return 0;
}

Output of the Program:

Program: Program in c to insert an element at given position in an array.


Programming Code:

#include<stdio.h>
int main()
{
int a[20],i,n,ele,pos;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 73


printf("Enter the Number of Elements: ");
scanf("%d",&n);
printf("\nEnter the elements of array :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\nArray enter by user are :\n");
for(i=1;i<=n;i++)
printf("%d\t",a[i]);

printf("\nEnter the position you want to enter :");


scanf("%d",&pos);
printf("\nEnter the element you want to enter :");
scanf("%d",&ele);
for(i=n+1;i>0+1;i--)
{
if(i>pos)
a[i]=a[i-1];
else
{
if(i==pos)
a[i]=ele;
else
a[i]=a[i];
}

}
printf("\nArray After Inserting element :\n");
for(i=1;i<=n+1;i++)
printf("%d\t",a[i]);
printf("\n\n");
return 0;
}

Output of the Program:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 74


Program: Program in c to merge two unsorted array in descending order.
Programming Code:

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 75


}
for(i=1;i<=s;i++)
{
for(j=1;j<=s;j++)
{
if(sum[i]>=sum[j])
{
temp=sum[i];
sum[i]=sum[j];
sum[j]=temp;
}
}
}
printf("\nElement of array after merging and sorting :\n");
for(i=1;i<=s;i++)
printf("%d\t",sum[i]);
return 0;
}

Output of the Program:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 76


UNIT III FUNCTIONS AND POINTERS 9
Introduction to functions: Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion – Example Program: Computation of Sine series,
Scientific calculator using built-in functions, Binary Search using recursive functions – Pointers –
Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program:
Sorting of names – Parameter passing: Pass by value, Pass by reference – Example Program:
Swapping of two numbers and changing the value of a variable using pass by reference

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

4.2 Declaration of Function ( Function prototype)


All the function need to be declared before they are used. (i.e. called)

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 77


General form:

returntype function_name (parameter list or parameter type)


list);
a) Return type – data type of return value. It can be int, float, double, char, void etc.
b) Function name – name of the function
c) Parameter type list –It is a comma separated list of parameter types. Parameter names are
optional.
Ex: int add(int, int);
or
int add(int x, int y);

Function declaration must be terminated with a semicolon(;).

4.3 FUNCTION DEFINITION


It is also known as function implementation. Every function definition consists of 2 parts:
1. Header of the function
2. Body of the function

1. Header of the function


General form:
returntype functionname (parameter list)

1. The header of the function is not terminated with a semicolon.


2. The return type and the number & types of parameters must be same in both function header &
function declaration.

2. Body of the function


 It consists of a set of statements enclosed within curly braces.
 The return statement is used to return the result of the called function to the calling
function.

General form of Function Definition


returntype functionname (parameter list)

statements;

return (value);

4.4 FUNCTION CALL:


 A function can be called by using its name & actual parameters.
 It should be terminated by a semicolon ( ; ).
4.4.1. Working of a function

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 78


void main()
{
int x,y,z;
int abc(int, int, int) // Function declaration
…..
…..
abc(x,y,z) // Function Call
… Actual arguments

}

int abc(int i, int j, int k) // Function definition


{ Formal arguments
…….
….
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.

Steps for function Execution:


1. After the execution of the function call statement, the program control is transferred to the
called function.
2. The execution of the calling function is suspended and the called function starts execution.
3. After the execution of the called function, the program control returns to the calling
function and the calling function resumes its execution.
FUNCTION PROTOTYPES:
4.4.2. Classification of Function based on arguments (Function Invocation)
Depending upon their inputs and outputs, functions are classified into:
1. Function with no input and output or (With no arguments and no return values)
2. Function with inputs and no output or (With arguments and no return values)
3. Function with input and one output or (With arguments and one return value)
4. Function with input and outputs or (With arguments and more than one return values)
1. Function with no input and output
 This function doesn’t accept any input and doesn’t return any result.
 These are not flexible.
Example program:

#include<stdio.h>
void main()
{
void show( );
show( );
} No arguments are passed.
No values are sent back.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 79


void show( )
{
printf(“Hai \n”);
}

Output:
Hai

2. Function with inputs and no output


Arguments are passed through the calling function. The called function operates on the values
but no result is sent back.
Example program:
#include<stdio.h>
void main()
{
int a;
void show( );
printf(“Enter the value for a \n”);
scanf(“%d”, &a);
show(a);
} Arguments are passed.
No values are sent back.

void show(int x)
{
printf(“Value =%d”, x);
}
Output:
Enter the value for a
10
Value = 10

3. Function with input and one output


 Arguments are passed through the calling function i.e.) the actual argument is copied to
the formal argument.
 The called function operates on the values.
 The result is returned back to the calling function.
 Here data is transferred between calling function and called function.
 A function can return only one value. We can’t return more than one value by writing
multiple return statements.
Example program:
#include<stdio.h>
void main()
{
int r;
float area;
float circlearea(int);
printf(“Enter the radius \n”);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 80


scanf(“%d”,&r);
area=circlearea(r);
printf(“Area of a circle =%d\n”, area);
} Arguments are passed
int circlearea(int r1) Result is sent back
{
return 3.14 * r1 * r1;
}
Output:
Enter the radius
2
Area of circle = 12.000
4. 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.4.3 Pass by value & Pass by reference
Argument passing methods in ‘C’ are,
1. Pass by value
2. Pass by reference

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

void swap(int a1,int b1)


{
int temp;
temp=a1;
a1=b1;
b1=temp;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 81


}

OUTPUT:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 82


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

OUTPUT:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 83


Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10

Main function
a b

10 20

1000 1002
Swap function
a1 b1

1000 1002 a1, b1 points to a and b.

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.

Library of standard input & output functions


Header file: stdio.h
Example:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 84


This function is used to print the character, string, float, integer, octal
1 printf()
and hexadecimal values onto the output screen
2 scanf() This function is used to read a character, string, and numeric data from keyboard.
3 getc() It reads character from file
4 gets() It reads line from keyboard

Library of String functions:


Header file: string.h
Example:
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

String Operations:(Length, Compare, Concatenate, Copy):


Definition:
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:
We can use 2 ways for initializing.
2. 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
These functions are defined in string.h header file.
8. strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not counted.
Syntax
temp_variable = strlen(string_name);
E.g.
s= “hai”;
strlen(s)-> returns the length of string s i.e. 3.
9. strcpy() function
It copies the source string to the destination string

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 85


Syntax
strcpy(destination,source);
E.g.
s1=“hai”;
s2= “welcome”;
strcpy(s1,s2); -> s2 is copied to s1. i.e. s1=welcome.
10. strcat() function
It concatenates a second string to the end of the first string.
Syntax

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 86


strlwr(string_name);

E.g.
str[10]= “HELLO”;
strlwr(str);
puts(str);
Output: hello

13. strupr() function


It converts all the lowercase characters in that string to uppercase characters.
Syntax

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

Example: String Comparison


void main()
{
char s1[20],s2[20];

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 87


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”);
getch();
}
Output:
Enter String 1
Computer
Enter String 2
Programming
Two Strings are not equal
String Arrays
They are used to store multiple strings. 2-D char array is used for string arrays.

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 88


Direct & Indirect Recursion:
Direct Recursion:
A function is directly recursive if it calls itself.
A( )
{
….
….
A( );// call to itself
….
}
Indirect Recursion:
Function calls another function, which in turn calls the original function.
A( )
{


B( );

}
B( )
{


A( );// function B calls A

}

Consider the calculation of 6! ( 6 factorial )


ie 6! = 6 * 5 * 4 * 3 * 2 * 1
6! = 6 * 5!
6! = 6 * ( 6 - 1 )!
n! = n * ( n - 1 )!
E.g. Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int fact(int);
int n,f;
printf(“Enter the number \n”);
scanf(“%d”,&n);
f=fact(n);
printf(“The factorial of a number =%d”,f);
getch();
}
int fact(int n)
{
if(n==1)
return(1);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 89


else
return n*fact(n-1);
}
OUTPUT
Enter the number to find the factorial
5
The factorial of a number=120
Pattern of Recursive Calls:
Based on the number of recursive calls, the recursion is classified in to 3 types. They are,
1. Linear Recursion
Makes only one recursive call.
2. Binary Recursion
Calls itself twice.
3. N-ary recursion
Calls itself n times.
4.6EXAMPLE PROGRAM:
COMPUTATION OF SINE SERIES:
program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
float x, sum, t;
clrscr();
printf(" Enter the value for x : ");
scanf("%f",&x);
printf(" Enter the value for n : ");
scanf("%d",&n);
x=x*3.14159/180;
t=x;
sum=x;
/* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}

printf(" The value of Sin(%f) = %.4f",x,sum);


getch();
}
OUTPUT:
Enter the value for x :45
Enter the value for n: 5
The value of Sin(0.7853980 = 0.7071

SCIENTIFIC CALCULATOR USING BUILT-IN FUNCTIONS:


Program:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 90


#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(void)
{
int choice, i, a, b;
float x, y, result;
clrscr();
do {
printf(“\nSelect your operation (0 to exit):\n”);
printf(“1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n”);
printf(“5. Square root\n6. X ^ Y\n7. X ^ 2\n8. X ^ 3\n”);
printf(“9. %\n110. log10(x)\n);
printf(“Choice: “);
scanf(“%d”, &choice);
if(choice == 0) exit(0);
switch(choice) {
case 1:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x + y;
printf(“\nResult: %f”, result);
break;
case 2:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = x – y;
printf(“\nResult: %f”, result);
break;

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 91


result = x / y;
printf(“\nResult: %f”, result);
break;
case 5:
printf(“Enter X: “);
scanf(“%f”, &x);
result = sqrt(x);
printf(“\nResult: %f”, result);
break;
case 6:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = pow(x, y);
printf(“\nResult: %f”, result);
break;
case 7:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 2);
printf(“\nResult: %f”, result);
break;
case 8:
printf(“Enter X: “);
scanf(“%f”, &x);
result = pow(x, 3);
printf(“\nResult: %f”, result);
break;
case 9:
printf(“Enter X: “);
scanf(“%f”, &x);
printf(“\nEnter Y: “);
scanf(“%f”, &y);
result = (x * y) / 100;
printf(“\nResult: %.2f”, result);
break;
case 10:
printf(“Enter X: “);
scanf(“%f”, &x);
result = log10(x);
printf(“\nResult: %.2f”, result);
break;
}
} while(choice);
getch();
return 0;
}
BINARY SEARCH USING RECURSIVE FUNCTIONS:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 92


Program:
#include <stdio.h>
int RecursiveBinarySearching(int arr[], int low, int high, int element)
{
int middle;
if(low > high)
{
return -1;
}
middle = (low + high) / 2;
if(element > arr[middle])
{
RecursiveBinarySearching(arr, middle + 1, high, element);
}
else if(element < arr[middle])
{
RecursiveBinarySearching(arr, low, middle - 1, element);
}
else
{
return middle;
}
}

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:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 93


Enter the Limit of Elements in Array: 5
Enter 5 Elements in Array:
12345
Enter Element To Search:3
Element 3 Found at Position 3
4.7. POINTERS
Definition:
A pointer is a variable that stores the address of a variable or a function
Advantages
1. Pointers save memory space
2. Faster execution
3. Memory is accessed efficiently.
Declaration
datatype *pointername;

E.g ) int *p //p is an pointer to an int


float *fp //fp is a pointer to a float

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;

p is a pointer to a pointer to an integer.


int a=12;
int *p=&a; a
int **pptr=&p;
12
p 4000
4000
6000

6000 pptr
8000
So **pptr=12

Operations on pointers:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 94


1. Referencing operation: 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.

Eg) float a=12.5;


float *p;
p=&a;

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 95


a

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.

4.9. Pointers Arithmetic


Arithmetic operations on pointer variables are also possible.
E.g.) Addition, Increment, Subtraction, Decrement.

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.

Eg) if p is a pointer to an object then


p+1 =>points to next object
p+i=>point s to ith object after p

(ii)Addition of 2 pointers is not allowed.


2. Increment
Increment operator can be applied to an operand of pointer type.
3. Decrement
Decrement operator can be applied to an operand of pointer type.
4. Subtraction
i) A pointer and an int can be subtracted.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 96


ii) 2 pointers can also be subtracted.

S.no Operator Type of Type of Result Example Initial Final Description


operand operand type value value
1 2
1 + Pointer to int Pointer Result =
type T to type initial value
T of ptr +int
operand *
sizeof (T)

Eg. int * int int * p=p+5 p=2000 2010 2000+5*2=


2010
2 ++ Pointer to Pointer Post
type T - to type increment
T Result =
initial value
of pointer

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 97


4 -- Pointer to Pointer Post
type T - to type decrement
T Result =
initial value
of pointer

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)

4.10. Pointers and Arrays


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); 10 15 20
printf(“3nd element of array is at %u\n”, a+2);
1000 1002 1004
}
Output
First element of array is at 1000
2nd element of array is at 1002
3nd element of array is at 1004
ii)Any operation that involves array subscripting is done by using pointers in c language.
E.g.) E1[E2]=>*(E1+E2)
Example
#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);
}

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 98


Output:
Elements are 10 15 20
Elements are 10 15 20
Array of pointers
An array of pointers is a collection of addresses. Pointers in an array must be the same type.
int a=10,b=20,c=30;
int *b[3]={&a,&b,&c};
a b c

10 20 30

4000 4100 4400

b 4000 4100 4400

5000 5002 5004


Example Programs:
Sorting of Names:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int myCompare (const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
void sort(const char *arr[], int n)
{
qsort (arr, n, sizeof (const char *), myCompare);
}
int main ()
{
const char *arr[] = {"GeeksforGeeks", "GeeksQuiz", "CLanguage"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
printf("Given array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
sort(arr, n);
printf("\nSorted array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
return 0;
}

Output:
Given array is
0: GeeksforGeeks

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 99


1: GeeksQuiz
2: CLanguage

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

void swap(int a1,int b1)


{
int temp;
temp=a1;
a1=b1;
b1=temp;
}

OUTPUT:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 100


Before swapping: a =10 and b =20
After swapping: a =10 and b = 20

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 101


OUTPUT:
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10

Main function
a b

10 20

1000 1002
Swap function
a1 b1

1000 1002 a1, b1 points to a and b.

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.

4.12.EXAMPLE PROGRAM: SWAPPING OF TWO NUMBERS


Pass by Value:
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);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 102


swap(a, b);
printf("\n After swapping: a= %d and b= %d",a,b);
getch();
}

void swap(int a1,int b1)


{
int temp;
temp=a1;
a1=b1;
b1=temp;
}

OUTPUT:
Before swapping: a =10 and b =20
After swapping: a =10 and b = 20

4.13.EXAMPLE PROGRAM:CHANGING THE VALUE OF A VARIABLE USING PASS BY


REFERENCE

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 103


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

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;

Some Important Definitions of Structures:


1. Each member declared in Structure is called member.
char name[64];
char course[128];

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 104


intage; int year;
2. Name given to structure is called as tag
student
3. Structure member may be of different data type including user defined data-type also

typedef struct {
char name[64];
char course[128];
book b1;
int year;
} student;

Here book is user defined data type.

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

Some Important Points Regarding Structure in C Programming:


1. Struct keyword is used to declare structure.

2. Members of structure are enclosed within opening and closing braces.


3. Declaration of Structure reserves no space.
4. It is nothing but the “Template / Map / Shape” of the structure.
5. Memory is created, very first time when the variable is created /Instance is created.

Different Ways of Declaring Structure Variable:


Way 1 : Immediately after Structure Template

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 105


struct date
{
int date;
char month[20];

int year;
}today;
// 'today' is name of Structure variable

Way 2 : Declare Variables using struct Keyword


struct date
{

int date;
char month[20];
int year;
};
struct date today;
Where “date” is name of structure and “today” is name of variable.

Way 3: Declaring Multiple Structure Variables


struct Book
{
int pages;
char name[20];
int year;

} book1, book2, book3;


We can declare multiple variables separated by comma directly after closing curly.

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
{

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 106


char name[30];
int age; };

Then the array of structure used as,

struct emp-data employee[100];


the first record is referred as employee[0], second record is referred by employee[1], and so on.
employee *0+.name = “raja1”
employee[0].age = 25
employee*1+.name = “raja3”
employee[1].age = 35

hence array of structures is used to manage large number of records easily.

Example for Array of Structures


When database of any element is used in huge amount, we prefer Array of structures.

Example: maintain the details of 3 students using Array of Structure.

#include<stdio.h>

#include <string.h>

struct student{

int rollno;

char name[10];

};

int main(){

int i;

struct student st[3];

printf("Enter Records of 100 students");

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

printf("\nEnter Rollno:"); Enter Records of 3 students


Enter Rollno:1
scanf("%d",&st[i].rollno); Enter Name:Akila
Enter Rollno:2
Enter Name:Aruna
Enter Rollno:3
Enter Name:Subhiksha
Student Information List:
KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 107
Rollno:1, Name: Akila
Rollno:2, Name: Aruna
Rollno:3, Name: Subhiksha
printf("\nEnter Name:");

scanf("%s",&st[i].name);

printf("\nStudent Information List:");

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

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);

return 0;

In Array of structures each element of array is of structure type as in above example.

Array within structures:


A structure can have an array within it.
Char name[30]; //Like this is a structure can have no. of arrays as members.
Eg:
Struct student
{

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 108


sizeof(s1);

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.

4. STRUCTURE WITHIN STRUCTURE:

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];

struct date dob;


};
Nested structure may also be initialized at the time of declaration like in above example.

struct emp-data emp={“name”, {date, month, year}};

{“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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 109


{

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;

};

struct student s1;

struct student s2,s3;

Nested structure may also be initialized at the time of declaration like in above example.

struct student s={“name”,200, {date, month}};

{“ram”,201, {12,11}};

Nesting of structure within itself is not valid. Nesting of structure can be extended to any level.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 110


struct time

{ int hr,min;

};

struct day

{ int date,month;

struct time t1;

};

struct student

char nm[20];

struct day d;

}stud1, stud2, stud3;

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 time t1;

};

struct student

char nm[20];

struct day d;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 111


}stud1, stud2, stud3;

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

Structure and functions


This method is to pass each member of the structure as an actual arguments of the function call.
The actual arguments are then treated independently ordinary variables. This is the most elementary
methods and becomes inefficient when the structure size is large.

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 112


NESTED STRUCTURES

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;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 113


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;

};

struct student s1;

struct student s2,s3;

Nested structure may also be initialized at the time of declaration like in above example.

struct student s={“name”,200, {date, month}};

{“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 time t1;

};

struct student

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 114


char nm[20];

struct day d;

}stud1, stud2, stud3;

Example : Convert the distance in foot to inches.

#include <stdio.h>

struct Distance

int feet;

float inch;

} dist1, dist2, sum;

int main()

printf("1st distance\n");

// Input of feet for structure variable dist1

printf("Enter feet: ");

scanf("%d", &dist1.feet);

// Input of inch for structure variable dist1

printf("Enter inch: ");

scanf("%f", &dist1.inch);

printf("2nd distance\n");

// Input of feet for structure variable dist2

printf("Enter feet: ");

scanf("%d", &dist2.feet);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 115


// Input of feet for structure variable dist2

printf("Enter inch: ");

scanf("%f", &dist2.inch);

sum.feet = dist1.feet + dist2.feet;

sum.inch = dist1.inch + dist2.inch;

if (sum.inch > 12)

//If inch is greater than 12, changing it to feet.

++sum.feet;

sum.inch = sum.inch - 12;

// printing sum of distance dist1 and dist2

printf("Sum of distances = %d\'-%.1f\"", sum.feet, sum.inch);

return 0;

Output

1st distance

Enter feet: 12

Enter inch: 7.9

2nd distance

Enter feet: 2

Enter inch: 9.8

Sum of distances = 15'-5.7"

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 116


Structures Containing Pointers

POINTER AND STRUCTURES

Structures can contain pointers, as shown below:

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 117


This technique is useful when only some records actually contained a comment in the comment
field. If there is no comment for the record, then the comment field would consist only of a pointer (4
bytes). Those records having a comment then allocate exactly enough space to hold the comment
string, based on the length of the string typed by the user.

Keyword typedef while using structure

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:

typedef struct complex

int imag;

float real;

} comp;

int main()

comp comp1, comp2;

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.

Accessing structure's member through pointer

A structure's member can be accesssed through pointer in two ways:

1. Referencing pointer to another address to access memory

2. Using dynamic memory allocation

1. Referencing pointer to another address to access the memory

Consider an example to access structure's member through pointer.

#include <stdio.h>

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 118


typedef struct person

int age;

float weight;

};

int main()

struct person *personPtr, person1;

personPtr = &person1; // Referencing pointer to memory address of person1

printf("Enter integer: ");

scanf("%d",&(*personPtr).age);

printf("Enter number: ");

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 119


// *(classes + i) is equivalent to classes[i]
sum += *(classes + i);
}
printf("sum = %d", sum);
return 0;
}
output
enter 6 numbers:
2
3
4
5
3
4
sum = 21

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.

EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C:


This program is used to store and access “id, name and percentage” for 3 students. Structure array is
used in this program to store and display records for many students. You can store “n” number of
students record by declaring structure variable as ‘struct student record[n]“, where n can be 1000 or
5000 etc.

#include <stdio.h>

#include <string.h>

struct student

int id;

char name[30];

float percentage;

};

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 120


int main()

int i;

struct student record[2];

// 1st student's record

record[0].id=1;

strcpy(record[0].name, "Raju");

record[0].percentage = 86.5;

// 2nd student's record

record[1].id=2;

strcpy(record[1].name, "Surendren");

record[1].percentage = 90.5;

// 3rd student's record

record[2].id=3;

strcpy(record[2].name, "Thiyagu");

record[2].percentage = 81.5;

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

printf(" Records of STUDENT : %d \n", i+1);

printf(" Id is: %d \n", record[i].id);

printf(" Name is: %s \n", record[i].name);

printf(" Percentage is: %f\n\n",record[i].percentage);

return 0;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 121


}

OUTPUT:

Records of STUDENT : 1

Id is: 1

Name is: Raju

Percentage is: 86.500000

Records of STUDENT : 2

Id is: 2

Name is: Surendren

Percentage is: 90.500000

Records of STUDENT : 3

Id is: 3

Name is: Thiyagu

Percentage is: 81.500000

#include <stdio.h>

#include <string.h>

struct student

int id;

char name[30];

float percentage;

};

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 122


int main()

int i;

struct student record1 = {1, "Raju", 90.5};

struct student record2 = {2, "Mani", 93.5};

printf("Records of STUDENT1: \n");

printf(" Id is: %d \n", record1.id);

printf(" Name is: %s \n", record1.name);

printf(" Percentage is: %f \n\n", record1.percentage);

printf("Records of STUDENT2: \n");

printf(" Id is: %d \n", record2.id);

printf(" Name is: %s \n", record2.name);

printf(" Percentage is: %f \n\n", record2.percentage);

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

A self referential structure

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 123


A self referential structure is used to create data structures like linked lists, stacks, etc. Following is an
example of this kind of structure:

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,

typedef struct listnode {


void *data;
struct listnode *next;
} linked_list;

In the above example, the listnode is a self-referential structure – because the *next is of the type struct
listnode.

1. In Singly Linked List


1. struct node{
2. int data;
3. struct node *next; // self-referential
4. };
5. In the above declaration next is the pointer to the structure of type node.Here next is the
pointer which will contains the address of the structure of the same type (i.e address of next
node) and data will contain the actual data.

6. pictorial representation:

In
Doubly Linked List

1. struct node{
2. int item;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 124


3. struct node *prev; //self-referential
4. struct node *next; //self-referential
5. };
6. In the above declaration prev & next are the pointer to the structure of type node.Here prev
pointer contains the address of the previous node and next pointer contains the address of the
next node.

7. pictorial representation:

DYNAMIC MEMORY LOCATION

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.

Function Use of Function

malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 125


Function Use of Function

Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory

free() deallocate the previously allocated space

realloc() Change the size of previously allocated space

C malloc()

The name malloc stands for "memory allocation".

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

ptr = (cast-type*) malloc(byte-size)

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.

ptr = (int*) malloc(100 * sizeof(int));

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 name calloc stands for "contiguous allocation".

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

ptr = (cast-type*)calloc(n, element-size);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 126


This statement will allocate contiguous space in memory for an array of nelements. For example:

ptr = (float*) calloc(25, sizeof(float));

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.

Example #1: Using C malloc() and free()

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;

printf("Enter number of elements: ");


scanf("%d", &num);

ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc


if(ptr == NULL)
{
printf("Error! memory not allocated.");

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 127


exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

Example #2: Using C calloc() and free()

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

ptr = (int*) calloc(num, sizeof(int));


if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 128


}

printf("Enter elements of array: ");


for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

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

ptr = realloc(ptr, newsize);

Here, ptr is reallocated with size of newsize.

Example #3: Using realloc()


#include <stdio.h>
#include <stdlib.h>

int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 129


ptr = (int*) malloc(n1 * sizeof(int));

printf("Address of previously allocated memory: ");


for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);

printf("\nEnter new size of array: ");


scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0;
}
#include <stdio.h>
#include <stdlib.h>

int main()
{
int i, num;
float *data;

printf("Enter total number of elements(1 to 100): ");


scanf("%d", &num);

// Allocates the memory for 'num' elements.


data = (float*) calloc(num, sizeof(float));

if(data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 130


printf("\n");

// Stores the number entered by the user.


for(i = 0; i < num; ++i)
{
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}

// Loop to store largest number at address data


for(i = 1; i < num; ++i)
{
// Change < to > if you want to find the smallest number
if(*data < *(data + i))
*data = *(data + i);
}

printf("Largest element = %.2f", *data);

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:

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 131


A node is a collection of two sub-elements or parts. A data part that stores the element and a nextpart
that stores the link to the next 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.

Declaring a Linked list :

In C language, a linked list can be implemented using structure and pointers .

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.

Noticed something unusual with next?

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 132


Creating a Node:

Let's define a data type of struct LinkedListto make code cleaner.

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
}

typedef is used to define a data type in C.

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.

Let's see how to add a node to the linked list:

node addNode(node head, int value){


node temp,p;// declare two nodes temp and p
temp = createNode();//createNode will return a new node with data = value and next pointing to
NULL.
temp->data = value; // add element's value to data part of node
if(head == NULL){
head = temp; //when linked list is empty
}
else{
p = head;//assign head to p
while(p->next != NULL){
p = p->next;//traverse the list until p is the last node.The last node always points to NULL.
}
p->next = temp;//Point the previous last node to the new node created.
}
return head;
}

Here the new node will always be added after the last node. This is known as inserting a node at the
rear end.

Food for thought

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 133


This type of linked list is known as simple or singly linked list. A simple linked list can be traversed
in only one direction from head to the last node.

The last node is checked by the condition :

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.

Traversing 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++)

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 134


{
p=malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
if(head==NULL)
head=p;
else
prev->next=p;
prev=p;
}
return 0;
}

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 −

typedef unsigned char BYTE;


After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned
char, for example..

BYTE b1, b2;


By convention, uppercase letters are used for these definitions to remind the user that the type name is
really a symbolic abbreviation, but you can use lowercase, as follows −

typedef unsigned char byte;


You can use typedef to give a name to your user defined data types as well. For example, you can use
typedef with structure to define a new data type and then use that data type to define structure
variables directly as follows –

#include <stdio.h>

#include <string.h>

typedef struct Books {

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 135


char title[50];

char author[50];

char subject[100];

int book_id;

} Book;

int main( ) {

Book book;

strcpy( book.title, "C Programming");

strcpy( book.author, "Nuha Ali");

strcpy( book.subject, "C Programming Tutorial");

book.book_id = 6495407;

printf( "Book title : %s\n", book.title);

printf( "Book author : %s\n", book.author);

printf( "Book subject : %s\n", book.subject);

printf( "Book book_id : %d\n", book.book_id);

return 0;

When the above code is compiled and executed, it produces the following result −

Book title : C Programming


Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 136


typedef vs #define
#define is a C-directive which is also used to define the aliases for various data types similar
to typedef but with the following differences −

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

The following example shows how to use #define in a program −

#include <stdio.h>

#define TRUE 1

#define FALSE 0

int main( ) {

printf( "Value of TRUE : %d\n", TRUE);

printf( "Value of FALSE : %d\n", FALSE);

return 0;

When the above code is compiled and executed, it produces the following result −

Value of TRUE : 1
Value of FALSE : 0

TYPEDEF CAN BE USED FOR:


1. Types that combine arrays,structs,pointers or functions.
2. To facilitate the portability , typedef the type you require .Then when you port the code to
different platforms,select the right type by making changes only in the typedef.
3. A typedef can provide a simple name for a complicated type cast.
4. typedef can also be used to give names to unnamed types. In such cases, the typedef will be the
only name for said type.
NOTE:-SHOULDNT USE TYPEDEF WITH STRUCTS. ALWAYS USE A TAG IN A STRUCTURE
DEFINITION EVEN IF ITS NOT NEEDED.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 137


Unit-V
FILE PROCESSING

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 .

Common File Functions

fopen() open a stream


fclose() close a stream
putc()& fputc() write a character to a stream
getc()& fgetc() read a character from a stream
fprintf()& formatted I/O
fscanf

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 138


fgets() & string handling
fputs()
fseek() position the file pointer at a particular
byte
feof() tests if EOF

Opening and Closing Files

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.

r opens a text file for reading (must exist)


w opens a text file for writing (overwritten or
created)
a append to a text file
rb opens a binary file for reading
wb opens a binary file for writing
ab appends to a binary file
r+ opens a text file for read/write (must exist)
w+ opens a text file for read/write
a+ append a text file for read/write
rb+ opens a binary file for read/write
wb+ opens a binary file for read/write
ab+ append a binary file for read/write

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 139


fclose( fp ) ;

fclose() will automatically flush any data remaining in the data buffers to the file.

Reading & Writing Characters

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.

For Example :- Program to copy a file byte by byte

#include <stdio.h>
void main()
{
FILE *fin, *fout ;
char dest[30], source[30], ch ;

puts( "Enter source file name" );


gets( source );
puts( "Enter destination file name" );
gets( dest ) ;

if ( ( fin = fopen( source, "rb" ) ) == NULL ) // open


as binary as we don’t
{// know what is in file
puts( "Cannot open input file ") ;
puts( source ) ;
exit( 1 ) ;
}

if ( ( fout = fopen( dest, "wb" ) ) == NULL )


{
puts( "Cannot open output file ") ;
puts( dest ) ;
exit( 1 ) ;
}

while ( ( ch = fgetc( fin ) ) != EOF )


fputc( ch , fout ) ;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 140


fclose( fin ) ;
fclose( fout ) ;
}
NB : When any stream I/O function such as fgetc() is called the current position of the file pointer is
automatically moved on by the appropriate amount, 1 character/ byte in the case of fgetc() ;

Working with strings of text

This is quite similar to working with characters except that we use the functions fgets() and
fputs() whose prototypes are as follows :-

int fputs( const char *str, FILE *fp ) ;


char *fgets( char *str, int maxlen, FILE *fp ) ;

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 ;

printf( "Enter file Name : " );


gets( file );

if (( fp = fopen( file, "w" )) == NULL )//open for writing


{
printf( "Cannot open file %s", file ) ;
exit( 1 ) ;
}

while ( strlen ( gets( str ) ) > 0 )


{
fputs( str, fp ) ;
fputc( '\n', fp ) ; /* must append \n for readability --
not stored by gets() */
}

fclose( fp ) ;

if (( fp = fopen( file, "r" )) == NULL )//open for reading


{
printf( "Cannot open file %s", file ) ;
exit( 1 ) ;
}

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 141


while (fgets( str, 79, fptr ) != EOF )// read at most 79
characters
puts( str ) ;

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 ;

if ( ( fp = fopen( "test.dat", "w" ) ) == NULL )


{
puts( "Cannot open file test.dat") ;
exit(1) ;
}

puts( "Enter a string and a number") ;


scanf( "%s %d", s, &t );
fprintf( fp, "%s %d", s, t );
fclose( fp ) ;

if ( ( fp = fopen( "test.dat", "r" ) ) == NULL )


{
puts) "Cannot open file") ;
exit(1) ;
}

fscanf( fp, "%s %d" , s , &t ) ;


printf( "%s, %d\n", s, t ) ;

fclose( fp ) ;
}

Note : There are several I/O streams opened automatically at the start of every C program.

stdin --- standard input ie. keyboard

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 142


stdout --- standard output ie. screen
stderr --- again the screen for use if stdout malfunctions

It is through these streams that the console functions we normally use operate. For example in reality a
normal printf call such as

printf( "%s %d", s, t ) ;

is in fact interpreted as

fprintf( stdout, "%s %d", s, t ) ;

fread() and fwrite()

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.

size_t fread( void *buffer, size_t num_bytes, size_t count, FILE


*fp ) ;
size_t fwrite( const void *buffer, size_t num_bytes, size_t
count, FILE *fp ) ;

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

if ( (fp = fopen ( "test.dat", "wb+" ) ) == NULL )


{
puts( "Cannot open File" ) ;
exit(1) ;
}

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 143


fwrite( &d, sizeof( double ), 1, fp ) ;
fwrite( i, sizeof( int ), 4, fp ) ;
fwrite( &customer, sizeof( struct tag ), 1, fp ) ;

rewind( fp ) ; /* repositions file pointer to start */

fread( &d, sizeof( double ), 1, fp ) ;


fread( i, sizeof( int ), 4, fp ) ;
fread( &customer, sizeof( struct tag ), 1, fp ) ;

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.

Random Access I/O

The fseek() function is used in C to perform random access I/O and has the following prototype.

int fseek ( FILE *fp, long num_bytes, int origin ) ;

where origin specifies one of the following positions as the origin in the operation

SEEK_SET --- beginning of file


SEEK_CUR --- current position
SEEK_END --- EOF

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

fseek ( fp, ( 49 * sizeof( int ) ), SEEK_SET ) ;


fscanf( fp, "%d", &i ) ;

from anywhere in the program.

8.2 Low -- Level I/O

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 144


Low level I/O makes use of a file handle or descriptor, which is just a non-negative integer, to
uniquely identify a file instead of using a pointer to the FILE structure as in the case of stream I/O.

As in the case of stream I/O a number of standard files are opened automatically :-

standard input --- 0


standard output --- 1
standard error --- 2

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

open() opens a disk file


close() closes a disk file
read() reads a buffer of data from
disk
write() writes a buffer of data to
disk

The open function has the following prototype and returns -1 if the open operation fails.

int open ( char *filename, int oflag [, int pmode] ) ;

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.

O_APPEND appends to end of file


O_BINARY binary mode
O_CREAT creates a new file if it doesn't
exist
O_RDONLY read only access
O_RDWR read write access
O_TEXT text mode
O_TRUNC truncates file to zero length
O_WRONLY write only access

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 145


This will actually set the read / write access permission of the file at the operating system level
permanently unlike oflag which specifies read / write access just while your program uses the file.

The close() function has the following prototype

int close ( int handle ) ;

and closes the file associated with the specific handle.

The read() and write() functions have the following prototypes

int read( int handle, void *buffer, unsigned int count ) ;


int write( int handle, void *buffer, unsigned int count ) ;

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 ;

handle=open(" test.dat", O_BINARY|O_RDONLY, S_IREAD | S_IWRITE );


if ( handle == -1 ) return ;
if ( read( handle, buff, 1000 ) == 1000 )
puts( "Read successful");
else
{
puts( Read failed" ) ;
exit( 1 );
}

close( handle ) ;

handle = open("test.bak",
O_BINARY|O_CREAT|O_WRONLY| O_TRUNC,
S_IREAD | S_IWRITE ) ;

if ( write( handle, buff, 1000 ) == 1000 )


puts( "Write successful") ;
else
{

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 146


puts( "Write Failed") ;
exit( 1 ) ;
}

close( handle ) ;
}

Low level file I/O also provides a seek function lseek with the following prototype.

long _lseek( int handle, long offset, int origin );

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

For Example : Program to determine the size in bytes of a file.

#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <sys\stat.h>

void main()
{
int handle ;
long length ;
char name[80] ;

printf( “Enter file name : ” ) ;


gets( name ) ;
handle=open( name,O_BINARY| O_RDONLY, S_IREAD | S_IWRITE );

lseek( handle, 0L, SEEK_SET ) ;


length = lseek( handle, 0L, SEEK_END ) ;

close( handle ) ;

printf( “The length of %s is %ld bytes \n”, name, length ) ;


}
8.3 Exercises

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 147


performance in practical programming rather than calculating values on the spot. Using the standard
library random number generator to generate the angles compare the time it takes to ‘calculate’ Sin(x)
for 100 values of x using the look-up table and calculating them straight. You might find the standard
library time functions useful to compare times accurately.

3. Programming Assignment : Simple DataBase.

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.

typedef struct details {


int rec_id ;
char name[20] ;
char address[80] ;
long UCCid ;
} DETAILS ;

typedef struct list {


DETAILS **data_items ;
int numrecords ;
int selrecord ;
} LIST ;

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 148


Your program should set up a data structure of the type described above and allow the user to perform
the following tasks.

1. Add a record to the database.


2. Search for a record by field in the database.
3. Order the database by field.
4. Retrieve a record from the database.
5. Extract a record from the database, deleting it completely.
6. Save the database appropriately to a file.
7. Load an existing database from a file.

Your program should contain the following functions / features.

 void initlist( LIST *list ) ;


This function should set <selrecord> = <numrecords> = 0 and <data_items> = NULL.

 void add( LIST *list, DETAILS *new );


This function should add the record pointed to by <new> onto the end of the list pointed to by <list>.
This means that <selrecord> and <numrecords> will have to be modified appropriately and the pointer
<list->data_items> must be resized to hold the address of one extra record ( using realloc( ) for
example ), and memory must be allocated for the actual record i.e. for *( list-> data_items
+ list->numrecords - 1 ).

 DETAILS *probe( LIST *list, int i ) ;


This function returns a pointer to the current record and automatically moves you onto the next record.
If the current selection is 0, i.e. no record exists in the list, the function should return NULL. If the
current selection is otherwise invalid <selrecord> should be reset to the first record and continue as
normal. If <i> is equal to zero the list is to be reset and continue as normal, otherwise ignore <i>.

 void extract( LIST *list );


This function removes the current selection completely from the list. It removes nothing if the current
record is invalid.

 void swap( LIST *list, int i, int j ) ;


Swaps records i and j in the list. Note you should only swap the actual addresses of the individual
records.

 void orderlist( LIST *list, int field ) ;


This function should ideally order the complete list in terms of the field given, e.g. in terms of name,
UCCid, etc. However it will suffice to do this in terms of name only say.

 DETAILS *search( LIST *list, char *item, int field ) ;


Search the list from the current position on, for the next occurrence of the searchitem, <item>, in a
particular field of the list ( with the same proviso as above ). The function returns the null pointer if the
item is not found, or a pointer to the particular record if it is found. The record becomes the current
selection.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 149


Assignments: NPTEL Question and Answer

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

if((a==b) || (b==c) || (a==c)){


printf("0\n");
}else{
printf("1\n");
}

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 150


001
002
is an upper triangular matrix. (The diagonal itself, and the entries above and below the
diagonals can be zeroes or non-zero integers.) A matrix is lower triangular if every entry above
the diagonal is 0. For example,
200
310
422
is a lower triangular matrix.

A matrix is triangular if it is either upper triangular or lower triangular or both.

You may not use arrays for this program.

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++;
}

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 151


for(;counter<n+1;)
{
scanf("%d",&z);
counter++;
if(z==0);
else
q=1;
}

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 152


Q4: Write a C function to find the kth occurrence of an even integer in a sequence of non-
negative integers, and then call your function from main. Your function should be according to
the following declaration: int find_even(int k);

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

Solution: #include <stdio.h>

void find_even ( int k )


{
int even_count=0;
int curr;

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 153


return ;
}
int main()
{
int k;

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

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 154


int read_array(int arr[])
{
int i, n;
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);

return n;
}

int present(int arr[], int n, int elt) {


int i;
for (i = 0; i < n; i++) {
if (arr[i] == elt) {
return 1;
}
}
return 0;
}

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 155


Output
The output should be the number of distinct elements in the sequence.

Sample Input
4
1231

Sample Output
3
Solution: #include <stdio.h>

#define SIZE 1000

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;

/* see if arr[i] occurs previously in the array */


for(j=i-1;j>=0;j--){
if(arr[j] == arr[i]){
found=1;
break;
}
}
if ( found == 0 ){ /* arr[i] is a new element */
count = count + 1;
}
}

printf("%d\n",count);
return 0;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 156


}

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;

void print(student *s,int n){


int i;
for(i=0;i<n;i++){
printf("%s\t",s[i].name);
printf("%d\t",s[i].phy);
printf("%d\t",s[i].che);
printf("%d\n",s[i].math);
}
}

int comparator(const void *p, const void *q)


{
float l = ((student *)p)->phy;
float r = ((student *)q)->phy;

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 157


if((l-r)!=0) return (l-r);
else{
l = ((student *)p)->che;
r = ((student *)q)->che;
if((l-r)!=0) return(l-r);
else{
l = ((student *)p)->math;
r = ((student *)q)->math;
return (l-r);
} }
}

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.

While printing, the entries of the list must be separated by a single


space.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 158


Sample Input
------------
3 4 5 6 -1
1

Sample Output
-------------
6

Solution: #include <stdio.h>


#include <stdlib.h>

struct node {
int data;
struct node *next;
};
int list_length;

struct node* create_node ( int n )


{
struct node *new_node;
new_node = (struct node *) malloc ( sizeof(struct node) );
new_node->data = n;
new_node->next = NULL;
return new_node;
}
struct node* create_list ( struct node *head )
{
int number;
struct node *current_node, *new_node;
scanf("%d",&number);
if(number != -1){
head = create_node ( number );
current_node = head;
list_length++;
scanf ( "%d", &number );
while ( number != -1 ){
new_node = create_node ( number );
current_node->next = new_node;
list_length++;
current_node = new_node; /* advance to next node */
scanf ( "%d", &number );
}
}

return head;
}
/* Delete the first num nodes from the list */
struct node *delete_first ( int num, struct node *head )

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 159


{
int i=1;
struct node *current_node = head;
struct node *next_node;

while ( i <= num ) {


next_node = current_node->next;
free(current_node);
current_node = next_node;
i++;
}
head = current_node;
return head;
}
void print_list ( struct node *head )
{
struct node * current_node;
if ( head == NULL ){
return;
}
current_node = head;
while ( current_node != NULL ) {
printf ( "%d ", current_node->data );
current_node = current_node->next;
}
printf("\n");
return;
}

int main()
{

int number;
int pruned_length=0;
struct node *head;

head = create_list ( head );


scanf("%d", &pruned_length);

if(pruned_length > list_length){


printf ( "-1\n" );
return 0;
}else{
head=delete_first(list_length-pruned_length, head);
print_list(head);
}
return 0;
}

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 160


Gate Questions

Answer 31

Answer 26

Answer B

Web page references


https://onlinecourses-archive.nptel.ac.in/noc18_cs33/progassignment?name=115
https://www.programiz.com/c-programming
https://www.cprogramming.com/

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 161


https://www.tutorialspoint.com/cprogramming/
http://phy.ntnu.edu.tw/~cchen/pdf/ctutor.pdf
http://nptel.ac.in/courses/106105085/2
http://nptel.ac.in/courses/106105085/9
http://students.iitk.ac.in/programmingclub/course/

Specific Core Company Information

The languages like Python, PHP etc. are all developed in C.


1. Google : Android OS Chrome Server Other products
2. Facebook : Apache Hive, Thrift, HHVM etc.
3. Microsoft : Windows, Visual Studio, Microsoft Server etc
4. VMware: Entire ...

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 162


CSE DEPARTMENT PROGRAM OUTCOMES

COMPUTER SCIENCE AND ENGINEERING GRADUATES ARE ABLE TO:

PO1:Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

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.

PO3:Design/development of solutions: Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, and the cultural, societal, and environmental considerations.

PO4:Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

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.

PO7:Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

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.

PO10:Communication:Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.

PO11:Project management and finance: Demonstrate knowledge and understanding of the


engineering and management principles and apply these to one’s own work, as a member and leader in
a team, to manage projects and in multidisciplinary environments.

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.

KLNCE/B.E./CSE/II/CS8251 Programming in C/2019-2020 163

You might also like