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

sem 1 cs

Uploaded by

Nandha Kishore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

sem 1 cs

Uploaded by

Nandha Kishore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

OSMANIA UNIVERSITY

FACULTY OF SCIENCE
B.Sc. (Computer Science)
CBCS Pattern with Effect from the Academic Year 2019-2020
Structure of Curriculum
Course Title Hours/Week Credits
Theory Practical
Semester –I
Programming in C 4 3 4+1 = 5
Semester –II
Programming in C++ 4 3 4+1 = 5
Semester –III
Data Structures using C++ 4 3 4+1 = 5
Semester –IV
Data Base Management 4 3 4+1 = 5
Systems (DBMS)
Semester –V
Programming in Java 4 3 4+1 = 5
Semester –VI
Web Technologies 4 3 4+1 = 5

AECC
Hours/Week Credits
Theory
Fundamentals of Computers 2 2
SEC
Semester –III
Communication Skills(or) 2 2
Professional Skills (Sec –I)
Python –I (Sec –II) 2 2
Semester –IV
Leadership & Management 2 2
Skill (or) (Sec –III)
Universal Human Values
Python –II (Sec –IV) 2 2
Generic Elective (GE)

Information Technologies 4 4
Project/Optional
Semester –VI
PHP with MY SQL Theory Practical 3+1=4
3 3
OSMANIA UNIVERSITY
FACULTY OF SCIENCE
B.Sc. (Computer Science)
SEMESTER – I
Programming in C
Theory 4 Hours/Week 4 Credit Internal marks = 20
Practical 3 Hours/Week 1 Credit External Marks = 80
Unit – I
Computer Fundamentals: Introduction of Computers, Classification of Computers, Anatomy
of a Computer, Memory Hierarchy, Introduction to OS, Operational Overview of a CPU.
Program Fundamentals: Generation and Classification of Programming Languages,
Compiling, Interpreting, Loading, Linking of a Program, Developing Program, Software
Development.
Algorithms: Definitions, Different Ways of Stating Algorithms (Step-form, Pseudo-code,
Flowchart), Strategy for Designing Algorithms, Structured Programming Concept.
Basics of C: Overview of C, Developing Programs in C, Parts of Simple C Program, Structure
of a C Program, Comments, Program Statements, C Tokens, Keywords, Identifiers, Data
Types, Variables, Constants, Operators and Expressions, Expression Evaluation–precedence
and associativity, Type Conversions.

Unit – II
Input-Output: Non-formatted and Formatted Input and Output Functions, Escape Sequences,
Control Statements: Selection Statements – if, if-else, nested if, nested if-else, comma operator,
conditional operator, switch; Iterative Statements–while, for, do-while; Special Control
Statement–goto, break, continue, return, exit.
Arrays and Strings: One-dimensional Arrays, Character Arrays, Functions from ctype.h,
string.h, Multidimensional Arrays.

Unit – III
Functions: Concept of Function, Using Functions, Call-by-Value Vs Call-by-reference,
Passing Arrays to Functions, Score of Variables, Storage Classes, Inline Functions, and
Recursion.
Pointers: Introduction, Address of Operator (&), Pointer, Uses of Pointers, Arrays and Pointers,
Pointers and Strings, Pointers to Pointers, Array of Pointers, Pointer to Array, Dynamic
Memory Allocation.

Unit – IV
User-defined Data Types: Declaring a Structure (Union) and its members, Initialization
Structure (Union), Accessing members of a Structure (Union), Array of Structures (Union),
Structures verses Unions, Enumeration Types.
Files: Introduction, Using Files in C, Working with Text Files, Working with Binary Files,
Files of Records, Random Access to Files of Records, Other File Management Functions.

Textbook: Pradip Dey, Manas Ghosh, Computer Fundamentals and Programming in C (2e)
References:
1. Ivor Horton, Beginning C
2. Ashok Kamthane, Programming in C
3. Herbert Schildt, The Complete Reference C
4. Paul Deitel, Harvey Deitel, C How to Program
5. Byron S. Gottfried, Theory and Problems of Programming with C
6. Brian W. Kernighan, Dennis M. Ritchie, The C Programming Language
7. B. A. Forouzan, R. F. Gilberg, A Structured Programming Approach Using C
OSMANIA UNIVERSITY
FACULTY OF SCIENCE
B.Sc. (Computer Science)
SEMESTER – I
Programming in C Lab
Practical 3 Hours/Week 1 Credit Marks: 25

Note:
• Programs of all the Concepts from Text Book including exercises must be practice and
execute.
• Faculty must take care about UG Standard Programs.
• In the external lab examination student has to execute two programs with compilation
and deployment steps are necessary. Write the Pseudo Code and draw Flow Chart for
the programs.
• Recommended to use Open Source Software: GCC on Linux; DevC++ (or) CodeBlocks
on Windows10.
• External Vice-Voce is compulsory.

1. Write a program to find the largest two (three) numbers using if and conditional
operator.
2. Write a program to print the reverse of a given number.
3. Write a program to print the prime number from 2 to n where n is given by user.
4. Write a program to find the roots of a quadratic equation using switch statement.
5. Write a program to print a triangle of stars as follows (take number of lines from user):
*
* * *
* * * * *
* * * * * **
6. Write a program to find largest and smallest elements in a given list of numbers.
7. Write a program to find the product of two matrices.
8. Write a program to find the GCD of two numbers using iteration and recursion.
9. Write a program to illustrate the use of storage classes.
10. Write a program to demonstrate the call by value and the call by reference concepts.
11. Write a program that prints a table indicating the number of occurrences of each
alphabet in the text entered as command line arguments.
12. Write a program to illustrate use of data type enum.
13. Write a program to demonstrate use of string functions string.h header file.
14. Write a program that opens a file and counts the number of characters in a file.
15. Write a program to create a structure Student containing fields for Roll No., Name,
Class, Year and Total Marks. Create 10 students and store them in a file.
16. Write a program that opens an existing text file and copies it to a new text file with all
lowercase letters changed to capital letters and all other characters unchanged.
UNIT-I
Chapter-1
Computer Fundamentals

⚫ Computer: A computer is an electronic device, operating under the control of instructions


stored in its own memory that can accept data (input), process the data according to specified
rules, produce information (output), and store the information for future use.

⚫ CHARACTERISTICS OF COMPUTERS
The characteristics of computers have made them so powerful and universally
useful .They are:

1.Speed
• Computer is a very fast device.
• It is capable of performing calculation of very large amount of data.
• The computer has units of speed in microsecond, nanosecond, and even the picosecond.
• It can perform millions of calculations in a few seconds as compared to man who will
spend many months to perform the same task.
2.Accuracy
• In addition to being very fast, computers are very accurate.
• The calculations are 100% error free.
• Computers perform all jobs with 100% accuracy provided that the input is correct.
3. Storage Capability
• Memory is a very important characteristic of computers.
• A computer has much more storage capacity than human beings.
• It can store large amount of data.
• It can store any type of data such as images, videos, text, audio, etc.
4. Diligence
• Unlike human beings, a computer is free from monotony, tiredness, and lack of
concentration.
• It can work continuously without any error and boredom.
• It can perform repeated tasks with the same speed and accuracy.
5. Versatility
• A computer is a very versatile machine.
• A computer is very flexible in performing the jobs to be done.
• This machine can be used to solve the problems related to various fields.
• At one instance, it may be solving a complex scientific problem and the very next
moment it may be playing a card game.
6. Reliability
• A computer is a reliable machine.
• Modern electronic components have long lives.
• Computers are designed to make maintenance easy.
7.Automation
• Computer is an automatic machine.
• Automation is the ability to perform a given task automatically. Once the computer
receives a program i.e., the program is stored in the computer memory, then the
program and instruction can control the program execution without human interaction.

P.Sowmya Sree Unit-I Page 1


8. Reduction in Paper Work and Cost
• The use of computers for data processing in an organization leads to reduction in paper
work and results in speeding up the process.
• As data in electronic files can be retrieved as and when required, the problem of
maintenance of large number of paper files gets reduced.
• Though the initial investment for installing a computer is high, it substantially reduces
the cost of each of its transaction.

⚫ Classification of Computers
Most designs of computers today are based on concepts developed by John von
Neumann and are referred to as the von Neumann architecture. Computers can be classified in
variety of ways on the basis of various parameters such as usage, cost, size, processing power,
and so on. The classification of computers is presented below based on their power and their
use.

 Based on Type:

 Analog Computer
An analog computer (spelt analogue in British English) is a form of computer that
uses continuous physical phenomena such as electrical, mechanical, or hydraulic quantities to
model the problem being solved.

 Digital Computer
A computer that performs calculations and logical operations with quantities
represented as digits, usually in the binary number system

 Hybrid Computer
A combination of computers those are capable of inputting and outputting in both
digital and analog signals. A hybrid computer system setup offers a cost effective method of
performing complex simulations.

P.Sowmya Sree Unit-I Page 2


Based on Size:

 Supercomputer:
Supercomputer is the most expensive and fastest type of computer that performs at or
near the currently highest operational rate for computers. A Cray supercomputer is a typical
example. These are employed for specialized applications that require immense amounts of
mathematical calculations such as weather forecasting, nuclear energy research, and petroleum
exploration etc.

 Mainframe:
A mainframe computer supports a vast number of users to work simultaneously and
remotely. Apart from providing multi-user facility, it can process large amounts of data at very
high speeds and support many input, output and auxiliary storage devices. These computers are
very large in size, and expensive. The main difference between a supercomputer and a
mainframe is that a supercomputer can execute a single program faster than a mainframe,
whereas a mainframe uses its power to execute many programs concurrently. The IBM 370 and
IBM 3090 are examples of mainframe computers.

Minicomputers
A minicomputer is powerful enough to be used by multiple users (between 10 to
100) but is smaller in size and memory capacity and cheaper than mainframes. Two classic
examples were the Digital Equipment Corporation VAX and the IBM AS/400.

Microcomputers:
The microcomputer has been intended to meet the personal computing needs of an
individual. It typically consists of a microprocessor chip, a memory system, interface units and
various I/O ports, typically resided in a motherboard. There are many types of microcomputers
available.
Desktop computer:
A microcomputer sufficient to fit on a desk.
Laptop computer
A portable microcomputer with an integrated screen and keyboard.
Palmtop computer/Digital diary/Notebook/PDAs
A handsized microcomputer having no keyboard. The screen serves both as an
input and output device.

Based on Purpose

1. General Purpose
General computers can do various everyday tasks such as writing a word
processing letter, Document preparation, recording, financial analysis, Printing documents,
creating databases, and calculations with accuracy and consistency.
The size, storage capacity, and cost of such computers are mainly less. The ability of these
computers is limited in performing specialized tasks. Still, it has versatility and useful for
serving people’s basic needs at home or in the workplace in the environment.

Examples:
The desktops, laptops, smartphones, and tablets are used on daily basis for general
purposes.

P.Sowmya Sree Unit-I Page 3


2. Special Purpose
These computers are designed to perform a particular or specialized task. The size,
storage capacity, and cost of such computers mainly depend on the nature and size of the work.
The function of these computers is consistent with any particular task.
The special computer needs specific processors and input and devices to conduct work
efficiently.

⚫ ANATOMY OF A COMPUTER:
A computer can accept input, process or store data, and produce output
according to a set of instructions which are fed into it. A computer system can be divided into
two components which are responsible for providing the mechanisms to input and output data,
to manipulate and process data, and to electronically control the various input, output, and their
storage. They are known as hardware and software.

 Input unit:
Data and instructions are fed into computer system for any calculation process.This
process is performed by the input that leads the external environment with computer system,the
data and instruction inter input units in the form that depends upon the media used. All input
devices provide data and instructions to the computer in binary form input inter faces converts
data instruction in computer acceptable form.

INPUT DEVICES:

1.Keyboard: -
➢ It is a input device consisting of a set of type writer like keys that enable you to enter
data into a computer.
➢ The keys on the computer keyboard are often classified as follows:
i) Alpha numeric keys numbers and characters.
ii) Puntuations keys (,,.,”, “,?,…..etc.)
iii) Special keys Function keys,control keys,Caps lock,Arrow keys.

➢ There are different personal computer keyboard are available.The original pc keyboard
with 84 keys,enhanced keyboard with 101 keys.
➢ IBM keyboards contain the following keys:-
➢ Page up,page down,home,end,insert pause,num lock,break,print screen.

2.Mouse:-
➢ Mouse is an input device that controls the movement of the cursor on a display screen.
➢ It is used to drive Microsoft windows.As you move the mouse,the pointer on the
display screen moves in the same direction.

P.Sowmya Sree Unit-I Page 4


➢ It is an input device that can be connected to personal computer.
➢ By focusing the pointer on a particular file or icon and clicking the mouse ,the file or
icon will be opened like a window.

3.Joystick:-
➢ This I one of the popular input device which is used to play video games.
➢ As the joystick is moved in the socket,the movements are converted into binary
instructions with help of electrical contacts at the base of joystick.

4.Track ball:-
➢ This is similar to joystick,the difference is that drag ball uses hardsphere instead of
handle for cursor controlThis hard ball can be rotated by hand in any direction.The
sphere speed and direction of the rotation is translated into digital signals which control
the cursor.

5.Scanner:-
➢ Scanner is an input device that can read text or pictures printed on paper and translates
the information into a term that the computer can use.
➢ The keyboard can only input text through keys provided in it .if the user wants to input
a picture, the keyboard cannot do that .
➢ A scanner is an optical device that can input any graphical matter and display it back.
➢ The common optical scanner device are Magnetic Ink Character
Recognition(MICR),Optical Mark Reader(OMR),and Magnetic Card Reader
(MCR).
Magnetic Ink Character Recognition(MICR):-
• This is widely used by banks to process large volumes of cheques and drafts
.cheques are kept inside the MICR.
• As they enter the reading unit ,the Cheques pass through the magnetic field ,which
causes the read head to recognize the character on the cheques.
Optical Mark Reader(OMR):-
This technique is used for evaluation of objective type answers .
• The answering will be done by darkening a square or circular space by pencil .
• The OMR is used to read and compares them with the answers in the memory for
evaluation.
Magnetic Card Reader (MCR):-
• It registers the data from the magnetic strip on a plastic card.When the employees go to
the office,they use these cards to punch their timings.

5.Touch screen:-
When the finger touches on any object of the screen,that object registers the input.

Storage Unit:
Data and Instructions that are entered into the computer system through input
units have to be stored some where in the computer,similarly result after processing are also
needed to be stored in the computer for this purpose there is a storage unit of the computer
system called primary memory or main memory.Thus provides space for data,instructions and
results every data,instruction and result is stored in the computer before and after the processing

Arithmetic and Logical unit:


The calculations and comparisons are performed according to the instructions on
to the data in ALU of the computer system that data and instructions are taken from main
memory for arithmetic and logical operations. Intermediate and final results are again stored in
the main memory of the processing.

P.Sowmya Sree Unit-I Page 5


The ALU performs four basic arithmetic operations like add. subtract, divide and logical
operations such as (>,<,=).

Control Unit:
The control of all the operations like when to input data, apply instructions on
data, output the result, reading and writing from the memory is handled by the control unit
which works as central nerves system.
The control unit manages and coordinates the entire computer system.

Central Processing Unit:


The control unit and the arithmetic logic unit are jointly known as CPU. The
CPU is the brain of the computer system.
The hardware devices attached to the computer devices are usually reference to us peripherals
this equipment include input, output and mass storage devices.
An input device is computer hardware that transmits data to the computer, these are like
keyboard, joystick, mouse, light pen, touch pads ….etc.
An output device is computer hardware that communicates the results of computer
operations.These are monitor,printer,plotter,speakers…….etc.

Output unit:
Output unit supplies information and results of process to outside world,That links
the computer with external environment.Computer stores,data and instructions in binary
form,Similarly the output results are also stored in binary form.Hence before supplying the
result to the outside world,this must be converted into human acceptable form.This job is done
by output inter faces.

 OUTPUT DEVICES
It displays the output from the computer processing for the user. The popular output
devices are:

1.MONITOR:
The monitor is a cathode ray tube display, which resembles a television. This can
generate electronic display of text or graphics. Images on the screen of the monitor are
displayed as a matrix of pixels. Monitor is known as the Visual Display Unit (VDU). It has a
screen which displays the output. The output displayed by the monitor is known as Soft Copy.
The monitor also displays the software which is loaded in the computer.

2 .PRINTER:
The printer is used to give output in the printed form. The printed output is called
Hard Copy. Printers produce the printed output of the results, instructions and data. These are
characterized by their speed and letter quality. Some printers print each character at a time and
some print each line at a time and so on. Some examples of printers include Dot Matrix
printers, Daisy Wheel printers, Line printers, Thermal printers and Laser printers. Printers are
classified as Impact printers and Non-Impact printers.
Impact printers use some electro-mechanical mechanism that causes head of the printer to
strike against a ribbon and paper to print the text. In a Non-Impact printer the mechanism will
not make any contact with the printer in order to print.

3.SPEAKERS:
Speakers are used to output sounds, voice, and music from the computer system.
The quality of music played on the computer is digital sound.

4.PLOTTERS:

P.Sowmya Sree Unit-I Page 6


Plotters are used in places where images like graphs, charts, maps, etc. are required
to be printed. Plotters have a pen fitted on a movable arm. They are mainly used by engineers,
architects and seismologists. Some plotters have the ability to sketch the diagram on plastic or
metal plates. They are basically two types of plotter: Flat bed plotters and Drum plotters.

⚫ Memory hierarchy:

Memory:
A memory is just like a human brain. It is used to store data and instructions.
Computer memory is the storage space in the computer, where data is to be processed and
instructions required for processing are stored. The memory is divided into large number of
small parts called cells. Each location or cell has a unique address, which varies from zero to
memory size minus one.

Memory is primarily of two types:


• Primary Memory/Main Memory
• Secondary Memory

Primary Memory (Main Memory):


Primary memory holds only those data and instructions on which the computer
is currently working. It has a limited capacity. It is generally made up of semiconductor device.
It is divided into two subcategories RAM and ROM.

RAM:
Random Access Memory is where the programs are loaded. RAM is known as
temporary or volatile memory, i.e., the data stored in RAM gets erased when switch off the
computer. RAM can be accessed directly for reading or writing data in the same time
irrespective of its location.

ROM:
Read Only Memory contains a set of start-up instructions for the computer system
like checking the input and output devices, loading the Operating System into the RAM etc. It
is a permanent memory. The instructions stored here cannot be over written. These instructions
have been stored at the time of manufacture of the computer.

SECONDARY MEMORY:
It is the memory of the computer of the computer which is used for long term storage
of data. Secondary storage devices are Magnetic disk, Floppies, Hard disk, Compact disk, Pen
drive etc.

P.Sowmya Sree Unit-I Page 7


1) Magnetic Disk: These are made of rigid metals or synthetic plastic material. The disk
platter is coated on both the surfaces with magnetic material and both the surfaces can be
used for storage. The magnetic disk provides direct access and is popular for both small
and large computer systems. The magnetic disk comes in two forms: floppy disk and hard
disks.

2) Floppy: It is a small plastic disk, coated with a magnetic material and enclosed in a plastic
casing. These are introduced in the early 1970’s and used on microcomputer. They are
reliable and portable. They are available in sizes like 51/4 inches and 31/2 inches. The 3.5
inch floppy can hold 1.44MB to 2.88 MB of storage and 5.2 inch floppy can hold 360 KB
to 1.2 MB of storage.

3) Hard Disk: It is a metal platter with magnetic coating on both sides. Several such disks are
stacked one on the other, without touching each other, into a disk pack for large storage.
The disk pack, housed in metal container with a read/write head unit, is fixed inside a
computer permanently. A disk pack is a collection of disks stacked vertically one on the
other and it is mounted on a disk drive. The disk drive has a head assembly with a
read/write arm for each pair of recording surfaces. Each disk has 2 surfaces for storage.

4) Optical Disk: It is a storage device which uses a laser beam to read and write data. The
Compact Disk and Digital Video Disk are types of optical disks.
i) Compact Disk: The compact disk or CD is a circular plastic disk encased within a
highly reflective metallic material. A CD can hold around 700MB of data. CDs are very useful
for storing images, music and video files. They are used to store and transfer application
software, computer games, utility programs, etc. CDs are 3 types. They are CD-ROM, CD-R,
CD-RW.
ii) Digital Video Disk: It is similar to CD but its storage capacity is 7 times that of CD.
A DVD has 4.7 GB of storage capacity.

5) USB/Pen Drive: This is a convenient way of transferring data. It is also known as USB
drive (Universal Service Bus). The storage capacity of a pen drive can be 1 GB or more. It
is a solid state device which means that it has no movable parts. It can be plugged into any
USB port of computer.

⚫Operating System

An Operating System (OS) is an interface between a computer user and computer


hardware and controls the execution of all kinds of programs. An operating system is a
software which performs all the basic tasks like file management, memory management,
process management, handling input and output, and controlling peripheral devices such as disk
drives and printers.
Some popular Operating Systems include Linux, Windows, OS X, VMS, OS/400, AIX, z/OS,
etc.

Functions of Operating system:


Following are the some of important functions of an operating System.
1. Process management:
The process abstraction is a fundamental mechanism implemented by the
operating system for management of the execution of programs. A process is basically a
program in execution. The operating system decides which process gets to run, for how long
and perhaps at what priority or level of importance.

P.Sowmya Sree Unit-I Page 8


2. Memory Management:
Operating System also Manages the Memory of the Computer System
means Provide the Memory to the Process and Also Deallocate the Memory from the Process.
And also defines that if a Process gets completed then this will deallocate the Memory from the
Processes.

3. Device Management
An Operating System manages device communication via their respective drivers. It does the
following activities for device management −
• Keeps tracks of all devices. Program responsible for this task is known as the I/O
controller.
• Decides which process gets the device when and for how much time.
• Allocates the device in the efficient way.
• De-allocates devices.

4. Security − By means of password and similar other techniques, it prevents unauthorized


access to programs and data

5. Coordination between other softwares and users − Coordination and assignment of


compilers, interpreters, assemblers and other software to the various users of the computer
systems.

6. Control over system performance − Recording delays between request for a service and
response from the system.

7. Error detecting aids − Production of dumps, traces, error messages, and other debugging
and error detecting aids.

Operational overview of CPU:

Any processing executed by central processing unit is directed by the instruction.


The processing required for a single instruction is called an instruction cycle. The four steps
which the CPU carries out for each machine language instruction are fetch, decode, execute,
and store
The steps involved in the instruction cycle while executing a
program are described below. The Program Counter (PC) is the register that keeps track of
what instruction has to be executed next. At the first step, the instruction is fetched from main
memory and loaded into Instruction Register (IR), whose address is specified by PC register.
Immediately the PC is incremented so that it points to the next instruction in the program. Once
in IR, the instruction is decoded to determine the actions needed for its execution. The control
unit then issues the sequence of control signals that enables execution of the instruction. Data
needed to be processed by the instructions are either fetched from a register from RAM through
an address register. The result of the instruction is stored (written) to either a register or a
memory location. The next instruction of a program will follow the same steps. This will
continue until there is no more instruction in the program or the computer is turned off, some
sort of unrecoverable error occurs.

P.Sowmya Sree Unit-I Page 9


Chapter-2
Program Fundamentals

⚫PROGRAMMING LANGUAGES:
A programming language is a formal language that specifies a set
of instructions that can be used to produce various kinds of output. Programming languages
generally consist of instructions for a computer. Programming languages can be used to
create programs that implement specific algorithms.

Generations of programming language


Programming languages have been developed over the year in a phased manner.
Each phase of developed has made the programming language more user-friendly, easier to use
and more powerful. Each phase of improved made in the development of the programming
languages can be referred to as a generation. The programming language in terms of their
performance reliability and robustness can be grouped into five different generations,

1. First generation languages (1GL)


2. Second generation languages (2GL)
3. Third generation languages (3GL)
4. Fourth generation languages (4GL)
5. Fifth generation languages (5GL)

1. First Generation Language (Machine language)


The first generation programming language is also called low-level
programming language because they were used to program the computer system at a very low
level of abstraction. i.e. at the machine level. The machine language also referred to as the
native language of the computer system is the first generation programming language. In the
machine language, a programmer only deals with a binary number.

Advantages of first generation language


• They are translation free and can be directly executed by the computers.
• The programs written in these languages are executed very speedily and efficiently by
the CPU of the computer system.
• The programs written in these languages utilize the memory in an efficient manner
because it is possible to keep track of each bit of data.

2. Second Generation language (Assembly Language)


The second generation programming language also belongs to the category of low-
level- programming language. The second generation language comprises assembly languages
that use the concept of mnemonics for the writing program. In the assembly language, symbolic
names are used to represent the opcode and the operand part of the instruction.

Advantages of second generation language


• It is easy to develop understand and modify the program developed in these languages
are compared to those developed in the first generation programming language.
• The programs written in these languages are less prone to errors and therefore can be
maintained with a great case.
3. Third Generation languages (High-Level Languages)
The third generation programming languages were designed to overcome
the various limitations of the first and second generation programming languages. The
languages of the third and later generation are considered as a high-level language because they

P.Sowmya Sree Unit-I Page 10


enable the programmer to concentrate only on the logic of the programs without considering the
internal architecture of the computer system.

Advantages of third generation programming language


• It is easy to develop, learn and understand the program.
• As the program written in these languages are less prone to errors they are easy to
maintain.
• The program written in these languages can be developed in very less time as compared
to the first and second generation language.

Examples: FORTRAN, ALGOL, COBOL, C++, C

4. Fourth generation language (Very High-level Languages)


The languages of this generation were considered as very high-level
programming languages required a lot of time and effort that affected the productivity of a
programmer. The fourth generation programming languages were designed and developed to
reduce the time, cost and effort needed to develop different types of software applications.

Advantages of fourth generation languages


• These programming languages allow the efficient use of data by implementing the
various database.
• They require less time, cost and effort to develop different types of software
applications.
• The program developed in these languages are highly portable as compared to the
programs developed in the languages of other generation.

Examples: SOL, CSS, coldfusion

5. Fifth generation language (Artificial Intelligence Language)

The programming languages of this generation mainly focus on constraint


programming. The major fields in which the fifth generation programming language are
employed are Artificial Intelligence and Artificial Neural Networks

Advantages of fifth generation languages


• These languages can be used to query the database in a fast and efficient manner.
• In this generation of language, the user can communicate with the computer system in a
simple and an easy manner.

Examples: mercury, prolog, OPS5

⚫Translators:
A program written in high-level language is called as source code. To convert the
source code into machine code, translators are needed.
A translator takes a program written in source language as input and converts it into a program
in target language as output.
It also detects and reports the error during translation.

Different type of translators


The different types of translator are as follows:

P.Sowmya Sree Unit-I Page 11


Compiler
Compiler is a translator which is used to convert programs in high-level language to
low-level language. It translates the entire program and also reports the errors in source
program encountered during the translation.

Interpreter

Interpreter is a translator which is used to convert programs in high-level language to low-level


language. Interpreter translates line by line and reports the error once it encountered during the
translation process.
It directly executes the operations specified in the source program when the input is given by
the user.
It gives better error diagnostics than a compiler.

Differences Between Compiler and Interpreter


Complier Interpreter
1.Compiler takes entire program as input 1.Interpreter takes as single instruction as input
2. Intermediate object code generated. 2.No Intermediate object code generated
3.Conditional control statements are executes 3.Conditional control statement are executes
faster slower
4.Memory requirement is low 4. Memory requirement is high.
5. Program need not be complied every time. 5. Everytime higher level program is converted
into lower level program.
6.Errors are displayed after entire program is 6. Errors are displayed for every instruction.
checked
7. Programming languages like 7. Programming languages like PYTHON,
C,C++,COBOL, use compiler. JAVA, use interpreters.

Loader:
Loader is a program which is responsible for performing the loading function i.e. it brings
executable file into a given memory location. The loader carries out four functions.
1. It loads machine as well as data instruction into its specified memory location.
2. It assigns load time storage memory area to the program.
3. It relocates the program so that is can be executed appropriately.
4. It link two separate object programs with each other.
P.Sowmya Sree Unit-I Page 12
Linker:
Linker is a program in a system which helps to link a object modules of program
into a single object file. It performs the process of linking. Linker are also called link editors.
Linking is process of collecting and maintaining piece of code and data into a single file.
Linker also link a particular module into system library. It takes object modules from
assembler as input and forms an executable file as output for loader.
Linking is performed at both compile time, when the source code is translated into machine
code and load time, when the program is loaded into memory by the loader. Linking is
performed at the last step in compiling a program.
Source code -> compiler -> Assembler -> Object code -> Linker -> Executable file ->
Loader
Program Development

When we want to develop a program using any programming language, we


follow a sequence of steps. These steps are called phases in program development. The program
development life cycle is a set of steps or phases that are used to develop a program in any
programming language.
Generally, the program development life cycle contains 6 phases, they are as follows….

1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of
the problem. In this phase we need to understand the problem statement, what is our
requirement, what should be the output of the problem solution. These are defined in this first
phase of the program development life cycle.

2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to
solve the problem. That means we gather the required resources to solve the problem defined in
the problem definition phase. We also determine the bounds of the solution.

3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem
using the specification given in the previous phase. This phase is very important for program
development. That means we write the solution in step by step statements.

P.Sowmya Sree Unit-I Page 13


4. Coding & Documentation
This phase uses a programming language to write or implement the
actual programming instructions for the steps defined in the previous phase. In this phase, we
construct the actual program. That means we write the program to solve the given problem
using programming languages like C, C++, Java, etc.,

5. Testing & Debugging


During this phase, we check whether the code written in the previous step is
solving the specified problem or not. That means we test the program whether it is solving the
problem for various input data values or not. We also test whether it is providing the desired
output or not.

6. Maintenance
During this phase, the program is actively used by the users. If any enhancements
found in this phase, all the phases are to be repeated to make the enhancements. That means in
this phase, the solution (program) is used by the end-user. If the user encounters any problem or
wants any enhancement, then we need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.

Software Development

Software Development Life Cycle (SDLC) aims to produce a high-


quality system that meets or exceeds customer expectations, works effectively and
efficiently in the current and planned information technology infrastructure, and is
inexpensive to maintain and cost-effective to enhance.

1. Planning
In the Planning phase, project leaders evaluate the terms of the project.
This includes calculating labor and material costs, creating a timetable with target
goals, and creating the project’s teams and leadership structure.
Planning can also include feedback from stakeholders. Stakeholders are
anyone who stands to benefit from the application. Try to get feedback from
potential customers, developers, subject matter experts, and sales reps.

2. Define Requirements
Defining requirements is considered part of planning to determine what the
application is supposed to do and its requirements. For example, a social media application
would require the ability to connect with a friend. An inventory program might require a search
feature.

P.Sowmya Sree Unit-I Page 14


Requirements also include defining the resources needed to build the project.
For example, a team might develop software to control a custom manufacturing
machine. The machine is a requirement in the process.

3. Design and Prototyping


In this third phase, the system and software design documents are prepared as
per the requirement specification document. This helps define overall system architecture. It has
two steps:
HLD – High-Level Design – It gives the architecture of the software product to be
developed and is done by architects and senior developers
LLD – Low-Level Design – It is done by senior developers. It describes how each and
every feature in the product should work and how every component should work. Here, only
the design will be there and not the code
The outcome from this phase is High-Level Document and Low-Level Document which works
as an input to the next phase

4.Development:

Once the system design phase is over, the next phase is coding. In this phase,
developers start build the entire system by writing code using the chosen programming
language. In the coding phase, tasks are divided into units or modules and assigned to the
various developers. It is the longest phase of the Software Development Life Cycle process.

In this phase, Developer needs to follow certain predefined coding guidelines. They also need
to use programming tools like compiler, interpreters, debugger to generate and implement the
code.

5. Testing

When the software is ready, it is sent to the testing department where Test team
tests it thoroughly for different defects. They either test the software manually or using
automated testing tools depends on the process defined in STLC (Software Testing Life
Cycle) and ensure that each and every component of the software works fine. Once the QA
makes sure that the software is error-free, it goes to the next stage, which is Implementation.

6. Deployment

Once the software is complete, and it is deployed in the testing environment. The
testing team starts testing the functionality of the entire system. This is done to verify that the
entire application works according to the customer requirement.

During this phase, QA and testing team may find some bugs/defects which they
communicate to developers. The development team fixes the bug and send back to QA for a re-
test. This process continues until the software is bug-free, stable, and working according to the
business needs of that system.’

7. Operations and Maintenance

At this point, the development cycle is almost finished. The application is done
and being used in the field. The Operation and Maintenance phase is still important, though. In
this phase, users discover bugs that weren’t found during testing. These errors need to be
resolved, which can spawn new development cycles.
P.Sowmya Sree Unit-I Page 15
Algorithms
An algorithm is a method of representing step by step procedure for solving a
problem. An algorithm is very useful for finding the right answer to a problem or to a difficult
problem by breaking the problem into simple cases.

Charters tics of an Algorithm


An algorithm must possess the following characteristics,

1. Finiteness: An algorithm should terminate in a finite number of steps.


2. Definiteness: Each step of the algorithm must be precisely.
3. Effectiveness: Each step must be effective, in the sense that, it should be easily
convertible into program statement and can be performed exactly in a finite amount of
time.
4. Generality: The algorithm should be complete in itself, so that it can be used to solve
all problems of a given for any input data.
5. Input/output: Each algorithm must take zero, one or more quantities as input data and
yield one or more output values.

Steps for Algorithm Development


The steps to be followed while developing an algorithm are,
1. Initially understand the problem.
2. Then, identify the expected output for the problem.
3. Identify the necessary input for the problem.
4. Develop a logic that produces the expected output from the selected input.
5. Finally, test the algorithm with various sets of input.

Advantages :-
1. It is the step by step solution to a given problem hence easy to understand.
2. It is very easy to draw a flowchart using Algorithm.
3. It is independent of programming language.
4. It is easy to debug as every step has got its own logical sequence.
5. It has got definite procedure to generate required output

Disadvantages
1. It is time consuming.
2. In large algorithm the flow of program controls becomes difficult to track
3. It is difficult to convert it into flowchart and then into a program

Different Ways of Stating Algorithms (Step-form, Pseudo-code, Flowchart)


1. Stepform:
This form of algorithm is the simplest and consists of a sequence of numbered steps or
points. It is the easiest to learn at first since it is rather like a "to-do" list however once you have
mastered other ways of stating algorithms you are unlikely to continue using this form.
Examples:

Let us write an Algorithm to calculate the addition of two numbers


Step 1 :- Start
Step 2:- Read two number A and B
Step 3:- Add numbers A and B then store C i.e., C=A+B
Step 4:- Display C
Step 5:- End

P.Sowmya Sree Unit-I Page 16


2. Flow Chart:

Flowchart is a diagrammatic representation of sequence of logical steps of a


program. Flowcharts use simple geometric shapes to depict processes and arrows to show
relationships and process/data flow.

Flowchart Symbols

Symbol Symbol Name Purpose

Used at the beginning and end of the algorithm to show


Start/Stop
start and end of the program.

Indicates processes like mathematical operations.


Process

Input/ Output Used for denoting program inputs and outputs.

Stands for decision statements in a program, where


answer is usually Yes or No.
Decision

Shows relationships between different shapes.


Arrow

Connects two or more parts of a flowchart, which are on


the same page.
On-page Connector

Connects two parts of a flowchart which are spread over


different pages.
Off-page Connector

Advantages of Flow Chart:


1. It is a convenient method of communication.
2. It indicates very clearly just what is being done, where as a program has logical
complexities.
3. It is an important tool for planning and designing a new system.
4. It is clearly indicates the role-played at each level.

P.Sowmya Sree Unit-I Page 17


5. It saves the inconveniences in future and serves the purpose of documentation for a
system.
6. It provides an overview of the system and also demonstrates the relationship between
various steps.
7. Facilitates troubleshooting.
8. It promotes logical accuracy.
9. It makes sure that no logical path is left incomplete without any action being taken.
Disadvantages of Flow Chart:
1. Flow chart are waste of time and slow down process of software development.
2. Flowchart are quiet costly to produce and difficult to use and manage.
3. Flowcharts are not meant for man to computer communication.

Draw a flowchart for addition of two numbers.

START

READ
A,B

C=A+B

PRINT
C

STOP

3. Pseudo code:
Pseudo code is a simple way of writing programming code in English. Pseudo
code is not actual programming language. It uses short phrases to write code for programs
before you actually create it in a specific language. Once you known what the program is about
and how it will function, then you can use pseudo code to create statements to achieve the
required results for your program.
It is used in planning an algorithm with sketching out the structure of the program before the
actual coding take a place.

Advantages of Pseudo code:


1. Pseudo code uses English like statements. Therefore, it can be written easily and
quickly.
2. In pseudo code , each step is independent of other steps. Therefore, if any modification
is done in any step, it does not affect the codes of other module i.e. the code has not to
be rewritten if any change occurs in any other step.
3. The format of pseudo code is similar to that of the programs. Both pseudo code and
program consist a set of sequential statements and use defined set of keywords.
Therefore, pseudo code and be converted to a full-fledged program using any
programming language.
4. The learning curve of pseudo code is very smooth. Since, it is written in highly simple
language and thus can be understood by any naïve user also.

P.Sowmya Sree Unit-I Page 18


Example: If students grade is greater than or equal to 60
Print “Passed”
else
Print “failed

Structured Programming

Structured programming frequently employs a top-down design


model, Structured programming is a programming paradigm aimed at improving the clarity,
quality, and development time of a computer program .C is called a structured programming
language because to solve a large problem, C programming language divides the problem into
smaller modules called functions or procedures each of which handles a particular
responsibility. The program which solves the entire problem is a collection of such functions.
One major drawback of C language is that similar functions cannot be grouped inside a module
or class. Also functions cannot be associated to a type or structure. Thus data and functions
cannot be bound together. C++ language overcomes these problems by introducing object
oriented functionality in its programming capabilities.
Advantages
• C structured programming is simple and easy to understand and implement.
• It is well sited for small size implementation. However this is not restricted. A good
design can extend it to large size implementation.
• Programmers do not require to know complex design concepts to start a new program.
Disadvantages
• Data and methods and not be bind together in a module.
• Polymorphism and inheritance are not available.
• Complex design and full object oriented design cannot be implemented.
• Programmers generally prefer object oriented programming language over structured
programming language when implementing a complex gaming applications or front end
business applications.

P.Sowmya Sree Unit-I Page 19


Unit-I
Chapter III
Basics of C

Introduction to C:
C is a procedural programming language. It was initially developed by
Dennis Ritchie in the year 1972 at bell laboratories of AT&T (American Telephone &
Telegraph), located in the U.S.A.It is developed for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.

Development cycle of ‘C’:


Initially, C language was developed to be used in UNIX operating
system. It inherits many features of previous languages such as B and BCPL.

ALGOL 60
(Algorithmic Language developed in the year 1960 by an international committee)

CPL
(Combined Programming Language developed in 1963 by Cambridge University and
University of London)

BCPL
(Basic Combined Programming Language developed by Martin Richards of Cambridge
University in 1967)

B
(Developed by Ken Thompson of Bell Laboratories in 1970)

C
(Developed by Dennis Ritchie of Bell Laboratories in 1972)

Applications/uses of C Programming
C was initially used for system development work, particularly the
programs that make-up the operating system. C was adopted as a system
development language because it produces code that runs nearly as fast as the code
written in assembly language. Some examples of the use of C are -
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities

P.Sowmya Sree Unit-I Page 20


Features of C

It is a very simple and easy language, C language is mainly used for develop desktop based
application. All other programming languages were derived directly or indirectly from C
programming concepts. This language have following features;

1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed on different machines with
some machine specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language


Although, C is intended to do low-level programming. It is used to develop system
applications such as kernel, driver, etc. It also supports the features of a high-level language.
That is why it is known as mid-level language.

4) Structured programming language


C is a structured programming language in the sense that we can break the
program into parts using functions. So, it is easy to understand and modify. Functions
also provide code reusability.

6) Rich Library
C provides a lot of inbuilt functions that make the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.

9) Recursion
In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.

10) Extensible
C language is extensible because it can easily adopt new features.

P.Sowmya Sree Unit-I Page 21


Structure of C program:

documentation section :The documentation section contains a set of comment including the
name of the program other necessary details. Comments are ignored by compiler and are used
to provide documentation to people who reads that code. Comments are be giving in C
programming in two different ways:
1. Single Line Comment
2. Multi Line Comment

// This is single line comment


/*
This is
multi line
comment
*/

Link Section
The link section consists of header files while contains function prototype of Standard Library
functions which can be used in program. Header file also consists of macro declaration.
Example:
#include <stdio.h>
In the above code, stdio.h is a header file which is included using the preprocessing directive
#include. Learn more about header files in C programming.

Definition Section
The definition section defines all symbolic constants. A symbolic constant is a constant value
given to a name which can't be changed in program. Example:
#define PI 3.14
In above code, the PI is a constant whole value is 3.14

Global Declaration
In global declaration section, global variables and user defined functions are declared.

main() Function Section


The main () function section is the most important section of any C program. The compiler start
executing C program from main() function. The main() function is mandatory in C
programming. It has two parts:

P.Sowmya Sree Unit-I Page 22


Declaration Part - All the variables that are later used in the executable part are declared in
this part
Executable Part - This part contains the statements that are to be executed by the compiler.
main()
{
... .. ...
... .. ...
}

Subprogram Section
The subprogram section contains all the user defined functions. A complete and
fully functions C program can be written without use of user-defined function in C
programming but the code maybe be redundant and inefficient if user-defined functions are not
used for complex programs.

Note: Except for the main () function section, other sections of the C program may be omitted
as per the requirement of the program.

First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run
the first c program.
To write the first c program, open the C console and write the following code:

#include <stdio.h>
main()
{
printf("Hello C Language");
}

1. #include <stdio.h> includes the standard input output library


functions. The printf() function is defined in stdio.h

2. main() The main() function is the entry point of every


program in c language.
3. printf() The printf() function is used to print data on the console

C Tokens

Tokens in C is the most important element to be used in creating


a program in C. We can define the token as the smallest individual element in C. For `example,
we cannot create a sentence without using words; similarly, we cannot create a program in C
without using tokens in C. Therefore, we can say that tokens in C is the building block or the
basic component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

P.Sowmya Sree Unit-I Page 23


Identifiers:

Identifiers are names given to various program elements such as constants,


functions, arrays and structures.

Rules for creating identifiers:

1. The first character must be an alphabet


2. No more then 8 or 31 charters in length.
3. The allowed characters are upper case letters, lower case letters, digits and some special
symbols.
4. Blank spaces are not allowed in between identifiers.
5. Can not use keywords.

Keywords: These are certain reserved words. Those have a standard pre define meaning in C
language. These keywords can be used only for their internal purpose. They can not be used as
program defined identifiers. Identifiers are generally generated by the users. So these are called
user defined identifiers. But keywords are system define identifiers. They must be in lower case
letters.In ‘C’ we have 32 Keywords . They are as follows

int break goto def

unsigned case double else

sizeof short register enum


switch signed if do
long float const union
void extern return static
char continue struct For
auto default type while

Constants
C Constants is a most basic and important part of C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the same
during the entire execution of the program.
• Constants are also called literals.
• Constants can be any of the data type.
• Syntax:

P.Sowmya Sree Unit-I Page 24


• const type constant_name;
• const keyword defines a constant in C.

Constant Types in C
Integer Constant
Its refer to sequence of digits. Integers are of three types viz:
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6

Real constant
The numbers containing fractional parts like 99.25 are called real or floating points constant.
Single Character Constants
It simply contains a single character enclosed within ‘ and ‘ (pair of single quote). It is to be
noted that the character ‘8‘ is not the same as 8. Character constants have specific set of integer
values known as ASCII values (American Standard Code for Information Interchange).
Example:
‘X’, ‘5’, ‘;’

String Constants
These are sequence of characters enclosed in double quotes and they may include letters, digits,
special characters and blank-spaces. It is again to be noted that “G” and ‘G‘ are different –
because “G” represents string as it is enclosed within pair of double quotes whereas ‘G’
represents a single character.
Example:
“Hello!”, “2015”, “2+1”

Strings in C

Strings in C are always represented as an array of characters having null character '\0' at the end
of the string. This null character denotes the end of the string. Strings in C are enclosed within
double quotes, while characters are enclosed within single characters. The size of a string is a
number of characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "Sowmya"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "Sowmya"; // The compiler allocates the memory at the run time.

char a[10] = {'S','o','w','m','y','a','\0'}; // String is represented in the form of characters.

Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be
used for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.

P.Sowmya Sree Unit-I Page 25


o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when printing
the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that
we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.

Escape sequences :
A character constant can be any of the valid printing characters in
the ASCII character set enclosed in single quotes. They are assigned to an identifier through an
assignment statement just as in the case of the integer and floating point constants. We can
represent non printing characters such as a new line in a character constant with a two
character sequence. A new line character, for example, is represented as a backslash followed
by the letter n, (/n). Although, represented in two characters, it occupies only one character
space in storage. Some of the common escape sequences for character constants are,

\n new line
\r carriage return
\t horizontal tab
\f form feed
\a audible alert (bell)
\\ back slash
\v vertical tab
\’ single quote
\” double quotes
\? question mark
\-- null character
\b back space

P.Sowmya Sree Unit-I Page 26


Data types:
Data types means what kind of data can be stored in the variable and the amount of
memory that should be allocated to the variable.Datatypes vary according to their use ,
C++ supports several fundamental data types .
Syntax: Data type vaiable_name;
C++ language supports 3 different types of data types,

Datatypes

Primary Derived UserDefined


Datatype Datatype Datatype

→Primary data type:

Primary data types are the actual data types which are already defined in C and they
should be used in the same way as they are defined in C++.They are: integer (int), floating
(float), character (char) and void

Integer type : Integers are numbers without fractional points (i.e. decimal points).Integers are
allocated two bytes of storage i.e. two cells in the memory.

Declaration of integer variables:


1. Integer variables should declare with the keyword ‘int’.
2. More than one variable can be declared with single int, separating variable names by commas.
3. We can also initialize them with in the same statement.

Size and range of Integer type on 16-bit machine

P.Sowmya Sree Unit-I Page 27


Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295

Example: int i;

Floating type: A float is a single precision floating point number. These numbers have a
precision of only 6 digits i.e. float can have 6 decimal points and it is fixed. Float are allocated
four bytes of storage i.e. four cells in the memory.

Declaration of float variables:


1. Floating variable are declared with the keyword float.
2. More than one variable can be declared with single float separating variable names bycommas.
3. We can also initialize them with in the
Type Size(bytes) Range same statement.
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

Size and range of floating type on 16-bit machine


Example: float f;

Character type: Character data type allocates one byte of memory i.e. one cell in the
memory. It capable of storing one character from the character set.

Declaration of character variables:


1. Character variables are declared with the keyword char.
2. More than one variable can be declared with single char, separating variables names by
commas.
3. We can also initialize them with in the same statement.

Size and range of character type on 16-bit machine


Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255

Example: char ch;

P.Sowmya Sree Unit-I Page 28


void type: void type means no value. This is usually used to specify the type of functions.

→Derived Datatypes: Derived data types are data types which can be created using basic data
types i.e. they are derived from basic data types
They are: arrays, pointers, functions.

→ User Defined Data types are the data types using which we can create our own data types
They are: structures, union, enumerations.

Operators
Operator is a symbol having pre defined meaning and that is used to perform some specific
operation. Operators acts on operands.
Here operands are nothing but a variable, a constant, or a value.
Based on the operands operators are classified into three types.
They are,
1. Unary operators: These operators act on single operand.
2. Binary operators: These operators act on two operands.
3. Ternary operators: These operators act on three operands.

In C language the Operators are classified as follows……


1. Arithmetical Operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Increment/Decrement Operators
6. Condition / Ternary Operator.
7. Bit wise Operators.
8. Special Operators.

1. Arithmetical Operators: C provides all the basic arithmetic operators which are used to
perform the basic arithmetic operations such as: “+ “Addition, “– “Subtraction
“* “Multiplication, “/ “Division,”%” Modules Division.

Note: The modules operator operates on integers


only and returns an integer. It is going to return the Output:
remainder of that integer division. Line 1 - Value of c is 31
Line 2 - Value of c is 11
/*Sample program on Arithmetical Operators*/ Line 3 - Value of c is 210
Line 4 - Value of c is 2
#include <stdio.h> Line 5 - Value of c is 1
main()
{
int a = 21,b=10,c;
c = a + b;
printf("Line 1 - Value of c is %d",c);
c = a - b;

P.Sowmya Sree Unit-I Page 29


printf("\nLine 2 - Value of c is %d",c);
c = a * b;
printf("\nLine 3 - Value of c is %d ",c);
c = a / b;
printf("\nLine 4 - Value of c is %d",c);
c = a % b;
printf("\nLine 5 - Value of c is %d",c); }

2.Relational Operators: Relational Operators is used to compare two operands given in the
expression. The result is either True or False. The relational operators come under category of
binary operator.
The Relational Operators are
“< “ Less than
“> “ Greater than Output:
“<= “ Less than or equal to The value of a<b is :1
“>= “ Greater than or equal to The value of a>b is: 0
“= “ Equal to The value of a<=b is :1
“== “ Comparison Equal to The value of a>=b is : 0
“!= “ Not equal to The value of a==b is :0
The value of a!=b is: 1
/*Sample program on Relational Operators*/
#include<stdio.h> Note: Here “1” means true and “0”
main() means false
{
int a=10,b=20;

printf(”The value of a<b is : %d” ,(a<b));


printf( “\n The value of a>b is: %d”,(a>b));
printf(”\n The value of a<=b is : %d”,(a<=b));
printf( “\n The value of a>=b is: %d”,(a>=b));
printf( “\n The value of a==b is : %d”,(a==b));
printf( “\n The value of a!=b is: %d” ,(a!=b));
}

3.Logical Operators: Logical Operators are used when we want to test more than one condition
in relational expression and making decision.
The expression which combines two or more relational expression is known as logical
expression or a compound relation expression.

The logical Operators are:


‘&&’ Logical And
‘||’ Logical Or
‘ ! ’ Logical Not

Logical Operator Chart:

P.Sowmya Sree Unit-I Page 30


Operator Applied Final
Condition1 Condition2
Between Output

AND True True True

True False False

False True False

False False False

OR True True True

True False True

False True True

False False False

NOT True - False

False - True

/*Sample program on Logical Operators*/

//Sample program on Logical Operators


#include<stdio.h>
main()
{
int num1=30,num2=40; Output:
if(num1>=40 || num2>=40) OR If Block Gets Executed
printf("Or If Block Gets Executed"); AND If Block Gets Executed
if(num1>=20 && num2>=20) NOT If Block Gets Executed
printf("And If Block Gets Executed");
if( !(num1>=40))
printf("Not If Block Gets Executed");

4.Assignment Operators: It is used to assign or store a value on right hand side to the variable
on left hand side. There must be a single variable on the left hand side.

Assignment Operator Meaning


a =1 a=1(assign 1 to a)
a+=b a=a+b
a-=b a=a-b

P.Sowmya Sree Unit-I Page 31


a*=b a=a*b
a/=b a=a/b
a%=b a=a%b

/*Sample program on Assignment Operator*/


#include<stdio.h>
main()
{
int res;
res = 11;
res += 4;
printf("\nResult of Ex1 = %d", res);

res = 11;
res -= 4;
printf("\nResult of Ex2 = %d", res);

res = 11;
res *= 4;
printf("\nResult of Ex3 = %d", res);

res = 11;
res /= 4;
printf("\nResult of Ex4 = %d", res);

res = 11;
res %= 4;
printf("\nResult of Ex5 = %d", res);
}

5.Increment And Decrement Operators These two operators are unary operators.

→Increment Operator: This Operator is used to increment the value of an integer by ‘1’.The
increment Operator symbol is ++ (double plus).
If we use this symbol (++) before an operand then it is known as prefix increment Operator.
Ex: ++a.
If we use this symbol (++) after an operator then it is known as post increment operator.
Ex: a++
Note: In the case of pre – fixing the operator with the variable it gets increments and then
participate in the operation whereas, if you post – fix the increment operation with the variable.
The variable participate in the expression with the old value and then increments

/*Sample program On Increment Operator*/


#include<stdio.h>
#include<conio.h>
void main()
{

P.Sowmya Sree Unit-I Page 32


int a,b,x=10,y=10;
clrscr();

a = x++;
b = ++y;

printf("Value of a : %d",a);
printf("Value of b : %d",b);
getch();
}

→Decrement Operator: This operator is used to decrement the value of an integer by ‘1’,The
decrement operator symbol is—(double minus).
If we use this symbol (--) before an operand then it is known as prefix decrement Operator.
Ex:--a.
If we use this symbol (--) after an operator then it is known as post decrement operator.
Ex: a--

/*Sample program on Decrement Operator*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,x=10,y=10;
clrscr();

a = x--;
b = --y;

printf("Value of a : %d",a);
printf("Value of b : %d",b);
getch();
}

6. Condition / Ternary Operator: They are also called as Ternary Operator .They also called as
“?:” operator. Ternary Operators takes on 3 Arguments

Syntax: variable = (condition)? exp1: exp2;

Note: In this, first, the condition is checked, if it returns true then the value returned by exp1
otherwise the value return by exp2

P.Sowmya Sree Unit-I Page 33


/*Sample program on Condition/Ternary Operator*/

#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf(“Even number”):printf(“Odd number);
getch();
}

/*Write a program to print biggest of three number using conditional operator*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b, c, big; Output:
clrscr(); Enter the Number : 58
printf(“Enter three numbers:”); Even number
scanf(“%d%d%d”,&a,&b,&c);
big=(a>b&&a>c)?a:((b>c)?b:c);
printf(“\nBiggest=%d”,big);
getch();
}

7.Bit wise Operators: All data items are stored in the computer’s memory as a sequences of
bits(0’s and 1’s).Bit wise operators are used for manipulation of the data at bit level. These
bitwise operators work with int and char type data only but not with float and double.

Bitwise Operators are:


“ & ‟ Bitwise And
“ | ‟ Bitwise Or
“ ~ ‟ Complement
“ ^ ‟ Exclusive – Or

P.Sowmya Sree Unit-I Page 34


“<< ‟ Left shift
“>> ‟ Right shift
Bit wise Operator Chart:
Operator Applied Final
Condition1 Condition2
Between Output

AND True True True

True False False

False True False

False False False

OR True True True

True False True

False True True

False False False

XOR True True False

True False True

False True True

False False False

/*Sample program on Bitwise Operator*/


#include <stdio.h>
#include<conio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
clrscr();
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );

P.Sowmya Sree Unit-I Page 35


c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */


printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */


printf("Line 6 - Value of c is %d\n", c );
getch();
}

8.Special Operators: C supports some special operators such as :

Comma Operator(,)
Sizeof() Operator
Address Operator(&)
Dereferencing Operator (*)
Dot Operator(.)
Arrow Operator(->)

→Sizeof() Operator: The sizeof operator is used with an operand,it returns the number of bytes
the operand occupies.The operand may be a variable,a constant or a datatype qualifier.

/*Sample program on Sizeof Operator*/


#include <stdio.h>
#include<conio.h>
void main()
{
Output:
int a = 4; Line 1 - Size of variable a = 4
short b; Line 2 - Size of variable b = 2
double c; Line 3 - Size of variable c= 8
int* ptr; value of a is 4
*ptr is 4.
/* example of sizeof operator */ Value of b is 30
printf("Line 1 - Size of variable a = %d\n", sizeof(a) ); Value of b is 20
printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
printf("Line 3 - Size of variable c= %d\n", sizeof(c) );

/* example of & and * operators */


ptr = &a; /* 'ptr' now contains the address of 'a'*/
printf("value of a is %d\n", a);
printf("*ptr is %d.\n", *ptr);

/* example of ternary operator */


a = 10;

P.Sowmya Sree Unit-I Page 36


b = (a == 1) ? 20: 30;
printf( "Value of b is %d\n", b );

b = (a == 10) ? 20: 30;


printf( "Value of b is %d\n", b );
}

Expressions:
The combination of an operator and operands forms an expression.
The expressions are classified into 3 types.
They are,
Arithmetical Expression These are formed by using arithmetical operators.
Ex: a+b
Logical Expression These are formed by using relational operators.
Ex: a>b
Compound Expression These are formed by using logical operators.
Ex: a>b && a>c

Expression evaluation
In c++ language expression evaluation is mainly depends on priority and associativity.
Priority
This represents the evaluation of expression starts from "what" operator.
Associativity
It represents which operator should be evaluated first if an expression is containing more than
one operator with same priority.

Operator Priority Associativity


{}, (), [] 1 Left to right
++, --, ! 2 Right to left
*, /, % 3 Left to right
+, - 4 Left to right
<, <=, >, >=, ==, != 5 Left to right
&& 6 Left to right
|| 7 Left to right
?: 8 Right to left
=, +=, -=, *=, /=, %= 9 Right to left

Example 1:

P.Sowmya Sree Unit-I Page 37


Example 2:

Type Conversion

Converting one datatype into another is known as type casting or, type-conversion. There are
two types of type conversion:
1.Implicit Type Conversion
Implicit type casting means conversion of data types without losing its original
meaning. This type of typecasting is essential when you want to change data
types without changing the significance of the values stored inside the variable.
Implicit type conversion happens automatically when a value is copied to its
compatible data type.

Example program on implicit Conversion


#include<stdio.h>
main()
{
int x; // integer x
char y = 'a'; // character c
x=y;
printf("The value of x=%d",x);
}
Output:
The value of x=97

P.Sowmya Sree Unit-I Page 38


2.Explicit Type Conversion
This process is also called type casting and it is user defined. Here the
user can type cast the result to make it of a particular data type.
The syntax in C:
(type) expression
Example program on Explicit Conversion
#include <stdio.h>
main()
{
//variables
float
x = 24.5,
y = 7.2;

//converting float to int


int result = (int) x / (int) y;

//output
printf("Result = %d\n", result);

}
Output
Result=3

P.Sowmya Sree Unit-I Page 39


UNIT-II

Chapter –I
Input and Output

Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input and to display data
on screen when there is a need to output the result.

Un-formatted Input and Output Functions:

Unformatted console input/output functions are used to read a single input from the user at
console and it also allows us to display the value in the output to the user at the console.

1. getchar() : The getchar() function reads character type data form the input. The
getchar() function reads one character at a time till the user presses the enter key.

Syntax
/* getchar accepts character & stores in ch */
char ch = getchar();

2. putchar() : putchar() function prints only one character at a time.

Syntax:

putchar(var);

Unit -2 C-language P.Sowmya Sree Page 1


/*program on getchar() and putchar()*/
#include <stdio.h>
main ()
{ Output:
char c; Enter character:S
printf("Enter character: "); Character entered:S
c = getchar(); //reads a single character
printf("Character entered: ");
putchar(c); // dispalys a character
}

gets() and puts() functions:

The gets() function reads string from user and puts() function prints the string. Both functions are
defined in <stdio.h> header file.

Syntax for gets():

Char var_name[size];// declaring a character array

gets(var_name); // reading string

Syntax for puts():

puts(var_name); //printing the string

/* program on gets() and puts()*/

#include<stdio.h>
main()
{ Output:
char name[50]; Enter your name: Sowmya sree S
printf("Enter your name: "); Your name is: Sowmya sree
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
}

Formatted input/output functions


Formatted console input/output functions are used to take one or more inputs from the user at
console and it also allows us to display one or multiple values in the output to the user at the console.
Some of the most important formatted console input/output functions are –

•scanf():
• scanf() function reads all the types of data values.
• It is used for runtime assignment of variables.
• The scanf() stops functioning when some input entered does not match format string

Syntax: scanf(“format specifier”, &var1,&var2,……);

Unit -2 C-language P.Sowmya Sree Page 2


&(address):
scanf() statement requires ‘&’ operator called address operator .The address operator prints the
memory location of the variable . scanf() statement the role of ‘&’ operator is to indicate the memory
location of the variable, so that the value read would be placed at that location.

/* Example program on “scanf()” */


#include<stdio.h>
main() Output:
{ Enter your age:20
int age; Your age is 20
printf("Enter your age:");
scanf("%d",&age);//Accepts the age from user
printf("\n Your age is %d ",age);
}

•printf()
❖ This function displays output with specified format
❖ It requires format conversion symbol or format string and variables names to the print the data
❖ The list of variables are specified in the printf() statement
❖ The values of the variables are printed as the sequence mentioned in printf()
❖ The format string symbol and variable name should be the same in number and type

Syntax
printf(“format specifier”, variable 1, variable 2,..., variable n);

/*Example program on printf() and scanf()*/


#include<stdio.h>
main()
{ Output:
int a; Enter a character:K
float b; You entered a character:K
char c; Enter a number: 10
printf("Enter a character"); You entered a number:10
scanf("%c",&c); Enter a real number: 15.66
printf("\nYou entered a character:%c",c); You entered a real number:15.660000
printf("\nEnter a number");
scanf("%d",&a);
printf("\nYou entered a number:%d",a);
printf("\nEnter a real number");
scanf("%f",&b);.
printf("\nYou entered a real number:%f",b);
}

Unit -2 C-language P.Sowmya Sree Page 3


•Escape Sequence

Escape sequences are basically control characters used for formatting the output. These are
combinations of a backslash and a character in lowercase. We have already used “\n”, which shifts the
curser to the next line.
The following are the examples of an
escape sequence.

/*Example program on Escape sequence*/


#include <stdio.h>
main() Output:
{ Hello
printf("Hello\nWorld!"); //use of \n World!
printf("\nHello\tWorld!"); // use of \t Hello World!
printf("\n\"Hello World!\""); //use of \" “Hello World”
printf("\nHello\bWorld!"); //use of \b HellWorld
}

Chapter –II

Control Statements

“Statements used to control the flow of execution in a program”, means a statement


through which we control the behavior of our program like what kind of function it will perform, when
it will terminate or continue under certain circumstances or conditions.

There are three types of Control Statements


• Selection Statements/Decision making
• Iterative Statements/looping statements
• Special Control Statement

Selection Statements
A structure which select which statement or block of statements will execute on the basis of our
programming logic.
The Selection statements /Decision making statements are:
➢ if
➢ if-else
➢ nested if
➢ nested if-else
Unit -2 C-language P.Sowmya Sree Page 4
➢ comma operator
➢ conditional operator
➢ Switch
 if Statement:
The if statement is used to check some given condition and perform some operations
depending upon the correctness of that condition.

Syntax: if (condition)
{
Block of statements
}

Here a ‘condition’ is a relational or logical expression and it produces either true(means 1) or


false(means 0) result.
If the condition is true then the block of statement is executed and if the condition is false then
the block of statement is ignored and the control is transferred to the next statement after if statement.

Flowchart for if statement

/*Example program on if statement*/


#include<stdio.h>
main( ) Output:
{
int age=18; //local variable declaration You are not Eligible to vote
if(age<=18) Thank you
{
printf("You are not Eligible to vote");
}
printf("\nThank you");
}

 if…else statement
It is similar to if statement i.e. It is also used to execute or ignore a set of statements
after testing a condition.In if-else statement one condition and two blocks of statements are
given.First blocks contain if statement with condition and its body
part.Second is else and it contain only body part.

Unit -2 C-language P.Sowmya Sree Page 5


if(condition)
Syntax:
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}

A condition is a logical or relational expression and it produces either true or false


result.If the condition is true the first block of if-else statement (which is if-statement) is executed
and second is ignored and after executing the first block , the control is transferred to next
statement after if -else structure.
If the condition is false then the first blocks of statement is ignored and the second
block of statement is executed. After the executing the second block of statement the control is
transferred to next statement after if-else structure.

Flowchart of the if-else statement

/*Program to find number is Even or Odd using if-else statement*/


#include<stdio.h>
main()
{
int Num;
printf("Enter Number to check it is Even or Odd: "); Output:
scanf(“%d”,&Num); Enter Number to check it is Even or
if(Num%2==0) Odd: 6
{ Number is Even
printf("Number is Even");
}
else
{
printf(" Number is Odd");
}}

Unit -2 C-language P.Sowmya Sree Page 6


Nested if:
Nested if in C Programming is placing if Statement inside another if Statement.

Syntax:

if ( condition 1)
{
//If thecondition 1 is TRUE then it will check for condition 2
if (condition 2)
{
statement-1;
}
else
{
Statement-2;
}
else
{
//If the condition 1 is FALSE then these statements will be executed
statement-3
}

Here if the condition-1 is TRUE then it enters into if body and condition -2 will be checked ,if
condition-2 is TRUE then Statement-1 alone will be executed ,if condition-2 is FALSE then
Statement- alone will be executed .
If the Condition- 1 is FALSE then else block statement-3 will only be executed.

Flowchart of Nested if

/* Example program on nested if */

#include<stdio.h>
main() Output:
{
int a=10,b=30,c=20; b is greatest number
if(a>b)
{

Unit -2 C-language P.Sowmya Sree Page 7


if(a>c)
{
printf("a is greatest number");
}
else
{
printf("c is greatest number");
}
}
else
if(b>c)
{
printf("b is greatest number");
}
else
{
printf("c is greatest number");
}
}

 Nested if..else statement


When a series of decision is required, nested if-else is used. Nesting means using
one if-else construct within another one.
if (condition-1)
Syntax: {
statement1;
}
else if (condition 2)
{
Statement2;
}
else if (condition 3)
{
Statement3;
}
else if (condition n)
{
Statement n;
}
else
{ default; }

Flowchart of Nested if_elsse

Unit -2 C-language P.Sowmya Sree Page 8


/*Example Program on Nested if_else */
#include <stdio.h>
main ()
{
// declare local variable Output:
int marks = 55; U got 3rd class !!
// check the boolean condition
if( marks >= 80 )
{
// if 1st condition is true
printf("U got 1st class !!");
}
else if( marks >= 60 && marks < 80)
{
// if 2nd condition is false
printf("U got 2nd class !!");
}n , 0
else if( marks >= 40 && marks < 60)
{
// if 3rd condition is false
printf("U got 3rd class !!");
}
else
{
// none of condition is true
printf("U are fail !!");
}
}

•Comma operator:
As an operator − The comma operator { , } is a binary operator that discards the first expression
(after evaluation) and then use the value of the second expression. This operator has the least
precedence.

/*Example Program on Comma Operator*/


#include<stdio.h>
main() Output:
{ a
char ch ;
ch= 'a', 'b', 'c';
printf("%c", ch);
}

Note: It gives a as output as it works because the ‘,’ works as operator but it precedence is below
assignment operator hence the output is a.

•conditional operator:
They are also called as Ternary Operator .They also called as “?:” operator. Ternary Operators
takes on 3 Arguments
Syntax: variable = (condition)? exp1: exp2;

Unit -2 C-language P.Sowmya Sree Page 9


Note: In this, first, the condition is checked, if it returns true then the value returned by exp1 otherwise
the value return by exp2

/*Sample program on Condition/Ternary Operator*/


#include<stdio.h>
Output:
main()
Enter the Number 15
{
Odd number
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf(“Even number”):printf(“Odd number”);
}

❖ Switch statement:
o Switch is also a control structure and it is used to select one option from a set of options.
o It compares the value of an expression or a variable against a list of cases.
o The case labels and the value of expression or variable must be an integer or a character.
o It must not be a float or double value. If the value of expression in switch is float or double type
then the compiler will generate error message.

Syntax:
switch(expression)
{
case value 1: statement1;
break;
case value 2: statement 2;
break;
.
.
.
.
default: default statement;
}

/*Example program on switch case*/*


#include<stdio.h>
void main()
{
int day;
printf("1. Sunday\n");
printf("2. Monday\n");
printf("3. Tuesday \n");

Unit -2 C-language P.Sowmya Sree Page 10


printf("4. Wednesday\n");
printf("5. Thursday \n"); Output:
printf("6. Friday \n");
printf("7. Saturday \n"); 1. Sunday
printf("Enter your choice"); 2. Monday
scanf(“%d”,&day); 3. Tuesday
switch (day) 4. Wednesday
{ 5. Thursday
case 1 : printf("Sunday"); 6. Friday
break; 7. Saturday
case 2 : printf("Monday");
break; Enter your choice 7
case 3 : printf("Tuesday");
break; Saturday
case 4 : printf("Wednesday");
break;
case 5 : printf("Thursday");
break;
case 6 : printf("Friday");
break;
case 7 : printf("Saturday");
break;
default :printf("Invalid number");
break;
}
}

►Loops/ Repetition/ Iteration


• There may be a situation, when you need to execute a block of code several number of
times.
• In general statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
• Programming languages provide various control structures that allow for more complicated
execution paths.
• A loop statement allows us to execute a statement or group of statements multiple times.
C provide 3 types of looping statements they are :
➢for loop
➢while loop
➢do..while loop

for loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

Syntax
for ( initialization; condition; increment /decrement)
{
statement(s);
}

Unit -2 C-language P.Sowmya Sree Page 11


• The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after the
for loop.
• After the body of the for loop executes, the flow of control jumps back up to
the increment/decrement statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the condition.
• The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.

Flow Chart

Output:
value of a:1
//Program to print numbers from 1 to 10 using for loop
value of a:2
#include<stdio.h>
value of a:3
void main()
value of a:4
{
value of a:5
int a;
value of a:6
for( a = 1; a <=10; a ++ )
value of a:7
{
value of a:8
printf("value of a: %d\n", a);
value of a:9
}
value of a:10
}

Nested for loop


The nested for loop means any type of loop which is
defined inside the 'for' loop.

Unit -2 C-language P.Sowmya Sree Page 12


Syntax:
for (initialization; condition; update)
{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}

/*Example program on nested for loop*/


#include <stdio.h> Output:
main() 0, 0
0, 1
{
0, 2
int i,j; 0, 3
for (i=0; i<2; i++) 1, 0
{ 1, 1
for (j=0; j<4; j++) 1, 2
{ 1, 3
printf("%d, %d\n",i ,j);
}
}
}
while loop:
A while loop statement repeatedly executes a target statement as long as a given condition
is true.while is a entry controlled loop i.e first the condition is checked and then the statement is
executed.

Syntax

while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true.

Flow Diagram

Unit -2 C-language P.Sowmya Sree Page 13


//Program to print numbers from 1 to 10 using while loop
#include<stdio.h> Output:
main() value of a:1
{ value of a:2
int a = 1; value of a:3
while( a <=10) value of a:4
{ value of a:5
printf("value of a: %d\n", a); value of a:6
a ++ ; value of a:7
} value of a:8
} value of a:9
value of a:10

/*Write a program to print the prime number from 2 to n


where n is given by user*/

#include<stdio.h>
main()
{
int num,i=1,j,count;
printf(“Enter Num value To Print Prime Numbers between 1 and Num: ");
scanf(“%d”,&Num);
printf("Prime Numbers
upto:"<<num<<"\n");
Output:
while(i<=num)
Enter Num value To Print Prime Numbers between 1 and
{
Num: 10
count=0;
Prime Numbers upto: 10
for(j=1;j<=i;j++)
2
{
3
if(i%j==0)
5
count++;
7
}
if(count==2)
printf(“%d”,n);
i++;
}
Printf(“n\n”);
}

do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.

Syntax do
{
statement(s);
}while( condition );

Unit -2 C-language P.Sowmya Sree Page 14


Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.

Flowchart

Output:
value of a:1
//Program to print numbers from 1 to 10 using do…while loop value of a:2
#include<stdio.h> value of a:3
main() value of a:4
{ value of a:5
int a = 1; value of a:6
do value of a:7
{ value of a:8
printf("value of a:%d\n ", a); value of a:9
a ++ ; value of a:10
} while( a <=10);
}
//Program to check whether a given number is amstrong or not
#include<stdio.h>
void main()
{
intorigNum, num, rem, sum = 0;
printf("Enter a positive integer: ");
scanf(“%d”,&origNum);
Output:
num = origNum;
Enter a positive integer: 153
while(num != 0)
{ 153 is an Armstrong number.
rem= num % 10;
sum =sum+(rem * rem * rem);
num =num/ 10;
}

if(sum == origNum)

Unit -2 C-language P.Sowmya Sree Page 15


printf("%d is an Armstrong number.",origNum);
else
printf("%d is not an Armstrong number.",origNum);

Difference between while and do while loop

Special Control Statement


The Special Control Statements are as follows
• goto
• break
• continue
• return
• exit.

► goto Statement:-
goto statement is used for altering the normal sequence of program execution by transferring
control to some other part of the program.

Syntax

goto label;

.. .. ... .

... .. ...
... .. ...
label:
statement;
... .. ...

Unit -2 C-language P.Sowmya Sree Page 16


//Example program on goto statement
#include<stdio.h>
main ()
{ OUTPUT:
/* local variable definition */ value of a: 10
int a = 10; value of a: 11
value of a: 12
/* do loop execution */ value of a: 13
LOOP: value of a: 14
do value of a: 16
{ value of a: 17
if( a == 15) value of a: 18
{ value of a: 19
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
}
►break Statement

The break statement terminates the loop (for, while and do...while loop) immediately when it is
encountered. The break statement is used with decision making statement such as if...else,switch.

Syntax break;

Flowchart

Output:
/*Example program on break*/ 0
#include<stdio.h> 1
main() 2
{ 3
int i; 4
for(i=0;i<=10;i++)
{

Unit -2 C-language P.Sowmya Sree Page 17


if(i==5)
break;
printf("%d\n",i);
}
}

►continue Statement

The continue statement skips some statements inside the loop. The continue statement is used with
decision making statement such as if...else.

Syntax of continue Statement

continue;

Flowchart of continue Statement

/*Example program on continue*/


#include<stdio.h> Output:
main() 0
1
{ 2
int i; 3
for(i=0;i<=10;i++) 4
{ 6
if(i==5) 7
continue; 8
printf("%d\n",i); 9
} 10
}

►return
The return statement returns the flow of the execution to the function from where it
is called. This statement does not mandatorily need any conditional statements. As soon as the
statement is executed, the flow of the program stops immediately and returns the control from where
it was called. The return statement may or may not return anything for a void function, but for a non -
void function, a return value is must be returned.

Unit -2 C-language P.Sowmya Sree Page 18


Syntax:
return[expression];

Examples:

return (value or variable);

return 10;

return a;

return a+b;

►exit: In C, exit() terminates the calling process without executing the rest code which is after the
exit() function. The return code "0" exits a program without any error message.

Syntax:
exit(0);

/*Example program on exit()*/


#include <stdio.h>
main()
{
printf("START"); Output:

exit(0); // The program is terminated here START

// This line is not printed


printf("End of program");
}

Chapter –III

Arrays and Strings

ARRAYS:

Array is a collection of similar data type. A single variable can hold only one value at a time,
If we want a variable to store more than one value of same type we use array. Array is linear data
structure.

(Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.)

A specific element in an array is accessed by an index.All arrays consist of contiguous memory


locations.

Unit -2 C-language P.Sowmya Sree Page 19


We are having 2 types of arrays they are:

❖One Dimensional array


❖Multi Dimensional array

→One Dimensional array

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows −

datatype arrayName [ arraySize ];


This is called a single-dimensional array. The arraySize must be an integer constant greater than zero
and datatype can be any valid C data type

Example:

int a[6];

Initializing Arrays

You can initialize C++ array elements either one by one or using a single statement as follows:

type arrayName[ arraySize ]= {list};

The number of values between braces { } cannot be larger than the number of elements that we declare
for the array between square brackets [ ].
Example: int a[5]={2,3,4,5,6};

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore,
if you write:

int a[]={2,3,4,5,6};

Accessing Array Elements:


An element is accessed by indexing the array name. This is done by placing the index of the element
within square brackets after the name of the array.

Example: int a[10]; a[0]=5; a[1]=2; . . .

For example, an array containing 5 integer values of type int called ‘a’ could be represented as:

Unit -2 C-language P.Sowmya Sree Page 20


a

/*Example program on reading and displaying array values*/

#include<stdio.h>
main()
{ Output:
int a[10],i,n; Enter the size of an array:5
printf(“Enter the size of an array:”); Enter the array elements
scanf(“%d”,&n); 12345
printf(“\nEnter the array elements”); the elements are:
for(i=0;i<n;i++)
1
scanf(“%d”,&a[i]); //reading elements into an array
2
printf(“\nthe elements are:\n”);
for(i=0;i<n;i++) 3
printf(“%d\n”,a[i]); //displaying elements from an array 4
} 5

//C++ Program to Find Largest and Smallest Element in Array


#include<stdio.h>
main()
{
int Arr[100],n,i,small,large;
printf( "Enter number of elements you want to insert ");
scanf(“%d”,&n);

for(i=0;i<n;i++)
{ Output:
printf("Enter element %d:",i+1); Enter number of elements
scanf(“%d”, Arr[i]); you want to insert 4
} Enter element 1:10
Enter element 2:1
small=Arr[0]; Enter element 3:30
large=Arr[0]; Enter element 4:100
for(i=1;i<n;i++) Largest element is : 100
{
Smallest element is : 1
if(Arr[i]<small)
small=Arr[i];
if(Arr[i]>large)
large=Arr[i];
}

printf("\nLargest element is :%d",large);


printf("\nSmallest element is :%d",small);
}

Unit -2 C-language P.Sowmya Sree Page 21


Multi Dimensional array:
Arrays with more than one dimension are called
multidimensional arrays.

Syntax:datstype name[size1][size2]...[sizeN];

→Two Dimensional array


The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of
size x,y, you would write something as follows:

datatype arrayName [ x ][ y ];

.Where type can be any valid C data type and arrayName will be a valid C identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y number of
columns. A 2-dimensional array a, which contains three rows and four columns can be shown as
below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays

Two-Dimensionalarrays may be initialized by specifying bracketed values for each row. Following is an
array with 3 rows and each row have 4 columns.

int a[3][4]={
{0,1,2,3},/* initializers for row indexed by 0 */
{4,5,6,7},/* initializers for row indexed by 1 */
{8,9,10,11}/* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous
example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Unit -2 C-language P.Sowmya Sree Page 22


Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array.
For example:
int val = a[2][3];
The above statement will take 4th element from the 3rd row
of the array.
Output:
//Example Program on two dimensional array
#include<stdio.h> a[0][0]: 0
main()
{ a[0][1]: 0
// an array with 5 rows and 2 columns.
int i,j,a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; a[1][0]: 1
// output each array element's value a[1][1]: 2
for ( i=0; i < 5; i++ )
for ( j = 0; j < 2; j++ ) { a[2][0]: 2
printf( "a[%d][%d]:%d\n",i,j,a[i][j]);
a[2][1]: 4
}
} a[3][0]: 3
→Multi Dimensional array a[3][1]: 6
C++ allows multidimensional arrays.
Syntax: a[4][0]: 4
type name[size1][size2]...[sizeN];
Example:int threedim[5][10][4]; a[4][1]: 8
Initialisation of three dimensional array

Example:int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12,


23,2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

STRINGS/ CHARACTER ARRAY:


A String is an array of characters i.e. the characters arranged one after another in the
memory .Any group of characters defined between double quotations is called as String.
Eg:"Hello","Welcome friend"

Declaration of a String:
The general format for declaring String variable is

Syntax: char arrayname[size];


Here the size determines the number of characters in the array name.
Array name must be any valid variable name.

Ex: char name[10];

Unit -2 C-language P.Sowmya Sree Page 23


A String constant is a one dimensional array of characters, terminated by null character ('\0').
When the compiler assigns a character string to a character array, it automatically supplies a null
character at the end of the string. Therefore the size should be equal to maximum number of characters
in the string plus '1'.

Initialization of String:
Character arrays may be initialize when they are declared.The initialization can be done in
either of the following ways.

Ex:1. char name[7]={'S', 'A', 'C', 'H', 'I', 'N', '\0'};


2. char name[7]="SACHIN";
Here in example-1 when we initialize a character array by listing the elements, the null terminator ('\0')
should be explicitly specified.
In example-2 when the character array is initialized as a string constant,null terminator is not
necessary,Since the 'C' compiler places the null character automatically.

'C' allows to initialize a character array without specifying the size .In this case, the size will be
determined automatically based on the number of elements initialized.
Ex:- char name[]="SACHIN";

/* program to illustrate a simple string */


#include<stdio.h>
main()
{ Output:
char add[30];
printf("Enter Your place:\n"); Enter Your place:
scanf("%s",add); Hyderabad
printf("Your place is:%s",add); Your place is: Hyderabad
getch();
}

Initialization of String through keyboard:


The scanf() function is used to initialize the string through keyboard.
Ex: char name[15];
scanf("%s",name);
'%s' is used a format specifier to read the string (character array).
Here the problem with scanf() function is that it terminates the string when it finds any white space
such as space etc.
Ex: If the following string is given through keyboard
PAVAN KALYAN
The array name stores only PAVAN because after PAVAN there is a space so scanf() treats it as
the end of the string.
Output:
/* program to illustrate the drawback of scanf() function*/
#include<stdio.h> Enter Your name:
main() college
{ Your name is:college
char name[20];
printf("Enter Your name:\n");
scanf("%s",name);

Unit -2 C-language P.Sowmya Sree Page 24


printf("Your name is:%s",name);

}
/* Program to print the string in following format
S
SO
SOW
SOWM
SOWMY
SOWMYA
*/
#include<stdio.h>
main()
{
char name[]="SOWMYA";
int i,j;
for(i=0;i<=6;i++)
{
for(j=0;j<i;j++)
printf("%c",name[j]);
printf("\n");
}
}

String Handling functions or Functions in String.h


'C' library supports a large number of string handling functions that can be used to manipulate
strings.if we are using the following string functions we must compulsory include <string.h> in our
program.
The string Handling functions are:
1. strlen()
2. strcat()
3. strcpy()
4. strcmp()
5. strlwr()
6. strupr()
7. strrev()

1. strlen() function: This function counts and returns the number of characters in a string.
Syntax:n=strlen(string);
Here 'n' is an integer variable which receives the value of the length of the string.
/* program to calculate the length of the string */
#include<stdio.h>
#include<string.h>
main()
{
char s[15]="hello";
printf("length of hello is :%d",strlen(s));
}
Output:
Length of hello is :5

Unit -2 C-language P.Sowmya Sree Page 25


2.strcat() function: This function is used to join two strings together
Syntax: strcat(string1,string2);

String 1 and string2 are character arrays.when the strcat() function is executed,string2 is appended to
string1.It does so by removing the null character at the end of string1 and placing string2 from there
.The string at string2 remains unchanged.

/* program on strcat() function*/


#include<stdio.h>
#include<string.h>
main()
{
char s1[15]="hello";
char s2[10]="world";
strcat(s1,s2);
printf("After concatenation:\n");
printf("%s",s1);
}

Output:
After concatenation:
Hello world

3.strcpy() function: strcpy() function is used to copy one string to another.


Syntax: strcpy(string1,string2);
Here string2 will be copied to string1

/* program on strcpy() function*/


#include<stdio.h>
#include<string.h>
main()
{
char s1[15]="hello";
char s2[10]
strcpy(s2,s1);
printf("first string:\n");
printf("%s",s1);
printf("second string:\n");
printf("%s",s2);
}

Output:
First string:hello
Second string:hello

4.strcmp() function:This function compares two strings and has a value 0 if they are equal.If they are
not equal it has the numberic difference between the ASCII values of the first non-matching pairs of
characters.

Unit -2 C-language P.Sowmya Sree Page 26


Syntax: n=strcmp(string1,string2);
Here 'n' is an integer variable which receives the value of the length of the string.

/* program on strcpy() function*/


#include<stdio.h>
#include<string.h>
main()
{
int i;
char s1[10]="ABC";
char s2[10]="ABC";
i=strcmp(s1,s2);
printf("i=%d",i);
}
Output:
i=0

5.strlwr() function:Converts the string to lowercase.


Syntax: strlwr(string);
Ex: strlwr("RAMU")
Output:ramu

6.strupr() function:Converts the string to Uppercase.


Syntax: strupr(string);
Ex: strlwr("ramu")
Output:RAMU

7.strrev() function: Displays the string in reverse .


Syntax:strrev("string");
Ex: strrev("college")
o/p:egelloc

/*program to count No of words ,Lines in a text.*/


#include<stdio.h>
void main()
{
char line[80],ctr;
int i,c,end=0,ch=0,w=0,l=0;
printf("Enter The Text\n");
while(end==0)
{
c=0;
while((ctr=getchar())!=’\n’)
line[c++]=ctr;
line[c]=’\o’;
if(line[0]==’\o’)
break;
else
{
w++;

Unit -2 C-language P.Sowmya Sree Page 27


for(i=0;line[i]!=’\o’;i++)
if(line[i]==’ ‘||;line[i]==’\t’)
w++;
}
l=l+1;
ch=ch+strlen(line);
}
printf("\n");
printf("Number Of Lines:%d\n",l);
prinf("Number Of Words:%d\n",w);
printf("Number Of Characters:%d\n",ch);
}

ctype.h
❖ The ctype.h header file of the C Standard Library declares several functions that are useful for
testing and mapping characters.

❖ All the functions return non-zero (true) if the argument c satisfies the condition described, and
zero(false) if not.

Library Functions under ctype.h

Function Work Of Function

isalnum Tests whether a character is alphanumeric or not

isalpha Tests whether a character is aplhabetic or not

iscntrl Tests whether a character is control or not

isdigit Tests whether a character is digit or not

isgraph Tests whether a character is grahic or not

islower Tests whether a character is lowercase or not

isprint Tests whether a character is printable or not

ispunct Tests whether a character is punctuation or not

isspace Tests whether a character is white space or not

isupper Tests whether a character is uppercase or not

isxdigit Tests whether a character is hexadecimal or not

tolower Converts to lowercase if the character is in uppercase

Unit -2 C-language P.Sowmya Sree Page 28


Function Work Of Function

toupper Converts to uppercase if the character is in lowercase

1.isalnum():
The C library function void isalnum(int c) checks if the passed character is alphanumeric.

/*program on isalnum()*/
#include <stdio.h> OUTPUT:
main()
{ Enter any character
char ch; @
printf("Enter any character\n"); Entered character is not alphanumeric
scanf("%c", &ch);

if ( isalnum ( ch ) )
printf ( "\nEntered character is alphanumeric" ) ;
else
printf ( "\nEntered character is not alphanumeric" ) ;
}

2.isalpha():

isalpha( ) function in C language checks whether given character is alphabetic or not.


Syntax
int isalpha ( int x );

EXAMPLE PROGRAM FOR ISALPHA( ) FUNCTION IN C:


#include <stdio.h>
main() OUTPUT:
{ Enter any character
char ch; 1
Entered character is not alphabetic
printf("Enter any character\n");
scanf("%c", &ch);
if ( isalpha ( ch ) )
printf ( "\nEntered character is alphabetic" ) ;
else
printf ( "\nEntered character is not alphabetic" ) ;
}

3.iscntrl():
iscntrl( ) function in C language checks whether given character is control character or not.

Syntax
int iscntrl( int x );

Unit -2 C-language P.Sowmya Sree Page 29


• Control characters in C language are ‘\a’ ( alert ), ‘\b’ ( backspace ), ‘\f’ ( form feed ), ‘\n’ ( new
line ), ‘\r’ ( carriage return ), ‘\t’ ( horizondal tab), ‘\v’ ( vertical tab) and ‘\0’ ( null ).

EXAMPLE PROGRAM FOR ISCNTRL() FUNCTION IN C:


#include <stdio.h>
main()
{
char ch[5] ="abc\a"; OUTPUT:
int i = 0; control character is found at 4th position
while(1)
{
if(iscntrl(ch[i]))
{
printf ( "control character is found at " \
"%dth position\n", i+1);
break;
}
i++;
}
}

4.isdigit():

isdigit( ) function in C language checks whether given character is digit or not.

Syntax
int isdigit ( int x );

EXAMPLE PROGRAM FOR ISDIGIT() FUNCTION IN C:


#include <stdio.h>
main()
OUTPUT:
{
char ch; Enter any character
printf("Enter any character\n"); 200
scanf("%c", &ch); Entered character is digit
if ( isdigit ( ch ) )
printf ( "\nEntered character is digit" ) ;
else
printf ( "\nEntered character is not digit" ) ;
}

5.isgraph():
isgraph( ) function in C language checks whether given character is graphical character or not.
Syntax
int isgraph( int x );

All printable characters are graphical characters except space ( ‘ ‘ ).

Unit -2 C-language P.Sowmya Sree Page 30


EXAMPLE PROGRAM FOR ISGRAPH() FUNCTION IN C:
• In this program, isgraph( ) function checks whether character is graphical character or not.
• If its a graphical character, it is printed in output. Else, control is coming out of while loop. Output
is printed as “fresh” since space (” “) is not a graphical character and it can’t be printed in output.

#include <stdio.h>
main()
{
char string[50] ="fresh 2 refresh \n string"; OUTPUT:
int i = 0; fresh
while(1)
{
if(isgraph(string[i]))
{
putchar(string[i]);
i++;
}
else break;
}
}

6.islower():
islower( ) function in C language checks whether given character is lower case or not.
Syntax
int islower( int x );

EXAMPLE PROGRAM FOR ISLOWER() FUNCTION IN C:

#include <stdio.h>
int main() OUTPUT:
{ Enter any character
char ch; a
printf("Enter any Entered character is lower case character
character\n");
scanf("%c", &ch);

if ( islower ( ch ) )
printf ( "\nEntered character is lower case character") ;
else
printf("\nEntered character is not lower case character");
}
7.isprint():

• isprint( ) function in C language checks whether given character is printable character or not.
Syntax for isprint( ) function is given below.
int isprint( int x );

Unit -2 C-language P.Sowmya Sree Page 31


EXAMPLE PROGRAM FOR ISPRINT() FUNCTION IN C:
• In this program, isprint( ) function checks whether character is printable or not.
• If its a printable character, it is printed in output. Else, control is coming out of while loop. Output
is printed as “sowmyasree” since “\n” is a control character and it can’t be printed in output.
#include <stdio.h>
main()
{
char string[50] ="sowmyasree \n string";
int i = 0;
while(1) OUTPUT:
{ sowmyasree
if(isprint(string[i]))
{
putchar(string[i]);
i++;
}
else
break;
}
}

8. ispunct()

ispunct( ) function in C language checks whether given character is punctuation or not.


Syntax
int ispunct( int x );

EXAMPLE PROGRAM FOR ISPUNCT() FUNCTION IN C:


#include <stdio.h>
main()
{ OUTPUT:
char ch = '!';
Character is a punctuation character
if ( ispunct ( ch ) )
printf ( "Character is a punctuation character" ) ;
else
printf ( "\nCharacter is not a punctuation character" ) ;
}

9. isspace()
isspace( ) function in C language checks whether given character is space or not.

Syntax
int isspace( int x );

Unit -2 C-language P.Sowmya Sree Page 32


EXAMPLE PROGRAM FOR ISSPACE() FUNCTION IN C:
#include <stdio.h>
main()
{
char ch; OUTPUT:
printf("Enter any character\n"); Enter any character
scanf("%c", &ch); a
Entered character is not space
if ( isspace ( ch ) )
printf ( "\nEntered character is space" ) ;
else
printf ( "\nEntered character is not space" ) ;
}

10. isupper()
isupper( ) function in C language checks whether given character is upper case or not.

Syntax
int isupper ( int x );

EXAMPLE PROGRAM FOR ISUPPER() FUNCTION IN C:


#include <stdio.h>
main() OUTPUT:
{ Enter any character
char ch; A
printf("Enter any character\n"); Entered character is upper case character
scanf("%c", &ch);

if ( isupper ( ch ) )
printf ("\nEntered character is uppercase character");
else
printf("\nEntered character is not uppercase character");
}

10. isxdigit()
isxdigit( ) function in C language checks whether given character is hexadecimal or not.

Syntax
int isxdigit( int x );

EXAMPLE PROGRAM FOR ISXDIGIT() FUNCTION IN C:


#include <stdio.h>
main()
{ OUTPUT
char ch; Enter any character
printf("Enter any character\n"); #
scanf("%c", &ch); Entered character is not hexadecimal

Unit -2 C-language P.Sowmya Sree Page 33


if ( isxdigit ( ch ) )
printf ( "\nEntered character is hexadecimal" ) ;
else
printf ( "\nEntered character is not hexadecimal" ) ;
}

11. tolower()
tolower( ) function in C language checks whether given character is alphabetic and converts to
lowercase.

Syntax
int tolower( int x );

/*EXAMPLE PROGRAM FOR TOLOWER() FUNCTION IN C*/


#include <stdio.h>
main()
{ OUTPUT:
char ch; Enter any character
printf("Enter any character\n"); A
scanf("%c", &ch); Entered character is converted into lower character : a

if(isalpha(ch))
printf ( "\nEntered character is converted into " \
"lower character : %c\n",tolower ( ch ) ) ;
else
printf("Entered character is not an alphabetic");
}

12. toupper()
toupper( ) function in C language checks whether given character is alphabetic and
converts to uppercase.

Syntax:
int toupper( int x );

/*Example program on toupper()*/


#include <stdio.h>
main() OUTPUT:
{
char ch; Enter any character
printf("Enter any a
character\n"); Entered character is converted into upper character : A
scanf("%c", &ch);
if(isalpha(ch))
printf ( "\nEntered character is converted into " \
"upper character : %c\n",toupper ( ch ) ) ;
else
printf("Entered character is not an alphabetic");
}

Unit -2 C-language P.Sowmya Sree Page 34


UNIT-III
CHAPTER-I
FUNCTIONS

A function is a self-contained block of program statements that performs a


particular task. It is often defined as a section of a program performing a specific job.

Types of functions
Depending on whether a function is defined by the user or already included in C compilers, there
are two types of functions in C programming

There are two types of functions in C programming:


• Standard library functions
• User defined functions

♦ Standard library functions


The standard library functions are built-in functions in C programming to handle tasks
such as mathematical computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file, these
functions are available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display
output on the screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions are
available for use.

♦ User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created by
the user are called user-defined functions.
Depending upon the complexity and requirement of the program, you can create as many
user-defined functions as you want.

►USES OF FUNCTIONS:

o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
o
►Defining a Function
The general form of a function definition in C programming language is as follows –

returntype function_name( parameter list )


{
body of the function
}

UNIT-III P.SOWMYA SREE Page 1


A function definition in C programming consists of a function header and a function body. Here are
all the parts of a function −
• Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In
this case, the return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function. Parameters are optional;
that is, a function may contain no parameters.
• Function Body − The function body contains a collection of statements that define what the
function does.

►Function Declarations
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.

A function declaration has the following parts − return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows –

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so
the following is also a valid declaration –

int max(int, int);

Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top of the file
calling the function.

►Calling a Function / Function Call


While creating a C function, you give a definition of what the function has to do. To
use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is executed or when
its function-ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.

/*Example program on function*/


#include <stdio.h> Output:
/* function declaration */
int max(int num1, int num2); Max value is :200
main ()
{
/* local variable definition */
UNIT-III P.SOWMYA SREE Page 2
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
}

/* function returning the max between two numbers */


int max(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

►Different aspects of function calling


For better understanding of arguments and return value from the function, user-defined
functions can be categorized as:

• Function with no arguments and no return value


• Function with no arguments and a return value
• Function with arguments and no return value
• Function with arguments and a return value.

1.Function with no arguments and no return value


In this method, We won’t pass any arguments to the function while defining,
declaring or calling the function. This type of functions will not return any value when we call the
function from main() or any sub function. When we are not expecting any return value but, we need
some statements to be printed as output then, this type of functions is very useful.

/*program on factorial of a number without arguments and no return value*/


#include<stdio.h>
void fact();

UNIT-III P.SOWMYA SREE Page 3


main()
{
fact(); Output:
}
void fact() Enter the number:5
{
int f=1,n,i; Factorial of 5 is 120
printf("Enter the number:");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
f = f*i;
}
printf("Factorial of %d is %d", n , f);
}

2.Function with no arguments and a return value


In this method, We won’t pass any arguments to the function while defining, declaring or calling the
function. This type of functions will return some value when we call the function from main() or any sub
function. Data Type of the return value will depend upon the return type of function declaration. For
instance, if the return type is int then return value will be int.

return statement
• A function may or may not return a value. A return statement returns a value to the calling
function and assigns to the variable in the left side of the calling function.
• If a function does not return a value, the return type in the function definition and declaration is
specified as void.
Syntax:

return(expression);

/*program on factorial of a number without arguments and return value*/


#include<stdio.h>
int fact(); Output:
main()
{ Enter the number:5
int f;
f=fact(); Factorial is 120
printf("Factorial is %d", f);
}

UNIT-III P.SOWMYA SREE Page 4


int fact()
{
int f=1,n,i;
printf("Enter the number:");
scanf("%d" ,&n);
for(i = 1; i <= n; i++)
{
f = f*i;
}
return(f);
}

3.Function with arguments and no return value


This method allows us to pass the arguments to the function while calling the function. But, This
type of functions will not return any value when we call the function from main () or any sub function.If
we want to allow our user to pass his own data to the function arguments but we are not expecting any
return value then, this type of functions are very useful.

/*program on factorial of a number withargumentsand no return value*/

#include<stdio.h>
void fact(int,int);
main()
{
int f=1,n;
printf("Enter the number:");
scanf("%d",&n); Output:
fact(n,f);
} Enter the number:5
void fact(intn,int f)
{ Factorial of 5 is 120
int i;
for(i = 1; i <= n; i++)
{
f = f*i;
}
printf("Factorial of %d is %d", n , f);
}

4.Function with arguments and a return value.


This method allows us to pass the arguments to the function while calling the function.
This type of functions will return some value when we call the function from main () or any sub
UNIT-III P.SOWMYA SREE Page 5
function. Data Type of the return value will depend upon the return type of function declaration. For
instance, if the return type is int then return value will be int.
This type of user defined functions are called as fully dynamic function means, it provide maximum
control to the end user.

/*program on factorial of a number with arguments and return value*/


#include<stdio.h>
int fact(int,int);
main()
{
int f=1,n;
printf("Enter the number:");
scanf("%d",&n);
printf("Factorial of %d is %d", n , fact(n,f)); Output:
}
int fact(int n,int f) Enter the number:5
{
int i; Factorial of 5 is 120
for(i = 1; i <= n; i++)
{
f = f*i;
}
return(f);

Actual Parameters: Actual Parameters are those, which are specified at the time of
function calling.

Formal Parameters: Formal Parameters are those, which are defined in the function
declaration and function definition.

 Call By Value
This is the safest way to call the functions. In this method, Values of the declared variables are passed as
the parameters to the function. When we pass the values to the function,
• Compiler is actually making a clone or copy of the original value and then passing that clone
values to the function instead of original values.
• So, Any changes made to the values of the variables inside function does not reflect the original
values.

UNIT-III P.SOWMYA SREE Page 6


/* Call By Value in C Example */

#include <stdio.h>
void CallByValue(int , int );
int main()
{
int a, b;
printf ("\nPlease Enter 2 Integer Values\n");
scanf("%d %d", &a, &b);
printf("\nBefore Calling CallByValue() Function A = %d and B = %d", a, b);
CallByValue(a, b);
printf(" \nAfter Calling CallByValue From Main() A = %d and B = %d", a, b);
}

voidCallByValue(int a, int b)
{
a = a * 10;
b = b * 20;
printf(" \nFrom the CallByValue() Function A = %d and B = %d", a, b);
}

Output:

Please Enter 2 Integer Values

10

20

Before Calling CallByValue() Function A = 10 and B = 20

From the CallByValue() Function A = 100 and B = 400

After Calling CallByValue From Main() A = 10 and B = 20

Call By Reference
In this method, Address of the declared variables are passed as the parameters to the function. When we
pass the address of the variable to the function,
• Function is actually accessing the address of the original value (Referring the address).
• So, Any changes made to the values of the variables inside function means we are actually
changing the original values.

/* Call By Reference in C Example */

#include <stdio.h>
void Swap(int *, int *);
int main()
{
int a, b;
UNIT-III P.SOWMYA SREE Page 7
printf ("Please Enter 2 Integer Values");
scanf("%d %d", &a, &b);
printf("\nBefore Swap A = %d and B = %d", a, b);
Swap(&a, &b);
printf(" \nAfter Swapping From Main() A = %d and B = %d", a, b);
}

void Swap(int *x, int *y)


{
int Temp;
Temp = *x;
*x = *y;
*y = Temp;
printf(" \nAfter Swapping from swap() A = %d and B = %d", *x, *y);
}

Output:

Please Enter 2 Integer Values 10 20

Before Swap A = 10 and B = 20

After Swapping From swap() A = 20 and B = 10

After Swapping From Main() A = 20 and B = 10

Difference between Call by Value and Call by Reference.

Call by Value Call by Reference


The actual arguments can be variable or The actual arguments can only be variable.
constant.
The values of actual argument are sent to formal The reference of actual argument are sent to
argument which are normal variables. formal argument which are pointer variables.
Any changes made by formal arguments will not Any changes made by formal arguments will
reflect to actual arguments. reflect to actual arguments.

Passing Arrays as Function Arguments:


Arrays can also be arguments of functions. When an array is passed to a function, the address of
the array is passed and not the copy of the complete array. Therefore, when a function is called with the
name of the array as the argument, address to the first element in the array is handed over to the
function. Hence when an array is a function argument, only the address of the array is passed to the
function called. This implies that during its execution the function has the ability to modify the contents
of the array that is specified as the function argument. Therefore, the array is not passed to a function by
value.

UNIT-III P.SOWMYA SREE Page 8


Syntax:
returntype function_name(type arrayname[],type size)
{
//function definition
}

/*Example program on Passing Arrays as Function Arguments*/


#include<stdio.h>
void fun(int [],int); Output:
main() enter the size:5
{ Enter the array elements :
int arr[5],i,n; 1
printf("enter the size:"); 2
scanf("%d",&n); 3
printf("\nEnter the array elements : ");
4
for(i=0;i< n;i++)
scanf("%d",&arr[i]); 5s
printf("\nPassing entire array ....."); Passing entire array .....
fun(arr,n); // Pass only name of array After Function call a[0] :11
for(i=0;i<n;i++) After Function call a[1] :12
printf("\nAfter Function call a[%d] : %d",i,arr[i]); After Function call a[2] :13
} After Function call a[3] :14
void fun(intarr[],int n) After Function call a[4] :15
{
int i;
for(i=0;i<n;i++)
arr[i] = arr[i] + 10;
}

Scope of a variable:
A scope is a region of a program. Variable Scope is a region in a program where a variable is
declared and used.

►Storage Classes in C
Storage Classes defines the scope and life time of variable declare in a function.Types of Storage
Classes
• Auto ( Automatic ) or Local Variable
• Static variable
• Extern ( External ) or Global Variable
• Register Variable

1.auto ( Automatic ) or Local Variable


o The variables declared inside the function are automatic or local variables.
o The local variables exist only inside the function in which it is declared.
o When the function exits, the local variables are destroyed.
o The auto keyword is optional, there is no need to write it.
o If not initialized auto variables have garbage value.

UNIT-III P.SOWMYA SREE Page 9


Syntax auto datatype var_name;
Example: auto int a;

main()
{
int n; // n is a local variable to main() function
... .. ...
}
void func()
{
int n1; // n1 is local to func() function
}

In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed
when main() exits.

/*Example program on auto variable*/


#include<stdio.h> Output :
void display();
main() A : 10
{ A : 20
auto int a=10; //OR int a=10; A : 10
printf("\nA : %d",a);
display();
printf("\nA : %d",a);
}
void display()
{
int a=20; //OR auto int a=20;
printf("\nA : %d",a);
}

2. static Variable:
Static variable also have local scope as automatic variables. During multiple calling static
variables retains their previous value.
• We must declare variable as static.
• Static variables can't be accessed outside the function.
• If not initialized static variables have zero as initial value.

Syntax of static storage class
static Data-type Variable-name;

/*Example of static storage class*/


#include<stdio.h>
void display();
main()
{
display();
display();
UNIT-III P.SOWMYA SREE Page 10
display(); Output :
}
void display() A:1
{ A:2
static int a=1; A:3
printf("\nA : %d",a);
a++;
}

In the above example, we does not use static keyword then the output will be :
Output :
A:1
A:1
A:1

3. extern ( External ) or Global Variable


• Variables that are declared outside of all functions are known as external variables. External or
global variables are accessible to any function.The extern keyword is optional, there is no need
to write it.
• The scope of external variable is the entire program.
• If not initialized external variable is assigned a zero value.
• The value is not lost after the execution of function.
• One function can assign value and another can display the value.

Syntax of external storage class or global variable

extern Data-type Variable-name;

OR

Data-type Variable-name;

Example of external storage class or global variable

#include<stdio.h>
void display();
int a=10; //global variable
main()
{
printf("\nA : %d",a); Output :
increment();
display(); A : 10
printf("\nA : %d",a); A : 20
} A : 20

UNIT-III P.SOWMYA SREE Page 11


void increment()
{
a = 20;
}
void display()
{
printf("\nA : %d",a);
}

4. register variables:
Register variables have local scope as automatic variables. They are declared within
motherboard's register memory. All the arithmetic and logical operations are carried out within these
registers.
• These variables are stored in registers. If registers are not available values are stored in main
memory.
• Register variables works faster then other kind of variables because register memory is fatser
then main memory.
• Address operator '&' can't be used with these variables.
• Pointer to register variables are not allowed.
• These variables are used for loops to increase efficiency.
Syntax of register storage class
register Data-type Variable-name;

Example of register storage class


Output :
#include<stdio.h>
main() A : 10
{
registerint a=10;
printf("\nA : %d",a);
}

Inline Functions:
The inline function can be substituted at the place where the function call is happening. Function
substitution is always compiler choice.
• In an inline function, a function call is replaced by the actual program code.
• Most of the Inline functions are used for small computations. They are not suitable for large
computing.
• An inline function is similar to a normal function. The only difference is that we place a keyword
inline before the function name.

Syntax:
inline function_name ()
{
//function definition
}

UNIT-III P.SOWMYA SREE Page 12


/*Example program on Inline Function*/
#include<stdio.h>
inline int mul(int a, int b) //inline function declaration
{
return(a*b); Output:
}
void main() Multiplication:6
{
int c;
c=mul(2,3);
printf("Multiplication:%d\n",c);
}

 Recursion in C
When a function calls itself from its body is called Recursion.
Advantages
• Reduce unnecessary calling of function.
• Through Recursion one can Solve problems in easy way while its iterative solution is very big
and complex.
/*factorial of a number using recursion*/
#include<stdio.h>
long Factorial(int);
main() Output :
{
int num; Enter any positive number :10
long fact;
printf("\n\tEnter any positive number : "); The Factorial of 10 is 3628800
scanf("%d",&num);
fact = Factorial(num);
printf("\n\tThe Factorial of %d is %ld",num,fact);
}
long Factorial(intnum)
{
if (num == 1)
return 1;
else
return num*Factorial(num-1);
}

UNIT-III P.SOWMYA SREE Page 13


Chapter-II
Pointers

Introduction to Pointers

A pointer is a derived data type in C. It is built from one of the fundamental data types available
in C. A Pointer is a variable that holds address of another variable of same data type.

Benefits of using pointers


• Pointers are more efficient in handling Array and Structure.
• Pointer allows references to function and thereby helps in passing of function as arguments to other
function.
• It reduces length of the program and its execution time.
• It allows C to support dynamic memory management.

Address of Operator (&)


An address-of operator is a mechanism within C that returns the memory address of a variable.
These addresses returned by the address-of operator are known as pointers, because they "point" to the
variable in memory.
The address-of operator is a unary operator represented by an ampersand (&). It is also known
as an address operator.

Pointer concept

Whenever a variable is declared in the program, system allocates a location i.e an address to that
variable in the memory, to hold the assigned value. This location has its own address number.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10 ;

We can access the value 10 by either using the variable name a or the address 80F. Since the memory
addresses are simply numbers they can be assigned to some other variable. The variable that holds
memory address are called pointer variables.
A pointer variable is therefore nothing but a variable that contains an address, which is a location of
another variable. Value of pointer variable will be stored in another memory location.

UNIT-III P.SOWMYA SREE Page 14


►Declaring a pointer variable
General syntax of pointer declaration is,

data-type *pointer_name;

Example: int *p;

Data type of a pointer must be same as the data type of a variable to which the pointer variable is
pointing. void type pointer works with all data types, but is not used often used.

►Initialization of Pointer variable

Pointer Initialization is the process of assigning address of a variable


to pointer variable. Pointer variable contains address of variable of same data type. In C
language address operator & is used to determine the address of a variable. The & (immediately
preceding a variable name) returns the address of the variable associated with it.

int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together

Pointer variable always points to same type of data.

float a;
int *ptr;
ptr = &a; //ERROR, type mismatch

►Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of
variable, pointer is dereferenced, using the indirection operator *.

int a,*p;
a = 10;
p = &a;

printf("%d",*p); //this will print the value of a.

printf("%d",*&a); //this will also print the value of a.

printf("%d",&a); //this will print the address of a.

printf("%d",p); //this will also print the address of a.

printf("%d",&p); //this will print the address of p.

UNIT-III P.SOWMYA SREE Page 15


/*Example program on pointer*/
#include<stdio.h>
main()
{ Output
int a=10,*p; value of a=10
p=&a; Address of a=6487628
printf("value of a=%d",a); value of p=6487628
printf("\nAddress of a=%d",&a); address of p=6487616
printf("\nvalue of p=%d",p); value of a=10
printf("\naddress of p=%d",&p);
printf("\nvalue of a=%d",*p);
}

Arrays and Pointers / pointer to an Array


When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also allocated by the
compiler.

Suppose we declare an array arr,


int arr[5]={ 1, 2, 3, 4, 5 };

Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will
be stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing to the element,arr[0].
Therefore arr is containing the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name of
an array and it acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] //by default

We can declare a pointer of type int to point to the array arr.


int *p;
p = arr;
or
p = &arr[0]; //both the statements are equivalent.

Now we can access every element of array arr using p++ to move from one element to
another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.

UNIT-III P.SOWMYA SREE Page 16


Example
#include<stdio.h>
main()
{
int arr []={78,45,12,89,56,23,79,46,13,82},a; // Array of 10 elements
int *ptr; // Pointer variable

ptr = arr; // Assigning reference of array in


// pointer variable

printf("\nValues : ");
for(a=1;a<=10;a++)
{
printf("%d, ",*ptr); // Displaying values of array
// using pointer
ptr++; // Incrementing pointer variable
}
}
Output:

Values : 78, 45, 12, 89, 56, 23, 79, 46, 13, 82,

Pointers and Strings:


The variable name of the string holds the address of the first element of the array i.e., it points at
the starting memory address.
So, we can create a character pointer and store the address of the string variable in it.

Syntax:
char var[size]=”value”;
char *ptr;

Example:
char str[6]=”Hello”
char *ptr;
ptr=str;

UNIT-III P.SOWMYA SREE Page 17


Example:
#include <stdio.h>
main() Output:
{
Hello
// string variable
char str[6] = "Hello";

// pointer variable
char *ptr = str;

// print the string


while(*ptr != '\0') // for(a=1;a<=6;a++)
{
printf("%c", *ptr);

// move the ptr pointer to the next memory location


ptr++;
}
}

Pointer to Pointer:
A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer
contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the
address of the second pointer, which points to the location that contains the actual value as shown
below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer
of type int:

int **var;

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that
the asterisk operator be applied twice, as is shown below in the example:

#include <stdio.h> Output:


main ()
{ Value of var :3000
int var; Value available at *ptr :3000
int *ptr; Value available at **pptr :3000
int **pptr;

UNIT-III P.SOWMYA SREE Page 18


var = 3000; // take the address of var
ptr = &var; // take the address of ptr using address of operator &
pptr = &ptr; // take the value using pptr
printf( "Value of var :%d\n",var);
printf( "Value available at *ptr :%d\n”, *ptr);
printf( "Value available at **pptr :%d" ,**pptr );
}

Array of Pointer:

Array is a collection of values of similar type. It can also be a collection of references of similar type.

Syntax Data-type * array [size];

Example:
#include<stdio.h>
main()
{
int x=10,y=20,z=30;
int *arr[3],a; // Declaring array of three pointer
arr[0] = &x; // Assigning reference of x to array 0th position
arr[1] = &y; // Assigning reference of y to array 1th position
arr[2] = &z; // Assigning reference of z to array 2nd position
printf("\nValues : "); Output:
for(a=0;a<3;a++)
printf("%d, ",*arr[a]);
Values : 10, 20, 30,
}

Dynamic Memory Allocation


In C, the exact size of array is unknown until compile time, i.e., the time when a compiler
compiles your code into a computer understandable language. So, sometimes the size of the array can be
insufficient or more than required.
Dynamic memory allocation allows your program to obtain more memory space while running, or to
release it if it's not required.
In simple terms, Dynamic memory allocation allows you to manually handle memory space for your
program.

Function Use of Function

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

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

free() deallocate the previously allocated space

realloc() Change the size of previously allocated space

UNIT-III P.SOWMYA SREE Page 19


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

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

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.

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

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

UNIT-III P.SOWMYA SREE Page 20


Unit – IV
Chapter-I
User-defined Data Types

Structure

A Structure is commonly referred to as user-defined data type. Structure is similar to an


array but the only difference is that array is collection of similar data type on the other hand
structure is collection of different data type. A structure can contain any data type including array
and another structure as well. Each variable declared inside structure is called member of
structure.

►Structure declaration and its members


Declaration of structure must start with the keyword struct followed by the structure name
and structure's member variables are declared within braces.

Syntax

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

Example:

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

►Declaring Structure variable:


Defining a structure like creating and naming a new data type. Memory is allocated to the
member variables of structure when structure variables are declared

Syntax:
struct struct-name variable1, variable2…;
Or
Structure variable can be declared while creating the structure

P.Sowmya Sree Unit-III Page 1


Syntax:
struct struct-name
{
datatype variable1;
datatype variable2;
……………….
……………….
} variable1, variable2;

Example:
struct Employee e1,e2;
or
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
}e1,e2;

► Initialization of structure:
Like normal variable structures can be initialized at the time of declaration. Initialization of
structure is almost similar to initializing array. The structure object is followed by equal sign and
the list of values enclosed in braces and each value is separated with comma.

Syntax:
struct struct-name var_name={values….};
or
var_name.member=value;

Example:
struct Employeee E1={ 2,"Suresh",35,35000};
or
E1.Id=2;
E1.Name=”Suresh”;

/*Example Program */ Output:


#include<stdio.h>
struct Employee Employee Id : 1
{ Employee Name : Kumar
int Id; Employee Age : 29
char Name[25]; Employee Salary : 45000
int Age;
long Salary;
};
main()
{
struct Employee E = {2,"Suresh",35,35000};

P.Sowmya Sree Unit-III Page 2


printf("\n\nEmployee Id : %d",E.Id);
printf("\nEmployee Name : %s",E.Name);
printf("\nEmployee Age : %d",E.Age);
printf("\nEmployee Salary : %ld",E.Salary);
}

► Accessing the structure members


We have to create an object of structure to access its members. Object is a variable
of type structure. Structure members are accessed using the dot operator(.) between structure's
object and structure's member name.

Syntax
struct struct-name obj;

/* Example for creating object & accessing structure members*/


#include<stdio.h>
struct Employee
Output:
{
int Id; Enter Employee Id : 1
char Name[25]; Enter Employee Name : Kumar
int Age; Enter Employee Age : 29
long Salary; Enter Employee Salary : 45000
};
main() Employee Id : 1
{ Employee Name : Kumar
struct Employee E; //Statement 1 Employee Age : 29
printf("\nEnter Employee Id : "); Employee Salary : 45000
scanf("%d",&E.Id);

printf("\nEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\nEnter Employee Age : ");


scanf("%d",&E.Age);

printf("\nEnter Employee Salary : ");


scanf("%ld",&E.Salary);

printf("\n\nEmployee Id : %d",E.Id);
printf("\nEmployee Name : %s",E.Name);

printf("\nEmployee Age : %d",E.Age);

printf("\nEmployee Salary : %ld",E.Salary);


}

P.Sowmya Sree Unit-III Page 3


►Array of Structure
Structure is collection of different data type. An object of structure represents a single
record in memory, if we want more than one record of structure type, we have to create an
array of structure or object. As we know, an array is a collection of similar type, therefore an
array can be of structure type.

Syntax struct struct-name


{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

struct struct-name obj [ size ];

/* Example for declaring structure array*/


Output:
#include<stdio.h> Enter details of 1 Employee
struct Employee Enter Employee Id : 101
{ Enter Employee Name : Suresh
int Id; Enter Employee Age : 29
char Name[25]; Enter Employee Salary : 45000
int Age;
long Salary; Enter details of 2 Employee
}; Enter Employee Id : 102
main() Enter Employee Name : Mukesh
{ Enter Employee Age : 31
int i; Enter Employee Salary : 51000
struct Employee Emp[ 3 ]; //Statement 1
Enter details of 3 Employee
for(i=0;i<3;i++) Enter Employee Id : 103
{ Enter Employee Name : Ramesh
Enter Employee Age : 28
printf("\nEnter details of %d Employee",i+1); Enter Employee Salary : 47000

Details of Employees
printf("\n\tEnter Employee Id : ");
101 Suresh 29 45000
scanf("%d",&Emp[i].Id);
102 Mukesh 31 51000
103 Ramesh 28 47000
printf("\n\tEnter Employee Name : ");
scanf("%s",&Emp[i].Name);

printf("\n\tEnter Employee Age : ");


scanf("%d",&Emp[i].Age);

printf("\n\tEnter Employee Salary : ");


scanf("%ld",&Emp[i].Salary);

P.Sowmya Sree Unit-III Page 4


}

printf("\nDetails of Employees");
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);

Union

Both structure and union are collection of different datatype. They are used to
group number of variables of different type in a single unit.

►Union declaration
Declaration of union must start with the keyword union followed by the union name and
union's member variables are declared within braces.
Syntax:
union union-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

Example:

Union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

►Declaring Union variable:

Defining an union like creating and naming a new data type. Memory is allocated to the
member variables of union when union variables are declared

Syntax:
union union -name variable1, variable2…;
Or
union variable can be declared while creating the union

P.Sowmya Sree Unit-III Page 5


Syntax:
union union -name
{
datatype variable1;
datatype variable2;
……………….
……………….
} variable1, variable2;

Example:
union Employee e1,e2;
or
union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
}e1,e2;

► Initialization of union:
Like normal variable union can be initialized at the time of declaration. Initialization of
union is almost similar to initializing array.
Syntax:
var_name.member=value;
Example:
E1.Id=2;

/*Example Program */ Output:


#include<stdio.h>
union Employee Employee Id : 101
{ Employee Name : Suresh
int Id; Employee Age : 25
char Name[25]; Employee Salary : 35000
int Age;
long Salary;
};
main()
{
union Employee E;
E.Id=101;
printf("\n\nEmployee Id : %d",E.Id);
strcpy(E.Name,"Suresh");
printf("\nEmployee Name : %s",E.Name);
E.Age=25;
printf("\nEmployee Age : %d",E.Age);
E.Salary=35000;
printf("\nEmployee Salary : %ld",E.Salary);
}

P.Sowmya Sree Unit-III Page 6


►Accessing the union members
We have to create an object of union to access its members. Object is a variable of
type union. Union members are accessed using the dot operator(.) between union's object and
union's member name.

Syntax
union union-name obj;

Example Output:

#include<stdio.h> Enter Employee Id : 1


union Employee Employee Id : 1
{
int Id; Enter Employee Name : Kumar
char Name[25]; Employee Name : Kumar
int Age;
long Salary; Enter Employee Age : 29
}; Employee Age : 29
main()
{ Enter Employee Salary : 45000
Employee Salary : 45000
union Employee E;

printf("\nEnter Employee Id : ");


scanf("%d",&E.Id);
printf("Employee Id : %d",E.Id);

printf("\n\nEnter Employee Name : ");


scanf("%s",&E.Name);
printf("Employee Name : %s",E.Name);

printf("\n\nEnter Employee Age : ");


scanf("%d",&E.Age);
printf("Employee Age : %d",E.Age);

printf("\n\nEnter Employee Salary : ");


scanf("%ld",&E.Salary);
printf("Employee Salary : %ld",E.Salary);

/*Example of comparing size of union and structure*/


#include<stdio.h> Output:
struct Employee1
{ Size of Employee1 is : 31
int Id;
char Name[25]; Size of Employee2 is : 25
long Salary;
}E1;

P.Sowmya Sree Unit-III Page 7


union Employee2
{
int Id;
char Name[25];
long Salary;
}E2;

void main()
{
printf("\nSize of Employee1 is : %d",sizeof(E1));
printf("\nSize of Employee2 is : %d",sizeof(E2));
}

►Difference between Structure and Union:

S.No Structure Union


1. The struct keyword is used to define a The union keyword is used to define
structure. union.
2. Syntax of declare a Structure in C is as syntax of declare a Union in C is as
follow : follow:
struct struct_name{ union u_name{
type element1; type element1;
type element2; type element2;
. .
. .
} variable1, variable2, ...; } variable1, variable2, ...;
3. When the variables are declared in a When the variable is declared in the
structure, the compiler allocates memory union, the compiler allocates memory to
to each variables member. The size of a the largest size variable member. The
structure is equal or greater to the sum of size of a union is equal to the size of its
the sizes of each data member. largest data member size.
4 The structure allows initializing multiple Union allows initializing only one
variable members at once. variable member at once.
5. It is used to store different data type It is used for storing one at a time from
values. different data type values.

►Enumeration Types
The enum in C is also known as the enumerated type. It is a user-defined data type that
consists of integer values, and it provides meaningful names to these values. The use of enum in
C makes the program easy to understand and maintain. The enum is defined by using the enum
keyword.

syntax

enum enum_name{const1, const2, ....... };

Example:
enum fruits{mango, apple, strawberry, papaya};

P.Sowmya Sree Unit-III Page 8


The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3. If we want to
change these default values, then we can do as given below:

enum fruits{ mango=2, apple=1, strawberry=5, papaya=7, };

/* Example program on enum data type*/


#include<stdio.h>

main()
{
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};

printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur,


Fri, Sat, Sun);

printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn,


Thurs, Frid, Satu, Sund);

}
Output:

The value of enum week: 10 11 12 13 10 16 17

The default value of enum day: 0 1 2 3 18 11 12

P.Sowmya Sree Unit-III Page 9


Chapter –II
Files

A file represents a sequence of bytes, regardless of it being a text file or a binary file. C
programming language provides access on high level functions as well as low level (OS level)
calls to handle file on your storage devices.

►Types of Files
When dealing with files, there are two types of files you should know about:

Text files
Binary files

1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.

When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.

2. Binary files
Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold a higher amount of data, are not readable easily, and provides better security than
text files.

►Working with files


When working with files, you need to declare a pointer of type file. This declaration is needed
for communication between the file and the program.

FILE *fptr;

► File Operations
In C, you can perform four major operations on files, either text or binary:

1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file

P.Sowmya Sree Unit-III Page 10


 Opening a file - for creation and edit
Opening a file is performed using the fopen() function defined in the stdio.h header file.

The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode");

Opening Modes in Standard I/O

Mode Meaning of Mode During Inexistence of file


r Open for reading. If the file does not exist,
fopen() returns NULL.
rb Open for reading in binary If the file does not exist,
mode. fopen() returns NULL.
w Open for writing. If the file exists, its contents
are overwritten.
If the file does not exist, it
will be created.
wb Open for writing in binary If the file exists, its contents
mode. are overwritten.
If the file does not
exist, it will be created.
a Open for append. Data is added to the end of
the file.
If the file does not exist, it
will be created.
ab Open for append in binary Data is added to the end of
mode. the file. If the file
does not exist, it will be
created.
r+ Open for both reading and If the file does not exist,
writing. fopen() returns NULL.
rb+ Open for both reading and If the file does not exist,
writing in binary mode. fopen() returns NULL.

w+ Open for both reading and If the file exists, its contents
writing. are overwritten.
If the file does not exist, it
will be created.
wb+ Open for both reading and If the file exists, its contents
writing in binary mode. are overwritten.
If the file does not exist, it
will be created.
a+ Open for both reading and If the file does not exist, it
appending. will be created.
ab+ Open for both reading and If the file does not exist, it
appending in binary mode. will be created.

P.Sowmya Sree Unit-III Page 11


For example
fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first
function creates a new file named newprogram.txt and opens it for writing as per the mode 'w'.

The writing mode allows you to create and edit (overwrite) the contents of the file.

Now let's suppose the second binary file oldprogram.bin exists in the location E:\cprogram. The
second function opens the existing file for reading in binary mode 'rb'.

The reading mode only allows you to read the file, you cannot write into the file.

Closing a File
The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.


fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf()

They are just the file versions of printf() and scanf(). The only difference is that fprint() and
fscanf() expects a pointer to the structure FILE.

Example 1: Write to a text file


#include <stdio.h>
main()
{
int num;
FILE *fptr;
Output:
// use appropriate location if you are using MacOS or Linux
fptr = fopen("C:\program.txt","w"); Enter num:25

if(fptr == NULL)
{
printf("Error!");
}

P.Sowmya Sree Unit-III Page 12


printf("Enter num: ");
scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);
}
This program takes a number from the user and stores in the file ” program.txt.”

After you compile and run this program, you can see a text file “program.txt” created in C drive
of your computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file


#include <stdio.h>
main()
{ Output:
int num;
FILE *fptr; Value of num=25
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file");

// Program exits if the file pointer returns NULL.


}

fscanf(fptr,"%d", &num);

printf("Value of num=%d", num);


fclose(fptr);
}
This program reads the integer present in the “program.txt” file and prints it onto the screen.

If you successfully created the file from Example 1, running this program will get you the integer
you entered.

Other functions like fgetw, fputc() etc. can be used in a similar way.

►Working with Binary Files


Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.

♦Writing to a binary file


To write into a binary file, you need to use the fwrite() function. The functions take four
arguments:
• address of data to be written in the disk
• size of data to be written in the disk
• number of such type of data
• pointer to the file where you want to write.

P.Sowmya Sree Unit-III Page 13


fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 1: Write to a binary file using fwrite()


#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


}

for(n = 1; n < 5; ++n)


{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
}
In this program, we create a new file “program.bin” in the C drive.

We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main
function as num.

Now, inside the for loop, we store the value into the file using fwrite().

The first parameter takes the address of num and the second parameter takes the size of the
structure threeNum.

Since we're only inserting one instance of num, the third parameter is 1. And, the last parameter
*fptr points to the file we're storing the data.

Finally, we close the file.

♦Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as above.

P.Sowmya Sree Unit-III Page 14


fread(addressData, sizeData, numbersData, pointerToFile);

Example 2: Read from a binary file using fread()


#include <stdio.h>

struct threeNum
{
int n1, n2, n3;
};

main()
{ Output
int n;
n1: 1 n2: 5 n3: 6
struct threeNum num;
FILE *fptr; n1: 2 n2: 10 n3: 11

if ((fptr = fopen("C:\\program.bin","rb")) == NULL) n1: 3 n2: 15 n3: 16


{
printf("Error! opening file"); n1: 4 n2: 20 n3: 21

// Program exits if the file pointer returns NULL.


}

for(n = 1; n < 5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);

}
In this program, you read the same file “program.bin” and loop through the records one by one.

In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr
into the structure num.

You'll get the same records you inserted in Example 1.

►Random Access to Files of Records

There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.

1. fseek()
2. ftell()
3. rewind()

P.Sowmya Sree Unit-III Page 15


fseek():
The fseek() function is used to set the file pointer to the specified offset. It is
used to write data into file at desired location.

Syntax: int fseek(FILE *stream, long int offset, int whence)

There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR
and SEEK_END.

Example:

#include <stdio.h>
main()
{ myfile.txt
FILE *fp;
This is sonoo jaiswal
fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);

fseek( fp, 7, SEEK_SET );


fputs("sonoo jaiswal", fp);
fclose(fp);
}

 ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell()
function to get the total size of a file after moving file pointer at the end of file. We can use
SEEK_END constant to move the file pointer at the end of file.

Syntax:
long int ftell(FILE *stream)

Example:
#include <stdio.h>
main () Output:
{
FILE *fp; Size of file: 21 bytes
int length;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);

length = ftell(fp);

fclose(fp);
printf("Size of file: %d bytes", length);
}

 rewind() function

P.Sowmya Sree Unit-III Page 16


The rewind() function sets the file pointer at the beginning of the stream. It is useful if you
have to use stream many times.

Syntax: void rewind(FILE *stream)

Example:

File: file.txt
Output
this is a simple text
this is a simple textthis is a simple text
File: rewind.c

#include<stdio.h>
main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");

while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}

rewind(fp);//moves the file pointer at beginning of the file

while((c=fgetc(fp))!=EOF){
printf("%c",c);
}

fclose(fp);
}

As you can see, rewind() function moves the file pointer at beginning of the file that is why "this
is simple text" is printed 2 times. If you don't call rewind() function, "this is simple text" will be
printed only once.

►file management functions

P.Sowmya Sree Unit-III Page 17


Following are the most important file management functions available in 'C,'

function Purpose

fopen () Creating a file or opening an existing file

fclose () Closing a file

fprintf () Writing a block of data to a file

fscanf () Reading a block data from a file

fgetc () Reads a single character from a file

fputc () Writes a single character to a file

getw () Reads an integer from a file

putw () Writing an integer to a file

fseek () Sets the position of a file pointer to a specified location

ftell () Returns the current position of a file pointer

rewind () Sets the file pointer at the beginning of a file

fprintf() function

The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.

Syntax :

int fprintf(FILE *stream, const char *format [, argument, ...])

Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello friend !\n");//writing data into file
fclose(fp);//closing file
}
 fscanf() function
The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.

P.Sowmya Sree Unit-III Page 18


Syntax:
int fscanf(FILE *stream, const char *format [, argument, ...])

Example:
#include <stdio.h> Output:
main()
{ Hello friend !
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}

 fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a
stream.

Syntax:
int fputc(int c, FILE *stream)
Example:
file1.txt
#include <stdio.h>
main() a
{
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}

 fgetc() function

The fgetc() function returns a single character from the file. It gets a character from the stream.
It returns EOF at the end of file.

Syntax:
int fgetc(FILE *stream)
Example:

#include<stdio.h>
main() Output:
{
FILE *fp; a
char c;

P.Sowmya Sree Unit-III Page 19


fp=fopen("file1.txt","r");

while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
}

putw() function
The putw() function is used to write integers to the file.

Syntax
putw(int number, FILE *fp);

The putw() function takes two arguments, first is an integer value to be written to the file and
second is the file pointer where the number will be written.

Example
#include<stdio.h>
main()
{ Output:
FILE *fp;
int num; Enter any number :59
char ch='n';

fp = fopen("file3.txt","w"); //Statement 1

if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");

printf("\nEnter any number : ");


scanf("%d",&num);

putw(num,fp);

fclose(fp);
}

 getw() function
The getw() function is used to read integer value form the file.

Syntax of getw() function

int getw(FILE *fp);

P.Sowmya Sree Unit-III Page 20


The getw() function takes the file pointer as argument from where the integer value will be read
and returns returns the end-of-file if it has reached the end of file.

Example

#include<stdio.h>

void main()
{
FILE *fp;
int num; Output:

fp = fopen("file3.txt","r"); //Statement 1 Data in file...


if(fp == NULL)
{ 52
printf("\nCan't open file or file doesn't exist.");
exit(0);
}

printf("\nData in file...\n");

while((num = getw(fp))!=EOF) //Statement 2


printf("\n%d",num);

fclose(fp);
}

fwrite() and fread()—refer to working with binary files above

P.Sowmya Sree Unit-III Page 21


BSc Ist Year (sem I)
Computer Science
Lab Programs (Record)

1.Write a program to find the largest two (three) numbers using if and conditional
operator

#include<stdio.h>
main()
{
int a, b, res;
printf("Enter two numbers : ") ;
scanf("%d %d ", &a, &b) ;
res=a>b?a:b>a?b:-1;
if(res==-1)
printf("\nThe two numbers are equal”) ;
else
printf(“\n The larger number is %d”,res);
}

Output:
Enter two numbers :
40
50
The larger number is 50

2. Write a program to print the reverse of a given number.

#include<stdio.h>
main()
{
int n,sum = 0,rem,m;
printf("\nEnter a Number:\t");
scanf("%d", &n);
m= n;
while(n > 0)
{
rem = n%10;
sum = (sum*10) + rem;
n = n/10;
}
printf("\nReverse of %d:\t%d\n", m, sum);
}
Output:

Enter a Number: 456

Reverse of 456: 654

1
Computer Science Sem-1
3. Write a program to print the prime number from 2 to n where n is given by user

#include<stdio.h>
main()
{
int num,i=1,j,count;
printf("Enter Num value To Print Prime Numbers between 1 and Num: ");
scanf("%d",&num);
printf("Prime Numbers upto %d :\n \n",num);

while(i<=num)
{
count=0;
for(j=1;j<=i;j++)
{
if(i%j==0) //checking whether num is dvisible by j
count++;
}
if(count==2) //if num is divisible by 2 numbers,then it is prime
printf("%d ",i);
i++;
}
printf("\n\n");
}

Output:

Enter Num value To Print Prime Numbers between 1 and Num: 10


Prime Numbers upto 10 :

2357

4. Write a program to find the roots of a quadratic equation using switch statement

#include<stdio.h>
#include<math.h>
main()
{
int flag;
float x, x1, x2;
float a, b, c, d;
float rpart, ipart;
printf("\n Enter 3 numbers: ");
scanf("%f %f %f", &a, &b, &c);
if(a==0)
{
x=-b/c;
printf("\n Only root x : %7.3f", x);
exit();
}
d=(b*b)-(4*a*c);
if(d>0)
flag=1;
2
Computer Science Sem-1
else if(d==0)
flag=2;
else
flag=3;
switch(flag)
{
case 1: printf("\n Real & Distinct roots are: ");
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("\n x1=%7.3f \n x2=%7.3f", x1, x2);
break;

case 2: printf("\n Repeated roots are: ");


x1=-b/(2*a);
x2=x1;
printf("\n x1 & x1 : %7.3f", x1);
break;

case 3: d=sqrt(abs(d));
rpart=-b/(2*a);
ipart=d/(2*a);
printf("\n Complex Roots are: ");
printf("\n x1=%7.3f+i%7.3f", rpart, ipart);
printf("\n x2=%7.3f-i%7.3f", rpart, ipart);
}
}

Output:

Enter 3 numbers:
5
8
4

Complex Roots are:


x1= -0.800+i 0.400
x2= -0.800-i 0.400

5.Write a program to print a triangle of stars as follows (take number of lines from user):

*
***
*****
*******

#include <stdio.h>
main()
{
int i, space, rows, k=0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i, k=0)
{
3
Computer Science Sem-1
for(space=1; space<=rows-i; ++space)
{
printf(" ");
}
while(k != 2*i-1)
{
printf("* ");
++k;
}
printf("\n");
}
}

Output:

Enter number of rows: 5


*
***
*****
*******
*********
6. Write a program to find largest and smallest elements in a given list of numbers.

#include<stdio.h>
main()
{
int a[50],i,n,large,small;
printf("Enter the size of an Array");
scanf("%d",&n);
printf("Enter the Array:");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
large=small=a[0];
for(i=1;i<n;++i)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("The largest element is %d",large);
printf("\nThe smallest element is %d",small);
}
Output:
Enter the size of an Array 5
Enter the Array:
10
50
40
20
30
The largest element is 50
The smallest element is 10
4
Computer Science Sem-1
7. Write a program to find the product of two matrices.

#include <stdio.h>
main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
printf("Enter the elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
}
Output:
Enter the number of rows and columns of first matrix
2
2
Enter the elements of first matrix
1
2
3
4
Enter the number of rows and columns of second matrix
2
2
5
Computer Science Sem-1
Enter the elements of second matrix
2
3
4
5
Product of entered matrices:-
10 13
22 29

8. Write a program to find the GCD of two numbers using iteration and recursion.

a) Using iteration

#include <stdio.h>
main()
{
int n1, n2, i, gcd;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
{
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
}

Output:
Enter two integers:
10
20
G.C.D of 10 and 20 is 10

b) Using Recursion

#include <stdio.h>
int gcd(int n1, int n2);
main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);

printf("G.C.D of %d and %d is %d.", n1, n2, gcd(n1,n2));


}
int gcd(int n1, int n2)
{
if (n2 != 0)
return gcd(n2, n1%n2);
else
return n1;
}
6
Computer Science Sem-1
Output:

Enter two positive integers:


3
15
G.C.D of 3 and 15 is 3.

9. Write a program to illustrate use of storage classes.

#include<stdio.h>
extern int x=9;
int z=10;
main()
{
auto int a=32;
register char b='G';
extern int z;
printf("Hello World!\n");
printf("\n This is the value of the auto integer 'a':%d\n",a);
printf("\n These are the values of the extern integers 'x' and 'z'\n respectively:%d and
%d\n",x,z);
printf("\n This is the value of the \n register character 'b':%c\n",b);
x=2;
z=5;
printf("\n These are the modified values \n of the extern integers 'x' and \n 'z' respectively:%d
and %d \n",x,z);
printf("\n 'y' is a static variable and its \n value is NOT initialized to 5 after \n the first
iteration! see for \n yourself:");
while(x>0)
{
static int y=5;
y++;
printf("The value of y is %d\n",y);
x--;
}
}
Output:

Hello World!

This is the value of the auto integer 'a':32

These are the values of the extern integers 'x' and 'z'
respectively:9 and 10

This is the value of the


register character 'b':G

These are the modified values


of the extern integers 'x' and
'z' respectively:2 and 5

7
Computer Science Sem-1
'y' is a static variable and its
value is NOT initialized to 5 after
the first iteration! see for
yourself:The value of y is 6
The value of y is 7

10. Write a program to demonstrate the call by value and the call by reference concepts

a)Call by Value

#include<stdio.h>
void swap(int,int);
main()
{
int a,b;
printf("Enter any 2 values\n");
scanf("%d%d",&a,&b);
printf("\nBefore swapping a and b values are \n %d \t %d \n",a,b);
swap(a,b);
printf("\nAfter swapping a and b values are \n %d \t %d in main()",a,b);
}
void swap(int a, int b)
{
int temp;
temp =a;
a=b;
b=temp;
printf("\nAfter swapping a and b values are \n %d \t %d \n",a,b);
}

Output:

Enter any 2 values


10
20

Before swapping a and b values are


10 20

After swapping a and b values are


20 10

After swapping a and b values are


10 20 in main()

b)Call by Reference

#include<stdio.h>
void swap(int *,int*);
main()
{
int a,b;
8
Computer Science Sem-1
printf("Enter any 2 values\n");
scanf("%d%d",&a,&b);
printf("\nBefore swapping a and b values are \n %d \t %d \n",a,b);
swap(&a,&b);
printf("\nAfter swapping a and b values are \n %d \t %d in main()",a,b);
}
void swap(int *a, int *b)
{
int temp;
temp =*a;
*a=*b;
*b=temp;
}

Output:
Enter any 2 values
10
20

Before swapping a and b values are


10 20

After swapping a and b values are


20 10 in main()

11. Write a program that prints a table indicating the number of occurrences of each alphabet in
the text entered as command line arguments.

#include<stdio.h>
#include<string.h>
#define max_size 100 //maximum size of a string
int main()
{
char string[max_size];
int i,len;
int occurance[26];
/*Read the text from the user */
printf("Enter any Text\n");
gets(string);
len=strlen(string);
/*Initialized occurances of each character*/
for(i=0;i<26;i++)
{
occurance[i]=0;
}
/*Finding total number of occurrences*/
for(i=0;i<len;i++)
{
if(string[i]>='a' && string[i]<='z')
{
occurance[string[i]-97]++;
}
9
Computer Science Sem-1
else if(string[i]>='A' && string[i]<='Z')
{
occurance[string[i]-65]++;
}
}

/*print the occurrences of all characters*/


printf("\n occurrences of all alphabets in the given text \n");
for(i=0;i<26;i++)
{
if(occurance[i]!=0)
{
printf("%c=%d \n",(i+97),occurance[i]);
}
}
}
Output:

Enter any Text


hi friend how are you ?

occurrences of all alphabets in the given text


a=1
d=1
e=2
f=1
h=2
i=2
n=1
o=2
r=2
u=1
w=1
y=1

12. Write a program to illustrate use of data type enum

#include<stdio.h>
main()
{
enum day
{
sunday,monday,tuesday,wednesday,thursday,
friday,saturday
};
enum day today;
int x;
printf("Enter the day of the week(0-6)\n");
scanf("%d",&x);
today=x;
if(today==sunday || today==saturday)
printf("\n Weekend\n");
else
10
Computer Science Sem-1
printf("Working day\n");
}

Output:

Enter the day of the week(0-6)


5
Working day

13. Write a program to demonstrate use of string functions string.h header file

#include <stdio.h>
#include<string.h>
main()
{
char ch1[10],ch2[10];
char ch3[15]="GoodMorning!";
int len;
printf("Enter the string\n");
scanf("%s",ch1);
len=strlen(ch1);
printf("Number of characters in a given string =%d",len);
strcpy(ch2,ch1);
printf("\n copied string is %s",ch2);
printf("\ncomparision of two strings is %d",strcmp(ch1,ch2));
printf("\nconcatination of two strings ch1 and ch3 %s",strcat(ch1,ch3));
}

Output:

Enter the string


hello
Number of characters in a given string =5
copied string is hello
comparision of two strings is 0
concatination of two strings ch1 and ch3 helloGoodMorning!.

14. Write a program that opens a file and counts the number of characters in a file.
#include<stdio.h>

main() {
char ch;
int count=0;
FILE *fptr;

fptr=fopen("text.txt","w");
if(fptr==NULL) {
printf("File can't be created\a");

exit(0);
}
printf("Enter some text and press enter key:\n");
while((ch=getche())!='\r') {
11
Computer Science Sem-1
fputc(ch,fptr);
}
fclose(fptr);
fptr=fopen("text.txt","r");
printf("\nContents of the File is:");
while((ch=fgetc(fptr))!=EOF) {
count++;
printf("%c",ch);
}
fclose(fptr);
printf("\nThe number of characters present in file is: %d",count);

}
Output:
Enter some text and press enter key:
hello how are you
Contents of the File is:hello how are you
The number of characters present in file is: 18

15. Write a program to create a structure Student containing fields for Roll No., Name, Class,
Year and Total Marks. Create 3 students and store them in a file.

#include<stdio.h>
struct student
{
int rollno;
char name[20];
char class[10];
int year;
int totalmarks;
}
main()
{
struct student s1[3],s2[3];
FILE *fptr;
int i;
fptr=fopen("file.txt","wb");
for(i=0; i<3; ++i) {
fflush(stdin);
printf("Enter roll number:");
scanf("%d",&s1[i].rollno);
printf("Enter your name");
scanf("%s",s1[i].name);
printf("Enter your class");
scanf("%s",s1[i].class);
printf("Enter Year");
scanf("%d",&s1[i].year);
printf("Enter totalmarks");
scanf("%d",&s1[i].totalmarks);
printf("\n");
}
fwrite(s1,sizeof(s1),1,fptr);
fclose(fptr);
12
Computer Science Sem-1
fptr=fopen("file.txt","rb");
fread(s1,sizeof(s1),1,fptr);
for(i=0; i<3; ++i)
{
printf("\n Roll no: %d \n Name: %s \n Class: %s \n Year:%d\n
Totalmarks:%d\n",s1[i].rollno,s1[i].name,s1[i].class,s1[i].year,s1[i].totalmarks);
}
fclose(fptr);

}
Output:

enter 1 student details


Enter roll number:45
Enter your name:AAA
Enter your class:MPCs
Enter Year:2020
Enter totalmarks:541

enter 2 student details


Enter roll number:68
Enter your name:BBB
Enter your class:MSCs
Enter Year:2021
Enter totalmarks:650

enter 3 student details


Enter roll number:84
Enter your name:CCC
Enter your class:MECs
Enter Year:2022
Enter totalmarks:490

Roll no: 45
Name: AAA
Class: MPCs
Year:2020
Totalmarks:541

Roll no: 68
Name: BBB
Class: MSCs
Year:2021
Totalmarks:650

Roll no: 84
Name: CCC
Class: MECs
Year:2022
Totalmarks:490

13
Computer Science Sem-1
16. Write a program that opens an existing text file and copies it to a new text file with all
lowercase letters changed to capital letters and all other characters unchanged.

#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("d:\myfile.txt","r");
if(fp1==NULL)
{
puts("\n cannot open file:");
exit(1);
}
fp2=fopen("d:\myfile1.txt","w");
if(fp2==NULL)
{
puts("\n Not able to open file:");
exit(1);
fclose(fp2);
}
do
{
ch=fgetc(fp1);
ch=toupper(ch);
fputc(ch,fp2);
}while(ch!=EOF);
fcloseall();

}
Note: The text in “myfile.txt” is copied into “myfile1.txt” with all lowercase letters changed to
uppercase letters. Check the file “myfile1.txt”.

14
Computer Science Sem-1

You might also like