0% found this document useful (0 votes)
42 views103 pages

Problem Solving in C

The document provides an overview of computer organization, detailing its main components: Input Unit, Central Processing Unit (CPU), and Output Unit. It explains the characteristics and limitations of computers, such as accuracy, speed, and inability to think or make decisions. Additionally, it discusses various applications of computers across different fields, including home, medical, education, and industry, as well as classifications based on size, type, and purpose.

Uploaded by

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

Problem Solving in C

The document provides an overview of computer organization, detailing its main components: Input Unit, Central Processing Unit (CPU), and Output Unit. It explains the characteristics and limitations of computers, such as accuracy, speed, and inability to think or make decisions. Additionally, it discusses various applications of computers across different fields, including home, medical, education, and industry, as well as classifications based on size, type, and purpose.

Uploaded by

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

Problem Solving in C B.

Sc 1st Year---1st Semester

P.Madhubabu M.C.A & M.Tech 1


Problem Solving in C B.Sc 1st Year---1st Semester
UNIT-1
Q1)Explain Basic Organization of Computer?
(or)
Explain various parts of the computer?
(or)
Explain Logical Organization of the Digital computer?
(or)
Explain Block diagram of the computer?
(or)
Explain various components of a digital computer?
Computer: Computer is an Electronic Device that takes the data as input from the user, stores
that data and process the data and generates the output as per the instructions given by the
user.
Just like the other machines, the computer has also a basic architecture. It comprises multiple
elements. These elements process the input and produce the desired output.
Let us look at the basic block diagram of the computer. Then, we will understand how each part
contributes to its functioning.
The computer system mainly divided into three units
1)Input Unit
2)Central Processing Unit
3)Output Unit
It can be diagrammatically represented as follows:

1)Input Unit: All the data received by the computer goes through the input unit. The input
unit comprises different devices. Like a mouse, keyboard, scanner, etc. In other words, each of
these devices acts as a mediator between the users and the computer.
The data that is to be processed is put through the input unit. The computer accepts the raw
data in binary form. It then processes the data, and produces the desired output.
The 3 major functions of the input unit are-
• Take the data to be processed by the user.
• Convert the given data into machine-readable form.
• And then, transmit the converted data into the main memory of the computer. The sole
purpose is to connect the user and the computer. In addition, this creates easy
communication between them.

P.Madhubabu M.C.A & M.Tech 2


Problem Solving in C B.Sc 1st Year---1st Semester
2)Central Processing Unit(CPU): Central Processing Unit or the CPU, is the brain of the
computer. It works the same way a human brain works. As the brain controls all human
activities, the CPU too controls all tasks.
Moreover, the CPU conducts all the arithmetical and logical operations in the computer.
This is again divided into three units.
a) Control Unit
b) Arithmetic Logic Unit
c) Memory Unit
a)Control Unit: The Control Unit is used to control all the other parts of the computer. For
example the input unit does not know when to send the data when the output unit receives the
data. The Control Unit gives direction to the other units. It gives the instructions to the data
from the input device to memory, from memory to ALU and ALU to Output device.
b)Arithmetic Logic Unit (ALU): ALU is used to perform all arithmetic(+, - ,* ,/ ,%) and
logical (and, or, not) operations. The input data in the form of binary numbers will be transfer
to ALU, whenever the processing is necessary.
c)Memory Unit: The computer Memory is used to store many types of information. The
memory locations are called memory cells. Each memory cell is capable of storing one character
also known as a byte. Byte is the combination of 8 bits. Bit is either 0 or 1.
The memory can be measured in terms of bits and bytes.
Nibble = 4bits
1 byte = 8 bits
1 kb = 1024 bytes
1 mb = 1024 kbs
1 gb = 1024 mbs
1 tb = 1024 gb
Memory is classified into 2 types:
i)Main Memory/primary memory
ii)Secondary Memory
i)Primary memory: This type of memory cannot store a vast amount of data. Therefore, it is
only used to store recent data. The data stored in this is temporary. It can get erased once the
power is switched off. Therefore, is also called temporary memory or the main memory.
RAM stands for Random Access Memory. It is an example of primary memory. This memory is
directly accessible by the CPU. It is used for reading and writing purposes. For data to be
processed, it has to be first transferred to the RAM and then to the CPU.
ii)Secondary memory: For permanent storage purposes, secondary memory is used. It is also
called the permanent memory or the auxiliary memory. The hard disk is an example of
secondary memory. Even in a power failure data does not get erased easily.
3)Output Unit: All the information sent to the computer once processed is received by the
user through the output unit. Devices like printers, monitors, projector, etc. all come under the
output unit.
The output unit displays the data either in the form of a soft copy or hard copy. The printer is
for the hard copy. The monitor is for the display. The output unit accepts the data in binary
form from the computer. It then converts it into a readable form for the user.
The most commonly used output devices are:
1)Visual Display Unit(Monitor)
2)Printer
3)Plotter
Q2)What is computer? Explain characteristics and limitations of a
computer?
Computer: Computer is an Electronic Device that takes the data as input from the user, stores
that data and process the data and generates the output as per the instructions given by the
user.

P.Madhubabu M.C.A & M.Tech 3


Problem Solving in C B.Sc 1st Year---1st Semester
Characteristics of Computer:
1) Accuracy
2) Speed
3) Versatility (Flexibility, usefulness)
4) Storage capability
5) Intellectual power (logical)
6) Diligence
7) Network capacity
1)Accuracy: Computer system always produces correct results. It cannot never do mistake.
Then the user given data is wrong then only it gives wrong results. The accuracy of a particular
computer depends upon the system design.
2)Speed: Computer can process millions of instructions per second. Even complex problems
also processed in fraction of seconds. The speed of the computer is measured in terms of Micro
seconds(10-6), Nano seconds(10-9) and Pico seconds(10-12).
3)Versatility: Versatility means it can do number of jobs at a time.
Example: In computer we can draw the picture on one side other side we can print the
documents.
4)Storage capability: The main purpose of the computer is storing of the data. The
computer can store large amount of data and information ones we store the data we can
retrieve the data any time. The storage capacity of computer can be increased by using
secondary storage devices such as magnetic discs, tapes etc.. The memory can be measured in
terms of bits and bytes.
Nibble = 4bits
1 byte = 8 bits
1 kb = 1024 bytes
1 mb = 1024 kbs
1 gb = 1024 mbs
1 tb = 1024 gb
5)Intellectual Power: A computer doesn’t take its own decision. Now a day some Artificial
Intelligence Technology has been developed. So that computer takes its own decision.
6)Diligence: Diligence means being constant in effort. Human being suffers from weakness
and tiredness lack of concentration. Computer machine don’t suffer and can work for hours and
perform limitless calculation without time limit.
7)Network Capacity: Computers can communicate with other computers and can receive
and send data in various forms like Text, video, audio and graphics. Per this computer network
internet is developed.
Limitations of a computer: Although a computer is far better in performance than a
human being, it fails in certain ways as follows:
i)computers can’t think: computers can not think and they can’t do any job unless they are
first programmed with specific instructions for same. They work as per stored instructions.
Algorithms are designed by humans to make a computer perform a special task. This is also
called artificial intelligence.
ii)Computers can’t Decide: computers are incapable of decision making as they do not
possess the essential elements necessary to take a decision. i.e. knowledge, information,
wisdom, intelligence and the ability to judge.
iii)computers can’t Express their Ideas: In any type of research ideas plays a vital role. In
this context, computers can’t express their ideas.
iv)computers can’t implement: Though computers are helpful in storage of data and can
contain the contents of encyclopedias even, but only human can decide and implement the
policies.

P.Madhubabu M.C.A & M.Tech 4


Problem Solving in C B.Sc 1st Year---1st Semester
Q3)What are the Applications of Computers? (or) What are the uses of
Computers?
Computers play a role in every field of life. They are used in homes, business, educational
institutions, research organizations, medical field, government offices, entertainment, etc.
1.Home: Computers are used at homes for several purposes like online bill payment,
watching movies or shows at home, home tutoring, social media access, playing games, internet
access, etc. They provide communication through electronic mail. They help to avail work from
home facility for corporate employees. Computers help the student community to avail online
educational support.
2.Medical Field: Computers are used in hospitals to maintain a database of patients’
history, diagnosis, X-rays, live monitoring of patients, etc. Surgeons nowadays use robotic
surgical devices to perform delicate operations, and conduct surgeries remotely. Virtual reality
technologies are also used for training purposes. It also helps to monitor the fetus inside the
mother’s womb.
3.Entertainment: Computers help to watch movies online, play games online; act as a
virtual entertainer in playing games, listening to music, etc. MIDI instruments greatly help
people in the entertainment industry in recording music with artificial instruments. Videos can
be fed from computers to full screen televisions. Photo editors are available with fabulous
features.
4.Industry: Computers are used to perform several tasks in industries like managing
inventory, designing purpose, creating virtual sample products, interior designing, video
conferencing, etc. Online marketing has seen a great revolution in its ability to sell various
products to inaccessible corners like interior or rural areas. Stock markets have seen phenomenal
participation from different levels of people through the use of computers.
5.Education: Computers are used in education sector through online classes, online
examinations, referring e-books, online tutoring, etc. They help in increased use of audio-visual
aids in the education field.
6.Government: In government sectors, computers are used in data processing, maintaining
a database of citizens and supporting a paperless environment. The country’s defense
organizations have greatly benefitted from computers in their use for missile development,
satellites, rocket launches, etc.
7.Banking: In the banking sector, computers are used to store details of customers and
conduct transactions, such as withdrawal and deposit of money through ATMs. Banks have
reduced manual errors and expenses to a great extent through extensive use of computers.
8.Business: Nowadays, computers are totally integrated into business. The main objective of
business is transaction processing, which involves transactions with suppliers, employees or
customers. Computers can make these transactions easy and accurate. People can analyze
investments, sales, expenses, markets and other aspects of business using computers.
9.Training: Many organizations use computer-based training to train their employees, to
save money and improve performance. Video conferencing through computers allows saving of
time and travelling costs by being able to connect people in various locations.
10.Arts: Computers are extensively used in dance, photography, arts and culture. The fluid
movement of dance can be shown live via animation. Photos can be digitized using computers.
11.Science and Engineering: Computers with high performance are used to stimulate
dynamic process in Science and Engineering. Supercomputers have numerous applications in
area of Research and Development (R&D). Topographic images can be created through
computers. Scientists use computers to plot and analyze data to have a better understanding of
earthquakes.
Q4)What are the classification of Computers? (or) What are the types
of Computers?
P.Madhubabu M.C.A & M.Tech 5
Problem Solving in C B.Sc 1st Year---1st Semester
Classification of computers is particularized in three main categories. They are:
1. Based on Size and Capacity.
2. Based on Type.
3. Based on Purpose.
1.Classification Based on Size and Capacity: The computer is classified into four
parts based on size and capability. They are:
a) Micro Computers
b) Mini Computers
c) Main frame computers
d) Super Computers
a)Micro Computers:
• These are small in size
• In this computational power is less.
• These are also called as Desktop computer.
• IC is used as processor
• CPU has small amount of storage space
• Memory capacity is 128kb to 1Mb
• It can process 8bits data or 16bits word length
• These are used as Personal computers
• In this high level languages are used like pascal, fortran
• These are used for banking system, Word processing.
Examples of microcomputers:
• Desktop Computer
• Laptop
• Smartphone
• Notebook
• Tablet
Characteristics of Micro Computers:
• Cheap and easy to use.
• Have a limit input and output device.
• Have a low storage capacity.
• Limited range of software can be use.
b)Mini Computers:
• A Mini Computer is a medium size i.e. more costly and power full than a Micro
Computer.
• An Important distinction between a Micro Computer and Mini Computer is usually
design to serve to multiples users.
• A Mini Computer system that support Multiples users. This process is also called Time
Sharing system.
• Mini Computer is less efficient and store less data than the Main Frame Computer.
• There are different types of Mini Computers.
▪ Tablet PC
▪ Desktop minicomputers
▪ Cell phones
▪ Notebooks
▪ High-end mP3 players
Characteristic of Mini Computers:
• Have a limited range of peripherals device.
• Limited software is used.
• Can be directly operated by the users.
c)Main frame computers:

P.Madhubabu M.C.A & M.Tech 6


Problem Solving in C B.Sc 1st Year---1st Semester
• A computer with a large storage capacity and very fast speed of processing compare to
Micro or Mini Computer.
• They Support a large numbers of terminals for used by a verity of users.
• They are several organizations such as Bank, Insurance Company, Hospital and Railway
etc.
• Main Frame Computer is Very Large computer.
• There are different types of Mainframe Computers.
▪ ENIAC (Electric Numerical Integrator and Calculator)
▪ UNIVAC
▪ ASCC (Automatic Sequence Control Computer)
Characteristic of Main Frame Computers:
• Based on the principle of that contributing power should be can lent rated.
• Many people can many use of the some machine at the same time.
• Qualified operator and programmer are required for operation.
• Support a wide range of peripherals & Have a large storage capacity.
d)Super computers:
• Super computer has internally large storage capacity and computing speed.
• Which are at least Ten Times faster than other computers.
• The Super Computer is rotated in terms of million instructions per second.
• Supercomputer is the largest, Fastest and Expensive Computer System in the world.
• There are different types of supercomputers is given below.
▪ Jaguar
▪ Titan
▪ Nebulae
▪ IBM Roadrunner
▪ K Computer
▪ Tianhe-I
▪ Jugene
▪ Kraken
▪ PleIades
▪ IBM Sequoia
2.Classification of Computer by Type:
• The computer is classified into three parts based on Type and the basis of Hardware
Design and Data Handling.
• You can also call it the classification of computers by functionality.
• These computer different roles in different fields.
• Classification of computer according to type is given below.
a) Analog Computers
b) Digital Computers
c) Hybrid Computers
a)Analog Computers:
• Analog computer is used to measure the physical quantities, temperature, pressure weight
and height and gives the result in the form of digits is called analog computer.
• Analog computers are used by civil engineers, mechanical engineers and electrical
engineers. Needle clock is an example of analog computer.
• There are different types of Analog Computer is given below.
▪ Castle Clock
▪ Slide Rules
▪ Differential Analysers
▪ Electronic Analog Computers
▪ Hydraulic Analog Computer
▪ Pneumatic Analog Computer
▪ Mechanical Analog Computers
P.Madhubabu M.C.A & M.Tech 7
Problem Solving in C B.Sc 1st Year---1st Semester
b)Digital Computers:
• Digital computers are used to calculate digits.
• Today digital computers are being used in everywhere.
• Smart Phone and Laptop are example of digital computer.
• There are different types of Digital computer is given below.
▪ Personal Desktop Computers
▪ Calculators
▪ Laptops
▪ Digital watch
▪ Smartphones and Tablets
▪ Workstations
▪ Digital clock
c)Hybrid Computers:
• Hybrid computers combine the both analog and digital computers which includes both
Analog and Digital properties.
• Hybrid computer is used in medical field.
• Smart watch is an example of Hybrid Computer.
• There are three types of Hybrid computer is given below.
▪ Large Electronic Hybrid Computer
▪ General-Purpose Hybrid Computers
▪ Special-Purpose Hybrid Computers
3.Classification of Computers According to Purpose:
These computers are designed for specific purpose. These are two types. They are:
a) Special Purpose computer
b) General Purpose computer
a)Special Purpose computers:
• These are Made for successfully meet the Requirement of particular task Or application.
• It Incorporates The Instruction Needed Into The Design Of Internal Storage.
• So That It Can Perform The Given Task On A Simple Commands.
• Automatic Teller Machine (ATM) is an example of Special Purpose computer.
• There are many different types of Special Purpose computers are given below:
▪ Washing machines
▪ Surveillance equipment
▪ Traffic-control computers
▪ Oil-exploration systems
▪ Weather-forecasting simulators
▪ Military planes controlling computers
b)General Purpose computers:
• A General Purpose Machines are used to prepare Pay Bill, Inventory Counters, and Print
Report etc.
• All microcomputers are examples of general purpose computer system.
Q5)What are Generation of Computers?
Generation means enhancement (extension, expansion) in technology such as speed, size
and Memory capacity. Based upon this the computer generations are classified into 5 types.
1)First Generation (1940-1956: Vacuum Tubes):
i) vacuum tubes are used in electronic circuits
ii) Mercury Delay lines are used as memory
iii) Magnetic drums are used as secondary memory
iv) Machine level language is used as programming
v) The size of computer is very large
vi) The maintenance is very difficult because it produces large amount of heat. So AC is
compulsory
P.Madhubabu M.C.A & M.Tech 8
Problem Solving in C B.Sc 1st Year---1st Semester
vii) Punched card are used to enter the data into the computer, punched card was a sheet of
thick paper, in which holes were punched according to a coding scheme.
2)Second Generation (1956-1963: Transistors)
i) Transistors were used
ii) Magnetic tapes are used as Secondary Memory
iii) Magnetic disks are used as primary memory
iv) High Level language is used as the programming
Ex: Fortran, cobol etc..
v) The size of computer is reduced
vi) Input, output operations made faster
vii) The maintenance of computer is reduced because the heat was reduced
viii) These are used for both commercial and Scientific applications
ix) Batch processing is possible
3)Third Generation (1964-1971: Integrated Circuits):
i) IC’s are used in electronic circuits
ii) Memory capacity is increased upto Mega Bytes.
iii) The size of computer is small
iv) Magnetic disks are used as secondary memory
v) IC’s are used as Main Memory
vi)The processing speed is very high. It can process 10 million
instructions per second.
vii) These are used for scientific and commercial applications
viii) Instead of punched cards and printouts, users interacted with third generation computers
through keyboards and monitors and interfaced with an operating system, which allowed the
device to run many different applications.
ix)simple input and output operations
4)Fourth Generation (1971-Present: Microprocessors):
i)The microprocessor brought the fourth generation of computers, as
thousands of integrated circuits were built onto a single silicon chip.
ii)Very Large Scale Integrated Circuits(VLSIC) were used
iii)The speed of the computer is very high
iv)It required less space, not necessary AC
5)Fifth Generation (Present and Beyond: Artificial Intelligence):
Fifth generation computing devices, based in Artificial intelligence, are still in development,
though there are some applications, such as voice recognition, that are being used today.
Artificial Intelligence is the branch of computer science concerned with making computers
behave like humans. Artificial intelligence includes:
• Games Playing: programming computers to play games such as chess and checkers
• Expert Systems: programming computers to make decisions in real-life situations (for
example, some expert systems help doctors diagnose diseases based on symptoms)
• Natural Language: programming computers to understand natural human languages.
Q6) What is an Algorithm? What are the characteristics of Computer?
Give an Example?
Algorithm: Algorithm is a step-by-step procedure, which defines a set of instructions to be
executed in a certain order to get the desired output. Algorithms are generally created
independent of underlying languages, i.e. an algorithm can be implemented in more than one
programming language.
Characteristics of an Algorithm:
An algorithm should have the below mentioned characteristics:
1.Unambiguous: Algorithm should be clear and unambiguous. Each of its steps (or phases),
and their input/outputs should be clear and must lead to only one meaning.
2.Input: An algorithm should have 0 or more well defined inputs.
P.Madhubabu M.C.A & M.Tech 9
Problem Solving in C B.Sc 1st Year---1st Semester
3.Output: An algorithm should have 1 or more well defined outputs, and should match the
desired output.
4.Finiteness: Algorithms must terminate after a finite number of steps.
5.Feasibility: Should be feasible with the available resources.
6.Independent: An algorithm should have step-by-step directions which should be
independent of any programming code.
Examples for Algorithm:
Ex1: Write an algorithm to add two numbers entered by user.
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Ex2: Write an algorithm to find the largest among three different numbers entered by
user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: if a>b
if a>c
Display a is the largest number.
else
Display c is the largest number.
else
if b>c
Display b is the largest number.
else
Display c is the greatest number.
Step 5: Stop
Q7) What is Flowchart ? Give the Example?
Flowchart: A graphical or symbolic representation of a process is called Flowchart.
→It Used to design and document complex processes to help the viewers to visualize the logic
of the process
→It provides a better understanding of the process and find flaws, bottlenecks, and other less
obvious features within it
→Usually drawn in the early stages of formulating computer solutions
Flowchart symbols:
The different flowchart symbols have different conventional meanings.
The various symbols used in Flowchart Designs are given below.
1.Terminal Symbol: In the flowchart, it is represented with the help of a circle for denoting
the start and stop symbol. The symbol given below is used to represent the terminal symbol.

2.Input/output Symbol: The input symbol is used to represent the input data, and the
output symbol is used to display the output operation. The symbol given below is used for
representing the Input/output symbol.

P.Madhubabu M.C.A & M.Tech 10


Problem Solving in C B.Sc 1st Year---1st Semester
3.Processing Symbol: It is represented in a flowchart with the help of a rectangle box used
to represent the arithmetic and data movement instructions. The symbol given below is used to
represent the processing symbol.

4.Decision Symbol: Diamond symbol is used for represents decision-making statements. The
symbol given below is used to represent the decision symbol.

5.Connector Symbol: The connector symbol is used if flows discontinued at some point and
continued again at another place. The following symbol is the representation of the connector
symbol.

6.Flow lines: It represents the exact sequence in which instructions are executed. Arrows are
used to represent the flow lines in a flowchart. The symbol given below is used for representing
the flow lines:

7.Hexagon symbol (Flat): It is used to create a preparation box containing the loop setting
statement. The symbol given below is used for representing the Hexagon symbol.

8.On-Page Reference Symbol: This symbol contains a letter inside that indicates the flow
continues on a matching symbol containing the same letters somewhere else on the same page.
The symbol given below is used for representing the on-page reference symbol.

9.Off-Page Reference: This symbol contains a letter inside indicating that the flow continues
on a matching symbol containing the same letter somewhere else on a different page. The
symbol given below is used to represent the off-page reference symbol.

10.Delay or Bottleneck: This symbol is used for identifying a delay in a flowchart. The
alternative name used for the delay is the bottleneck. The symbol given below is used to
represent the delay or bottleneck symbol.

11.Document Symbol: This symbol is used in a flowchart to indicate a document or


report.The symbol given below is used to represent the document symbol.

12.Internal storage symbol: The symbol given below is used to represent the internal
storage symbol.

P.Madhubabu M.C.A & M.Tech 11


Problem Solving in C B.Sc 1st Year---1st Semester
Advantages of Flowchart in C:
Following are the various advantages of flowchart:
1. Communication: A flowchart is a better way of communicating the logic of a
program.
2. Synthesis: Flowchart is used as working models in designing new programs and
software systems.
3. Efficient Coding: Flowcharts act as a guide for a programmer in writing the actual
code in a high-level language.
4. Proper Debugging: Flowcharts help in the debugging process.
5. Effective Analysis: Effective analysis of logical programs can be easily done with the
help of a related flowchart.
6. Proper Documentation: Flowchart provides better and proper documentation. It
consists of various activities such as collecting, organizing, storing, and maintaining all
related program records.
7. Testing: A flowchart helps in the testing process.
8. Efficient program maintenance: The maintenance of the program becomes easy
with the help of a flowchart.
Disadvantages of Flowchart in C:
Following are the various disadvantages of flowchart:
1. Time-consuming: Designing a flowchart is a very time-consuming process.
2. Complex: It isn't easy to draw a flowchart for large and complex programs.
3. There is no standard in the flowchart: there is no standard to determine the
quantity of detail.
4. Difficult to modify: It is very difficult to modify the existing flowchart.
Example: To prepare a flowchart to determine the greatest of two numbers. Here we use the
decision symbol. We also combine the two reads for numbers A and B in one box.
The steps are :
1. Start
2. Get two number A and B.
3. If A > B then print A else print B.
4. Stop

Q8)Explain The Generations of Languages?


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)
P.Madhubabu M.C.A & M.Tech 12
Problem Solving in C B.Sc 1st Year---1st Semester
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:
i) They are translation free and can be directly executed by the computers.
ii) The programs written in these languages are executed very speedily and efficiently by the
CPU of the computer system.
iii) 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:
i) 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.
ii) 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 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:
i) It is easy to develop, learn and understand the program.
ii) As the program written in these languages is less prone to errors they are easy to
maintain.
iii) 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:
i) These programming languages allow the efficient use of data by implementing the
various database.
ii) They require less time, cost and effort to develop different types of software applications.
iii) 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

P.Madhubabu M.C.A & M.Tech 13


Problem Solving in C B.Sc 1st Year---1st Semester
the fifth generation programming language are employed are Artificial Intelligence and Artificial
Neural Networks
Advantages of fifth generation languages:
i) These languages can be used to query the database in a fast and efficient manner.
ii) In this generation of language, the user can communicate with the computer system in a
simple and an easy manner.
Examples: mercury, prolog, OPS5
Q9)Explain Structured Programming Language with Advantages and
Disadvantages
Structured Programming Language: It can be defined as a programming approach in
which the program is made as a single structure. It means that the code will execute the
instruction by instruction one after the other. It doesn’t support the possibility of jumping from
one instruction to some other with the help of any statement like GOTO, etc. Therefore, the
instructions in this approach will be executed in a serial and structured manner. The languages
that support Structured programming approach are:
• C
• C++
• Java
• C#
..etc
The structured program mainly consists of three types of elements:
• Selection Statements
• Sequence Statements
• Iteration Statements
The structured program consists of well structured and separated modules. But the entry and
exit in a structured program is a single-time event. It means that the program uses single-entry
and single-exit elements. Therefore a structured program is well maintained, neat and clean
program. This is the reason why the Structured Programming Approach is well accepted in the
programming world.
Advantages of Structured Programming Approach:
• Easier to read and understand
• User Friendly
• Easier to Maintain
• Mainly problem based instead of being machine based
• Development is easier as it requires less effort and time
• Easier to Debug
• Machine-Independent, mostly.
Disadvantages of Structured Programming Approach:
• Since it is Machine-Independent, So it takes time to convert into machine code.
• The converted machine code is not the same as for assembly language.
• The program depends upon changeable factors like data-types. Therefore it needs to be
updated with the need on the go.
• Usually the development in this approach takes longer time as it is language-dependent.
Whereas in the case of assembly language, the development takes lesser time as it is fixed
for the machine.

P.Madhubabu M.C.A & M.Tech 14


Problem Solving in C B.Sc 1st Year---1st Semester
UNIT-2
Q1) Explain the History of C Language?
→C is a structured programming language. It is also known as function orientated programming
language. C programming language was developed in the year of 1972 by Dennis Ritchie at Bell
Laboratories in USA (AT&T).
→In the year of 1968, research was started by Dennis Ritchie on programming languages like
BCPL, CPL. The main aim of his research was to develop a new language to create an OS called
UNIX. After four years of research, a new programming language was created with solutions for
drawbacks in languages like BCPL & CPL. In the year of 1972, the new language was introduced
with the name “Traditional C”..
→The name 'c' was selected from the sequence of previous language ‘B’ (BCPL), because most of
the features of 'c' was derived from BCPL (B language).
→The first outcome of the c language was UNIX operating system. The initial UNIX OS was
completely developed using 'c' programming language.
→The founder of the ‘C’ language, Dennis Ritchie is known as “Father of C” and also “Father
of UNIX”.
→C programming language is a very popular programming language, because it is reliable,
simple and easy to use and it is the base for almost all the other programming languages.
→The following are the language before ‘c’ & various versions of ‘c’.
1.CPL (Common Programming Language): The CPL was invented by Martin
Richards at the University of Cambridge in the early of 1960's.
2.BCPL (Basic Combined Programming Language): The BCPL was invented
by Martin Richards at the University of Cambridge in the year of 1966. It was a popular
programming language at that time. BCPL allows the user, direct access to the computer
memory. BCPL is the extension of CPL.
3.B Language: B language is derived from BCPL. It was introduced in the year of 1969
by Ken Thompson and Dennis Ritchie at Bell Laboratory, USA. The B language is similar to the
BCPL.
4.C Language: C language is derived from B language. It was introduced in the year of
1972 by Dennis Ritchie at Bell Laboratory, USA. The C language was mainly developed to
create a operating system called UNIX. The name C is given based on the previous language B
and BCPL. Ninty percent of the UNIX operating system code is written in C language. During
1970's, the C language became very popular programming language. Many universities and
organizations began creating their own version of C language for thier respective projects. So C
language has got many variants at that time. Later it was standardized.
5.ANSI C (C89): In the year of 1983, the ANSI (American National Standards Institute)
formed a committee to frame standard specifications for the C language. In the year of 1989,
this committee introduced a standard version of C with the name "ANSI C" with standard library
files. The ANSI C is also called as C89 in short form.
6.C90: In the year of 1990, the ANSI C was got ISO (Intenational Organization for
Standardization) standardization with the inclusion of few new features like new library files,
new processor commands. And it was also added with keywords const, volatile and signedetc...
ISO standardized the ANSI C as ISO/IEC 9899:1990. This version is called as C90 in short form.
7.C99: In the year of 1995, many new features were added to the C90 to create a new
version of it. This new version of C was got ISO standardization in the year of 1999 with the

P.Madhubabu M.C.A & M.Tech 15


Problem Solving in C B.Sc 1st Year---1st Semester
name ISO/IEC 9899:1999. In the short form it is called as C99. Later C99 became the official
standard version of C.
Q2) What are the Features or characteristics of C - Language?
Features of C Language: C is the widely used language. It provides a lot of featuresthat
are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1)Simple: C is a simple language in the sense that it provides structured approach (to break
the problem into parts), rich set of library functions, data types etc.
2)Machine Independent or Portable: Unlike assembly language, c programs can be
executed in many machines with little bit or no change. But it is not platform-independent.
3)Mid-level programming language: C is also used to do low level programming. It is
used to develop system applications such as kernel, driver etc. It also supports the feature of
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.
5)Rich Library: C provides a lot of inbuilt functions that makes 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.
8)Pointers: 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.
10)Extensible: C language is extensible because it can easily adopt new features.
P.Madhubabu M.C.A & M.Tech 16
Problem Solving in C B.Sc 1st Year---1st Semester
Q3)Explain the structure of ‘c’ program?
Basic Structure of C Program: Every C program contains a number of several building
blocks known as functions. Each function of it perform task independently. A function is a
subroutine that may consist of one or more statements. A C program may have the following
sections.

1)Documentation Section
2)Link Section
3)Definition Section
4)Global Declaration section
5)Function main()
5.1)Declaration Part
5.2)Executable Part
6)Sub-Program Section
1.Documentation Section: The documentation section consists of a set of comment lines
giving the name of the program. Comments are providing description of the program.
When we write comments, we can understand what the program is doing as well as it
helps others to easily follow our code. This means readability and understandability of a
program will be more.
There are two types of comments in C
➔ Single Line comment
➔ Multi Line comment
Single Line Comment: These comments are for marking a single line as a comment. These
comments start with double slash symbol // and after this, whatever is written till the end of the
line is taken as a comment.
Ex: // this is single comment line.
Multi Line Comment: These comments are used for representing several lines as comments.
These comments start with /* and end with */. In between /* and */, whatever is written is
treated as a multi line comment.
Ex: /*
-------- line1--------

P.Madhubabu M.C.A & M.Tech 17


Problem Solving in C B.Sc 1st Year---1st Semester
--------line2--------
--------line3--------
*/
2.Link Section: The link section provides instructions to the compiler to link functions from
the system library i.e. header file. C program depends upon some header files for function
definition that are used in program. Each header file by default is extension with .h. The file
should be include using #include directive.
Ex: #include<stdio.h>
#include<conio.h>
3.Definition Section: The definition section definition defines all symbolic constants.
Ex: #define PIE 3.14
→in the above example PIE is a symbolic constant. Its value is 3.14. it is a fixed value.
Which means it can not be modified.
4.Global Declaration section: This section declares some variables that are used in more
than one function. These variables are known as global variables. These variables must be
declared outside of all the function.
Ex: int a=10; //here ‘a’ is gloabal variable
Void main()
{
}
5.main() Function section: Every program written in C language must contain main ( )
function. Empty parenthesis ({ }) after main are necessary. The function main() is the starting
point of every ‘C’ program. The execution of the program always begins with the function
main(). The program execution starts with the opening brace ’{‘ and ends with the closing brace
‘}’.
Ex: void main()
{
//executable statements
}
5.1.Declaration Part: The declaration part declares the entire variables that are used in
executable part. The initializations of variables are also done in this section. The initialization
means providing initial value to the variables.
Ex: void main()
{
Int a=10; //declaration part
//executable statements
}
5.2.Executable Part: This part contains the statement following the declaration of the
variables. This part contains a set of statements or a single statement. These statements are
enclosed between the braces.
Ex: void main()
{
Int a=10; //declaration part
//executable part
}
6.Sub-Program Section: The functions defined by the user are called user-defined functions.
These functions are generally defined after the main ( ) function. They can also be defined
before main() function. This portion is not compulsory.
Ex: void main()
{
Int a=10; //declaration part
//executable part
}
Add() //subprogram
P.Madhubabu M.C.A & M.Tech 18
Problem Solving in C B.Sc 1st Year---1st Semester
{
//function body
}
Rules of a Program:
A programmer while writing a program should follow the following rules.
❖ All statements should be written in lower case letters. Upper case letters are only used for
symbolic constants.
❖ Blank spaces may be inserted between the words. It is not used in the case of declaring a
variable, keyword, constant and function.
❖ The programmer can write the statement any where between the two braces following
the declaration part.
❖ The opening and closing braces should be balanced.

Q4)Explain how to Creating, Compiling and Executing C Program?


Generally, the programs created using programming languages like C, C++, Java etc., are
written using high level language like English. But, computer cannot understand the high level
language. It can understand only low level language. So, the program written in high level
language needs to be converted into low level language to make it understandable for the
computer. This conversion is performed using either Interpreter or Compiler.
Popular programming languages like C, C++, Java etc., use compiler to convert high
level language instructions into low level language instructions. Compiler is a program that
converts high level language instructions into low level language instructions. Generally,
compiler performs two things, first it verifies the program errors, if errors are found, it returns
list of errors otherwise it converts the complete code into low level language.
To create and execute C programs in Windows Operating System, we need to install
Turbo C software. We use the following steps to create and execute C programs in Windows
OS…

Step 1: Creating Source Code


Source code is a file with C programming instructions in high level language. To create
source code, we use any text editor to write the program instructions. The instructions written
in the source code must follow the C programming language rules. The following steps are used
to create source code file in Windows OS…
• Click on Start button
• Select Run
• Type cmd and press Enter
• Type cd c:\TC\bin in the command prompt and press Enter
• Type TC press Enter
• Click on File -> New in C Editor window
• Type the program
• Save it as FileName.c or Filename.cpp (Use shortcut key F2 to save)
Step 2: Compile Source Code (Alt + F9)
P.Madhubabu M.C.A & M.Tech 19
Problem Solving in C B.Sc 1st Year---1st Semester
Compilation is the process of converting high level language instructions into low level
language instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.
Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On
receiving a source file, the compiler first checks for the Errors. If there are any Errors then
compiler returns List of Errors, if there are no errors then the source code is converted
into object code and stores it as file with .obj extension. Then the object code is given to
the Linker. The Linker combines both the object code and specified header file code and
generates an Executable file with .exe extension.
Step 3: Executing / Running Executable File (Ctrl + F9)
After completing compilation successfully, an executable file is created with .exe extension. The
processor can understand this .exe file content so that it can perform the task specified in the
source file.
We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9,
the .exe file is submitted to the CPU. On receiving .exe file, CPU performs the task according to
the instruction written in the file. The result generated from the execution is placed in a window
called User Screen.
Step 4: Check Result (Alt + F5)
After running the program, the result is placed into User Screen. Just we need to open the User
Screen to check the result of the program execution. We use the shortcut key Alt + F5 to open
the User Screen and check the result.
Execution Process of a C Program:
When we execute a C program it undergoes with following process…

The file which contains c program instructions in high level language is said to be source
code. Every c program source file is saved with .c extension, for example Sample.c.
Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks
for the errors, if there are any errors, it returns list of errors, otherwise generates object code in
a file with name Sample.obj and submit it to the linker. Linker combines the code from specified
header file into object file and generates executable file as Sample.exe. With this compilation
process completes.
Now, we need to Run the executable file (Sample.exe). To run a program we press Ctrl
+ F9. When we press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs
the task according to the instructions written in that program and place the result into
UserScreen.
Then we press Alt + F5 to open UserScreen and check the result of the program.
Q5) Explain about ‘C’ Tokens ?
In a passage of text, individual words and punctuation marks are called tokens or lexical units.
Similarly, the smallest individual unit in a c program is known as a token or a lexical unit. C
tokens can be classified as follows:
1. Keywords
P.Madhubabu M.C.A & M.Tech 20
Problem Solving in C B.Sc 1st Year---1st Semester
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1.Keywords: The C keywords are reserved words by the compiler. All the C keywords have
been assigned fixed meaning. The keywords cannot be used as variable names because they
have been assigned fixed jobs. The C language has 32 keywords.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
2.Identifiers: Identifier can be defined as the name of the variable, which holds a value and
stores that value in the memory.
Example: char ch=’x’;
int a=10;
float b=5.7;
double c=234234.5656;
→in the above example, variable names: ch, a, b, c are called as Identifiers.
Rules for declaring the identifiers:
➔ The first character of an identifier should be either an alphabet or an underscore, and
then it can be followed by any of the character, digit, or underscore.
➔ It should not begin with any numerical digit.
➔ In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
➔ Commas or blank spaces cannot be specified within an identifier.
➔ Keywords cannot be represented as an identifier.
➔ The length of the identifiers should not be more than 31 characters.
➔ Identifiers should be written in such a way that it is meaningful, short, and easy to read.
3.Constants: A constant is a fixed value that cannot be altered during the execution of a
program. There are several types of constants in C.
Constant Example
Integer constant 10, 11, 34, etc.

P.Madhubabu M.C.A & M.Tech 21


Problem Solving in C B.Sc 1st Year---1st Semester
Floating-point constant 45.6, 67.8, 11.2, etc.
Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.
Character constant 'a', 'b', 'c', etc.
String constant "java", "c++", ".net", etc.

Types of Constants: There are mainly 2 types of constants. They are:


3.1.Numeric Constants
3.2.Character Constants
3.1.Numeric Constants: These are two types. They are:
3.1.1.Integer Constants
3.1.2.Real Constants
3.1.1. Integer Constants:
An integer constant refers to a sequence of digits. There are three types of integer’s namely:
a) decimal integer
b) octal integer
c) hexadecimal integer.
a)Decimal Integers: Decimal integers consists of set of digits 0 through 9, preceded by an
optional – or + sign.
Ex: 10, 20, +30, -15 etc.
b)Octal Integers: An octal integer constant consists of any combination of digits from the set 0
through 7, with a leading 0.
Ex: 037, 0456, 0, 0551 etc.
c)Hexa Decimal Integers: A sequence of digits preceded by 0x or 0X is considered as hexa
decimal integer. They may also include alphabets ‘A’ to ‘F’ or ‘a’ to ‘f’. The letters ‘A’ to ‘F’
represent the numbers 10 through 15.
Ex: 0x2, 0x9F, 0xbcd etc.
3.1.2.Real Constants: Real constants are often known as floating point constants. The real
constants can be written in exponential notation, which contains a fractional part and an
exponential part.
Ex: 2.5, 5.521, 2456.123
3.2)Character Constants:
a)Single character constants: A character constant is a single constant is a single character.
They are also represented with a single digit or a single symbol or white space enclosed within
a pair of single quote marks.
Ex: ‘a’, ‘A’, ‘8’ etc.
b) String constants: String constants are sequence of character enclosed within a double
quote marks.
Ex: “career”, “welcome” etc.
c)Back slash Character Constants:
C supports some special backslash character constants that are used in output functions.

P.Madhubabu M.C.A & M.Tech 22


Problem Solving in C B.Sc 1st Year---1st Semester
4.Strings: A String is an array of characters ended with a null character(\0). This null
character indicates that string has ended. Strings are always enclosed with double quotes(“ “).
Let us see how to declare String in C language:
Examples:
char string[20] = {‘s’,’t’,’u’,’d’,’y’, ‘\0’};
char string[20] = “demo”;
char string[] = “demo”;
5.Special Symbols: The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.
Some special characters are used in C, and they have a special meaning which cannot be used
for another purpose.
i) Square brackets[]: The opening and closing brackets represent the single and
multidimensional subscripts.
ii) Simple brackets ( ): It is used in function declaration and function calling. For example,
printf() is a pre-defined function.
iii) Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
iv) 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.
v) Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that
we are using the header file.
vi) Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
vii) Tilde (~): It is used as a destructor to free memory.
viii) Period (.): It is used to access a member of a structure or a union.
6.Operators: C operators are symbols that triggers an action when applied to C variables
and other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
i)Unary Operators: A unary operator is an operator applied to the single operand.
Example:

increment operator (++),

decrement operator (--),

sizeof,

(type)*.
ii)Binary Operators: The binary operator is an operator applied between two operands. The
following is the list of the binary operators:
a) Arithematic Operators
b) Relational Operators
c) Logical Operators
d) Increment & Decrement Operators
e) Assignment Operators
f) Bitwise Operators
g) Conditional Operator
h) Special Operators
iii)Ternary Operators: These operators requires three operands to act upon.
Example: ? : is the ternary operator.
Q6) Explain about Datatypes in C Language?
A data type represents the type of the variable, means what value that variable will
store. All ‘C’ compilers support variety of data types. Generally data is represented using

P.Madhubabu M.C.A & M.Tech 23


Problem Solving in C B.Sc 1st Year---1st Semester
numbers and characters. The number may be integer or real. The different compilers support
the different data types.

Classification of data types:


1. Primary Datatypes
1. User-defined Datatypes
1.Primary Datatypes: The primary datatypes are also called as simple datatypes or standard
datatypes.

These primary data types are divided into 3 categories . They are:
a)Integral Datatypes
b)Floating point Datatypes
c)Character Datatypes
a)Integral Datatypes: Integral data types are used to allocate memory for integer values.
→int, short int, long int are signed datatypes used to store positive values and also negative
values.
→unsigned int, unsigned short int, unsigned long int types allows only positive values.
→These integer datatype can also accepts octal values, hexa decimal values.
signed int – 2bytes -> -32,768 to +32767
unsigned int – 2bytes -> 0 to 65535
Syntax: Datatype variable-name; (or) Datatype identifier;
Ex: int a=26; //decimal representation
int a=032; //octal representation
int a=0x1a; //hexa decimal representation
b)Floating point Datatypes: float, double, long double are the floating datatypes, which are
used to store decimal values. float takes 4 bytes of memory and double takes 8 bytes of
memory it is capable of representing about twice as much precision as a float. The long double
takes 10 bytes of memory.

P.Madhubabu M.C.A & M.Tech 24


Problem Solving in C B.Sc 1st Year---1st Semester
Ex: float a;
a = 0.143;

float pi;
double pi_sqr;

pi = 3.1417;
pi_sqr = pi * pi;

c)Character Data Types: signed char, unsigned char are the character datatypes.
Signed char – 1 byte -128 to +127
Unsigned char – 1 byte 0 to 255
signed char is used to store alphabets and unsigned char is used to store unsigned integer value
upto 255.
It allocates 1 byte memory for single character and also allocate memory for 1 byte to
unsigned integer. In ‘c’ language every character has a decimal value called ASCII(American
Standard Code Information Interchange)
Ex: char ch1 = ‘a’;
unsigned char ch2 = 25;

printf(“%c”,ch1);
printf(“%d”,ch2);
2.UserDefined Datatypes: structures, unions, typedef are examples to Userdefined datatypes.
The c language provides to create your own names for data types with this typedef keyword.
Ex: typedef int integer;
integer a, b;
Makes the name integer a synonym for int. it is used same as int.
The typedef declaration does not create a new type in any sense. It adds a new name for the
existing type. It makes easy to identify which purpose the variable is used.
Q7) Explain about Variables?
Variable: A variable is a name of the memory location. It is used to store data. Its value can
be changed, and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Declaration of a variable:
Synatx: datatype variable1, variable2,…;
Example:
int a; int a,b,c;
float b; (or) float n,m,o;
char c; char x,y,z;
Here, a, b, c are variables. The int, float, char are the data types.
Assinging of Variables:
We can also provide values while declaring the variables as given below:
int a=10,b=20;//declaring 2 variable of integer type
float f=20.8;
char c='A';
Rules for defining variables:
→A variable can have alphabets, digits, and underscore.
→A variable name can start with the alphabet, and underscore only. It can't start with a digit.
→No whitespace is allowed within the variable name.
→A variable name must not be any reserved word or keyword, e.g. int, float, etc.
Valid variable names:
int a;

P.Madhubabu M.C.A & M.Tech 25


Problem Solving in C B.Sc 1st Year---1st Semester
int _ab;
int a30;
Invalid variable names:
int 2;
int a b;
int long;
Types of Variables in C:
There are 5 types of variables in c:
a) local variable
b) global variable
c) static variable
d) automatic variable
e) external variable
a)Local Variable:
→A variable that is declared inside the function or block is called a local variable.
→It must be declared at the start of the block.
void function1()
{
int x=10;//local variable
}
→You must have to initialize the local variable before it is used.
b)Global Variable:
→A variable that is declared outside the function or block is called a global variable.
→Any function can change the value of the global variable. It is available to all the functions.
→It must be declared at the start of the block.
int value=20;//global variable
void function1()
{
int x=10;//local variable
}
c)Static Variable:
→A variable that is declared with the static keyword is called static variable.
→It retains its value between multiple function calls.
void function1()
{
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in
each function call, e.g. 11, 12, 13 and so on.
d)Automatic Variable:
→All variables in C that are declared inside the block, are automatic variables by default. →We
can explicitly declare an automatic variable using auto keyword.
void main()
{
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}

P.Madhubabu M.C.A & M.Tech 26


Problem Solving in C B.Sc 1st Year---1st Semester
e)External Variable:
→We can share a variable in multiple C source files by using an external variable.
→To declare an external variable, you need to use extern keyword.
myfile.h
extern int x=10;//external variable (also global)
program1.c
#include "myfile.h"
#include <stdio.h>
void printValue()
{
printf("Global variable: %d", global_variable);
}
Q8)What is Symbolic Constant? How to declare and use it?
Symbolic constant is a name substituted for a variable. Its value cannot be changed
during the execution of the program. Symbolic constants are also called C-preprocessor.
Another definition of C-symbolic constant is compiler directives because these constants give a
direction to the compiler for assigning a constant value to a variable. The general syntax of
symbolic preprocessor or symbolic compiler directive can be defined by using #define statement
as: #define <symbolic name> symbolic constant
Here symbolic name should be in capital letters, you can also use small letters in the
Turbo C environment but not in the ANSI C environment. Symbolic names are also some times
called constant identifiers. There are some rules used to define the #(hash) define statement.
These rules are described as below:
1. Symbolic names are similar to a variable name. These are mostly written in capital letters. This
is used to create a distinction between variables and symbolic names.
2. There should not be at the end of this statement.
3. There should be a blank space between symbolic name and symbolic constant.
4. There should be no space between # and define.
5. d in define statement should be in small letters.
6. Don't take symbolic name as variable in the main program.
7. Special characters cannot be used in symbolic name.
8. There should not be any = sign between symbolic name and value of symbolic constant.
9. Every symbolic name should be declared in separate line (separate define statement).
Some valid and invalid examples are as follows:
Valid : #define PI 3.142
#define NAME "Madhu"
Invalid:
#define X=2.5 (because= sign is used)
# define MAX 10 (space between# and define statement)
#Define R 30 (because d of define is in capital letter)
#define M 20; (no semicolon should be used at end)
#define N $ 20 (no special character should be used
#define Me N 30 20 (multiple value cannot be used in the define statement)
#define manoj kumar 20 (due to long symbolic name)
#define a[ 10] 25 (array not allowed).
#dEFINE A 20 (define should be in small letters)
Q9) What are the delimiters in C-Language?
In the C programming language, there are some special character used for special
syntactic meaning and these are called C delimiters. There are five powerful C delimiters used in
a C program. These are described as:
Delimiter Meaning
: (colon) Used for label entry.

P.Madhubabu M.C.A & M.Tech 27


Problem Solving in C B.Sc 1st Year---1st Semester
( ) (parenthesis) Used for expression and enclosing the arguments in
the function declaration.
[ ] (square bracket) Used for describing the size for array.
{ } (curly bracket or brace) Used for beginning and ending of function, blocks and
main program.
Q10)What are the Input/OutPut Statements in C language?
Input and Output statements are used to read and write the data in C programming. These are
embedded in stdio.h (standard Input/Output header file). There are mainly two types of
Input/Output functions. They are:
1. Formatted I/O functions
2. Unformatted I/O functions
1)Formatted input/output functions: The formatted input/output functions read and
write all types of data values. They require conversion symbol to identify the data type. Hence,
they can be used for both reading and writing the data of all types. The formatted functions
return the values after execution. There are 2 types of formatted I/O functions. They are:
a) scanf ( )
b) printf ( )
a) scanf(): scanf( ) function is used to read any type of data from the keyboard. This function
should have atleast two parameters. First one is the control string which has ‘code characters’.
The other parameter is ‘variable name’s. There must be atleast one variable name should be
present.
Syntax: scanf("control strings",arg1,arg2,..............argn);
Ex: scanf("control strings",&v1,&v2,&v3,................&vn);
Where arg1,arg2,..........argn are the arguments for reading and v1,v2,v3,........vn all are the
variables.
The scanf() format code (spedifier) is as shown in the below table:

Format Code Meaning


%c To read a single character
%d To read a signed decimal integer (short)
%ld To read a signed long decimal integer
%e To read a float value exponential
%f To read a float (short0 or a single precision value
%lf To read a double precision float value
%g To read double float value
%h To read short integer
%i To read an integer (decimal, octal, hexadecimal)
%o To read an octal integer only
%x To read a hexadecimal integer only
%u To read unsigned decimal integer (used in pointer)
%s To read a string
%[..] To read a string of words from the defined range
%[^] To read string of words which are not from the defined range
Example:
/*Program to illustrate the use of formatted code by using the formatted scanf() function */
#include<stdio.h>

P.Madhubabu M.C.A & M.Tech 28


Problem Solving in C B.Sc 1st Year---1st Semester
#include<conio.h>
void main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}
b)printf(): This ia an output function. It is used to display a text message and to display the
mixed type (int, float, char) of data on screen. The general syntax is as:
Syntax: printf("control strings",&v1,&v2,&v3,................&vn);
or
printf("Message line or text line");
Ex: printf(“Total=”%d”,sum);
or
printf(“Hello World”);
Where v1,v2,v3,........vn all are the variables.
The control strings use some printf() format codes or format specifiers or conversion characters.
These all are discussed in the below table as:
Format Code Meaning
%c To read a single character
%s To read a string
%d To read a signed decimal integer (short)
%ld To read a signed long decimal integer
%f To read a float (short0 or a single precision value
%lf To read a double precision float value
%e To read a float value exponential
%g To read double float value
%o To read an octal integer only
%x To read a hexadecimal integer only
%u To read unsigned decimal integer (used in pointer)
Example:
/*Below the program which show the use of printf() function*/
#include<stdio.h>
#include<conio.h>
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}
2)Unformatted input/output functions: The unformatted input/output functions only
work with the character data type. They do not require conversion symbol for identification of

P.Madhubabu M.C.A & M.Tech 29


Problem Solving in C B.Sc 1st Year---1st Semester
data type because they work only with character data type. There is no need to convert the
data. There are mainly six unformatted I/O functions discussed as follows:
a) getchar( )
b) getche( )
c) getch( )
d) gets( )
e) putch( )
f) putchar( )
g) puts( )
a)getchar(): This function is an Input function. It is used for reading a single character from
the keyborad. It is buffered function. Buffered functions get the input from the keyboard and
store it in the memory buffer temporally until you press the Enter key.
syntax: v=getchar();
where v is the variable of character type.
Example: char n;
n=getchar();
Example Program: /*To read a single character from the keyboard using the getchar()
function*/
#include<stdio.h>
#include<conio.h>
void main()
{
char n;
n=getchar();
}
b)putchar(): This function is an output function. It is used to display a single character on the
screen.
Syntax: putchar(v);
where v is the variable of character type.
Example: char n;
putchar(n);
Example program: /*Program illustrate the use of getchar() and putchar() functions*/
#include<stdio.h>
#include<conio.h>
void main()
{
char n;
n=getchar();
putchar(n);
}
c)gets(): This function is an input function. It is used to read a string from the keyboar. It is
also buffered function. It will read a string, when you type the string from the keyboard and
press the Enter key from the keyboard. It will mark nulll character ('\0') in the memory at the
end of the string, when you press the enter key.
Syntax: gets(v);
where v is the variable of character type.
Example: char n[20];
gets(n);
Example Program: /*Program to explain the use of gets() function*/
#include<stdio.h>
#include<conio.h>
void main()
{
P.Madhubabu M.C.A & M.Tech 30
Problem Solving in C B.Sc 1st Year---1st Semester
char n[20];
gets(n);
}
d)puts(): This is an output function. It is used to display a string inputted by gets() function.
It is also used to display an text (message) on the screen for program simplicity. This function
appends a newline ("\n") character to the output.
Syntax: puts(v);
or
puts("text line");
where v is the variable of character type.
Example Program: /*Program to illustrate the concept of puts() with gets() functions*/
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}
OUTPUT IS:
Enter the Name
Laura
Name is:
Laura
e)getch(): This is also an input function. This is used to read a single character from the
keyboard like getchar() function. But getchar() function is a buffered is function, getchar()
function is a non-buffered function. The character data read by this function is directly assign to
a variable rather it goes to the memory buffer, the character data directly assign to a variable
without the need to press the Enter key.
Another use of this function is to maintain the output on the screen till you have not press the
Enter Key.
Syntax: v = getch();
where v is the variable of character type.
Example Program: /*Program to explain the use of getch() function*/
#include<stdio.h>
#include<conio.h>
void main()
{
char n;
puts("Enter the Char");
n=getch();
puts("Char is :");
putchar(n);
getch();
}
OUTPUT IS:
Enter the Char
Char is L
f)getche(): All are same as getch(0 function execpt it is an echoed function. It means when
you type the character data from the keyboard it will visible on the screen.
Syntax: v = getche();
P.Madhubabu M.C.A & M.Tech 31
Problem Solving in C B.Sc 1st Year---1st Semester
where v is the variable of character type.
Example: /*Program to explain the use of getch() function*/
#include<stdio.h>
#include<conio.h>
void main()
{
char n;
puts("Enter the Char");
n=getche();
puts("Char is :");
putchar(n);
getche();
}
OUTPUT IS:
Enter the Char L
Char is L

Q11)What is an Operator? List out various types of operators used in


‘C’?
Operator: An operator is a symbol used to perform mathematical and logical operations in a
program. That means an operator is a special symbol that tells to the compiler to perform
mathematical or logical operations. C programming language supports rich set of operators that
are classified as follows...
1. Arithematic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
1.Arithematic Operators (+, -, *, /, %): The arithematic operators are the symbols
that are used to perform basic mathematical operations like addition, subtraction,
multiplication, division and percentage modulo. The following table provides information
about arithematic operators...
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 5 * 10 = 50
/ Division 10 / 5 = 2
% Remaider of Division 5%2=1
⇒ The addition operator can be used with numerical data types and character data type. When
it is used with numerical values, it performs mathematical addition and when it is used with
character data type values, it performs concatination (appending).
⇒ The remainder of division operator is used with integer data type only.
2.Relational Operators (<, >, <=, >=, ==, !=): The relational operators are
the symbols that are used to compare two values. That means, the relational operators are used
to check the relationship between two values. Every relational operator has two results TRUE or
FALSE. In simple words, the relational operators are used to define conditions in a program. The
following table provides information about relational operators...
P.Madhubabu M.C.A & M.Tech 32
Problem Solving in C B.Sc 1st Year---1st Semester
Operator Meaning Example
Returns TRUE if first value is smaller than second value 10 < 5 is
<
otherwise returns FALSE FALSE
Returns TRUE if first value is larger than second value
> 10 > 5 is TRUE
otherwise returns FALSE
Returns TRUE if first value is smaller than or equal to 10 <= 5 is
<=
second value otherwise returns FALSE FALSE
Returns TRUE if first value is larger than or equal to 10 >= 5 is
>=
second value otherwise returns FALSE TRUE
Returns TRUE if both values are equal otherwise returns 10 == 5 is
==
FALSE FALSE
Returns TRUE if both values are not equal otherwise 10 != 5 is
!=
returns FALSE TRUE
3.Logical Operators (&&, ||, !): The logical operators are the symbols that are used to
combine multiple conditions into one condition. The following table provides information
about logical operators...
Operator Meaning Example
Logical AND - Returns TRUE if all conditions are 10 < 5 && 12 > 10 is
&&
TRUE otherwise returns FALSE FALSE
Logical OR - Returns FALSE if all conditions are 10 < 5 || 12 > 10 is
||
FALSE otherwise returns TRUE TRUE
Logical NOT - Returns TRUE if condition is FLASE !(10 < 5 && 12 >
!
and returns FALSE if it is TRUE 10) is TRUE
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE
then complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
then complete condition becomes TRUE.
4.Increment & Decrement Operators (++, --): The increment and decrement
operators are called as unary operators because, both needs only one operand. The increment
operators adds one to the existing value of the operand and the decrement operator subtracts
one from the existing value of the operand. The following table provides information about
increment and decrement operators...
Operator Meaning Example
int a = 5;
++ Increment - Adds one to existing value
a++; ⇒ a = 6
int a = 5;
-- Decrement - Subtracts one from existing value
a--; ⇒ a = 4
The increment and decrement operators are used infront of the operand (++a) or after the
operand (a++). If it is used infront of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement: In case of pre-increment, the value of the variable is
increased by one before the expression evaluation. In case of pre-decrement, the value of the
variable is decreased by one before the expression evaluation. That means, when we use pre
increment or pre decrement, first the value of the variable is incremented or decremented by
one, then modified value is used in the expression evaluation.
Example:
P.Madhubabu M.C.A & M.Tech 33
Problem Solving in C B.Sc 1st Year---1st Semester
#include <stdio.h>
void main()
{
int i=5;
printf("%d\t",++i);
printf("%d",--i);
}
Output: 6 5
Post-Increment or Post-Decrement: In case of post-increment, the value of the variable is
increased by one after the expression evaluation. In case of post-decrement, the value of the
variable is decreased by one after the expression evaluation. That means, when we use post-
increment or post-decrement, first the expression is evaluated with existing value, then the value
of the variable is incremented or decremented by one.
Example:
#include <stdio.h>
void main(){
int i=5;
printf("%d\t",i++);
printf(“%d”,i--);
}
Output: 6 6
5.Assignment Operators (=, +=, -=, *=, /=, %=): The assignment operators are
used to assign right hand side value (Rvalue) to the left hand side variable (Lvalue). The
assignment operator is used in different variants along with arithematic operators. The following
table describes all the assignment operators in C programming language.
Operator Meaning Example
= Assign the right hand side value to left hand side variable A = 15
Add both left and right hand side values and store the A+=10
+=
result into left hand side variable ⇒ A=A+10
Subtract right hand side value from left hand side
A-=B
-= variable value and store the result into left hand side
⇒ A=A-B
variable
Multiply right hand side value with left hand side
A*=B
*= variable value and store the result into left hand side
⇒ A=A*B
variable
Divide left hand side variable value with right hand side
A/=B
/= variable value and store the result into left hand side
⇒ A=A/B
variable
Divide left hand side variable value with right hand side
A%=B
%= variable value and store the remainder into left hand
⇒ A=A%B
side variable
6.Bitwise Operators (&, |, ^, ~, >>, <<): The bitwise operators are used to
perform bit level operations in c programming language. When we use the bitwise operators,
the operations are performed based on the binary values. The following table describes all the
bitwise operators in C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100)
Operator Meaning Example
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is A&B⇒16 (10000)

P.Madhubabu M.C.A & M.Tech 34


Problem Solving in C B.Sc 1st Year---1st Semester
0
| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A|B⇒ 29 (11101)
the result of Bitwise XOR is 0 if all the bits are same otherwise
^ A^B⇒ 13 (01101)
it is 1
the result of Bitwise once complement is nagation of the bit
~ ~A⇒ 6 (00110)
(Flipping)
the Bitwise left shift operator shifts all the bits to the left by A<<2⇒100
<<
specified number of positions (1100100)
the Bitwise right shift operator shifts all the bits to the right by A>>2⇒ 6
>>
specified number of positions (00110)

7.Conditional Operator (?:): The conditional operator is also called as ternary


operator because it requires three operands. This operator is used for decision making. In this
operator, first we verify a condition, then we perform one operation out of the two operations
based on the condition result. If the condition is TRUE the first option is performed, if the
condition is FALSE the second option is performed. The conditional operator is used with the
following syntax...
Condition ? TRUE Part : FALSE Part ;
Example:
A = (10<15) ? 100 : 200 ; ⇒ A value is 100
8.Special Operators (sizeof, pointer, comma, dot):
The following are the special operators in c programming language...
a)sizeof operator: This operator is used to find the size of the memory (in bytes) allocated
for a variable. This operator is used with the following syntax...
Syntax: sizeof(variableName);
Example: sizeof(A); ⇒ result is 2 if A is an integer
b)Pointer operator (*): This operator is used to define pointer variables in c programming
language.
c)Comma operator (,): This operator is used to separate variables while they are declaring,
separate the expresions in function calls etc..
d)Dot operator (.): This operator is used to access members of sructure or union.

Q12) Explain different Control Statements available in C?


Control Structures: Control structures are used to change the flow of execution program.
Default flow of execution program is sequential.
Generally In Low level languages statements flow is sequential. If we want to execute the
statements another time we must define the code another time that means redundancy will
occur. Program size is increases. To solve this redundancy in high level languages introduced
Control Structures. Using this structures we can execute the group of statements no. of times
without writing the code another time.
They are:
1)Conditional Control Statements
2)Un Conditional Control Statements
1)Conditional Control Statements: The Conditional Control statements are used to
change the sequence of program execution based on condition. There are three types of
conditional control statements.
i) Decision Making statements
ii) Branching statements
iii) Looping statements
P.Madhubabu M.C.A & M.Tech 35
Problem Solving in C B.Sc 1st Year---1st Semester
i)Decision Making statements: The decision making statements checks the given condition
and then executes its block. The decision statement decides the statement to be executed after
the success or failure of a given condition. The conditional statements use relational operators.
The relational operators are useful for comparing the two values. ‘if’ statement is called as
Decision Making statement.
if statement: C uses the keyword ‘if’ to execute a set of lines or one line when the condition is
true. The ‘if’ statement is is used to control the flow of execution of statements.
‘If’ statement can be classified into 4 types.
a) Simple if statement
b) if…else statement
c) nested-if statement
d) else-if (ladder) statement.
a)Simple-if statement: In this the statement is executed only when the given condition is
true. In case the condition is false the compiler skips the lines within the if block.
Syntax: if (condition)
{
Statement1;
}
Statement_x;
Flow-chart:

Example: Program to check whether the given number is EVEN or ODD.


#include<stdio.h>
#include<conio.h>
void main()
{
int num, a;
clrscr();
printf("\n Enter any number....");
scanf("%d",&num);
a=num%2;
if(a==0)
{
printf("\n Given number is EVEN...");
return;
}
printf("\n Given number is ODD...");
getch();
}
OUT PUT:
Enter any number.....8
Given number is EVEN...

P.Madhubabu M.C.A & M.Tech 36


Problem Solving in C B.Sc 1st Year---1st Semester
Enter any number.... 9
Given number is ODD....
b)if-else Statement: An ‘if’ statement with ‘else’ is called as if-else statement. If the
condition is true, true block statements are executed. If the condition is false, else block
statements are executed.
Syntax:
if (Condition)
{
True Statement;
}
else
{
False statement;
}
Statement_X;
Flow-chart:

Example: Program to check whether the given year is leap or not


#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("\n enter any year");
scanf("%d",&year);
if(year%4==0 )
printf("\n %d is a Leap Year...",year);
else
printf("\n %d is not a Leap Year....",year);
getch();
}
OUT PUT:
enter any year...2008
2008 is a Leap Year...

enter any year...2009


2009 is not a Leap Year...
c)Nested-if Statement: An ‘if’ statement which contains another ‘if’ statement is called as
nested if.
Syntax: if (Condition1)

P.Madhubabu M.C.A & M.Tech 37


Problem Solving in C B.Sc 1st Year---1st Semester
{
if (Conditon2)
Statement 1;
else
Statement 2;
}
else
{
Statement 3;
}
Statement X;

Flow-chart:

Program: Program to find biggest number from given three numbers using nested-if
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter the a,b,c values\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("a is big");
else
printf("c is big");
}
else
{
if(b>c)
printf("b is big");
else
printf("c is big");
}
}
OUTPUT:
enter the a,b,c values: 10 20 30
c is big

P.Madhubabu M.C.A & M.Tech 38


Problem Solving in C B.Sc 1st Year---1st Semester
d)else–if (ladder-if): It is a multi conditional checking statement that checks more than one
condition. The statements of the respective matched condition are the executed.
Syntax:
if(Condition 1)
Statement 1;
else if(Condition 2)
Statement 2;
else if(Condition 3)
Statement 3;
else
Statement 4;
Statement X;

Flow-chart:

Example: Program to check whether the given character is capital letter (or) small
letter (or) number (or) a symbol
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("\n enter any character.....");
scanf("%c",&ch);
if(ch>='A'&&ch<='Z')
printf("%c is a Capital Letter...",ch);
else if(ch>='a' && ch<='z')
printf("%c is a Small Letter...",ch);
else if(ch>='0' &&ch<='9')
printf("%c is a number.....",ch);
else
printf("%c is a symbol....",ch);
getch();
}
OUTPUT:
enter any character.... G
G is a Capital Letter.....
enter any character.. $
P.Madhubabu M.C.A & M.Tech 39
Problem Solving in C B.Sc 1st Year---1st Semester
$ is a symbol......
ii) Branching statements:
Switch Statement: Switch statement takes the given expression and executes the block of the
given expression. If expression not found then executes default block.
Syntax:
switch( expr )
{
case exp1 :
statement1;
break;
case exp2 :
statement2;
break;
.....
.....
case exp_n :
statement-n;
break;
default:
default_statements;
}
Example: Program to read the single digit number and print that digit number into Words
#include<stdio.h>
#include<conio.h>
void main( )
{
int no;
clrscr();
printf("Enter any number:");
scanf(“%d”,&no);
switch(no)
{
case 0: printf("zero");
break;
case 1: printf("two");
break;
case 2: printf("two");
break;
case 3: printf("three");
break;
case 4: printf("four");
break;
case 5: printf("five");
break;
case 6: printf("six");
break;
case 7: printf("seven");
break;
case 8: printf("eight");
break;
P.Madhubabu M.C.A & M.Tech 40
Problem Solving in C B.Sc 1st Year---1st Semester
case 9: printf("nine");
break;
default: printf("Invalid single digit");
}
}
iii)Looping statements: A portion of the program that is executed repeatedly is called a
loop. A looping statement can also be called as iterative statement that executes a set of
statements repeatedly for the specified number of times based upon the given condition. The C
programming language contains three different program statements for program looping. They
are:
a)while loop
b)do while loop
c)for loop
a)while Loop: while loop executes the block number of times until the condition is false.
Syntax: initialisation_section;
while(condition)
{
//statements
Increment/decrement
}
Next_statements;
Flow-chart:

Example: Program to generate the numbers from 1 to n using while loop


#include<stdio.h>
#include<conio.h>
void main( )
{
int i=1,n;
clrscr();
printf("How much range you want……");
scanf(“%d”,&n);
while(i<=n)
{
printf(“%d\t”,i);
i++;
}
getch();
}

P.Madhubabu M.C.A & M.Tech 41


Problem Solving in C B.Sc 1st Year---1st Semester
b)do..while Loop: As like while loop do..while also executes the block no. of times until the
condition is false. But difference is while loop first checks the condition and execute the
statement. So while loop is called entry checking loop. do..while first executes the block after
check the condition. So this is called exit checking loop.
Syntax: initialisation_section;
do
{
//statements
Increment/decrement
}while( condition );
Next_statements;
Flow-chart:

Example: Program to find sum of sequence numbers in a given range using do..while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,n,sum=0;
clrscr();
printf("How much range you want……");
scanf(“%d”,&n);
do
{
sum=sum+i;
i=i+1;
} while( i<=n);
getch();
}
c)for loop: ‘for’ statement execute the block n number of times until the condition is false.
This for loop statement contains 3 parts. First one is initialization section in this section we can
define the variables which are used in the block, second one is condition, third one is
increment/decrement block
Syntax:
for(initialization ; condition; increment/decrement)
{
//statements;
}

P.Madhubabu M.C.A & M.Tech 42


Problem Solving in C B.Sc 1st Year---1st Semester
Flow-Chart:

Example: Program to generate the numbers in ascending and descending order in a given
range using for loop
#include<stdio.h>
#include<conio.h>
void main( )
{
int n;
clrscr();
printf("How much range you want……");
scanf(“%d”,&n);
printf(“\nASCENDING ORDER\n”);
printf(“--------------------------------\n”);
for(int i=1;i<=n;i++)
{
printf(“%d\t”,i);
}
printf(“\nDESCENDING ORDER\n”);
printf(“--------------------------------\n”);
for(int i=n;i>=1;i--)
{
printf(“%d\t”,i);
}
getch();
}

Q13)Explain about Nested Loops?


As the name already suggests, a loop inside a loop is called Nested Loop. There can be any
number of loops inside a loop. We know there are generally many looping conditions like for,
while, and do-while. We can loop different kinds of loops within each other to form nested
loops. C language supports this functionality of Nested Loops. below is the syntax of Nested
Loop in C.
Syntax:
Outside_loop
{

P.Madhubabu M.C.A & M.Tech 43


Problem Solving in C B.Sc 1st Year---1st Semester
//Outside Loop Statements
Inside_loop
{
//Inside loop Statements
}
}
Flow chart:

Example: Program to generate the factorial of a numbers in the given range.


#include<stdio.h>
#include<conio.h>
void main( )
{
int i,n,fact,m;
clrscr();
printf(“enter the range……”);
scanf(“%d”,&m);
for( i=1; i<=m; i++)
{
n=i;
fact=1;
for(int j=1; j<=n; j++)
fact=fact*j;
printf(“%d factorial is %d”,n,fact);
}
getch();
}
2)Unconditional Control Statements: Unconditional control statements are used to
change the sequence of program execution without using any condition. Goto, continue, break,
exit, return statement is a unconditional control statements.
a)goto Statement: goto statement is used to execute the specific block.
The goto requires a label in order to execute the specific code. A ‘label’ is any valid
variable name, and must be followed by a colon. The label is placed immediately before the
statement where the control is to be transferred.
Syntax:
label:
P.Madhubabu M.C.A & M.Tech 44
Problem Solving in C B.Sc 1st Year---1st Semester
Statements;
goto label;

Forward branching Backward branching


goto label: Label:
……………. statement;
…………… …………….
…………… ……………
label: goto label:
statement;
(a) Forward Jump (b) mp

/************************************
EXAMPLE FOR goto
*************************************/
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
int no;
char ch;
read:
clrscr();
printf(“Enter the number “);
scanf(“%d”,&no);
if( no % 2 == 0 )
printf(“Given no is even”);
else
printf(“Given no is odd”);
printf(“Do u want to check another no(y/n):”);
ch=getche();
if(ch==’Y’ )
goto read;
}
b)break: Terminates the loop in middle of execution
/*********************************************************
EXAMPLE FOR break
**********************************************************/
#include<stdio.h>
#include<conio.h>
main()
{
int i=0;
while( i<=10 )
{
i++;
P.Madhubabu M.C.A & M.Tech 45
Problem Solving in C B.Sc 1st Year---1st Semester
if(i==5 )
break;
printf(“%3d”,i);
}
printf(“while terminated”);
}
Output:
1234
While terminated
c)continue: used to skip the specific iteration of the loop and continue the next iterations
/*********************************************************
EXAMPLE FOR continue
**********************************************************/
#include<stdio.h>
#include<conio.h>
main()
{
int i;
i = 0;
while( i<=10 )
{
i++;
if(i==5)
continue;
printf(“%3d”,i);
}
}
Output: 1 2 3 4 6 7 8 9 10
d)exit: Terminates the application in middle of execution
/*********************************************************
EXAMPLE FOR exit
**********************************************************/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int i=0;
while( i<=10 )
{
i++;
if(i==5 )
exit(0);
printf(“%3d”,i);
}
printf(“program terminated”);
}

Output:
1234
5)return: Terminates the function in middle of execution
/*********************************************************
EXAMPLE FOR ‘return’
**********************************************************/
P.Madhubabu M.C.A & M.Tech 46
Problem Solving in C B.Sc 1st Year---1st Semester
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int i=0;
while( i<=10 )
{
i++;
return;
printf(“%3d”,i);
}
printf(“program terminated”);
}

Output:
1

P.Madhubabu M.C.A & M.Tech 47


Problem Solving in C B.Sc 1st Year---1st Semester
UNIT-3
Q1)What is an Array? Explain about various types of Arrays?
Array: An Array is a collection of homogeneous (sametype) values, represented with a single
name. Array represents no. of blocks each block is identified with index.
• An array is a group of related data items that shares a common name (or) An array is a
collection of identically typed variables stored contiguously in memory.
• Each variable in an array is called an element and can be accessed by giving the array
name plus an index expression called a subscript. A subscript value of 0 identifies the
initial element; a value of 1 identifies the next element, and so forth.
• The most basic purpose of arrays is to store large amounts of related data that share the
same data type.
Advantages of Array:
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantages of Array:
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of Array:
Syntax: Datatype array_name [size];
→Where data type is a valid data type, array_name is the name of the array and size is the
number of elements that array contains.
Ex: int a[5];
This example will tells the compiler a is an array which contains 5 elements of type integer. The
first position of the array is 0 and last position is 4.
Array Initialization (or) Storing values in Array:
Ex1:
int a[5];

a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
(or)
Declaration with Initialization: We can initialize the array at the time of declaration. Let's
see the code.
Ex2:
int a[5]={10,20,30,40,50};
Note:In such case, there is no requirement to define the size. So it may also be written as the
following code.
Ex3:
int a[]={10,20,30,40,50};
Operation on Array: Following are the various operations supported by an array.
i) Traverse − print all the array elements one by one.
ii) Insertion − add an element at given index.
iii) Deletion − delete an element at given index.
iv) Search − search an element using given index or by value.
v) Update − update an element at given index.

P.Madhubabu M.C.A & M.Tech 48


Problem Solving in C B.Sc 1st Year---1st Semester
i.Traverse Operation: In traversing operation of an array, each element of an array is accessed
exactly for once for processing. This is also called visiting of an array.
ii.Insertion Operation: Insert operation is to insert one or more data elements into an array.
Based on the requirement, new element can be added at the beginning, end or any given index
of array.
iii.Deletion Operation: Deletion refers to removing an existing element from the array and
re-organizing all elements of an array.
iv.Search Operation: You can perform a search for array element based on its value or its
index.
v.Update Operation: Update operation refers to updating an existing element from the array
at a given index.
Types of Arrays:
1) Single Dimensional Arrays
2) Double Dimensional Arrays
3) Multi Dimensional Arrays
1)Single Dimensional Array: It is a collection of same type of number of values. It is a
collection of cells. Each cell is identified by a index. Starting index is ‘0’. Last index is array size-1.
Syntax: Datatype variable[size];
Ex: int a[10];
initialization of array:
int a[5] = {1,2,3,4,5};
(or)
int a[5];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
Example: program for static initialization of Array and print that array values
#include<stdio.h>
#include<conio.h>
main()
{
int i, a[5]={10,20,30,40,50};
clrscr();
printf(“The given Array is:\n”);
for( i=0; i<5; i++ )
printf(“%3d”,a[i]);
getch();
}
Example: program to read n no. of values in to array and print that array values
#include<stdio.h>
#include<conio.h>
main()
{
int i, n, a[10];
clrscr();
printf(“How many values do u want to read :”);
scanf(“%d”,&n);
printf(“Enter %d array values : \n“,n);

P.Madhubabu M.C.A & M.Tech 49


Problem Solving in C B.Sc 1st Year---1st Semester
for( i=0; i<n; i++ )
scanf(“%d”,&a[i]);
printf(“The given Array is:\n”);
for( i=0; i<n; i++ )
printf(“%3d”,a[i]);
getch();
}
2)Double Dimensional Array: It is a collection of single dimension arrays. It is a collection
of rows. It is also called as Matrix. Each array is identified by with ‘i’ i.e row position and each
column is identified with ‘j’ i.e. column position.
Syntax: Datatype variable[row_size][col_size];
Example: int a[2][4];
initialization of Double Dimensional array:
int a[2][4] = {
{1,2,3,4},
{5,6,7,8}
};

(or)

int a[2][4];
a[0][0]=1; a[0][1]=2; a[0][2]=3; a[0][3]=4;
a[1][0]=5; a[1][1]=6; a[1][2]=7; a[1][3]=8;

Example: Program to initialization of Double Dimensional array and access the values
#include<stdio.h>
#include<conio.h>
main()
{
int i, j;
int a[3][3] = {{1,2,3}, {4,5,6}, {7,8,9]};
printf(“Matrix is\n”);
for( i=0; i<3; i++ )
{
for(j=0; j<3; j++)
{
printf(“%3d”,a[i][j]);
}
printf(“\n”);
}
getch();
}
Example: Program to read matrix row, column sizes and read the matrix values and display the
matrix
#include<stdio.h>
#include<conio.h>
main()
{
int i, j, rows, cols, a[5][5];
clrscr();
printf(“Enter the matrix row, col sizes :”);
scanf(“%d%d”,&rows,&cols);
printf(“Enter a[%d][%d] matrix values :\n“,rows,cols);
P.Madhubabu M.C.A & M.Tech 50
Problem Solving in C B.Sc 1st Year---1st Semester
for( i=0; i<rows; i++ )
{
for( j=0; j<cols; j++ )
{
scanf(“%d”,&a[i][j]);
}
}
printf(“The Matrix is….. \n”);
for( i=0; i<rows; i++ )
{
for( j=0; j<cols; j++ )
{
printf(“%3d”,a[i][j]);
}
printf(“\n”);
}
getch();
}

3)Multi Dimensional Array: It is a collection of double dimension arrays. Each double


dimension array is identified by with ‘i’ each array is identified by ‘j’ and each value is identified
by with ‘k’.
Syntax: Datatype variable[no_of_dd_arrays][row_size][col_size];
EX:
int a[2][3][3];
initialization of array:
int a[2][3][3] ={
{
{1,2,3},
{4,5,6},
{7,8,9}
},
{
{1,2,3},
{4,5,6},
{7,8,9}
},
};

(Or)

int a[2][3][3]= {
{ {1,2,3},{4,5,6},{7,8,9} } ,
{ {1,2,3}, {4,5,6}, {7,8,9} }
};

Example: Program to initialize and print the Multi- Dimensional array


#include<stdio.h>
#include<conio.h>
main()
{
int i, j, k;
int a[2][3][3] = {{1,2,3}, {4,5,6}, {7,8,9},{1,2,3}, {4,5,6}, {7,8,9}};
clrscr();
P.Madhubabu M.C.A & M.Tech 51
Problem Solving in C B.Sc 1st Year---1st Semester
printf(“Matrix is\n”);
for( i=0; i<2; i++ )
{
for(j=0; j<3; j++)
{
for(k=0; k<3; k++ )
{
printf(“%3d”,a[i][j][k]);
}
printf(“\n”);
}
printf(“\n\n”);
}
getch();
}

Q2)What are the Character Handling Functioins?


Character test functions are used with getchar and putchar statements. These functions
are always used with decision making if statements and looping statements.
There are several character handling functions are linked with the "ctype.h" header file
and should be defined in the link section of the C program. They are:
1) isalnum()
2) isalpha()
3) iscntrl()
4) isdigit()
5) isgraph()
6) islower()
7) isprint()
8) ispunct()
9) isspace()
10) isupper()
11) isxdigit()
12) tolower()
13) toupper()
1)int isalnum(int c): This function returns nonzero if c is alphanumeric otherwise this will return
zero which will be equivalent to false.
Example:
#include<stdio.h>
#include<ctype.h>
int main()
{
if(isalnum(';'))
{
printf("Character ; is not alphanumeric\n");
}
if( isalnum( 'A' ) )
{
printf("Character A is alphanumeric\n");
}
return 0;
}
Output: Character A is alphanumeric
2)int isalpha(int c): This function returns nonzero if c is just alpha otherwise this will return
zero which will be equivalent to false.
P.Madhubabu M.C.A & M.Tech 52
Problem Solving in C B.Sc 1st Year---1st Semester
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if(isalpha('9'))
{
printf("Character 9 is not alpha\n");
}
if(isalpha('A'))
{
printf("Character A is alpha\n");
}
return 0;
}
Output: Character A is alpha
3)int iscntrl(int c): This function returns nonzero if c is control chracter line new line, back space
etc. otherwise this will return zero which will be equivalent to false.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if(iscntrl( 'a'))
{
printf( "Character a is not control character\n" );
}
if(iscntrl( '\n'))
{
printf( "Character \n is control chracter\n" );
}
return 0;
}
Output: Character \n is control chracter
4)int isdigit(int c): This function returns nonzero if c is a digit otherwise this will return zero
which will be equivalent to false.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if(isdigit('9' ))
{
printf("Character 9 is a digit\n");
}
if(isdigit('A'))
{
printf("Character A is digit\n");
}
return 0;
}
Output: Character 9 is a digit

P.Madhubabu M.C.A & M.Tech 53


Problem Solving in C B.Sc 1st Year---1st Semester
5)int isgraph(int c): This function returns nonzero if c is any character for which either isalnum
or ispunct returns nonzero.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if(isgraph('9'))
{
printf("Character 9 is a graph\n");
}
if(isgraph('A'))
{
printf( "Character A is graph\n" );
}
return 0;
}
Output: Character 9 is a graph
Character A is graph
6)int islower(int c): This function returns nonzero if c is lower case otherwise this will return
zero which will be equivalent to false.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if(islower('a'))
{
printf("Character a is lower case\n");
}
if(islower( 'A'))
{
printf("Character A is lower case\n");
}
return 0;
}
Output: Character a is lower case
7)int isprint(int c): This function returns nonzero if c is space or a character for which isgraph
returns nonzero.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if(isprint( ';' ))
{
printf( "Character ; is here\n" );
}
if( isprint( 'A' ) )
{
printf( "Character A is here\n" );
}
return 0;
P.Madhubabu M.C.A & M.Tech 54
Problem Solving in C B.Sc 1st Year---1st Semester
}
Output: Character ; is here
Character A is here
8)int ispunct(int c): This function returns nonzero if c is punctuation otherwise this will return
zero which will be equivalent to false.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if( ispunct('%' ))
{
printf("Character % is a punctuation\n");
}
if( ispunct('A'))
{
printf("Character A is a punctuation\n");
}
return 0;
}
Output: Character % is a punctuation
9)int isspace(int c): This function returns nonzero if c is space otherwise this will return zero
which will be equivalent to false.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if( isspace(' '))
{
printf( "Character is a space\n" );
}
if( isspace('A'))
{
printf( "Character A is a space\n" );
}
return 0;
}
Output: Character is a space
10)int isupper(int c): This function returns nonzero if c is upper case otherwise this will return
zero which will be equivalent to false.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if( isupper('a'))
{
printf("Character a is upper case\n");
}
if( isupper('A'))
{

P.Madhubabu M.C.A & M.Tech 55


Problem Solving in C B.Sc 1st Year---1st Semester
printf("Character A is upper case\n");
}
return 0;
}
Output: Character A is upper case
11)int isxdigit(int c): This function returns nonzero if c is hexa digit otherwise this will return
zero which will be equivalent to false.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
if(isxdigit('Z'))
{
printf( "Character Z is Hexa digit\n" );
}
if(isxdigit('A'))
{
printf("Character A is Hexa digit\n");
}
return 0;
}
Output: Character A is Hexa digit
12)int tolower(int c): This function returns the corresponding lowercase letter if one exists and
if isupper(c); otherwise, it returns c.
Example:
#include <stdio.h>
#include<ctype.h>
int main()
{
printf("Lower case of A is %c\n", tolower('A'));
printf("Lower case of 9 is %c\n", tolower('9'));
printf("Lower case of g is %c\n", tolower('g'));
return 0;
}
Output: Lower case of A is a
Lower case of 9 is 9
Lower case of g is g
13)int toupper(int c): This function returns the corresponding uppercase letter if one exists and
if islower(c); otherwise, it returns c.
Example
#include <stdio.h>
#include<ctype.h>
int main()
{
printf("Upper case of a is %c\n", toupper('a'));
printf("Upper case of 9 is %c\n", toupper('9'));
printf("Upper case of g is %c\n", toupper('g'));
return 0;
}
Output: Upper case of a is A
Upper case of 9 is 9
P.Madhubabu M.C.A & M.Tech 56
Problem Solving in C B.Sc 1st Year---1st Semester
Upper case of g is G
Q3)What is a String? How to read and write the Strings?
Strings are used to store the array of characters. A string is an array of characters terminated
by a null character. A null character is a character with a numeric value of zero. It represented
by the escape sequence ‘\0’.
A string constant, some times called a string literal, is any series of characters enclosed in
double quotes. It has a data type of array of char, and each character in the string takes up one
byte. In addition, the compiler automatically appends a null character to the end of the string.
Declaring Character Array:
Example:
char ch[6];
ch[0]=’H’;
ch[1]=’e’;
ch[2]=’l’;
ch[3]=’l’;
ch[4]=’o’;
ch[5]=’\0’; //don’t forget this!
(Or)
char ch[6]={‘H’,’e’,’l’,’l’,’o’,’\0’};
(Or)
char ch[]=”Hello”;

→If the string is shorter than the specified array size, the remaining elements of the array are
initialized to space.
Declaring Pointer Array: We may also initialize a char pointer with a string constant.
Example: char *ptr = “Hello”;
→All subsequent uses of the array name refer to the address of the array’s initial element. This
address as we said before cannot be changed. The pointer is a variable that is initialized with the
address of the array’s initial element. However we can assign a different address value to the
pointer. In this case the address with which it was initialized will be lost.
Note: Char array always refers to first value of the string. But pointer holds the address of
string. So we can modify the value of pointer but not modify the data in char[].
Rule for Declaring Array:
char st[]=”madhu”; //correct
st=”madhu”; //error
char *st=”madhu”;
st=”madhu”; //correct
Example-1: Program to assign the string into character array variable and print the string.
#include<stdio.h>
#include<conio.h>
main()
{
char st[6]={'m','a','d','h','u'};
int i;
clrscr();
for( i=0; i<6; i++ )
P.Madhubabu M.C.A & M.Tech 57
Problem Solving in C B.Sc 1st Year---1st Semester
printf("%c",st[i]);
getch();
}
Example-2: Program to assign the string into variable and print the string.
#include<stdio.h>
#include<conio.h>
main()
{
char st[]=”madhu”;
int i;
for( i=0; st[i]!=’\0’; i++ )
printf("%c",st[i]);
}
Example-3: Program to assign the string into variable and print the string.
#include<stdio.h>
#include<conio.h>
main()
{
char st[]=”madhu”;
int i;
clrscr();
printf(“%s”,st);
getch();
}
Example-4: Program to assign the string into character pointer variable and print the string.
#include<stdio.h>
#include<conio.h>
main()
{
char *st=”madhu”;
clrscr();
printf(“%s”,st);
getch();
}
Two dimensional array of characters: One character array is equal to one string. If we
want to store no. of strings into char variable we use two dimensional array.
Example:
char st[10]=”madhu”; //single array

char st[3][10]={”madhu”,”ramesh”,”mahesh”}; //two dimentional array


→The first subscript gives the number of names in the array, while the second subscript gives the
length of each item in the array.
Array of pointers to strings: As we know, a pointer variable always contains an address.
Therefore, if we construct an array of pointers it would contain a number of addresses.
Example:
char *st=”madhu”; //single string
char *st[]= {”madhu”,”ramesh”,”mahesh”}; //multiple strings
→ In the above example “madhu” is stored in st[0], “ramesh” is stored in st[1] and “mahesh” is
stored in st[2]. The st pointer array holds 3 address of strings.
Note: Pointer takes only size two bytes. Pointers are very helpful to manipulation the data
very fastly, there is no memory wastage in pointers. Observe the following example.
Example: Program for Array of pointers to strings

P.Madhubabu M.C.A & M.Tech 58


Problem Solving in C B.Sc 1st Year---1st Semester
#include<stdio.h>
#include<conio.h>
main()
{
char st[3][10] = {"madhu","ramesh","mahesh"};
char *ptr[3] = {"madhu","ramesh","mahesh"};
clrscr();
printf("%d\n",sizeof(st)); //size=30 bytes
printf("%d\n",sizeof(ptr)); //size=6 bytes
getch();
}
Note: Pointers always store the address of the strings. So memory is wastage in char array
compare to pointers.
Using pointers we can modify the strings fastly.
Example: Program to store 3 strings into char variable and print the strings
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char st[3][10]={“madhu”,”ramesh”,”mahesh”};
clrscr();
for( i=0; i<3; i++ )
printf(“%s”,st[i]);
getch();
}
Example: Program to store 3 strings into char pointer variable and print the strings
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char *st[3]={“madhu”,”ramesh”,”mahesh”};
clrscr();
for( i=0; i<3; i++ )
printf(“%s”,st[i]);
getch();
}
Example: Program to read n no. of strings and print the strings
#include<stdio.h>
#include<conio.h>
main()
{
int i, n;
char st[5][10];
clrscr();
printf(“How many strings do u want to read :”);
scanf(“%d”,&n);
for( i=0; i<n; i++ )
scanf(“%s”,&st[i]);
P.Madhubabu M.C.A & M.Tech 59
Problem Solving in C B.Sc 1st Year---1st Semester
printf(“Given strings\n”);
for( i=0; i<n; i++ )
printf(“%s”,st[i]);
getch();
}
Q4)Explain different String Handling Functions in C?
In ‘c’ language one header file is given to apply the different operations on strings that is
string.h. In this header file many string functions are available.
Ex: strcat, strlen, strrev, strupr,strlwr, strcmp, stricmp, strstr, strncmp,strncat etc…
Function Description
1) strcat() Appends a string to another string
2) strcmp() Compares two strings
3) strcmpi() Compares two strings ( case insensitive)
4) strcpy() Copies a string to another string
5) stricmp() Same as strcmpi()
6) strlen() Returns the length of a string
7) strlwr() String converted to lowercase
8) strncat() n characters of string appended
9) strncmp() n characters of two strings compared
10) strncpy() n character of a string are copied to another
11) strrev() Reverses characters in a string
12) strstr() Locates one string in another string
13) strupr() Converts string to uppercase
1)strcat(): Appends a string to another string
Syntax:
Strcat(string1,string2);
Ex:
char *st1 = “rama”;
char *st2 = “Krishna”;
strcat(st1,st2);
printf(“%s”,st1); //Ramakrishna
2)strcmp(): Compares to one string with another string. If both strings are equal this
function returns ‘0’, or if first string is greater than second string returns ‘1’ or if first string is less
than second string returns ‘-1’
Syntax: int res = Strcmp(string1,string2);
Ex:
int res = strcmp(“career”,”career”);
printf(“%d”,res); //0
3)strcmpi()/stricmp(): Compares to one string with another string without checking the
case. If both strings are equal this function returns ‘0’, or if first string is greater than second
string returns ‘1’ or if first string is less than second string returns ‘-1’
Syntax: int res = Stricmp(string1,string2);
Ex:
int res = stricmp(“career”,”CAREER”);
printf(“%d”,res); //0
4)strcpy(): Used to copy one string into another string
Syntax: strcpy(dest_string,source_string)
Ex:
char *st1=”career”;
char *st2;
strcpy(st2,st1);

P.Madhubabu M.C.A & M.Tech 60


Problem Solving in C B.Sc 1st Year---1st Semester
printf(“%s”,st2); //career
5)strlen(): Returns the length of string
Syntax: int length = Strlen(string1);
Ex:
char *st1= “govind”;
int length= Strlen(st1);
printf(“%d”,length); //6
6)strupr(): Converts the lower case string into uppercase
Syntax: strupr(string1);
Ex:
char *st1 = “madhu”;
strupr(st1);
printf(“%s”,st1); //MADHU
7)strlwr(): Converts the upper case string into lowercase
Syntax: strlwr(string1);
Ex:
char *st1 = “MADHU”;
strlwr(st1);
printf(“%s”,st1); //madhu
8)strrev(): Reverse the given string
Syntax: strrev(string1);
Ex:
char *st1 = “CAREER”;
strrev(st1);
printf(“%s”,st1); //REERAC
9)strncat(): Appends a ‘n’ no characters to another string
Syntax: Strncat(string1,string2,n);
Ex:
char *st1 = “rama”;
char *st2 = “Krishna”;
strncat(st1,st2,4);
printf(“%s”,st1); //Ramakris
10)strncmp(): Compares ‘n’ no of characters from one string with another string. If both
strings are equal this function returns ‘0’, or if first string is greater than second string returns ‘1’
or if first string is less than second string returns ‘-1’
Syntax: int res = Strncmp(string1,string2,n);
Ex:
int res = strncmp(“career”,”care”,3);
printf(“%d”,res); //0
11)strncpy: Used to copy ‘n’ no of characters from one string to another string
Syntax: strcpy(dest_string,source_string,n)
Ex:
char *st1=”career”;
char *st2;
strncpy(st2,st1,4);
printf(“%s”,st2); //care
12)strstr: Used to retrieve the sub porting of the string into main string
Syntax: Res_string = strstr(main_string,sub_string)
Ex:
char *st1 = "career degree college";
char *st2;
st2 = strstr(st1,"college");
printf(“%s”,st2); //college
P.Madhubabu M.C.A & M.Tech 61
Problem Solving in C B.Sc 1st Year---1st Semester
UNIT-4
Q1)What is a Function, what are the advantages of the functions (why
we need for functions)? How to declare, define and calling a function?
When we write a program to solve a larger problem, we divide that larger problem into smaller
subproblems and are solved individually to make the program easier. In C, this concept is
implemented using functions. Functions are used to divide a larger program into smaller
subprograms such that program becomes easy to understand and easy to implement. A function
is defined as follows...
Definition: Function is a subpart of program used to perform specific task and is executed
individually.
Every C program must contain atleast one function called main(). However a program may also
contain other functions.
Every function in C has the following...
1. Function Declaration (Function Prototype)
2. Function Definition
3. Function Call
1.Function Declaration: The function declaration tells the compiler about function name,
datatype of the return value and parameters. The function declaration is also called as function
prototype. The function declaration is performed before main function or inside main function
or inside any other function.
Function declaration syntax:
returnType functionName(parametersList);
In the above syntax, returnType specifies the datatype of the value which is sent as a return
value from the function definiton. The functionName is a user defined name used to identify the
function uniquely in the program. The parametersList is the data values that are sent to the
function definition.
2.Function Definition: The function definition provides the actual code of that function.
The function definition is also known as body of the function. The actual task of the function is
implemented in the function definition. That means the actual instructions to be performed by a
function are written in function definition. The actual instructions of a function are written
inside the braces "{ }". The function definition is performed before main function or after main
function.
Function definition syntax:
returnType functionName(parametersList)
{
Actual code...
}

3.Function Call: The function call tells the compiler when to execute the function
definition. When a function call is executed, the execution control jumps to the function
definition where the actual code gets executed and returns to the same functions call once the
execution completes. The function call is performed inside main function or inside any other
function or inside the function itself.
Function call syntax:
functionName(parameters);
Advantages of Functions:
1. Using funcions we can implement modular programming.
2. Functions makes the program more readable and understandable.
3. Using functions the program implementation becomes easy.
4. Once a function is created it can be used many times (code re-usability).
5. Using functions larger program can be divided into smaller modules.

P.Madhubabu M.C.A & M.Tech 62


Problem Solving in C B.Sc 1st Year---1st Semester
Q2)Explain the types (or) categories (or) classification of Functions?
In C Programming Language, based on providing the function definition, functions are divided
into two types. Those are as follows...
1. System Defined Functions
2. User Defined Functions
1.System Defined Functions: The C Programming Language provides pre-defined functions
to make programming easy. These pre-defined functions are known as syatem defined
functions. The system defined function is defined as follows...
Definition: The function whose definition is defined by the system is called as system defined
function.
Library Functions in Different Header Files and their functions…

C Header Files

<ctype.h> Character type functions Ex: isalpha(), islower(), isupper()…

<math.h> Mathematics functions Ex: pow(), sqrt(), ceil(), floor(),..

Standard Input/Output Ex: printf(), scanf(), putc(), getc(),..


<stdio.h>
functions

Standard Utility Ex: free(), abort(), exit(),….


<stdlib.h>
functions

<string.h> String handling functions Ex: strcat(), strcmp(), strcpy(), strlen()


Points to be Remembered:
• System defined functions are declared in header files
• System defined functions are implemented in .dll files. (DLL stands for Dynamic Link
Library).
• To use system defined functions the respective header file must be included.

2.User Defined Functions: In C programming language, users can also create their own
functions. The functions that are created by users are called as user defined functions. The user
defined function is defined as follows...
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,result;
int addition(int,int); // function declaration
clrscr();
printf("Enter any two integer numbers:") ;
scanf("%d%d",&num1,&num2);
result=addition(num1,num2); // function call
printf("SUM = %d", result);
getch() ;
}
int addition(int a,int b) // function definition
{
return a+b ;
}

P.Madhubabu M.C.A & M.Tech 63


Problem Solving in C B.Sc 1st Year---1st Semester
In the above example program, the function declaration statement "int
addition(int,int)" tells the compiler that there is a function with name addition which takes two
integer values as parameters and returns an integer value. The function call statement takes the
execution control to the additon() definition along with values of num1 and num2.
Then function definition executes the code written inside it and comes back to the function
call along with return value.
Based on the data flow between the calling function and called function, the functions
are classified as follows...
1. Function without Parameters and without Return value
2. Function with Parameters and without Return value
3. Function without Parameters and with Return value
4. Function with Parameters and with Return value
1.Function without Parameters and without Return value:
In this type of functions there is no data transfer between calling function and called function.
Simply the execution control jumps from calling function to called function and executes called
function, and finally comes back to the calling function.

Example:
#include <stdio.h>
#include<conio.h>
void main()
{
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}

2.Function with Parameters and without Return value:


In this type of functions there is data transfer from calling function to called function
(parameters) but there is no data transfer from called function to calling function (return value).
The execution control jumps from calling function to called function along with the parameters
and executes called function, and finally comes back to the calling function.

P.Madhubabu M.C.A & M.Tech 64


Problem Solving in C B.Sc 1st Year---1st Semester

Example:
#include <stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr();
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}

3.Function without Parameters and with Return value:


In this type of functions there is no data transfer from calling function to called function
(parameters) but there is data transfer from called function to calling function (return value).
The execution control jumps from calling function to called function and executes called
function, and finally comes back to the calling function along with a return value.

Example:
#include <stdio.h>
#include<conio.h>
void main()
{
int result ;
int addition() ; // function declaration
clrscr() ;

P.Madhubabu M.C.A & M.Tech 65


Problem Solving in C B.Sc 1st Year---1st Semester
result = addition() ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}

4.Function with Parameters and with Return value:


In this type of functions there is data transfer from calling function to called function
(parameters) and also from called function to calling function (return value). The execution
control jumps from calling function to called function along with parameters and executes called
function, and finally comes back to the calling function along with a return value.

Example:
#include <stdio.h>
#include<conio.h>
void main()
{
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}

Q3)Explain scope of variables?


When we declare a variable in a program, it can not be accessed against the scope rules.
Variables can be accessed based on their scope. The scope of a variable decides the portion of a
program in which the variable can be accessed. The scope of the variable is defined as follows...
“Scope of a variable is the portion of the program where a defined variable can be accessed.”
→The variable scope defines the visibility of variable in the program. Scope of a variable
depends on the position of variable declaration.

P.Madhubabu M.C.A & M.Tech 66


Problem Solving in C B.Sc 1st Year---1st Semester
→In C programming language, a variable can be declared in three different positions and they
are as follows...
1)Before the function definition (Global Declaration)
2)Inside the function or block (Local Declaration)
3)In the function definition parameters (Formal Parameters)
1)Before the function definition (Global Declaration): Declaring a variable before the
function definition (outside the function definition) is called global declaration. The variable
declared using global declaration is called global variable. Tha global variable can be accessed
by all the functions that are defined after the global declaration. That means the global variable
can be accessed any where in the program after its declaration. The global variable scope is said
to be file scope.
Example Program:
#include<stdio.h>
#include<conio.h>
int num1, num2 ;
void main()
{
void addition() ;
clrscr() ;
num1=10;
num2=20;
printf("num1=%d, num2=%d",num1,num2) ;
addition() ;
getch() ;
}
void addition()
{
int result ;
result=num1+num2;
printf("\naddition=%d",result) ;
}

→In the above example program, the variables num1 and num2 are declared as global
variables. They are declared before the main() function. So, they can be accessed by function
main() and other functions that are defined after main(). In the above example, the functions
main(), addition(), can access the variables num1 and num2.
2)Inside the function or block (Local Declaration): Declaring a variable inside the
function or block is called local declaration. The variable declared using local declaration is
called local variable. The local variable can be accessed only by the function or block in which it
is declared. That means the local variable can be accessed only inside the function or block in
which it is declared.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void addition() ;
int num1,num2 ;
clrscr() ;
num1=10 ;
num2=20 ;
printf("num1=%d, num2=%d",num1,num2) ;
addition() ;
getch() ;
P.Madhubabu M.C.A & M.Tech 67
Problem Solving in C B.Sc 1st Year---1st Semester
}
void addition()
{
int sumResult ;
sumResult=num1+num2;
printf("\naddition=%d",sumResult) ;
}

→The above example program shows an error because, the variables num1 and num2 are
declared inside the function main(). So, they can be used only inside main() function and not in
addition() function.
3)In the function definition parameters (Formal Parameters): The variables declared
in function definition as parameters have a local variable scope. These variables behave like
local variables in the function. They can be accessed inside the function but not outside the
function.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void addition(int,int) ;
int num1,num2 ;
clrscr() ;
num1=10 ;
num2=20 ;
addition(num1,num2) ;
getch() ;
}
void addition(int a,int b)
{
int sumResult;
sumResult=a+b;
printf("\naddition=%d",sumResult) ;
}

→In the above example program, the variables a and b are declared in function definition as
parameters. So, they can be used only inside the addition() function.
Q4)Explain about Storage Classes in ‘C’?
Storage class tells us:
1. Where the variable would be stored.
2. What will be the initial value of the variable, if the initial value is not specifically assigned
(i.e. the default initial value).
3. What is the scope of the variable; i.e., in which functions the value of the variable would be
available.
4. What is the life of the variable; i.e., how long would the variable exist.
There are four storage classes
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.

P.Madhubabu M.C.A & M.Tech 68


Problem Solving in C B.Sc 1st Year---1st Semester

1)Automatic Variables: ‘auto’ is a keyword which defines the local variable and having
a local lifetime. This is the default for local variables and therefore is rarely used. If we not
initialize the values into automatic variables it stores garbage values(which are not expected).
Syntax: [auto] <data definition>;
Ex: auto int a=10;
int b=20; //default is auto
Automatic variables are declared inside the function in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is exited,
hence the name automatic. Automatic variables are private to that function. Because of this
property, automatic variables are also referred to as local or internal variables.
Variables, which are declared in local scope with out storage classes, are ‘automatic’ by
default. One important feature is that their value cannot be changed accidentally by what
happens in some other function in the program and without causing any confusion to the
compiler.
Example: Program for AUTOMATIC variables
#include<stdio.h>
#include<conio.h>
auto int x=20; //wrong
void main()
{
auto int a=10; // Explicitly declared as auto.
int b=20; // Implicitly auto.
printf(“a=%d, b=%d”,a,b);
}
2)External Variables: If we define the variables with ‘extern’ keyword that variables are
called ‘Extern variables’. Extern variables are used in different source files. It doesn’t allocate the
memory every time whenever it defines no. of times. It allocates the memory only one time at
first time it initialized. From second time onwards it refers the first address. Extern variable
treated as like global any where it can access, mainly it can access in any function in current file
or in another file. By default extern variables are initialized with zero.
Ex: extern int a=5;
There is one important point to remember that is inside a function the following statement is
unacceptable.
extern int x = 5, //WRONG
Example: Program for EXTERN variable
//first.c
#include<stdio.h>
P.Madhubabu M.C.A & M.Tech 69
Problem Solving in C B.Sc 1st Year---1st Semester
#include<conio.h>
#include"second.c"
extern int a;
void func1()
{
a++;
printf("a=%d\n",a); //a=11
}
int a=10;
void func2()
{
a++;
printf("a=%d\n",a); //a=12
}
void main()
{
clrscr();
func1();
func2();
func3();
getch();
}
//second.c
int a;
void func3()
{
a++;
printf("a=%d\n",a); //a=13
}
3)Static Variables: Static keyword can be applied to variables and also to functions. If we
define the variable as static in file level that variables data can be accessible in all functions. if we
define the variable as static in function level that variable can accessible in that function inner
blocks, not accessible in outside functions. Static is treated as global. By default all functions are
treated as global. Static variables are initialized with 0 by default.
Syntax:
static<data definition>;
static<function definition>;
Example: Program for STATIC variable
#include<stdio.h>
#include<conio.h>
void func1();
void func2();
void func3();
void func4();
static int a; //static variable declaration
void main()
{
a=10;
func1();
func2();
func3();
P.Madhubabu M.C.A & M.Tech 70
Problem Solving in C B.Sc 1st Year---1st Semester
func4();
}
void func1()
{
a++;
printf("a=%d\n",a); //a=11
}
void func2()
{
a++;
printf("a=%d\n",a); //a=12
}
void func3()
{
static int b=20; //local static variable
b++;
printf("b=%d\n",b); //b=21
{
b++;
printf("b=%d\n",b); //b=22
}
}
void func4()
{
printf("a=%d\n",a);

printf("b=%d\n",b); //error
}
4)Register Variables: It is possible for use to attribute the register storage class to certain
variables. We can tell the compiler that variable should be kept in one of the machine’s register,
instead of keeping in the memory (where normal variables are stored). Since a register access is
mach faster than a memory access, keeping the frequently accessed variables in the register will
lead to faster execution of programs. This is done as fOllows:
Ex: register int count;

The important point while using register variables is, register of CPU do not have addresses.
Thus, we should not refer the address of a register variable.
Every computer has a limited number of registers, which are storage area within the
CPU. Each register is capable of holding a unit of data (typically two or four bytes) and
arithmetic calculations are processed using these registers.
Example: Program for REGISTER variables
#include<stdio.h>
#include<conio.h>
void main()
{
register int a, b;
int c;
clrscr();
a=10, b=20;
c = a + b;
printf("result=%d",c);
getch();
}

P.Madhubabu M.C.A & M.Tech 71


Problem Solving in C B.Sc 1st Year---1st Semester
Q5)What is a Recursion ?Explain its advantages and disadvantages?
In C programming language, function calling can be made from main() function, other
functions or from same function itself. The recursive function is definedd as follows...
Definition: A function called by itself is called recursive function.
The recursive functions should be used very carefully because, when a function called
by itself it enters into infinite loop. And when a function enters into the infinite loop, the
function execution never gets completed. We should define the condition to exit from the
function call so that the recursive function gets terminated.
When a function is called by itself, the first call remains under execution till the last call
gets invoked. Every time when a function call is invoked, the function returns the execution
control to the previous function call.

Example: Program to find factorial of a given number using Recursive function


#include <stdio.h>
#include<conio.h>
int factorial( int ) ;
void main( )
{
int fact, n ;
printf(“Enter any positive integer: ”) ;
scanf(“%d”, &n) ;
fact = factorial( n ) ;
printf(“Factorial of %d is %d”, n, fact) ;
}
int factorial( int n )
{
int temp ;
if( n == o)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}

Output:
Enter any positive integer: 3
Factorial of 3 is 6

In the above example program, the factorial() function call is initiated from main()
function with the value 3. Inside the factorial() function, the function calls factorial(2),
factorial(1) and factorial(0) are called recursively. In this program execution process, the
function call factorial(3) remains under execution till the execution of function calls factorial(2),
factorial(1) and factorial(0) gets completed. Similarly the function call factorial(2) remains under
execution till the execution of function calls factorial(1) and factorial(0) gets completed. In the
same way the function call factorial(1) remains under execution till the execution of function call
factorial(0) gets completed. The complete execution process of the above program is shown in
the following figure...
Pros (Advantages) of Recursion:
• It is simple, easily understandable, concise, compact and transparent to view a c
program.
• Lesser number of programming statements (coding) required with the use of recursion.
• It is very useful in solving mathematical (factorial, GCD, fibbonacci series etc.),
trigonometric (compute hyperbolic trigonometric value), logical games (tower of Hanoi,

P.Madhubabu M.C.A & M.Tech 72


Problem Solving in C B.Sc 1st Year---1st Semester
generating random number in system simulation, puzzles) and algebraic problems( to
solve Ackerman’s function).
• It is very useful where user-defined function or sub-program or procedure required.
• It is eminently useful if the solution to problem is in recursive terms.
• It is more useful in the multiprocessing and multitasking environment.
• It is very useful in solving the data structure problems like linked list, queues, stack, tree,
Quick sort and merge sort etc.

Cons (Disadvantages) of Recursion:


• It requires more memory to store the automatic variable to solve the problems like
stack and so waste the memory space. i.e. to consume more storage space.
• If properly recursion procedure is not checked, then it will create a problem for the
processing and procedure run out of memory.
• In some problems, it is a time consuming process and is not efficient.
• It will create indefinite looping process (non-terminating iteration), if condition not
be applied at the proper place.
Example: Program to display the Fibonacci series of the given number using Recursion function
#include<stdio.h>
#include<conio.h>
void fib(int,int,int);
void main()
{
int n, f1, f2;
clrscr();
printf("Enter the number :: ");
scanf("%d",&n);
f1 = 0, f2 = 1;
printf(" %d\t %d\t ",f1,f2);
fib( f1, f2, n );
getch();
}
void fib( int f1, int f2, int n )
{
int f3;
if( (f1+f2) <= n )
{
f3 = f1 + f2;
printf("%3d",f3);
f1 = f2;
f2 = f3;
fib( f1, f2, n);
}
}

Q6)Difference b/w Call By Value and Call By Reference


CALL BY VALUE: If we pass the values to function, in call by value if any changes occurred in
function not reflected to main function variables. If any changes or occurred in formal
parameters it will not reflected to actual parameters. This concept is called as Call By value.
Example: Program for CALL BY VALUE
#include<stdio.h>
#include<conio.h>
void swap( int x, int y );
void main()
P.Madhubabu M.C.A & M.Tech 73
Problem Solving in C B.Sc 1st Year---1st Semester
{
int a, b;
clrscr();
a=10, b=20;
printf(“Before swapping a=%d, b=%d\n”,a,b);//a=10, b=20
swap(a,b);
printf(“After swapping a=%d, b=%d\n”,a,b); //a=10,b=20
getch();
}
void swap( int a, int b )
{
int temp = a;
a = b;
b = temp;
printf(“After swapping a=%d, b=%d\n”,a,b); //a=20,b=10
}
CALL BY Reference: If we pass the values to function, in call by reference if any changes
occurred in function it will reflected to main function variables. If any changes or occurred in
formal parameters changes will reflected to actual parameters. This concept is called as Call By
Reference. In call by reference we pass the actual variable addresses to calling function.
Example: Program for CALL BY REFERENCE
#include<stdio.h>
#include<conio.h>
void swap( int *a, int *b );
void main()
{
int a, b;
clrscr();
a=10, b=20;
printf(“Before swapping a=%d, b=%d\n”,a,b);//a=10, b=20
swap(&a,&b);
printf(“After swapping a=%d, b=%d\n”,a,b); //a=10,b=20
getch();
}
void swap( int *a, int *b )
{
int temp = *a;
*a = *b;
*b = temp;

printf(“After swapping a=%d, b=%d\n”,*a,*b); //a=20,b=10


}

Q7) Explain about Structures with example?


A structure is heterogeneous collection of related fields. Here fields are called structure
member or structure element. Every field has different type specifier (data-type).
Declaration of a Structure: We can declare a structure outside the main program and also
can be declared within the, main program. The general syntax used to declare a structure and
structure variables is written as below:
Syntax:
struct <struct_name>
{
datatype variable;

P.Madhubabu M.C.A & M.Tech 74


Problem Solving in C B.Sc 1st Year---1st Semester
datatype variable;
};

Example:
struct Employee
{
int eid;
char ename[20];
double salary;
};

Initialization of structures:
struct student
{
int a;
char name[70],gender;
float height;
} x={786,”kumar”,’m’,5.8};

Creating Structure Object: If we create the variables to struct type that variables are
called as objects. These objects are used to store the values. We can create any no. of objects to
the structure type. Each object can hold different values.

Syntax: struct struct_type variable;

Ex: struct Employee v1;


Where v1, v2, …vn are the list of variables.

Accessing the members of structures: Accessing a member of structure elements using


dot (.) operator.

Syntax: structvariable.membername;

Ex: v1.structure-element-1;
scanf(“%d%s%f”,&v1.eid,v1.ename,&v1.salary);
Array of Structure: Declaring an array of structure is same as declaring an array of
fundamental types. Since an array is a collection of elements of the same type. In an array of
structures, each element of an array is of the structure type.
Example:
struct car
{
char make[20];
char model[30];
int year;
};
Initializing Array of Structures: We can also initialize the array of structures using the same
syntax as that for initializing arrays. Let's take an example:
struct car
{
char make[20];
char model[30];
int year;
P.Madhubabu M.C.A & M.Tech 75
Problem Solving in C B.Sc 1st Year---1st Semester
};
struct car arr_car[2]={
{"Audi", "TT", 2016},
{"Bentley", "Azure", 2002}
};

Structure with in structures(nested structures): A structure can be embedded within


another structure. In other words when a structure is declared and processed with in another
structure, then it is called Nesting of structure or structure within structure.
Syntax: struct tag1
{
member-element-1;
.......................
struct tag2
{
member-element-1;
........................
member-element-n;
}v1;
member-element-m;
} v2;

Example: struct Employee


{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
Initialization of structure with in structures:
Typedef struct sai
{
int d,m,y;
}date;
struct student
{
int no;
char name[30];
date birth;
}x={23,”kumar”,12,03,71};

Structure and Function: Structure can be implemented with the function easily. For this
process, passing of argument takes place similar to the array and variable. The relationship of
structure with the function can be viewed from three angle as:
i). Passing Structure to a Function
ii). Function Returning Structure
iii). Passing array of Structure to Function

i). Passing Structure to a Function:

P.Madhubabu M.C.A & M.Tech 76


Problem Solving in C B.Sc 1st Year---1st Semester
Similar to passing of array or variable, structure can be passed to the function as
argument. The general syntax used for the declaration of passing of structure to the function as:

type-specifier function-name(structure-variable); /*as actual argument*/


type-specifter function-name(structure-variable); /*as formal argument */
struct tag-name structure-variable;
{
….
….
}
A complete view of passing structure to the function be as:

main( ) /* main program


{
struct tag-name
{
data-type1 element1;
data-typen elementn;
}v1;
………………..
………………..
function-name(v1);
..................
getche( );
}
type function-name(v2) /*Function declaration */
struct tag-name v2;
{
..........
………
}
For example, suppose if you want to display the student result as a structure having.
fields rollno, name and grade by using function, then the procedure to write a C program be as
follows:

Example: Program to illustrate the concept of passing structure to function


#include<stdio.h>
main( )
{
struct student
{
int rn; char name[20]; char grade;
}s;
void display(struct student);
printf("\n Enter the rollno, name and grade of the student “);
scanf(“\n %d %s %c", &s.rn, s.name, &s.grade);
display(s);
getche( );
}
void display(m)
struct student m;
{
printf("\n Rollno is: %d", m.rn);
printf("\n Name is %s ", m.name);
P.Madhubabu M.C.A & M.Tech 77
Problem Solving in C B.Sc 1st Year---1st Semester
printf("\n Grade s: %c", m.grade);
}

ii). Function Returning Structure: All the values can be computed in the function programs
and return a combined value of whole structure back. This can be explained with a simple
problem to compute the net pay of an employee having structure as:
Example: Program to illustrate the concept of Function returning a Structure computed value
#include<stdio.h>
struct employee
{
char name[20]; float bp, da, hra, netpay;
}emp;
struct employee npay(struct employee);
void main( )
{
struct employee y;
printf("\n ENTER THE NAME, BASIC PAY, DA, HRA:");
scanf("%f%f%f", &y.bp, &y.da, &y.hra);
y=npay(y);
printf("\n Net pay is:%f ",y.netpay);
getch( );
}
struct employee npay(struct employee z)
{
z.netpay=z.bp+z.da+z.hra;
return(z);
}

iii). Passing array of Structure to Function:


A complete complicated passing of an array of structures to the function is a difficult job, but
the passing of array becomes very easy by using the passing of array as an individual element.
Pointers with structures: Structure can be directly handled by its address by using the
pointer with structure. We use pointer with structure through structure variable. Array of
structure variable directly stands for the address of zero th element. The general syntax used for
the declaration of pointer with the structure is as:
struct tag
{
type1 member;
.....
typen membern;
}V, *P;
Where v is the structure variable and p is the pointer variable. Note that structure variable is a
pointer variable and there are no pointer variables work as structure member. Also the structure
variable is an array of pointer variables pointing to a structure.
User can use the arrow operator (-->). The general way to use arrow operator is as:P-->e; Here
p is the pointer variable and e is the structure member element.
stuct student
{
int no;
char na[50];
} *p,x;
void main()
{
p=&x;
P.Madhubabu M.C.A & M.Tech 78
Problem Solving in C B.Sc 1st Year---1st Semester
scnaf(“%d%s”,&p->no,p->na);
}

Self referential structures: Self referential structures are those structures that contain a
refrence to data of its same type.ie in addition to other data, a self referential structure contains
a pointer to a data that is of the same type as that of the structure.
Ex:
struct node
{
Int val;
struct node *next;
};
Node contains 2 types one is integer val and next, which is a pointer to a node.

Q8)Explain Unions in C ?
A union is a variable that declares a set of multiple variables (called members or elements
having different data-types) sharing the same memory area. The compiler allocates sufficient
memory to hold the largest variable of the union.
All the members of union occupy the same memory locations called addresses. The old
value of the already declared member will be destroyed and new value to the new member will
be assigned in the memory by using the union concept.
Note that union declaration has more than one variable declaration, but only one can be
used at a time. Also with the declaration of union, the Turbo-C compiler will automatically
allocates the memory locations to the variable which has the long data type member element in
the union (i.e. the priority list be : double, long- float, float, long int, int, char).
Declaration of union: The general syntax used for the declaration of union be as follows:
Syntax: union union-tag
{
data type-1 member-element-1;
…………………..
dart type-n member-element-n;
}vl,v2 .... vn;

Example: union student


{
int mark;
char name[10];
float average;
};
Declaring union using normal variable:
union student report;
Initializing union using normal variable:
union student report = {100, “Mani”, 99.5};

Accessing union members using normal variable:


report.mark;
report.name;
report.average;
Declaration of array of union:
Syntax:
union union_name union_variable_name[size_of_array];

Example:
P.Madhubabu M.C.A & M.Tech 79
Problem Solving in C B.Sc 1st Year---1st Semester
void main()
{
//declaration of student array.
union student s[10];
}

Unions inside structures: Generally, unions can be very useful when declared inside a
structure.
Ex:
struct student
{
union
{
char name[80];
int rno;
};
int marks;
};
The fields of union will share memory, so in the main program we ask the user which data
he/she would like to store and depending on his/her choice the appropriated field is used.

Q9)What are the Differences between STRUCTURE and UNION?


STRUCTURE UNION
1)Structure allocates storage space for all 1)Union allocates one common storage space
its members separately. for all its members.
Union finds that which of its member needs
high storage space over other members and
allocates that much space
2)Structure occupies higher memory 2)Union occupies lower memory space over
space. structure.
3)We can access all members of 3)We can access only one member of union
structure at a time. at a time.
4)Structure example: 4)Union example:
struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };
5)For above structure, memory For above union, only 8 bytes of memory
allocation will be like below. will be allocated since double data type will
int mark – 2B occupy maximum space of memory over
char name[6] – 6B other data types.
double average – 8B
Total memory allocation = 2+6+8 = 16 Total memory allocation = 8 Bytes
Bytes

Q10) what are Enumerators (or) Enumerated datatypes in ‘c’?


enum datatype is used to define a set of constants of type int. Enumeration types are
particularly useful when we want to create a unique set of values that may be associated with a

P.Madhubabu M.C.A & M.Tech 80


Problem Solving in C B.Sc 1st Year---1st Semester
variable. The compiler reports an error if you attempt to assign a value that’s not part of the
declared set of legal values to an extern variable.
Syntax:
enum [<type_tag>]
{
<constant_name> [= <value>],
<constant_name>[= <value>],
...
} [var_list];

The syntax for declaring enumeration types is to start with the enum keyword followed
by the list of constant names enclosed in braces, followed by the names of the enum types.

Ex:
enum choice
{
FALSE=0,
TRUE=1
}ch;

Note: In the above example ch is a variable to type choice. That variable only allows either
0 or 1.
0’s Constant is FALSE, 1 constant is TRUE.
Constant names in an enum declaration receive a default integer value based on their
position in the enumeration list. In most cases, the integer value is not important because you
are treating the enumeration as a unique value.

For example, we declare two enumeration variables called color and intensity. Color
can be assigned one of four constant values: red, blue, green, and yellow. Intensity can be
assigned one of three constant values: bright, medium and dark.

enum{ red, blue, green, yellow }color;


enum{ bright, medium, dark }intensity;

color = yellow; /* ok */
color = bright ; /* type conflict */

intensity = bright; /* ok */
intensity = blue; /* type conflict */

color = 1; /* type conflict */


color = blue + green; /* misleading usage */

The default values start at zero and go up by one with each new name. In the
declaration of color, for instance, red, blue, green and yellow represent the integer values 0, 1,
2, and 3 respectively. The compiler need only allocates as much memory as is necessary for an
enum value. The potential values of color are small enough that only one byte is needed for
the variable.

Some more examples:

P.Madhubabu M.C.A & M.Tech 81


Problem Solving in C B.Sc 1st Year---1st Semester

enum { A, B, C, D, E }
0 1 2 3 4
enum { A=10, B, C, D, E }
10 11 12 13 14
enum { A, B=10, C, D=20, E }
0 10 11 20 21
enum { A, B, C=-5, D, E }
0 1 -5 -4 -3
Example: Program on Enumerated datatypes.
#include<stdio.h>
#include<conio.h>
enum{SUNDAY=1,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY } day;
enum{NO,YES}choice;
void main()
{
READ:
clrscr();
printf("Enter the week day (1..7): ");
scanf("%d",&day);
switch( day )
{
case SUNDAY: printf("day is Sunday"); break;
case MONDAY: printf("day is Monday"); break;
case TUESDAY: printf("day is Tuesday"); break;
case WEDNESDAY: printf("day is Wednesday"); break;
case THURSDAY: printf("day is Thursday"); break;
case FRIDAY: printf("day is Friday"); break;
case SATURDAY: printf("day is Saturday"); break;
default: printf("Invalid day");
}
printf("\n Do u want to continue(1/0) :");
scanf("%d",&choice);
if(choice==YES) goto READ;
}

P.Madhubabu M.C.A & M.Tech 82


Problem Solving in C B.Sc 1st Year---1st Semester
UNIT-5
Q1)What is a Pointer? what are the advantages of pointers?
Pointer: A pointer is a variable that holds the address of another variable; a pointer is said to
"point to" the variable whose address it holds. A pointer is declared like an ordinary variable
and its name is prefixed with ‘*’.
The two operators needed with pointers are the address-of operator (&) and the indirection
operator (*). When placed before a variable name, the address-of operator returns the variable's
address. When placed before a pointer name, the indirection operator returns the contents of
the pointed-to variable.
Syntax:
<Datatype> *<ptr_variable> [= &variable];
Ex:
int a=10;
int *p = &a;

printf(“address is %u”,p);
printf(“value is %d”,*p;

Uses of Pointers:

➢ Pointers provide a powerful and flexible method for manipulating the data of the
variables.
➢ Pointer is more efficient in handling arrays and different types of data.
➢ Pointers can be used to return multiple values from a function via function arguments.
➢ Pointers permit references to functions and they’re by facilitating passing of functions as
arguments to other functions.
➢ Pointers allow C to support dynamic memory management.
➢ Pointers reduce length and complexity of programs.
➢ They increase the execution speed and thus reduce the program execution time.
Example: Program to illustrate the concept of displaying the address of a Pointer variable
main ( )
{
int x, *q;
x = 220;
q=&x;
printf ("\n % d is stored at address % u", x, &x)
printf ("\n % d is stored at address % u", x, q) ;
printf ("\n % d is stored at address % u", * q, q)
printf ("\n % d is stored at address % u", * & x, &x)
getche ( );
}

Output:
220 is stored at address 5010
220 is stored at address 50 10
220 is stored at address 50 10
P.Madhubabu M.C.A & M.Tech 83
Problem Solving in C B.Sc 1st Year---1st Semester
220 is stored at address 5010

Q2) How to pointer expressions and pointer arithmetic?


Pointer expressions: Similar to other variables, pointer variables can also be used in
expressions.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int x=2,y=3,sum=0,mul=0,div=1;
int *ptr1,*ptr2;
ptr1=&x;
ptr2=&y;
sum=*ptr1+*ptr2;
mul=sum**ptr1;
*ptr2 +=1;
div=9+ *ptr1/ *ptr2-30;
printf("SUM=%d\n",sum);
printf("MUL=%d\n",mul);
printf("DIV%d",div);
getch();
}

Output: SUM=5
MUL=10
DIV=-21

c may add or subtract integers from pointers. We can also subtract one pointer from the other.
We can also use short hand operators with the pointer variables as we use with other variables.
C also allows to compare pointers by using relational operators in the expression.
Ex: p1>p2, p1==p2.
Rules:
1) A pointer vaiable can be assigned the address of another variable.
2) It can be assigned the value of another pointer variable
3) It can be initialized with a NULL( OR 0) value.
4) Prefix or postfix increment and decrement operators can be applied on a pointer
variable.
5) A pointer variable cannot be multiplied by a constant.
6) A pointer variable cannot be added to another pointer variable
7) An integer value can be added or subtracted from a pointer variable
8) Pointer variable can be compared with another pointer variable of the same type using
relational operators.

Pointer arithmetic: A pointer in c is an address, which is a numeric value. Therefore, you can
perform arithmetic operations on a pointer just as you can on a numeric value. There are four
arithmetic operators that can be used on pointers: ++, --, +, and –
To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic
operation on the pointer:
ptr++

P.Madhubabu M.C.A & M.Tech 84


Problem Solving in C B.Sc 1st Year---1st Semester
After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without impacting
the actual value at the memory location. If ptr points to a character whose address is 1000, then
the above operation will point to the location 1001 because the next character will be available
at 1001.
Example:
#include <stdio.h>
const int MAX = 3;
int main()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200

Q3)Explain about NULL Pointers with example?


It is always a good practice to assign a NULL value to a pointer variable in case you do
not have an exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
To declare a null pointer you may use the predefined constant NULL, which is defined in header
file <stdio.h>,<stdlib.h>,<string.h>
Example:
#include<stdio.h>
#includde<conio.h>
int main()
{
clrscr();
int *ptr=NULL;
printf("The value of ptr is : %x\n",ptr );
return 0;
}
Output: The value of ptr is : 0
Q4)Explain Passing Arguments to Functions using Pointer?
Pointer has deep relationship with function. We can pass pointer to the function and also
pointer addresses can be passed to the function as pointer arguments.

P.Madhubabu M.C.A & M.Tech 85


Problem Solving in C B.Sc 1st Year---1st Semester
When we pass a pointer as an argument instead of a variable then the address of the
variable is passed instead of the value. So any change made by the function using the pointer is
permanently made at the address of passed variable. This technique is known as call by
reference in C.
Example:
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("Before Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
/* pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
Before Swapping:
m = 10
n = 20
After Swapping:
m = 20
n = 10

Q5)Explain about Pointer and Arrays in C?


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 first
element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has
two purpose - it is the name of the array and it acts as a pointer pointing towards the first
element in the array.

P.Madhubabu M.C.A & M.Tech 86


Problem Solving in C B.Sc 1st Year---1st Semester
arr is equal to &arr[0] by default
We can also 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 the array arr using p++ to move from one element to
another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array: As studied above, we can use a pointer to point to an array, and then we
can use that pointer to access the array elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array one by one.
We can also use the Base address (a in above case) to act as a pointer and print all the values.

Array of Pointers: We can also have array of pointers. Pointers are very helpful in handling
character array with rows of varying length.
char *name[3] = {"Adam","chris","Deniel"};
//Now lets see same array without using pointer
char name[3][20] = { "Adam", "chris", "Deniel"};

P.Madhubabu M.C.A & M.Tech 87


Problem Solving in C B.Sc 1st Year---1st Semester

Q6)Explain the concept of Dynamic Memory Allocation?


The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of
stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.


memory can't be increased while memory can be increased while
executing program. executing program.
used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() allocates single block of requested memory.
calloc() allocates multiple block of requested memory.
realloc() reallocates the memory occupied by malloc() or calloc() functions.
free() frees the dynamically allocated memory.
1)malloc() Method: malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size. It returns a pointer of type void
which can be cast into a pointer of any form. It initializes each block with default garbage value.
Syntax: ptr=(cast-type*)malloc(byte-size)

P.Madhubabu M.C.A & M.Tech 88


Problem Solving in C B.Sc 1st Year---1st Semester
Example of malloc() function:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
2.calloc() Method: “calloc” or “contiguous allocation” method in C is used to dynamically
allocate the specified number of blocks of memory of the specified type. It initializes each block
with a default value ‘0’.
Syntax: ptr=(cast-type*)calloc(number, byte-size)

Example of calloc() function:


#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)

P.Madhubabu M.C.A & M.Tech 89


Problem Solving in C B.Sc 1st Year---1st Semester
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}

3.realloc() Method: “realloc” or “re-allocation” method in C is used to dynamically change


the memory allocation of a previously allocated memory. In other words, if the memory
previously allocated with the help of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory. re-allocation of memory maintains the already present
value and new blocks will be initialized with default garbage value.
Syntax: ptr = realloc(ptr, newSize);

Example of Realloc() function:


#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{
// Memory has been successfully allocated

P.Madhubabu M.C.A & M.Tech 90


Problem Solving in C B.Sc 1st Year---1st Semester
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.\n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
4.free() Method: “free” method in C is used to dynamically de-allocate the memory. The
memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence
the free() method is used, whenever the dynamic memory allocation takes place. It helps to
reduce wastage of memory by freeing it.
Syntax: free(ptr);

Example of free() function:


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

P.Madhubabu M.C.A & M.Tech 91


Problem Solving in C B.Sc 1st Year---1st Semester
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else
{
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.\n");
// Memory has been successfully allocated
printf("\nMemory successfully allocated using calloc.\n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}

Q7)Explain Advantages and disadvantages of pointers in c


Benefits(use) of pointers in c:
1. Pointers provide direct access to memory
2. Pointers provide a way to return more than one value to the functions
3. Reduces the storage space and complexity of the program
4. Reduces the execution time of the program
5. Provides an alternate way to access array elements
6. Pointers can be used to pass information back and forth between the calling function and
called function.
7. Pointers allows us to perform dynamic memory allocation and deallocation.
8. Pointers helps us to build complex data structures like linked list, stack, queues, trees,
graphs etc.
9. Pointers allows us to resize the dynamically allocated memory block.
10. Addresses of objects can be extracted using pointers

Drawbacks of pointers in c:
1. Uninitialized pointers might cause segmentation fault.
2. Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
P.Madhubabu M.C.A & M.Tech 92
Problem Solving in C B.Sc 1st Year---1st Semester
3. Pointers are slower than normal variables.
4. If pointers are updated with incorrect values, it might lead to memory corruption.
Basically, pointer bugs are difficult to debug. Its programmers responsibility to use pointers
effectively and correctly.

Q8) What is a File? Explain different types of files available in C ?


→A collection of data which is stored on a secondary device like a hard disk is known as a file.
→A file is generally used as real-life applications that contain a large amount of data.
→There are two problems with such applications:
• It is time-consuming and unmanageable for handling such huge amount of data.
• When the I/O terminal is used the entire data is lost if the program is terminated or the
computer is being turned off. So it is a compulsion for storing the data on a permanent
device.
Types of Files: Files are divided into two types
1)Stream-oriented
2)System-oriented
1.Stream-oriented: They are standard or high-level files. They are easier to work with than the
sytem-oriented data-files and are used more commonly.
2.System-oriented: they are low-level files.

Q9)What are the different operations on a file?


The processing of files has number of operations according to the user's requirement and the
problem definition. But some of the commonly used file operations are as follows:
1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
2. Opening an existing file (fopen)
3. Reading from file (fscanf or fgets)
4. Writing to a file (fprintf or fputs)
5. Moving to a specific location in a file (fseek, rewind)
6. Closing a file (fclose)
7. Renaming a file
8. Removing a file
1.Creation of a new file: You can use the fopen( ) function to create a new file or to open
an existing file.
Syntax for Establishing a file pointer:
FILE *fptr;

Where,

P.Madhubabu M.C.A & M.Tech 93


Problem Solving in C B.Sc 1st Year---1st Semester
FILE is the structure which is defined in the header file <stdio.h>.

A file should be opened before any operation is being performed on it.


The fopen() function is being used for opening the file.
Syntax: FILE *fopen(const char *filename, const char *mode);
In the above syntax, filename is the literal which is used for naming the files.
2.Opening an existing file (fopen):
The fopen() function is being used for opening the file.
Syntax: FILE *fopen(const char *filename, const char *mode);
They can be accessed by using the following modes:
Mode Description
“r” It opens an existing file for reading only.
“w” It opens a new file for writing. If the filename does not exist it will be created and
if the file already exists then its contents are deleted.
“a” It appends the existing file. If the filename does not exist it will be created.
“r+” It opens an existing file for reading and writing. It indicates that the file is to be
read before writing.
“w+” It opens a new file for reading and writing. If a file with the current filename exists
then it is destroyed and a new file name is created.
“a+” It opens an existing file for reading and appending. Its stream is positioned at the
end of the file content.

3.Reading from file (fscanf or fgets): Following are the list of functions which are used
for reading a file:
Functions Syntax Description
fscanf( ) int fscanf (FILE *stream, const It is used for reading the formatted data from
char *format,....); the stream.
fgets( ) char *fgets(char *str, int size, It stands for file get string. It is used for getting
FILE *stream); the string from a stream.
fgetc( ) int fgetc (FILE *stream); It will return the next character from the stream
from the end of the file or an error.
fread( ) int fread(void *str, size_t size, It is used for reading data from a file.
size_t num, FILE *stream);

4.Writing to a file (fprintf or fputs): Following are the list of functions which are used for
writing a file:
Functions Syntax Description
fprintf() int fprintf (FILE *stream, const It is used for writing the formatted output of the
char * format,...); stream.
fputs() int fputs(const char *str, FILE It is used for writing a line to a file.
*stream);
fputc() int fputc(int c, FILE *stream); It is opposite to fgetc() and is used for writing a
character to the stream.
fwrite() int fwrite(const void *str, It is used for writing data to a file.
size_t size, size_t count, file
*stream);

P.Madhubabu M.C.A & M.Tech 94


Problem Solving in C B.Sc 1st Year---1st Semester
5.Moving to a specific location in a file (fseek, rewind): Following are the functions
which are used for selecting a record randomly:
Functions Syntax Description
fseek() int fseek(FILE *stream, long It is used to reposition a binary stream.
offset, int origin);
ftell() long ftell (FILE *stream); It is used to know the current position of the file
pointer.
rewind() void rewind (FILE *f); It is used for adjusting the position of the file
pointer to the next I/O operation and it will
take place at the beginning of the file.
fgetpos() int fgetpos (FILE *stream, It is used for determining the current position of
fpos_t *pos); the stream.

6.Closing a file (fclose): To close a file, use the fclose( ) function. The prototype of this
function is:
int fclose( FILE *fp );

7.Renaming a file: The rename() function is used for renaming a file.


Syntax: int rename(const char *oldname, const char *newname);
Where,
oldname will be the pathname of the file that needs to be renamed.
newname will be the new pathname of the file.

8.Removing a file: The remove() function is used for erasing a file.


Syntax: int remove (const char *filename);
→All the files which are specified by the filename will be erased.
→If this function is successful it will return a zero else it will return a value other than zero.

Q10)What are the Error handling operations on a file?


Error handling in file operations: The function ferror() is used for checking the errors in the
stream.
Syntax: int ferror(FILE *stream);

→This function returns 0 if there are no errors and a value if there are some errors.

→Following are the functions which are used for detecting the errors:

Functions Syntax Description


clearerr() void clearerr(FILE *stream); It is used for clearing the end-of-file and error
indicators for the stream.
perror() void perror(char *msg); It stands for the print error.

Q11)How to Accepting the command line arguments?


Accepting the command line arguments: The main() can accept two arguments:
I) First argument will be an integer value that will specify the number of command-line
arguments.
II) The second argument is a full list of all the command-line arguments.
Syntax: int main (int arg c, char *argv[])

P.Madhubabu M.C.A & M.Tech 95


Problem Solving in C B.Sc 1st Year---1st Semester
Where,
→arg c will specify the number of arguments that are to be passed into the program from the
command-line including the name of the program.

→argv will contain the list of all the arguments.

→Each element of the array argv is a pointer where each pointer points to a string.
In main() the command line arguments are accepted by using the argc and argv.

Example: Write a program for reading a file character by character and display it on the
screen.

#include <stdio.h>
#include <string.h>
void main()
{
FILE *fp;
int c;
char fnm[25];
printf("\n Enter a filename:");
scanf("%s",fnm);
fp = fopen(fnm, "r");
if (fp==NULL)
{
printf("\n Error in opening the file");
exit(1);
}
c=fgetc(fp);
while(c!=EOF)
{
putchar(c);
c =fgetc(fp);
}
fclose(fp);
}

Q12)What are the input and output statements used in file handling?
Files have different Input/output statements used for different purposes. These are used
to put data from variable to data file. The various Input/output functions used with standard
1/0 are discussed as below:
a). Character Input/Output (Standard I/O)
b). String Input/Output (Standard I/O)
c). Formatted Input/Output (Standard I/O)
d). Record (Block) Input/Output (Standard I/O)
a). Character Input/Output Functions:
Now there need to be handle character data by using the following high-level
input/output functions. There are mainly four character 1/0 used which are discussed as:
1. putc( )
2. getc( )
3. putw( )
4. getw( )
1.putc(): This function is used to put or write a single character in the data file pressed from
the keyboard. The general syntax used is as:
putc (v,file-pointer);
P.Madhubabu M.C.A & M.Tech 96
Problem Solving in C B.Sc 1st Year---1st Semester
Here putc( ) is the high level character 1/0 function used in the C-Language, v is variable name
of character type. Note that when you use putc (), file should be open in "w" mode. It means a
new file will be created or it overwrites the data to an existing created file.
2.getc(): The purpose of getc( ) function is to read a single character from the existing data
file. The general syntax used for this purpose is as:
v = getc(fp);
Where fp is the file pointer, v is the character type variable and getc( ) is the high-level
input/output function used for reading the character data. Note that the file should be opened
in the read mode only and also file should be already created. Also note that data be stored in
the file before reading, otherwise it shows the empty space.
Example: Program for copy one file into Another File
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
FILE *f1,*f2;
char c,k;
clrscr();
f1=fopen("sai","w");
printf("ENTER INTO FILE\n");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("sai","r");
f2=fopen("duplicate","w");
while((c=getc(f1))!=EOF)
putc(c,f2);
fclose(f1);
fclose(f2);
f2=fopen("duplicate","r");
printf("COPIED FILE\n");
while((c=getc(f1))!=EOF)
{
k=toupper(c);
printf("%c",k);
}
fclose(f2);
getch();
}
3.putw(): This function is used to put or write a single integer digit in the data file pressed
from the keyboard. Note that when you use putw( ) function, file should be opened in the "w"
mode. The general syntax used for this statement is as:
putw (v,file-pointer);
Here v is the integer variable name.
4.getw(): The purpose of getw( ) is to read a single integer value from the data file. The
general syntax is as:
v = getw (fl);
Here v is the integer variable and fl is the file pointer, getw( ) is the high level input/output
function.
Example: Program to check EVEN (or) ODD numbers in the files
#include<stdio.h>
#include<conio.h>
void main()
P.Madhubabu M.C.A & M.Tech 97
Problem Solving in C B.Sc 1st Year---1st Semester
{
FILE *f1,*f2,*f3;
int n,i;
clrscr();
f1=fopen("data","w");
printf("enter in file1\n");
for(i=1;i<=100;i++)
{
scanf("%d",&n);
if(n==-1)
break;
else
putw(n,f1);
}
fclose(f1);
f1=fopen("data","r");
f2=fopen("even","w");
f3=fopen("odd","w");
while((n=getw(f1))!=EOF)
{
if(n%2==0)
putw(n,f2);
else
putw(n,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
printf("EVEN NOS\n");
f2=fopen("even","r");
while((n=getw(f2))!=EOF)
printf("%4d",n);
fclose(f2);
printf("\n");
printf("ODD NOS\n");
f3=fopen("odd","r");
while((n=getw(f3))!=EOF)
printf("%4d",n);
fclose(f3);
getch();
}
b). String Input/Output: Strings are the major element of the character data, which can be
handled by the files. It is very easy to handle group of characters instead if individual character
using the file operations. There are mainly two types of string 1/0 functions used. These are as
follows:
1. fputs() 2. fgets()
1.fputs(): The purpose of this file is to write a string to the opened file in write mode. The
general syntax used is as follows:
fputs(ab, fp);
Where fp is the file pointer and A is a pointer, which points to an array of characters. For
example, below written are the valid statements for the proper use of fputs().

FILE *fp;
char ab[20];
P.Madhubabu M.C.A & M.Tech 98
Problem Solving in C B.Sc 1st Year---1st Semester
fp =fopen( "Mona", "w");
fputs(ab,fp);

Example: Program to illustrate the concept of writing the string by using the fputs()
main( )
{
FILE *f;
char xy[50];
printf("\n Enter any string from the keyboard “);
gets(xy);
f = fopen("Mona", "W");
fputs( xy, f);
fclose(f);
getche( );
}

Output:
Enter any string from the keyboard: Madhu
2.fgets(): The purpose of this file is to read a string from the opened file in read mode. The
general syntax used is as follows:
fgets (ab, n, fp);
Where fp is the file pointer, ab is a pointer, which points to an array of characters and n
is the length of the array (size of the array). For example, below written are the valid statements
for the proper use of gets FILE *fp; char ab[20]; int n; printf("\n Enter the value of n:");
scanf("%d", &n); fp =fopen( "Mona", "r"); fgets(ab, n, fp); This can be further explained by
taking an example of a C program as:
Example: Program to illustrate the concept of reading a string by using the fgets()
main( )
{
FILE *f;
char xy[50], ab[50];
int i=0;
printf("\n Enter any string from the keyboard “);
gets(xy);
f = fopen("Mona", "w");
fputs( xy, f);
fclose(f);
f = fopen("Mona", "r");
printf("\n Entered string is “);
if(fgets(ab,50,fp) !='\0')
{
while(ab[i] !='\0')
{
putchar(ab[i]);
i++;
}
}
fclose(f);
getche( );
}

Output:
Enter any string from the keyboard: Raj Kumar
Entered string is : Raj Kumar
P.Madhubabu M.C.A & M.Tech 99
Problem Solving in C B.Sc 1st Year---1st Semester
c)Formatted Input/Output:
We have discussed here character 1/0 and string 1/0 function to enter single character and
group of character data. Now question arises how can you handle mixed data. i.e. data of
integer, float, double and character type. The answer is the formatted Input/Output functions.
There are mainly two formatted 1/0 functions are used, which are discussed as below:
1. fscanf ( )
2. fprinff ( )
1.fprintf(): The function fprintf( ) is to write mixed data type in the data file. The mixed data
type are of integer, float, double, string and character type. The general syntax used for this
purpose is as follows:
fprintf (fp, "Control String", V1, V2,…… Vn);
Where fp is the file pointer, control string has all format codes or character conversion
codes (like % d for integer, %f for float value, % s for the string data, % c for character only
etc.), which are used for the output statement. Here V1, V2,… vn is the list of variable. Note
that the file should be opened in the write mode. For example, Write a C-program to explain
the concept of fprintf I/O function as:

2.fscanf(): The purpose of this function is to read mixed data from the data file. Note that file
should be opened in the read mode only. The general syntax used for this function is as follows:
fscanf (fp, "Control String ", & v1, & v2 ,…& vn);
Where fp is the file pointer, control strings are %d for the integer data, %f for the float
data, %s for the string , %c for the single character data etc. Here vl, v2......... vn are all the
variables. Also here &(Ampersand sign) is used to read data at the address of the memory cells.
For example, If you want to read data of different data-types, then a C program procedure be
used as below:
Example: Program for fscanf() and fprintf()
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct person
{
char name[20];
long telno;
};
void appendData()
{
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","a");
printf("*****Add Record****\n");
printf("Enter Name : ");
scanf("%s",obj.name);
printf("Enter Telephone No. : ");
scanf("%ld",&obj.telno);
fprintf(fp,"%20s %7ld",obj.name,obj.telno);
fclose(fp);
}
void showAllData()
{
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","r");
P.Madhubabu M.C.A & M.Tech 100
Problem Solving in C B.Sc 1st Year---1st Semester
printf("*****Display All Records*****\n");
printf("\n\n\t\tName\t\t\tTelephone No.");
printf("\n\t\t=====\t\t\t===============\n\n");
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
printf("%20s %30ld\n",obj.name,obj.telno);
}
fclose(fp);
getch();
}
void findData()
{
FILE *fp;
struct person obj;
char name[20];
int totrec=0;
clrscr();
fp=fopen("data.txt","r");
printf("*****Display Specific Records*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
if(strcmpi(obj.name,name)==0){
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
totrec++;
}
}
if(totrec==0)
printf("\n\n\nNo Data Found");
else
printf("\n\n===Total %d Record found===",totrec);
fclose(fp);
getch();
}
void main()
{
char choice;
while(1)
{
clrscr();
printf("*****TELEPHONE DIRECTORY*****\n\n");
printf("1) Append Record\n");
printf("2) Find Record\n");
printf("3) Read all record\n");
printf("4) exit\n");
printf("Enter your choice : ");
fflush(stdin);
choice = getche();
switch(choice){
case'1' : //call append record
P.Madhubabu M.C.A & M.Tech 101
Problem Solving in C B.Sc 1st Year---1st Semester
appendData();
break;
case'2' : //call find record
findData();
break;
case'3' : //Read all record
showAllData();
break;
case'4' :
case 27 : exit(1);
}
}
}
d). Record Input/Output (Block I/O):
The purpose of this function is to read and write the data at once i.e. used to read or
write the entire block (group of records) using the permanent disk storage device. Every blocks
has some fixed size and works similar to an array or a structure. This is mainly used to write the
numeric data (integer, long integer, float and double) to the disk file in the binary format. For
this purpose mainly two record input/output functions are used. These are discussed in detail as
follows:
1. fwrite ( )
2. fread ( )
1.fwrite(): The purpose of this function is to write group of record (block) to a data file on the
secondary storage device disk. The general syntax used for this purpose is:
fwrite (p, n, s, fp);
Where p is an address of an array or structure (the pointer to array of structure), n is the
size of array or structure, s is the number of array or structure declared for writing the data and
fp is a file pointer. File should be opened in binary write mode. For example, write a C
program to explain the working of fwrite( ) function.
2. fread(): The purpose of this function is to read group of record (block) from the existing
created data file stored on the secondary storage device disk. The general syntax used for this
purpose is:
fread(p, n, s,fp);
Where p is an address of an array or structure (the pointer to array of structure) where
block will be stored after reading, n is the size of array or structure, s is the number of array or
structure declared for writing the data and fp is d file pointer. For example, write a C program
to explain the working of fread( ) function. File should be opened in binary read mode. This
can be done as follows:

Example: Program for fread() and fwrite()


#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main()
{
struct s a[5],b[5];
FILE *fptr;
int i;
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
P.Madhubabu M.C.A & M.Tech 102
Problem Solving in C B.Sc 1st Year---1st Semester
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %sHeight:%d\n",b[i].name,b[i].height);
}
fclose(fptr);
}

P.Madhubabu M.C.A & M.Tech 103

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy