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

C Programming Sample Questions For Exams and Interviews Useful For Students in Exams and Interviews

Uploaded by

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

C Programming Sample Questions For Exams and Interviews Useful For Students in Exams and Interviews

Uploaded by

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

C PROGRAMMING SAMPLE QUESTIONS

FOR EXAMS AND INTERVIEWS

Published by Rashmi
Version 1.0
Copyright 2020
Author: Rashmi
Preface
The Author is in Computer Science and Engineering teaching
field for Engineering colleges.
During the service when the questions are asked on any sub-topic
of C programming, many students used to get confusion to give the
right answer. The same way they used to get confusion from the
questions raised by the interviewer also for Jobs.
In order to share the knowledge in the form of questions and
show the C program solutions in the form of Kindle book.
The are many C Programming books. In general the students seek
the real programming questions either for their exams or for the job
interviews.
The current version of this kindle book contains the basic syntax
or usage of the C program’s sub-topic with a solved C program for the
students understanding. The programs are tested and the same output
is written in this book.
The reader can right away look into the questions and the answers
with program.
This book will have periodical updates.

Good Luck!
Contents
1. What is Problem Solving?
1.1 What are the Problem Solving Tools?
1.2 What are The Problem Solving Techniques?
1.3 How the Computer Acts as a Problem Solving Tool?
1.4 What are the Programming languages?
1.5 How to Create and Run Programs?
1.6 What is an Algorithm?
1.7 What is a Flowchart?
1.8 What is Top Down Design?
2. How To Write C Program?
2.1 How the Structure of C program look like?
2.3 What are the Basic Data Types?
2.4 What are C Tokens?
2.5 What are Identifiers?
2.6 What are Constants?
2.7 What are Variables?
2.8 What are the Input and Output Statements?
3. What are the Control statements?
3.1 What are the Conditional Statements?
3.1.1 What is Simple if Statement?
3.1.2 What is if else Statement?
3.1.3 What is else-if Statement?
3.1.4 What is Nested if?
3.1.5 What are Multiway Selection Statements Using switch Case?
3.2 What are the Iterative Statements?
3.2.1 What Is The Use Of Looping Using The while Statement?
3.2.2 How to do More Looping Using The do-while Statement?
3.2.3 How to do Still More Looping Using The for Statement?
3.3 What is break Statement?
3.4 What is continue Statement?
3.5 What is goto Statement?
4. What is an Array?
4.1 How to Declare an Array?
4.2 How to Find Elements of Array?
4.3 How to Initialize an Array?
4.4 What are the Different Types of Array?
4.5 What are the Application of Arrays?
5. What is a String?
5.1 How to Declare a String?
5.2 What are String Input and Output functions?
5.3 What are C String Manipulation Operations?
6. What are Functions?
6.1 What are the Different Category of functions?
6.2 What are the Variable Storage Classes?
6.3 What is Recursion?
6.4 What are the Standard Library Functions?
7. What are Pointers?
7.1 What are the Pointers And Function Arguments?
7.2 What is Dangling Memory?
7.3 What are Pointers And Function Arguments?
7.4 What is Pointer to Pointer?
7.5 What is Pointers And Multidimensional Arrays?
7.6 What is Dynamic Memory Management Functions?
8. What is an Enumerated Datatype?
9. What is a Structure?
9.1 How to Initialize a Structure?
9.2 How to Access Structure Members?
9.3 What is a Nested Structure?
9.4 What is Arrays of Structures?
9.5 How to use Structure as Function Arguments?
9.6 How to Use Pointers to Structures?
9.7 What are Self Referential Structures?
10. What is Union?
11. What are File Operations?
11.1 How to Create a File?
11.2 How to do Input/Output Operations in a File?
1. What is Problem Solving ?
1.1 What are the Problem Solving Tools?
In order to solve any problem the following should be done. They are:
1) Problem definition phase
2) Getting started on a problem
3) Use of specific examples
4) Similarities among problem
5) Working backwards from solution
6) General problem-solving strategies
1) Problem definition phase: Initially the problem should be identified from
the given question required by the user.
2) Getting started on a problem: Based on the problem we should identify the
requirements.
3) Use of specific examples: Consider a simple example for the given problem
and solve it.
4) Similarities among problem: Based on the examples identify the
similarities and identify a solution to solve a large number of problems.
5) Working backwards from solution: After identification of the solution we
have to check if it correct or not.
6) General problem-solving strategies: Steps involved in the problem solving
process are shown as following.

a. Become aware of the problem


b. Define the problem
c. Choose the particular problem to be solved
d. Identify potential solutions
e. Evaluate the valid potential solutions to select the
best one.
f. Develop an action plan to implement the best
solution
1.2 What are the Problem Solving Techniques?
Procedure to Solve a Problem (Steps Involved in Problem Solving):
A computer cannot solve a problem on its own. One has to provide step by
step solutions of the problem to the computer. In fact, the task of problem
solving is not that of the computer. It is the programmer who has to write down
the solution to the problem in terms of simple operations which the computer
can understand and execute.
In order to solve a problem by the computer, one has to pass though certain
stages or steps. They are

1. Understanding the problem


2. Analyzing the problem
3. Developing the solution
4. Coding and implementation.
1. Understanding the problem: Here we try to understand the problem to
be solved in totally. Before with the next stage or step, we should be
absolutely sure about the objectives of the given problem.
2. Analyzing the problem: After understanding thoroughly the problem to
be solved, we look different ways of solving the problem and evaluate each
of these methods. The idea here is to search an appropriate solution to the
problem under consideration. The end result of this stage is a broad
overview of the sequence of operations that are to be carries out to solve the
given problem.
3. Developing the solution : Here the overview of the sequence of
operations that was the result of analysis stage is expanded to form a detailed
step by step solution to the problem under consideration.
4. Coding and implementation: The last stage of the problem solving is the
conversion of the detailed sequence of operations in to a language that the
computer can understand. Here each step is converted to its equivalent
instruction or instructions in the computer language that has been chosen for
the implantation.
1.3 How the Computer Acts as a Problem Solving Tool?
Question: What is the need for programming language?
Answer:
If we want the computer to solve the problem any number of times we need
a programming language. Computer can repeatedly solve the problem any
number of times. If we have to tell the computer to repeatedly solve the problem
any number of times.
Question: What is a Problem?
Answer:
A Problem is an obstacle which makes it difficult to achieve a desired goal,
objective or purpose.
Question: What is Problem Solving?
Answer:
Every problem in the real world needs to be identified and solved. Trying to
find a solution to a problem is known as problem solving.
Question: How to Solve a Problem?
Answer:
If you have a problem you can solve it manually or solve the problem using
a computer.
Question: What is computer? Explain parts of computer?
Answer:
Computer is a device capable of performing computations and making
logical decisions at speed of millions and even billions of times faster than
human being can.
Or
Computer is an electronics device which performs arithmetic and logical
operations.
A computer system made of two major components. They are:
1. Software
2. Hardware.
The hardware component of the computer system consists of five parts:
input devices, central processing unit (CPU), primary storage, output devices,
and auxiliary storage devices
The input device is usually a keyboard where programs and data are
entered into the computers. Examples of other input devices include a mouse, a
pen or stylus, a touch screen, or an audio input unit.
The central processing unit (CPU ) is responsible for executing
instructions such as arithmetic calculations,comparisons among data, and
movement of data inside the system. Today’s computers may have one ,two, or
more CPU’s .Primary storage which is also known as main memory, is a place
where the programs and data are stored temporarily during processing. The data
in primary storage are erased when we turn off a personal computer or when we
log off from a time-sharing system.
The output device is usually a monitor or a printer to show output. If the
output is shown on the monitor, we say we have a soft copy . If it is printed on
the printer, we say we have a hard copy.
Auxiliary storage , also known as secondary storage , is used for both
input and output. It is the place where the programs and data are stored
permanently. When we turn off the computer, or programs and data remain in the
secondary storage, ready for the next time we need them.
Question: What is a Computer Software?
Answer:
Computer software is divided in to two broad categories: system software
and application software .System software manages the computer resources .It
provides the interface between the hardware and the users. Application
software, on the other hand is directly responsible for helping users solve their
problems.
Question: What is the need of software?
Answer:
The need of software is to implement any specific task in a computer i.e.
if you want to solve your problem through computer, then you have to
develop software according to your problem and you have to install that
software in your system. Then your system is ready to serve your
requirement.
Note: Generally softwares are developed by using computer programming
languages like C, C++, JAVA, .NET etc.
Question: What is SOFTWARE? Explain types of software?
Answer:
The software is the collection of programs that allow the hardware to do its
job. Computer software is divided into two broad categories.
a) System Software
b) Application software
a) SYSTEM SOFTWARE
System software consists of programs that manage the hardware resources
from computer and perform required information processing tasks. These
programs are divided into 3 classes.

1. The operating system


2. System support
3. System development.
a) APPLICATION SOFTWARE:
Application software is broken into two classes.
1) General purpose software
2) Application specific software
General purpose software is purchased from a software developer and can
be used for more than one word application processors. Data base management
system etc.
Application specific software can be used only for its intended purpose.
A general ledger system used by accountant and a material requirement.
Planning system used by a manufacturing organization are the examples of
application specific software.
1.4 What are the Programming languages ?
Question: What is a programming language?
Answer:
A programming language is an artificial language designed to communicate
instructions to a machine, particularly a computer. Programming languages can
be used to create programs that control the behavior of a machine and/or to
express algorithms precisely.
A programming language is usually split into the two components of syntax
(form) and semantics (meaning). Some languages are defined by a specification
document. To write a program for a computer we must use a computer
language. A summary of computer languages as shown below

Question: What is a Machine Level Language?


Answer:

1. Machine level language has been introduced in 1940’s.


2. The only language understood by computer is machine level language.
3. Each computer has its own machine language, which is made streams
of Os and 1’s because the internal circuits of a computer are made of
switches, transistors and other electronic devices that can be in one of
two states off and on.
4. In this the off state is represented by “O” and the on state is represented
by 1.

Question: What are the Advantages Of Machine Level Language?


Answer:

1. Machine level language easily understood by the CPU.


2. The time taken for executing the program is very less.
3. The execution speed is very high because of machine instructions are
directly understood by the CPU and no translation of the program is
required.

Question: What are the Disadvantages of Of Machine Level Language?


Answer:

1. It is machine dependent language.


2. Length of the program is very high so difficult to modify.
3. Machine language is difficult to program. It is necessary for the
programmer either to memorize the dozens of code numbers.
4. Difficult to check the errors

Question: What Is a Symbolic Level Language?


Answer:

1. Symbolic level language has been introduced in 1950’s.


2. Symbolic language uses symbols or mnemonics to represent the various
machine language instructions. It is developed by admiral grace happen
in the early 1950s.
3. It is also called as Assembly level language.
4. Computer does not understand symbolic language. So it must be
translated to the machine language.
5. A special program called as assembler translates symbolic code into
machine language.

Question: What are the Advantages Of Symbolic Level Language?


Answer:

1. It is easier to understand and use.


2. It reduces the cost of associated ROM chips because of reduced code
size.
3. It is easy to modify the program.
4. It is easy to rectify the errors.

Question: What are the Disadvantages of Symbolic Level Language?


Answer:

1. It is Machine dependent language.


2. To develop the assembly code, knowledge of hardware compulsory
required.
3. Execution time is more because of translating of assembly code into
machine level code.

Question: What is a High Level Language?


Answer:

1. High level language has been introduced in 1960’s.


2. The languages which are developed in general language (English) are
called as high level languages.
3. High level having greater efficiency.
4. These are portable languages.
5. FORTAN, COBOL, C, C++, JAVA etc are the examples of high level
languages.
6. Machine does not understand high level languages directly. So to
convert high level languages into its equivalent machine level
languages translators are used.
7. The translators are interpreter and compiler.

Question:What are the advantages of High Level Language?


Answer:

1. High level languages are always Machine independent.


2. These languages are easy to learn and used.
3. Preparation cost is less due to it takes less time and effort to develop the
application.
4. Easy to maintain compare to machine level and assembly level
languages.

Question:What are the Disadvantages of High Level Language?


Answer:

1. The efficiency of the program less compared with machine and


assembly level languages.
2. Execution time is more because of translation i.e. high level to machine
level languages.
3. This are having less flexible than assembly language.

1.5 How to Create and Run Programs?


C is a procedural programming language. It was initially developed by
Dennis Ritchie in 1972 at AT&T labs.
It is the job of the programmer to write test the program. There are four
steps in this process.
1. Writing and editing the program
2. Competing the program
3. Linking the program with equaled library modules
Executing the program

Creating and running programs:


● The software used to write programs is as a text editor.
● The file created from a text editor is known as a source file.
● The code in a source file must be translated into machine languages using
the ‘c’ compiler, which is made of two separate programs they are the
preprocessor and the translator.
● The file created from the compiler is known as an object module.
● An object module is linked to the standard functions necessary for running
the program by the linker.

Fig. 1.1: Creation and Running of a C Program


● Linker generates new code called executable code i.e the code which is
having the functionality of the application that code is called as executable
code.
● Executable code given to the runner or loader which will give the final
result of our application.
Consider a C program (or) source code named name.c is compiled
through a compiler like Turbo C compiler, it will be converted to an object file
named name.obj . Linker links the library functions and converts the name.obj
to name.exe file, then finally loader executes the program to get the output as a
result.
1.6 What is an Algorithm?
Definition: Step by step procedure to solve a particular problem is called as an
algorithm.
A set of sequential steps usually written in Ordinary Language to solve a
given problem is called Algorithm.
It may be possible to solve to problem in more than one ways, resulting in
more than one algorithm. The choice of various algorithms depends on the
factors like reliability, accuracy and easy to modify. The most important factor in
the choice of algorithm is the time requirement to execute it, after writing code
in High-level language with the help of a computer. The algorithm which will
need the least time when executed is considered the best.

Question: What are the steps involved in algorithm development?


Answer:
An algorithm can be defined as “a complete, unambiguous, finite number of
logical steps for solving a specific problem“.
Step 1: Identification of input: For an algorithm, there are quantities to be
supplied called input and these are fed externally. The input is to be identified
first for any specified problem.
Step 2: Identification of output: From an algorithm, at least one quantity is
produced, called for any specified problem.
Step 3: Identification the processing operations: All the calculations to be
performed in order to lead to output from the input are to be identified in an
orderly manner.
Step 4: Processing Definiteness: The instructions composing the algorithm
must be clear and there should not be any ambiguity in them.
Step 5: Processing Finiteness: If we go through the algorithm, then for all
cases, the algorithm should terminate after a finite number of steps.
Step 6: Possessing Effectiveness: The instructions in the algorithm must be
sufficiently basic and in practice they can be carries out easily.

Question: What are the features of algorithm (or) characteristics of good


algorithm?
Answer:
An algorithm must possess the following properties
1. Finiteness: An algorithm must terminate in a finite number of steps
2. Definiteness: Each step of the algorithm must be precisely and
unambiguously stated
3. Effectiveness: Each step must be effective, in the sense that it should be
primitive easily convert able into program statement) can be performed exactly
in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it can be used to
solve problems of a specific type for any input data.
5. Input/output: Each algorithm must take zero, one or more quantities as input
data produce one or more output values.
An algorithm can be written in English like sentences or in any standard
representation sometimes, algorithm written in English like languages are called
Pseudo Code.
EXAMPLE 1: Suppose we want to find the average of three numbers, the
algorithm is as follows
Step 1: Read the numbers a, b, c
Step 2 :Compute the sum of a, b and c
Step 3 :Divide the sum by 3
Step 4:Store the result in variable d
Step 5:Print the value of d
Step 6: Stop

EXAMPLE 2: Write an algorithm for Write an algorithm to calculate the simple


interest using the formula. Simple interest = P*N* R/100.
Where P is principle Amount, N is the number of years and R is the rate of
interest.
Step 1: Read the three input quantities P, N and R.
Step 2: Calculate simple interest as Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.

EXAMPLE 3: Write an algorithm to find the largest of three numbers X, Y,Z.


Step 1: Read the numbers X,Y,Z.
Step 2: if (X > Y) Big = X else BIG = Y
Step 3 : if (BIG < Z)
Step 4: Big = Z
Step 5: Print the largest number i.e. Big
Step 6: Stop.

EXAMPLE 4: Write an algorithm to calculate the perimeter and area of


rectangle. Given its length and width.
Step 1: Read length of the rectangle.
Step 2: Read width of the rectangle.
Step 3: Calculate perimeter of the rectangle using the formula perimeter = 2*
(length + width)
Step 4: Calculate area of the rectangle using the formula area = length *width.
Step 5: Print perimeter.
Step 6: Print area.
Step 7: Stop.

EXAMPLE 5: Algorithm/pseudo code to add two numbers


Step 1: Start
Step 2:Read the two numbers in to a,b
Step 3: c=a+b
Step 4: write/print c
Step 5: Stop.
1.7 What is a Flowchart ?
Definition:
A flow chart is a step by step diagrammatic representation of the logic paths
to solve a given problem. (or) A flowchart is visual or graphical representation of
an algorithm.
The flowcharts are pictorial representation of the methods to b used to solve
a given problem and help a great deal to analyze the problem and plan its
solution in a systematic and orderly manner. A flowchart when translated in to a
proper computer language, results in a complete program.

Question: What are the advantages of Flowcharts?


Answer:
1. The flowchart shows the logic of a problem displayed in pictorial fashion
which felicitates easier checking of an algorithm.
2. The Flowchart is good means of communication to other users. It is also a
compact means of recording an algorithm solution to a problem.
3. The flowchart allows the problem solver to break the problem into parts.
These parts can be connected to make master chart.
4. The flowchart is a permanent record of the solution which can be consulted at
a later time.

Question: What are the basic symbols used in flow-charts?


Answer:
The symbols that we make use while drawing flowcharts as given below are
as per conventions followed by International Standard Organization (ISO).
1. Oval: Rectangle with rounded sides is used to indicate either START/ STOP
of the program.

2. Input and output indicators : Parallelograms are used to represent input and
output operations. Statements like INPUT, READ and PRINT are represented in
these Parallelograms.

3. Process Indicators: Rectangle is used to indicate any set of processing


operation such as for storing arithmetic operations.

4. Decision Makers: The diamond is used for indicating the step of decision
making and therefore known as decision box. Decision boxes are used to test the
conditions or ask questions and depending upon the answers, the appropriate
actions are taken by the computer. The decision box symbol is

5. Flow Lines: Flow lines indicate the direction being followed in the flowchart.
In a Flowchart, every line must have an arrow on it to indicate the direction. The
arrows may be in any direction

6. On- Page connectors: Circles are used to join the different parts of a
flowchart and these circles are called on-page connectors. The uses of these
connectors give a neat shape to the flowcharts. Ina complicated problems, a
flowchart may run in to several pages. The parts of the flowchart on different
pages are to be joined with each other. The parts to be joined are indicated by the
circle.
7. Off-page connectors: This connector represents a break in the path of
flowchart which is too large to fit on a single page. It is similar to on-page
connector. The connector symbol marks where the algorithm ends on the first
page and where it continues on the second.

EXAMPLE 1: Draw a flowchart to add two numbers entered by user.

Fig. 1.2: Flowchart to add two numbers entered by user

EXAMPLE 2: Draw flowchart to find the largest among three different numbers
entered by user.
Fig. 1.3: Flowchart to find the largest among three different numbers entered by user

Question: What are the differences between Algorithm and Flowchart?


Answer:
Algorithm is a method of representing the step-by-step procedure logically
to solve a particular problem, where as a flow chart is a diagrammatic
representation of an algorithm. It is constructed using different types of boxes
and symbols. An algorithm consists of step-by-step English descriptions in
which each step belongs to a particular operation leading to a solution of a
problem. The flowchart shows the series of blocks and arrows each of which
represents a particular step in an algorithm. An algorithm is used particularly for
small problems where as flowchart is used for large problems. For complex
problems the algorithm had been proved to be inadequate and flowchart is
adequate for complex problems.
1.8 What is Top Down Design?
A top -down design is the decomposition of a system into smaller parts in
order to comprehend its compositional sub-systems.
Top Down approach in C:
In this approach we look at the overall requirement and start coding. We
build the main function first, then add calls to various functions like add,
subtract etc... and then display the output. After doing all these we code the
individual functions for addition, subtraction etc.
So what we did here was approached the problem by first looking at the
overall objective which is the top, then deciding when and where to call the
functions and eventually going down to the lowest level detail of designing the
functions themselves, hence it is called the "top-down" approach. In this top
down approach, a large project divides into small programs, and these programs
are known as modules.
C programming language supports this approach for developing projects. It
is always good idea that decomposing solution into modules in a hierarchy
manner.
The basic task of a top-down approach is to divide the problem into tasks
and then divide tasks into smaller sub-tasks and so on.
In this approach, first we develop the main module and then the next level
modules are developed. This procedure is continued until all the modules are
developed.

Question: What is the advantages of top-down approach?


Answer:

1. In this approach, first, we develop and test most important module.


2. This approach is easy to see the progress of the project by developer
or customer.
3. Using this approach, we can utilize computer resources in a proper
manner according to the project.
4. Testing and debugging is easier and efficient.
5. In this approach, project implementation is smoother and shorter.
6. This approach is good for detecting and correcting time delays.

Example for top down approach is shown below.


Fig. 1.4: Top down approach example
2. How to Write C Program ?
Question: What are the advantages of C language?
Answer:
Advantages of C are shown below.

1. C is Portable: This means a program written for one computer may


run successfully on other computer also.
2. C is fast: This means that the executable program obtained after
compiling and linking runs very fast.
3. C is compact: The statements in C Language are generally short
but very powerful.
4. Simple / Easy: The C Language has both the simplicity of High
Level Language and speed of Low Level Language. So it is also
known as Middle Level Language
5. C has only 32 Keywords
6. C Compiler is easily available
7. C has ability to extend itself. Users can add their own functions

2.1 How the Structure of C program look like?


The program written in C language follows this basic structure. The
sequence of sections should be as they are in the basic structure. A C program
should have one or more sections but the sequence of sections is to be followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration section
Executable section
}
6. Sub program or function section
1. DOCUMENTATION SECTION : comes first and is used to document the
use of logic or reasoning your program. It can be used to write the program's
objective, developer and logic details.
The documentation is done in C language with /* and */ . Whatever is
written between these two are called comments.
2. LINKING SECTION : This section tells the compiler to link the certain
occurrences of keywords or functions in your program to the header files
specified in this section.
Example: #include <stdio.h>
3. DEFINITION SECTION : It is used to declare some constants and assign
them some value.e.g. #define MAX 25
Here #define is a compiler directive which tells the compiler whenever
MAX is found in the program replace it with 25.
4. GLOBAL DECLARATION SECTION : Here the variables which are used
through out the program (including main and other functions) are declared so as
to make them global(i.e accessible to all parts of program)
e.g. int i; (before main())
5. MAIN FUNCTION SECTION : It tells the compiler where to start the
execution from main()
{
point from execution starts
}
main function has two sections
1. declaration section : In this the variables and their data types are
declared.
2. Executable section : This has the part of program which actually
performs the task we need.
TURBO C EDITOR:
Question: What is IDE?
Answer:
Turbo c features as integrated Development environment, or IDE,. It is also
referred to as the programmer’s platform.) in IDE you can able to
write/save/open your programs or code, compile using short cut keys, and also
perform code debugging very easily.

Question: What is turbo c editor?


Answer:
It is a compiler of C program and it can be also used as a general editor. To
enter into editor first change into the directory this contains the software and
enters the command TC at the command prompt.
C:\> CD TC
C:\TC> tc
Then it opens the editor which contains a menu bar at the top, a status bar at the
bottom and a main window to write the programming statements and a sub
window which shows the messages.
The menu bar contains some menu pads and they can be selected by pressing
ALT and the highlighted character in the required menu pad.
Then it shows the sub menu which contains some bars and they can be selected
using arrow keys.
The status bar shows online help and the keys information.
1) To write a new program selects ‘New’ command from “File” menu.
2) To save the working program select ‘Save’ command from “File” menu.
Or press F2 and enter a name.
3) To compile the program select ‘Compile to OBJ’ command from “compile”
menu or press Alt + F9. Then it shows the list of Errors or warnings. If the
program is error-free then the compiler Creates an object file (.OBJ) and an
executable file (.EXE).
4) To execute the program select ‘Run’ command from “Run” menu or press Ctrl
+ F9.
5) To see the output of the execution select ‘User Screen’ command from “Run”
menu or press Alt + F5.
6) To close the editor select ‘Quit’ command from “File” menu or press Alt + X.
Common Short cut Keys Description:
F2 press to Save current work
F3 press to open an existing file
ALT-F3 press to close current
ALT-F9 press to compile only
ALT-F5 press to view the desired output of the program.
CTRL-F9 press to compile+run
ALT-X or ALT-F-X press to exit from TC IDE
2.3 What are the Basic Data Types?
Question: What do mean by data type?
Answer:
Data types reserves space for data. A data type defines for which type of data
how much memory to be allocated.

1. Type
2. Size
Question: What are the different data types?
Answer: There are five data types

1. Primary data types


2. Extended data types
3. Derived data types
4. User defined data type
5. Null data type

1. Primary Data Types:

Primary data types include integer data type, floating point data type and
character data types.
Integer Data Type:
Keyword: int
Memory size : 2 bytes
Range: -215 to -215 -1
Signed: -32,768 to 32,767
Control String: %d
Unsigned: 0 to 216 -1: 0 to 65,535
Floating Point Data Type:
Keyword: float
Memory rage: 4 bytes (32) bits
Range: -3276999 to 3276998
Control String: %f
Character Data Type:
Keyword: char
Memory Size: 1 byte
Range: -128 to 127 (ASCII code)
Control String: %c
Note: every character should denote between in single quotations (‘a’)
ASCII: The American Standard Code for Information Interchange (ASCII) is a
character-encoding scheme based on the ordering of the English alphabet. ASCII
codes represent text in computers, communications equipment, and other devices
that use text. Most modern character-encoding schemes are based on ASCII,
though they support many more characters than ASCII does.
For example ASCII code for character A is 65.

2. Extended Data Types:


The extended data types includes the following.
i) Long Integer Data Type:
Keyword: long int
Memory Size: 4 bytes (32) bits
Control String: %ld
ii) Double Data Type:
Keyword: double
Memory Size: 8 bytes
Control String: %lf

3. Derived data types:

The derived data types are again classified as shown below.


1) Arrays
2) structures
3) pointers
4) Unions
4. User defined data type:
The classification of user defined data types are shown below.
1. Functions
2. Typedef
3. Enum
5. Null data type:
Using the key word: void
Question: What are all the predefined data type ranges?
Answer:
Predefined data type ranges are:
Type Typical Size Minimal Range
in bits
char 8 -128 to 127
unsigned char 8 0 to 255
signed char 8 -128 to 127
short int 16 -32,768 to 32,767
unsigned short int 16 0 to 65535
signed short int 16 -32,768 to 32,767
long int 32 -2,147,483,647 to 2,147,483,647
long long int 64 -(263 ) to 263 -1
signed long int 32 -2,147,483,647 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
unsigned long long int 64 264 -1
float 32 3.4e-38 to 3.4e+38
double 64 1.7e-308 to 1.7e+308
long double 80 3.4e-4932 to 1.1e+4932
void - data type that do not return any
value

2.4 What are C Tokens?


Question: What is token? Explain types of tokens in c language?
Answer:
The smallest individual units of a C- program are known as Tokens.
Basically c tokens are classified into four types. They are
1. Key word
2. Identifiers
3. Constants
4. Operators

Question: What is a Keyword?


Answer:
Key words are the pre defined words meaning has already been explained to
the “C” Compilers. These key words are also called as “Reserved words”. There
are 32 keywords available in standard C language. Following are the list of
keywords in C
auto, break, case, char, const, continue, default, do.double, else, enum, extern,
float, far, for, goto, if, int, long, near, register, short,return, signed, static, struct,
switch, type def, union, voids, unsigned, while.
➢ These are the 32 keywords available in C programming language.
➢ All keywords must and should write in all small caps only.
➢ We can’t add anything to the keywords because this all are predefined.
➢ We can’t change the operation of any key words.
➢ We can’t combine two keywords.
2.5 What are Identifiers?
➢ Identifiers are user defined words or names which doesn’t have specific
meaning with in language. The meaning of these words understood by
programmer/developer.
➢ Identifiers are used to identify the data instruction or user defined types.
Question: What are the Rules for Identifiers?
Answer:
1. It consists of sequence of letters and digits.
2. Identifier name always start with alphabet.
3. The only special characters allowed is under score (-)
4. The length of the Identifier is up to 32 characters.
5. Identifiers should not be a keyword.
6. No two successive underscores are not allowed
7. It can be defined in uppercase or lowercase letters.
8. Identifiers are case sensitive in programming.
9. Duplicate names are not allowed.
10. Don’t give any white spaces whenever we are writing identifier names.
2.6 What are Constants?
Constants refer to fixed values that the program may not alter and they are
called literals .
A constant is a value which never changes throughout the program. These
values are represented in different formats.
Types of Constants:
Constants mainly classified in the two types.
1. Numeric Constants
2. Alpha - numeric Constants
➢ Numeric constants are again classified into two types

1. Integer Constant 2. Real constants

1. Integer Constant:
Integer constants again classified into three types

1. Decimal integer
2. Octal integers
3. Hexa decimal integer

Decimal integer :
An integer value with base 10 is called decimal integer.
This integer value consists of digits from 0 to 9.
This integer is prefix with 1-9 sign(+/-)
Valid decimal integers are 100, 456, -345, 23456, -19202 etc.
Octal integers:
An integer value with base 8 is called octal integer.
This integer value consists of digits from 0 to 7.
This integer is prefix with ‘0’
Ex: 0123, 0725 …etc are the valid octal integers.
Ex: 0128, 4647……etc are the invalid octal integers.
Hexa decimal integer:
An integer value with base 16 is called Hexa decimal integer.
This integer value consists of digits from 0 to9 and A-F or a-f.
This integer value is prefix with “ox”
Ex: 1ab - invalid
Ox1ab - valid
2. Real constants:
Real constants are also called as floating point constants.
Real constants are having both decimal and fractional parts.
Alpha numeric constants:
Character constants again classified into two types.

1. Single character constant


2. String constant

1. Single character constant:


✓ A non numeric value represented with in ‘ ‘ is called single character value
or constant.
✓ Every character occupies 1 byte of memory.
2. String constant:
✓ A non numeric value represented with in “ “ is called string or constant.
✓ A string is collection of characters.
Examples:
“rama” – Alphabetic string
“A101” - Alphabetic string
“a**” - Alphabetic string
✓ Every string is terminated with a special character called NULL which
occupies 1- byte.
Note: In C program constants are declared by using “ const” keyword.
Example:
const int a=10;
const float f=1.5;
const char =’f’;
2.7 What are Variables?
Variable:
➢ While solving a problem we need to remember some data values
temporarily. Such values are placed in the named locations in the memory.
These named locations in the memory are called variables.
➢ A variable is an identifier. It can be consider as a name given to the
location in memory where values are stored.
➢ The quantities which can be changed during the execution of program are
called Variables.
➢ Variable is a container which contains data or Information.
➢ Before using any variable in a program it must be declared first.
SYNTAX:
<Data-type><variable-name>;
Example: int count;
float X;
char name;
Rules:
1) Variable names can consist of alphabets, Digits, underscore, dollar character
etc.
2) A variable name should not begin with a digit or any special symbol except #.
3) White spaces are not allowed in variable names.
4) Upper and lower case distinct I.e.,”A” Is differed from ‘a’.
5) The maximum length of variable length is 32 characters.
Important points to remember:

1. In c programming language variable declaration must be exist top of the


program i.e. after opening the curly braces and before writing the first
instruction.
2. In variable declaration existing keyword, operators, separators, and
constants values are not allowed.
3. At least once space should be required in between data-type and
variable-name.
4. All data-types must write in small caps only.
5. Variable names are case sensitive.

Note : one variable contain only one value. If you change the value of the
variable then old value will be erased and new value will be stored.

Question: What does a variable contain?


Answer:
Variable contain mainly three things
1) Name of the variable
2) Value of the variable
3) Address of the variable
Example:
int a=10;

Fig. 2.1: Variable name, value and address

Question: What are Different Types of variables?


Answer:
Variables are broadly classified into four types. They are
1) Local variables
2) Global variables
3) Block level variables
4) Constant variable
1. Local variables means, the variables which are defined inside a function.
These variables are work within that function only. The scope of the local
variables is inside a function in which variables are defined.
2. Global variables are nothing but the variables which are defined outside of
any function (generally main). The scope of these variables is throughout the
program i.e. in all functions we can use these variables.
3. The variables which are defined inside a block is called as block level
variables . The scope of the block level variables is within the block.
Block variables again classified into 2 types. They are

1. Conditional block(generally conditional statements)

Ex: while, for, do-while

2. Iteration block(generally loops)


Ex: if, switch
4. The variables which are declared with const keyword, those variables are
called as constant variables. Constant variables data we can’t change it at any
cost. Constant variable may be local, global and block level.

Question: How to initialize a variable?


Answer:
A variable can be initialized in two ways. They are
1) Static variable initialization
2) Dynamic variable initialization
1) Static variable initialization:
Declaring a variable by assigning constant value is called Static variable
initialization.
Or
The value assigned to variable is known before compiling program is called
Static variable initialization.
Ex:
int x=10;
float y=200;
char c=”ngc”;
2) Dynamic Variable Initialization:
Declaring a variable by assigning expression or variable is called Dynamic
variable initialization.
Or
The value assigned to variable is not known during compiling time is called
Dynamic variable initialization.
Dynamic initialization can be done by using pre defined functions which
available in c library.
Example:
int c;
scanf(“%d”,&c); // dynamic initialization
c= 10; //static initialization
Structure of a ‘C’ program:
<Preprocessor commands>
<Global declarations>
void main ()
{
<Local declarations>;
<Statements>;
}
Function (arguments)
{
<Local declarations>;
<Statements>;
}
➢ The ‘C’ program has a free formatted structure.
➢ Every statement must be terminated with a semicolon (;)
➢ A program is a collection of functions. There may be a lot of functions or
not but at least one function must be there that is main (), where the
execution starts.
➢ C has case sensitivity. All the keywords are defined in lower case.
➢ So better to write entire program in lower case.

Question: What is a Preprocessor command?


Answer:
The commands which start with a hash (#) symbol are called Preprocessor
commands. These commands are used to place library information in our
program. Generally in C programs library information placed in the form of
header files.
Example:
# include <stdio.h>
# include “conio.h”
# define PI 3.14159

Question: What are Global declarations?


Answer:
To use any variable it must be declared with its data type before the first
executable statement. The variables which declared inside a block are available
in that block only. Such variables are called as local variable.
To use the variable in entire program with same effect it must be declared as
global. These global variables are declared outside the functions.

Question: What is a main () function?


Answer:
➢ It is starting point for program execution. This function has no arguments
and no parameters.
➢ C language does not allow more than one main () function in a single
program.
➢ main () function always write in small caps only.
➢ Every function must and should call through main () only (directly or
indirectly).
➢ This function consists of declarations and executable statements.
➢ C compiler does not consider anything out of the main.
2.8 What are the Input and Output Statements?
Input and output operations are performed by using predefined library
functions.
printf():
printf() is a pre defined output function in C language. Basically printf() is used
to for three purposes.
✓ 1st purpose is to display some message on the console screen
Syntax:
printf(“Some text message”);
Ex: printf (“My name is C”);
✓ 2nd purpose is to display some values on the console screen
Syntax:
printf(“format specifier”, variable_names);
Example: printf(“%d”,a);
printf(“%d%d”,a,b);
printf(“%d%f%c”,a,b,c);
printf(“value of a =%d”,a);
printf(“addition =%d”,c);
✓ If you want to print address of the variable then go for printf()
Syntax:
printf(“control string”,&variable_name);
Example: printf(“%d”,&a);
printf(“address of a =%d”,&a);
printf(“address of a and b=%d%f”,a,b);
Note:
1. The return type of the printf() function is integer type.
2. printf() defined in stdio.h(standard input output) header file.

scanf ():-
✓ Scanf function is a predefined function by using scanf() function we can
read the data at run time.
✓ Scanf function returning an integer value i.e. total number of scanned
values.
✓ The complete behavior of scanf() function will depends on format
specifying only but not on argument list.
✓ When we working with scanf() function if you not provide ampersand to
the argument then scanf() will read the values but those not stored in
memory.
Syntax:
scanf (‘’format string ‘’, & (variables));
Example:
scanf (‘’%d %d ‘”, &a,& b);
3. What are the Control statements ?
3.1 What are the Conditional Statements?
Question: What are Selection statements?
Answer:
These statements are also called ‘Branching Statements or conditional
statements. Because they are used to transfer control from one statement to
another statement.
Conditional statements are mainly classified into two types they are
1) if statements
2) switch statement.
3.1.1 What is Simple if Statement?
“C” uses the keyword “if” to implement the decision control statement or
instructions. The general form of its statement looks like is
Syntax:
if (condition)
{
Statements 1;
Statements n;
}
Flow chart for if condition

Fig. 3.1: Flowchart for if condition

If the condition is true then executes the if block statements otherwise it


does not execute the statements. In implementation when we need to create
decision making block then go for if. Constructing the body is always optional.
For a single statements body need not be constructed. If the body is not specified
then automatically condition path terminated with next semi colon.

Question: Write a Program to print big value of given two numbers by


using if statement.
PROGRAM:
#include<stdio.h>
#include<<conio.h>
void main()
{
int a,b;
clrscr();
printf ("enter a,b, values =");
scanf("%d%d",&a,&b);
if(a>b)
{
printf("a is greater than b", a, b);
}
if(b>a)
{
printf("b is greater than a", b, a);
}
getch();
}
OUTPUT:
enter a,b, values =10
20
b is greater than a
3.1.2 What is if else Statement?
The if else statement is an extension of the simple if statement. The general
form is or syntax is
Syntax:
if (condition)
{
Block of statements; //true block
}
else
{
Block of statements; //false block
}
If the condition is true then it executes the if block statements otherwise if
executes the else block statements.
Flow chart of if else statements:

Fig. 3.2: Flowchart for if else statement

Question #1: Write a program to print the given value is even or odd.
PROGRAM:
//Program to print the given value is even or odd
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("enter a value=");
scanf("%d", &a);
if(a%2==0)
{
printf("a is even ", a );
}
else
{
printf("a is odd", a);
}
getch();
}
OUTPUT:
enter a value=50
a is even

Question #2: Write a program to check the given number is positive or


negative.
PROGRAM:
//Program to check the given number is positive or negative
#include<stdio.h>
#include<conio.h>
void main()
{
int k;
clrscr();
printf("enter any number=");
scanf("%d", &k);
if(k==0)
{
printf("the number is zero");
}
else if(k>0)
{
printf("the number is positive");
}
else
{
printf("the number is negative");
}
getch();
}
OUTPUT:
enter any number=25
the number is positive
3.1.3 What is else-if Statement?
It is also an extension of if else statement to implement multiple conditions.
General form is
Syntax:
if (condition)
{
Block of statements;
}
else if (condition)
{
Block of statements;
}
...
...
else
{
Block of statements;
}
If the condition is true then it executes the block statements otherwise it
executes the else block statements .if, 1st if condition is not true then compiler
moves into second if condition if it is true then compiler enter into body of that
particular block. If suppose above all mentioned condition are fail then finally
compiler moves to else block

Question: Write a C Program for else-if Statement.


PROGRAM:
//Program to check the given character is vowel or not
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("enter a character =");
scanf("%c", &c);
if(c=='a'||c==’A’)
{
printf("It is vowel");
}
else if(c=='e'||c==’E’)
{
printf("It is vowel");
}
else if (c =='o'||c==’O’)
{
printf("It is vowel");
}
else if(c=='i'||C=’I’)
{
printf("It is a vowel");
}
else if (c =='u'||c==’U’)
{
printf("It is vowel");
}
else
{
printf("%c is a not vowel", c);
}
getch();
}
OUTPUT:
enter a character=E
It is vowel

3.1.4 What is Nested if?


if...else Ladder (if...else if....else Statement) executes two different codes
depending upon whether the test expression is true or false. Sometimes, a choice
has to be made from more than 2 possibilities.
The if...else ladder allows you to check for multiple test expressions and
execute different statements.
Syntax:
if(testExpression1)
{
Statements;
}
else if(testExpression2)
{
Statements;
}
...
...
else
{
Statements;
}

Question: Write a C Program using nested if … else.


PROGRAM:
//Program using nested if … else
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
if (number1 >= number2)
{
if (number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
else
{
printf("Result: %d > %d", number1, number2);
}
}
else
{
printf("Result: %d < %d",number1, number2);
}
return 0;
}
OUTPUT:
Enter two integers:24
25
Result 24<25
3.1.5 What are Multiway Selection Statements Using switch Case?
Switch is keyword, by using switch we can constructs multiple blocks of a
selection statements. Multiple blocks can be constructed with “case” keyword.
➢ It provides an easy way to dispatch execution to different parts of your code
based on the value of an expression. As such it often provides a better alternative
than a large series of if-else statements.
Syntax:
switch (expression)
{
case value1:
//Statements;
break;
case value 2;
//Statements;
break;
...
...
...
case value n;
//Statements
break;
default:
//default statement
}
➢ The switch statement works like this: the value of the expression is
compared with each of the constant values in the case statement. If a match
is found, the code sequence following that case statement is executed. If
none of the constants matches the value of the expression then the default
statement is executed.
➢ Default is a special kind of case which will be executed automatically
when the matching case is not found. Using default is always optional. It is
recommended to use when we are not handling all provisions of switch
block.
FLOW CHART OF SWITCH CASE:

Fig. 3.3: Flowchart for switch case

Question #1: Write a C Program to implement Arithmetic operation in a


switch case.
PROGRAM:
//Program to implement Arithmetic operation in a switch case
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,k;
clrscr();
printf("enter two numbers=");
scanf("%d%d", &a, &b);
printf("\n 1.addition:");
printf("\n 2. Subtraction:");
printf("\n 3.multiplication:");
printf("\n 4.division");
printf("\n select your choice:");
scanf("%d", &k);
printf("\n");
switch(k)
{
case 1:printf("the addition=%d", a+b);
break;
case 2:printf("the subtraction =%d",a-b);
break;
case 3:printf("the multiplication=%d", a*b);
break;
case 4:printf("the division=%d", a/b);
break;
default:printf("in valid choice");
}
getch();
}
OUTPUT:
enter two numbers=30
50
1. addition:
2. Subtraction:
3 .multiplication:
4. division
select your choice:1
the addition=80

Question #2:Write a C program to find given number is less than or greater


than five by using switch case.
PROGRAM:
//Program to find given number is less than or greater than five by using switch
case
# include <stdio.h>
# include <conio.h>
void main()
{
int k ;
clrscr() ;
printf("Enter any number " );
scanf("%d", &k) ;
switch(k)
{
case 0 : printf("\n Number is zero " );
case 1 :
case 2 :
case 3 :
case 4 : printf("\n Number is less than five ") ;
break ;
case 5 : printf("\n Number is five " );
break ;
default : printf("\n Number is greater than five ") ;
}
getch() ;
}
OUTPUT:
Enter any number 3
Number is less than five

Question #3: Write a C program for switch case.


PROGRAM:
# include <stdio.h>
# include <conio.h>
main()
{
char k;
clrscr() ;
printf("Enter any one of the alphabets: " );
k = getche() ;
switch(k)
{
case 'a' :
case 'A' : printf("\n A for Active ") ;
break ;
case 'b' :
case 'B' : printf("\n B for Brave ") ;
break ;
case 'c' :
case 'C' : printf("\n C for Courage ");
break ;
case 'd' :
case 'D' : printf("\n D for Dare ") ;
break ;
default : printf("\n You are timid ") ;
}
getch() ;
}
OUTPUT:
Enter any one of the alphabets: D
D for Dare
3.2 What are the Iterative Statements?
Question: What is the use of Iterative Statements?
Answer:
Iteration means repeated execution of statements. In most situations, we
need to execute a set of statements repeatedly for a given number of times.
Writing the same set of statements repeatedly will have the following
drawbacks.
1) Wastage of time.
2) Wastage of memory.
3) Chances of creating errors.
To overcome this problem, we go to the concept of loops. Using loops, we
will write the statements only once, and execute them as many no. of times as
required.

Question: What do meant by conditional control statement?


Answer:
The statements which can be executed for specified set of times until the
given condition satisfies are known as conditional controlled statements. These
statements are supported under C language with following key words such as
1) while
2) do-while
3) for

Question: What is a loop?


Answer:
Loop is a group of instructions compiler executes repeatedly while some
condition remains true.

Question: Explain types of loops?


Answer:
Loops are classified into two types. They are
1) Entry control loop
2) Exit control loop
1) Entry control loop:
In this control loop compiler will check condition first. If condition is true
then compiler move into the body. If condition fail compiler doesn’t execute
body at least once.
Entry control loop is also called as Pre-checking control loop.
Ex: while, for
2) Exit control loop:
In this kind of control loop compiler first executes the body then it go for
the condition. If condition is true again it goes to the body.
If condition fails it goes out of the body.
So in exit control loop without knowing condition compiler execute body
minimum one time. Exit control loop is also as post control loop.

Question: Explain steps how to implements loops in a program?


Answer:
Generally every loop require three steps
1) Initialization
2) Condition
3) Iteration
Question: Explain the need of initialization, condition, iteration in a loop?
Answer:
Initialization indicates the starting point of the loop. Condition indicates
ending point of loop (i.e. .when condition fail automatically loop terminated). To
rotate the body of the loop either in clock or anti clock wise direction iteration
required in a loop.
The Pretest Loop:
The key feature of the pretest loop is that we test to see whether or not to
continue before executing the body of the loop. The effect of this is that we
might not execute the body at all. So, if we're designing a program that has a
section which might be executed 0 or more time (that is we're not guaranteed
that it will be executed at all), a pretest structure is what we want.
The Post-Test Loop:
Just as we have a structure that tests the continuation condition at the top,
we have on that tests it at the bottom. This is called the post-test loop and is
illustrated in this flowchart:

Fig. 3.4: Post test loop


The test is to determine whether or not to continue until after executing the
block, the loop body will always be executed at least once. This distinguishes it
from the pretest loop.
The Mid-Test Loop:
There is a loop structure that generalizes both the pretest and the post-test
loop. Here we test in the middle of the loop as in this flowchart:
Fig. 3.5: Mid test loop

3.2.1 What Is the Use Of Looping Using The while Statement?


If condition is true it execute statements which are present in side block. If
condition is fail it goes out of body. When we are working with while loop
always pre-checking process will be occur. While loop will be repeats in clock
direction.
Syntax:
while(condition)
{
statements1;
Statement2;
...
...
increment/ decrement;
}
Flow Chart For While Loop:
Fig. 3.6: Flowchart for while condition

If condition is true it execute statements which are present in side block. If


condition is fail it goes out of body. When we are working with while loop
always pre checking process will be occur. While loop will be repeats in the
clock wise direction.

Question #1: Write a program to print one to given number of values.


PROGRAM:
//Program to print one to given values
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("enter n values=");
scanf("%d",&n);
i=1;
while (i<=n)
{
printf("\t%d",i);
i++;
}
getch();
}
OUTPUT:
enter n values=6
123456
NOTE:
✓ Because the condition is placed at the entry of the loop, do-while is also
called “entry-restricted loop”.
✓ In while loop, without executing the statements for at least one time, we
can terminate the loop

Question #2: Write a C program to print given number table.


PROGRAM:
//Program to print given number table
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
clrscr();
printf("enter n value=");
scanf("%d",&n);
i=1;
while(i<=10)
{
printf("\n %d * %2d = %2d",n,i,n*i);
i=i+1;
}
getch();
}
OUTPUT:
enter n value=2
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Question #3: Write a C program to find the reverse of a given number


PROGRAM:
/*Program to find the reverse of a given number
1) number 2)sum of digits 3)number of digits*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n, rn, sd, nd;
/* n->number, rn->reverse number, sd-> sum of digits nd-> number of digits */
clrscr();
printf("enter n value=");
scanf("%d",&n);
rn=sd=nd=0;
while(n>0)
{
rn=rn*10+n%10;
sd=sd+n%10;
nd=nd+1;
n=n/10;
}
printf("\n reverse number : %d", rn);
printf("\n sum of digits : %d", sd);
printf("\n number of digits : %d", nd);
getch();
}
OUTPUT:
enter n value=45678
reverse number : 87654
sum of digits : 30
number of digits : 4

Question #4: Write a C Program for fibnoacci series.


PROGRAM:
//Program for finonacci service
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,f;
clrscr();
printf("enter a value=");
scanf("%d",&n);
i=0;
j=1;
printf("%d\t%d",i,j);
f=i+j;
while(f<=n)
{
printf("\t %d",f);
i=j;
j=f;
f=i+j;
}
getch();
}
OUTPUT:
enter a value=125
0 1 1 2 3 5 8 13 21 34 55 89
3.2.2 How to do More Looping Using the do-while Statement?
If condition is true it execute statements which are present in side a block. If
condition is false it goes out of body. When we are working with do while loop
always post checking process will be occur. The do while loop will be repeats in
anti clock direction. In do while loop first execute the statement block then only
it check the condition In implementation when we need to execute statement
block at least once then go for do while loop.
Syntax:
do
{
statements 1;
Statement2:
.
.
increment/decrement;
}
while(condition);
Flow Chart of do while Loop:

Fig. 3.7: Flowchart for do while loop

Question: Write a Program to print one to given values.


PROGRAM:
//Program to print one to given values
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("enter n values=");
scanf("%d",&n);
i=1;
do
{
printf("\t%d",i);
i++;
}
while (i<=n);
getch();
}
OUTPUT:
enter b values= 6
123456
NOTE:
✓ Because the condition is placed at the end of the loop, do-while is also
called “exit-restricted loop”.
✓ In do-while loop, irrespective of the value of the condition, the statements
are executed for at least one time.
3.2.2 How to do Still More Looping Using the for Statement?
The execution process of the for loop will starts from initialization block
and the initialization block will be executed only once when we are entering into
the loop first time. After the execution of initialization block control will pass to
condition block. If the condition is evaluated as true then control will pass to
statement block. After executing of the statement block once again the control
will pass to condition block after execution of iteration block.
Syntax:
for (initialization; condition; iteration)
{
Statements;
}
FLOWCHART FOR FOR LOOP:

Fig. 3.8: Flowchart for for loop


Always the reputation will happen between conditional statement block and
iteration only. When we are working with for loop everything is optional in for
loop but it should be required two semicolons. Always the execution process is
faster in for loop. Because in for loop is no any bouncing process will be takes
place. When we are working with the for loop always pre checking process will
be occur and it repeats in anti-clock wise direction.

Question #1: Write a C program to print n number of values


PROGRAM:
//program on for loop to print n number of values
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
clrscr();
printf("enter n values=");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\t %d",i);
}
getch();
}
OUTPUT:
enter n values=10
1 2 3 4 5 6 7 8 9 10

Question#2: Write a program to find out factorial of a given number.


PROGRAM:
//Program to find out factorial of a given number
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact=1;
clrscr();
printf("enter the number=");
scanf("%d",&n);
for(i=n; i>0; i--)
{
fact=fact*i;
}
printf("factorial=%d",fact);
getch();
}
OUTPUT:
enter the number=5
factorial=120

Question #3: Write a C program to calculate average of n numbers.


PROGRAM:
//Program to calculate average of n numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n, no, sum=0;
float average;
clrscr();
printf("Enter total no.of number=");
scanf ("%d",&n);
for (i=1;i<=n;i++)
{
printf("Enter the number=");
scanf ("%d",&no);
sum=sum+no;
}
average=sum/n;
printf ("\n Average=%f", average);
getch();
}
OUTPUT:
Enter total no.of number=5
Enter the number=1
Enter the number=2
Enter the number=3
Enter the number=4
Enter the number=5
Average=3.000000

Question: Explain about nested for loops? Give one Example?


Answer:
A for loop can be executed with in another loop is called as nested for loop.
By using nested loops we can easily solve complex problems.

Question: Write a C program using a nested for loop to find the prime
numbers from 2 to 10.
PROGRAM:
//program uses a nested for loop to find the prime numbers from 2 to 10
#include <stdio.h>
#include<conio.h>
int main ()
{
int i, j;
clrscr();
for(i = 2; i<10; i++)
{
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j))
printf("%d is prime\n", i);
}
return 0;
}
3.3 What is break Statement?
The break statement in C programming has the following two usages −
1. When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
2. It can be used to terminate a case in the switch statement (covered
in the next chapter).

If you are using nested loops, the break statement will stop the execution of
the innermost loop and start executing the next line of code after the block.
Syntax:
break;
Flow Diagram for break statement:

Fig. 3.9: Flow chart for break statement

Question:Write a C program using break statement.


PROGRAM:
//Example program using break statement
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
if( a > 15) {
/* terminate the loop using break statement */
break;
}
}
return 0;
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
3.4 What is continue Statement?
The continue statement in C programming works somewhat like the break
statement. Instead of forcing termination, it forces the next iteration of the loop
to take place, skipping any code in between. For the for loop, continue statement
causes the conditional test and increment portions of the loop to execute. For the
while and do…while loops, continue statement causes the program control to
pass to the conditional tests.
Syntax:
continue;
Flow Diagram:
Fig. 3.10: Flow chart for continue statement

Question:Write a C program using continue statement.


PROGRAM:
//Example Program for continue statement
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++ ;
} while( a < 20 );
return 0;
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
3.5 What is goto Statement?
goto is a jumping statement in c language, which transfer the program’s
control from one statement to another statement (where label is defined).
Defining a label
Label is defined following by the given syntax
label_name:
label_name should be a valid identifier name.
: (colon) should be used after the label_name.
Transferring the control using ‘goto’
Program’s control can be transfer following by the given syntax
goto label_name;
Transferring the control from down to top
label-name :
statement1;
statement2;
..
if(any-test-condition)
goto label-name;

Question: Write a C program using goto statement.


PROGRAM:
//Program using goto statememt
void main()
{
int number;
number=1;
repeat:
printf("%d\n",number);
number++;
if(number<=10)
goto repeat;
}
OUTPUT:
1
2
3
4
5
6
7
8
9
10
4. What is an Array?
Question: What is the need of arrays?
Answer:
A variable having only one memory location so we can store only one value
at a time. But my requirement is I want to store multiple data values into one
variable at a time (the total data belonging to similar data only). In c language by
using arrays we can achieve this requirement (i.e. storing set of data values into
single variable). This is the need of arrays.

Question: What is array? Explain its properties?


Answer:
✓ An array is a collection of data storage locations, each having the same
data type and the same name.
✓ Each storage location in an array is called an array element or array index.
✓ Array is derived data type.
✓ Array is a composite data type.
Properties:
1. Array index values always start from zero(0).
2. The variable name of array contains the base address of the memory block.
3. The array variable is created at the time of compilation.
4. The size of the array can’t be alerted at run time.
5. The address held by the array variable is static.
6. The array size must be constant.

Question: What are the advantages and disadvantages of array?


Answer:
Advantages:

Array supporting grouping of similar data elements.


Referring more than one value with the same name which decreases
complexity in reading and writing values.

Disadvantages:
The disadvantage of array is wastage of memory because of its static behavior.
4.1 How to Declare an Array?
To declare an array,
Syntax:
data_type array_name[array_size];
For example,
float mark[6];
Here, we declared an array, mark, of floating-point type and size 6. Meaning, it
can hold 6 floating-point values.
4.2 How to Find Elements of Array?
Access of elements in an array is done by indices.
Suppose you declared an array mark as above. The first element is mark[0],
second element is mark[1] and etc.

Fig. 4.1: Internal memory representation for array mark


Note:
➢ Arrays have 0 as the first index not 1. In this example, mark[0]
➢ If the size of an array is n, to access the last element, (n-1) index is used. In
this example, mark[4]
➢ Suppose the starting address of mark[0] is 2120. Then, the next address,
a[1], will be 2124, address of a[2] will be 2128 and so on. It's because the
size of a float is 4 bytes.
4.3 How to Initialize an Array?
It's possible to initialize an array during declaration. For example,
int mark[5] = {11, 12, 13, 14, 15};
Another method to initialize array during declaration:
int mark[ ] = {11, 12, 13, 14, 15};

Fig. 4.2: Elements in memory for array mark


Here,
mark[0] is equal to 11
mark[1] is equal to 12
mark[2] is equal to 13
mark[3] is equal to 14
mark[4] is equal to 15
Question: Write a C Program to find the average of n numbers using
arrays.
PROGRAM:
// Program to find the average of n numbers using arrays
#include <stdio.h>
#include<conio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
clrscr();
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i )
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
OUTPUT:
Enter n: 3
Enter number 1:10
Enter number 2:15
Enter number 3:5
Average=10
4.4 What are the Different Types of Array?
Arrays are broadly classified in two types. They are
1) Single Dimensional arrays.
2) Multi Dimensional arrays.

Question: What is single dimensional array? Explain with examples?


Answer:

One dimensional array is a list of values of the same data type. A one
dimensional array contains only one subscripts
A subscript is a number inside a bracket that follows an array's name.
This number can identify the number of individual elements in the
array.
Array elements are stored in sequential memory locations

Syntax:
<data-type> <variable> [size] ;
Example:
int rno[100];
float sal[200];
chat name[50];

Before going to use any array we have to declare first.


The data-type can be int, float, char, double, long etc.
The size must be integer value only.
Size must be constant.
We can’t store different data type values into single array.

Initialization:
Syntax:
<Data-type> <arrayname> [size]={ele1,ele2,ele3,..,.,.,.,.,.elen};
Ex:
int eno[5] = { 26, 47, 55, 69, 45};
char ename[] = { ‘a’, ‘b’, ‘c’, ‘d’ } ;
float base[] = { 56.19, 900.25, 527 } ;
NOTE:
Remember that array elements start with 0 but not 1. Also remember that the last
element is one less than the number of elements in the array. For example, an
array with 10 elements contains elements 0 through 9.

Question: What is a Two dimensional array? Explain with examples?


Answer:
An array of arrays is known as 2D array. The two dimensional (2D) array
in C programming is also known as matrix. A matrix can be represented as a
table of rows and columns. Before we discuss more about two Dimensional
array lets have a look at the following C program.

Question: Write a C Program for implementing Simple Two dimensional


(2D) Array.
PROGRAM:
#include<stdio.h>
int main(){
int disp[2][3];
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
printf("2D array elements are:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("\t%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
OUTPUT:
Enter value for disp[0][0]:13
Enter value for disp[0][1]:21
Enter value for disp[0][2]:31
Enter value for disp[1][0]:41
Enter value for disp[1][1]:51
Enter value for disp[1][2]:9 8
2D array elements are:
13 21 31
41 51 98

Question: How to Initialize a Two Dimensional Array?


Answer:
There are two ways to initialize a two Dimensional arrays during
declaration.
int disp[2][4] = {
{19, 11, 12, 13},
{14, 15, 16, 17}
};
OR

int disp[2][4] = { 19, 11, 12, 13, 14, 15, 16, 17};

Some more examples are,


/* Valid declaration*/
int abc[2][2] = {5, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {5, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {5, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {5, 2, 3 ,4 }

Consider a C program as shown below.


#include<stdio.h>
int main() {
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++) {
for(j=0;j<4;j++) {
printf("Enter value for ab[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
return 0;
}
Fig. 4.3: Two Dimensional array conceptual memory representation

Question: How to Declare N-Dimensional Array?


Answer:
Syntax for declaring n-dimensional array is
data_type array_name[size1][size2]....[sizeN];
Here,
data_type: Type of data to be stored in the array .
Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions
Examples:
int two_d[10][20]; // Two dimensional array
int three_d[10][20][30]; // Three dimensional array
Note: Size of multidimensional arrays can be calculated by the total number of
elements that can be stored in a multidimensional array can be calculated by
multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

THREE DIMENTIONAL ARRAY:


Fig. 4.4: Three Dimensional internal array representation

Question: How to Initialize a Three Dimensional Array?


Answer:
Initialization in Three-Dimensional array is same as that of Two-
dimensional arrays. The difference is as the number of dimension increases so
the number of nested braces will also will increase.
Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23};
Method II:
int x[2][3][4] = {{{0,1,2,3},{4,5,6,7},{8,9,10,11}},{{12,13,14,15},
{16,17,18,19}, {20,21,22,23} }};
Here in both the methods, total elements required here are 2*3*4=24 elements
are considered.

Question: Write a C Program for Matrix Addition.


PROGRAM:
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++ )
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}
OUTPUT:
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
12
34
Enter the elements of second matrix
56
21
Sum of entered matrices:-
68
55

Question: Write a C Program for Matrix Multiplication.


PROGRAM:
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}
OUTPUT:
Enter number of rows and columns of first matrix
3
3
Enter the elements of first matrix
120
011
201
Enter the number of rows and columns of second matrix
3
3
Enter the elements of second matrix
112
211
121
Product of entered matrices:-
5 3 4
3 3 2
3 4 5

Question: Write a C Program to Check Matrix Symmetry.


Answer:
C program to check if a matrix is symmetric or not: we find transpose of
the matrix and then compare it with the original matrix. For a symmetric matrix
A T = A.
PROGRAM:
#include<stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &matrix[c][d]);
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
transpose[d][c] = matrix[c][d];
if (m == n) /* check if order is same */
{
for (c = 0; c < m; c++)
{
for (d = 0; d < m; d++)
{
if (matrix[c][d] != transpose[c][d])
break;
}
if (d != m)
break;
}
if (c == m)
printf("The matrix is symmetric.\n");
else
printf("The matrix isn't symmetric.\n");
}
else
printf("The matrix isn't symmetric.\n");
return 0;
}
4.5 What are the Application of Arrays?
In c programming language, arrays are used in wide range of applications.
Few of them are as follows.

1. Arrays Store List of values

In c programming language, single dimensional arrays are used to store list


of values of same data type. In other words, single dimensional arrays are used
to store a row of values.
In single dimensional array data is stored in linear form.

2. Arrays are used to Perform Matrix Operations

We use two dimensional arrays to create matrix. We can perform various


operations on matrices using two dimensional arrays
Examples are Matrix Addition, Matrix Multiplication, Transform of Matrix,
Subtraction of Matrices,

3. Arrays are used to implement Search Algorithms

We use single dimensional arrays to implement search algorithms.


Example: Linear Search, Binary Search
4. Arrays are used to implement Sorting Algorithms
We use single dimensional arrays to implement sorting algorithms.
Example: Insertion Sort, Bubble Sort, Selection Sort, Quick Sort, Merge
Sort.
5. Arrays are used to implement Data structures
We use single dimensional arrays to implement data structures.
Example: Stack Using Arrays, Queue Using Arrays
6. Arrays are also used to implement CPU Scheduling Algorithms
For the CPU scheduling the arrays are used in OS (Operating System).
5. What is a String?
A c-string is a variable length array of characters that is delimited by the
null character.
Storing strings:
In c, a string is stored in an array of characters. It is terminated by the null
character \0
H E L L O \0

Question: Why do we need a null character at the end of a string?


Answer:
A string is not a data type but a data structure. This means that its
implementation is logical, not physical.
Difference between the strings and character arrays are shown below.
H E L L O \0 H E L L O

Question: What is a String Literal?


Answer:
A string literal is a sequence of characters enclosed in double quotes.
Example:
“Have a nice day” “Hello”
“Hai”
“Prasad”
Strings:
Strings concepts :

Fig. 5.1: Types of String

Fixed length strings : When implementing a fixed length string format the first
decision is the size of the variable. If we make it too small, we can‟t store all
the data. If we make it too big, we waste memory.
Example :
1. char str[15]=”Have a nice day”;
2. char str[100]=”Hi”;

Variable length strings : In variable length strings the user can use the required
memory only. So reduce the memory wastage and data losses.
Example : char str[]=”Good day”;
1. Length controlled strings : Length controlled strings add a count that
specifies the number of characters in the string.
2. Delimited strings : Another techniques used to identify the end of the
string is the delimiter at the ends of delimited strings.
Strings and characters : Data can be stored in two ways.
1. Data as character literal.
2. Data as string literal.
Data stored as character literal, we can use single quote marks.
Example:
‘a’ - Here a is a character.
“a” - Here a is a string.
‘ ‘ - It is an empty character.
“ “ -It is an empty string..
5.1 How to Declare a String?
String declaration defines memory for a string when it is declared as an
array in local memory.
Syntax : 1. char str[9];
Syntax : 2. string pointer declaration.
char *pstr;
Initializing strings :
We can initialize a string the same way that we initialize any storage
structure by assigning a value to it when it is defined.
Example:

1. char str[9]=”good day”;


2. char name[9]=”Rashmi”

String initialized as a character pointer.


char *pstr=”good day”;
String initialized as an array of characters.
char str[9]={’g’,’o’,’o’,’d’,’ ‘,’d’,’a’,’y’};
Strings are ended with null character.
5.2 What are String Input and Output functions?
C provide two basic ways to read and write strings. First, we can
read and write strings with the formatted input/output functions.
They are,
scanf/fscanf and printf/fprintf
We can use a special set of strings only which are also functions. They are
shown below.

1. getstring → (gets/fgets)
2. putstring→ (puts/fputs)

Formatted string input :


scanf(): scanf is the general input statement. It is used to read character
data or numeric data from the keyboard.
Syntax :
scanf(“Format specifier”, variablename);
Example:
char str[9];
scanf(“%s”,str);
Formatted string output :
printf(): printf is the general output statement. It is used to write character
data or numeric data on the output units.
Syntax:
printf(“Format specifier”,variablename);
Example:
char str[9]=”Hello”;
printf(“%s”, str);

Question: Write a C program to print the entered string.


PROGRAM:
#include<string.h>
#include<conio.h>
voidmain()
{
char str[9]; clrscr();
printf(“Enter your string:”); scanf(“%s”,str);
printf(“Your string is %s”,str); getch();
}
OUTPUT:
Enter your string:Rashmi
Your string is Rashmi

String functions (input and output):


String input : gets()
The function gets accepts the name of string as a parameter, and fills the
string with characters that are input from the keyboard, till a newline character is
encountered, at the end, the function gets appends a null terminator as must be
done for any string and returns. The new line character is not added to the string.
Syntax:
gets(variable);
String output : puts()
This function is used to print the string message on to the output screen and
also display the stored string in variable.
Syntax:
puts(“string message”);
puts(variable);

Question: Write a C Program using gets() and puts().


PROGRAM:
#include<string.h>
#include<conio.h>
void main()
{
char str[10];
clrscr();
puts(“Enter your name”);
gets(str);
puts(“Entered name is “);
puts(str);
getch();
}
OUTPUT:
Enter your name Rashmi
Entered name is Rashmi

Question: What are Character Input Output Functions?


Answer:
Character input functions are

1. getchar()
2. getch()
3. getche()

Above three statements used for read a single character from keyboard at a
time.
1) getchar(): This function is used read a character from the keyboard and
assigned the character to variable, the variable stored the character.
Syntax :
variable=getchar();
PROGRAM :
#include<stdio.h>
void main()
{
char c;
printf(“Enter your character\n”);
c=getchar();
printf(“Entered character is \n”);
putchar(c);
getch();
}
OUTPUT:
Enter your character:A
Entered character is A
2) getch(): It is also read the characters from the keyboard and passes it
immediately to the program with echoing on the screen.
PROGRAM:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getch();
printf(“Entered character is %c”,ch);
getch();
}
OUTPUT:
Enter your character:A
Entered character is A
3) getche() : Accepts a character and passes it to the program and
echos(displays) the same character on the screen also.
PROGRAM:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter your character \n”); ch=getche();
printf(“Entered character is \n”); putchar(ch);
getch();
}
OUTPUT:
Enter your character:A
Entered character is A

Question: What is Character Output Function?


Answer:
putchar() :
putchar() is the character output function it is used to print the stored
character in the variabale on to the screen.
Syntax :
putchar(variable);
PROGRAM:
#include<stdio.h>
void main()
{
char ch;
clrscr();
printf(“Enter your character \n”);
ch=getchar();
printf(“Your character is \n”);
putchar(ch);
getch();
}
OUTPUT:
Enter your character:A
Entered character is A
5.3 What are C String Manipulation Operations?
The following are the different functions for string manipulations.
Function Description
S.
No.
1 strlen() Determines length of a string
2 strcpy() Copy the string from one to another
3 strncpy() Copies characters of a string to another string upto
specified length
4 strcmp() Compares two strings
5 stricmp() Compare two strings(function does not
discriminates between small and capital letter)
6 strlwr() Converts uppercase letters to lowercase letters
7 strupr() Converts lowercase letters to uppercase letters
8 strdup() Duplicate a string
9 strchr() First character of the given string
10 strrchr() Last character of the given string
11 strstr() Determines first occurrence of the given string in
another string
12 strcat() String concatenation, means second string appends
to the first string.
13 strncat() Appends source string to destination string up to
specified length.
14 strrev() String reverse, reverse the all character of a string
15 strset() Sets all characters of string with a given argument
or symbol
16 strnset() Sets specified numbers of characters of string with
a given number or Symbol
17 strspn() Finds up to what length two strings are identical
18 strpbrk() Searches the first occurrence of a character in a
given string and then it displays the string
starting from that character.

strlen(): This functions returns the number of character of a string data as an


nteger.
Syntax: strlen(variable);
PROGRAM:
#include< string.h>
#include<conio.h>
void main()
{
char
str[20]; int
i; clrscr();
puts(“Enter your string:”);
gets(str);
i=strlen(str);
printf(“Length of the given string is %d”,i);
getch();
}
OUTPUT:
Enter your string:Rashmi
Length of the given string is 6

strcpy(): This function is used to copy the data of one string to another string
variable.
Syntax:
strcpy(stringvariable,stringvariable1);
The string in the second position is the source string that contains the data to
be copied. The string in the first position is destination string that receives the
data.
PROGRAM:
#include< string.h>
#include<conio.h>
void main()
{
char str[20],str1[20];
clrscr();
puts(“Enter your string:”);
gets(str);
strcpy(str1,str);
puts(str1);
getch();
}
OUTPUT:
Enter your string:Hello
Hello

strcat(): This function is used concatenate two strings.


Syntax:
strcat(stringvariable,stringvariable1);
The string in the first position is called destination string and the string
in the second position is called source string the source is joined with the
destination and the combined string is stored the destination itself.
PROGRAM:
#include<string.h>
#include<conio.h>
void main()
{
char str1[20],str2[20];
clrscr();
puts(“Enter both string1 and string2:”);
gets(str1);
gets(str2);
Printf(“After strcat():”);
strcat(str1,str2);
puts(str1);
getch();
}
OUTPUT:
Enter both strings string1 and string2: Tom
Jerry
After strcat():TomJerry

strcmp(): This function is used to compare two strings.


Syntax:
strcmp(stringvariable1,stringvariable2);
The strcmp() functionreturn an integer value as the result.
1. result +ve : String variable1 is greater than string variable2.
2. result –ve : String1is lessthan string2.
3. result is zero : Both strings are equal.

PROGRAM:
#include< string.h>
#include<conio.h>
#include<stdio.h>
void main()
{
int i;
char str1[20],str2[20];
clrscr();
puts(“Enter both strings:”);
gets(str1);
gets(str2);
i=strcmp(str1,str2);
printf(“Difference is %d”,i);
getch();
}
OUTPUT:
Enter both strings:Rashmi
Rashmi
Difference is 0

strrev() : This function is used to get the reverse string of a given string.
Syntax:
strrev(string);
PROGRAM:
#include< string.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char str[20];
clrscr();
puts(“Enter a string:”);
gets(str);
strrev(str);
puts(“Reverse string of the given string is:”);
puts(str);
getch();
}
OUTPUT:
Enter a string:RASHMI
Reverse string of the given string is:IMHSAR

strlwr(): This function is used to convert the uppercase string to lower case
string.
Syntax:
strlwr(string);
PROGRAM:
#include< string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
puts(“Enter the string in uppercase:”);
gets(str);
strlwr(str);
printf(“Entered string in lowercase:”);
puts(str);
getch();
}
OUTPUT:
Enter the string in uppercase:YEAR
Entered string in lowercase:year

strupr(): This function is used to convert the lowercase string to uppercase


string.
Syntax:
strupr(string);
PROGRAM:
#include< string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
puts(“Enter the string in lowercase”);
gets(str);
printf(“Entered string in uppercase”);
strupr(str);
puts(str);
getch();
}
OUTPUT:
Enter string in lowercase:new
Entered string in uppercase:NEW

Question: Write a C program to check the given string is palindrome or not.


PROGRAM:
#include< string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20],str1[20];
clrscr();
puts(“Enter a string:”);
gets(str);
strcpy(str1,str);
strrev(str);
i=strcmp(str,str1);
if(i==0)
puts(“Given string is palindrome”);
else
puts(“Given string is not palindrome”);
getch();
}
OUTPUT:
Enter a string:MADAM
Given string is palindrome
6. What are Functions?
Question: What is modular programming?
Answer:
If a program is large, it is subdivided into a number of smaller programs that
are called modules or subprograms. If a complex problem is solved using more
modules, this approach are known as modular programming

Question What is a function?


Answer:
A function is a named, independent section of C code that performs a
specific task and optionally returns a value to the calling program.
Now let's look at the parts of this definition:

1. A function is named: Each function has a unique name. By using that


name in another part of the program, you can execute the statements
contained in the function. This is known as calling the function. A
function can be called from within another function.
2. A function is independent: A function can perform its task without
interference from or interfering with other parts of the program.
3. A function performs a specific task: This is the easy part of the
definition. A task is a discrete job that your program must perform as
part of its overall operation, such as sending a line of text to a printer,
sorting an array into numerical order, or calculating a cube root.
4. A function can return a value to the calling program. When your
program calls a function, the statements it contains are executed. If you
want them to, these statements can pass information back to the calling
program.

Question:What are the Advantages of Structured Programming?


Answer:
Why is structured programming so great? There are two important reasons:
1. It's easier to write a structured program, because complex programming
problems are broken into a number of smaller, simpler tasks. Each task is
performed by a function in which code and variables are isolated from the rest of
the program. You can progress more quickly by dealing with these relatively
simple tasks one at a time.
2. It's easier to debug a structured program. If your program has a bug
(something that causes it to work improperly), a structured design makes it easy
to isolate the problem to a specific section of code (a specific function).

Question: How to write a function? Give it’s description?


Answer:
Syntax:
return_type function_name (argument_list))
{
Local variable declarations,
Executable statement1;
Executable statement2’
...
return (expression);
}
❖ The first line of every function is the function header, which has three
components, each serving a specific function.
❖ The function return type specifies the data type that the function returns to
the calling program. The return type can be any of C's data types: char, int,
long, float, or double. You can also define a function that doesn't return a
value by using a return type of void .
❖ You can name a function anything you like, as long as you follow the rules
for C variable names.
❖ Many functions use arguments, which are values passed to the function
when it's called. A function needs to know what kinds of arguments to
expect i.e the data type of each argument.
❖ You can pass a function any of C's data types. Argument type information is
provided in the function header by the parameter list. For each argument that
is passed to the function, the parameter list must contain one entry. This
entry specifies the data type and the name of the parameter.
Function Body:
The function body is enclosed in braces, and it immediately follows the
function header. It's here that the real work is done. When a function is called,
execution begins at the start of the function body and terminates (returns to the
calling program) when a return statement is encountered or when execution
reaches the closing brace.
Function Statements:
There is essentially no limitation on the statements that can be included
within a function. The only thing you can't do inside a function is define another
function. You can, however, use all other C statements, including loops, if
statements, and assignment statements. You can call library functions and other
user-defined functions.
Returning a Value:
To return a value from a function, you use the return keyword, followed by a
C expression. When execution reaches a return statement, the expression is
evaluated, and execution passes the value back to the calling program.
EXAMPLE:
return 0;
return a;
Function Body:
The function body is enclosed in braces, and it immediately follows the
function header. It's here that the real work is done. When a function is called,
execution begins at the start of the function body and terminates (returns to the
calling program) when a return statement is encountered or when execution
reaches the closing brace.
Function Statements:
There is essentially no limitation on the statements that can be included
within a function. The only thing you can't do inside a function is define another
function. You can, however, use all other C statements, including loops, if
statements, and assignment statements. You can call library functions and other
user-defined functions.
Returning a Value:
To return a value from a function, you use the return keyword, followed by a
C expression. When execution reaches a return statement, the expression is
evaluated, and execution passes the value back to the calling program.
EXAMPLE:
return 0;
return a;

Question: What are the advantages of functions?


Answer:
The advantages of functions are
Reusability: write the code once and use many times which decreases the size
of the program.
Modularity: dividing problem into small parts (modules) in which each and
every module having separate operation. Due to this we can easily develop the
programs and we can easily debug the program.
Efficiency: Avoid redundant instructions which decreases size of the program
and increases efficiency.
Some more advantages:

1. Debugging is easier
2. It is easier to understand the logic involved in the program
3. Testing is easier
4. Recursive call is possible
5. Irrelevant details in the user point of view are hidden in functions
6. Functions are helpful in generalizing the program

Question: Explain types of functions?


Answer:
Basically we have two types of functions.

1. Pre defined
2. User defined.

1. PREDEFINED:
A function which has own definition and comes along with the software is
called as predefined functions. Or library functions are called as predefined.
Ex: printf, scanf, get char() , put char() etc.
✓ We can’t change the predefine function operation.
✓ We can’t modify predefined function.

2. USER DEFINED:
A function which is defined by user for a particular purpose is called as user
defined functions.
➢ User defined functions follow the c language functions pre- defined rules.
➢ Pre defined rules user can’t change.
➢ In user defined functions user can implement their own operation.
➢ User defined functions names and the operations can change when user
want.
Example:
void main()
int abc(int a, int b);
float addition(float a, float b);

Question: What is a function and built-in function?


Answer:
A large program is subdivided into a number of smaller programs or
subprograms. Each subprogram specifies one or more actions to be performed
for large program. Such subprograms are functions. The function supports only
static and extern storage classes. By default, function assumes extern storage
class. Functions have global scope. Only register or auto storage class is allowed
in the function parameters. Built-in functions that predefined and supplied along
with the compiler are known as built-in functions. They are also known as
library functions.

Question: What are the Parameters? Explain types of parameters?


Answer:
In c language parameters are classified into two types. They are Formal
parameter and Formal parameters.

1. Actual parameter:
The values which are send/pass from calling function to called function are
called actual parameters are actual arguments

2. Formal parameter:
Function parameters are called formal parameters. These are local variable
which receive values from calling function.

Question: Explain about Local Variables?


Answer:
You can declare variables within the body of a function. Variables declared
in a function are called local variables.
The term local means that the variables are private to that particular function
and are distinct from other variables of the same name declared elsewhere in the
program.
A local variable is declared like any other variable, using the same variable
types and rules f Local variables can also be initialized when they are declared.
Here is an example of four local variables being declared within a function:
int func1(int y)
{
int a, b = 11;
float rate;
double cost = 12.35;
/* function code goes here... */
}
The preceding declarations create the local variables a, b, rate, and
cost, which can be used by the code in the function. Note that the function
parameters are considered to be variable declarations, so the variables, if
any, in the function's parameter list also are available.
When you declare and use a variable in a function, it is totally separate and
distinct from any other variables that are declared elsewhere in the program.
This is true even if the variables have the same name.
Note: scope of the local variable is always with in block only.

Question: Explain about Global Variables?


Answer:
You can declare variables outside of the body of a function(main). Variables
declared outside of the function are called as global variables.
The term global means that the variables are public. For now, you should
learn how to declare global variables.
A global variable is declared like any other variable, using the same variable
types and rules of normal variables can also be initialized when they are
declared.
You can declare any of C's variable types in a function.
Note: sometimes global variables are called as extern variables.

Question: If global variables can be used anywhere in the program, why not
make all variables global?
Answer:
As your programs get bigger, you will begin to declare more and more
variables. There are limits on the amount of memory available. Variables
declared as global take up memory for the entire time the program is running;
however, local variables don't. For the most part, a local variable takes up
memory only while the function to which it is local is active. Additionally,
global variables are subject to unintentional alteration by other functions. If this
occurs, the variables might not contain the values you expect them to when
they're used in the functions for which they were created.

Question: How does the computer knows the difference between a global
variable and a local variable that have the same name?
Answer:
The important thing to know is that when a local variable is declared with
the same name as a global variable, the program temporarily ignores the global
variable. It continues to ignore the global variable until the local variable goes
out of scope.

Question: Can I declare a local variable and a global variable that have the
same name, as long as they have different variable types?
Answer:
Yes. When you declare a local variable with the same name as a global
variable, it is a completely different variable. This means that you can make it
whatever type you want. You should be careful, however, when declaring global
and local variables that have the same name
6.1 What are the Different Category of functions?
Functions are categories depending on whether arguments are present or not
and whether a value is returned or not. In C language functions May belong to
one of the following categories
1) Functions with no arguments and no return values.
2) Functions with arguments and no return values.
3) Functions with arguments and returns values.
1. Function With No Arguments And No Return Values:
` When a function has no arguments it does not receive, any data from the
calling function. Similarly, when it does not return a value the calling function
does not receive any data from the called function. It shows in the figure. The
dotted lines indicate that there is only a transfer of control but not data..

Fig. 6.1: Function with no arguments and no return values

Question: Write a C Program with no arguments and no return type using


functions.
PROGRAM:
/* no arguments and no return type*/
#include<stdio.h>
#include<conio.h>
void first (void);
void second (void);
void third (void)
{
printf("\n this is in third function");
}
void fourth (void)
{
printf("\n this is in fourth function");
}
void main()
{
clrscr();
printf("this is in main");
first();
second();
third();
fourth();
printf("\n this is in main again");
getch();
}
void first (void)
{
printf("\n this is in first function");
}
void second (void)
{
printf("\n this is in second function");
}
OUTPUT:
this is in main
this is in first function
this is in second function
this is in third function
this is in fourth function
this is in main again

2. Arguments But No Return Values:


When a function has arguments it receive data from the calling function.
Similarly when it does not return a value the calling function does not receive
any data from the called function.
The nature of data communication between the calling function and the
called function with arguments but no return values as shown below.

Fig. 6.2: Function with arguments and no return values

Question: Write a C program with arguments with no return value using


functions.
PROGRAM:
/*arguments with no return value functions*/
#include<stdio.h>
#include<conio.h>
void replicate (int n, int ch)
{
int k;
for (k=1; k<=n; k++)
printf("%c", ch);
}
void main()
{
clrscr();
replicate (9, 'x');
printf("\n hello \n");
replicate (6, '#');
printf("\n bhano daya \n");
replicate (10, '%');
printf("\n welcome \n");
replicate (4, '@');
getch();
}
OUTPUT:
xxxxxxxxx
hello
######
bhano daya
%%%%%%%%%%
welcome
@@@@

3. Arguments With Return Values:


When a function have arguments it receive data from the calling function
similarly when function having return a value the calling function receive data
from the called function. In effect the data transfer between the calling function
and called function happened.
Two -way data communication between the called function and
calling function as shown below.

Fig. 6.3: Function with arguments and return values

Question: Write a C program with arguments and with return value using
functions.
PROGRAM:
/*arguments with return value functions*/
#include<stdio.h>
#include<conio.h>
int add (int x, int y)
{
int z;
z=x+y;
return z;
}
int subtr(int p, int q)
{
return (p-q);
}
int mult (int, int);
int div (int, int);
int main()
{
int a,b,c;
clrscr();
printf("Enter any two numbers \n");
scanf("%d%d", &a, &b);
c=add(a, b);
printf("\n the addition is %d", c);
printf("\n the subtraction %d", subtr(a, b));
c=mult(a, b);
printf("\n the multiplication %d", mult(a,b));
printf("\n the division %d", div(a,b));
getch();
return(0);
}
int mult (int a, int b)
{
return a*b;
}
int div(int m, int n)
{
int p=m/n;
return p;
}
OUTPUT:
Enter any two numbers
10
3
the addition is 13
the subtraction 7
the multiplication 30
the division 3

Question: What is the difference between pass by reference and pass by


value?
Answer:
In call by value the actual argument will not be affected by the change of the
formal parameter. Where as in Call by reference the actual argument will be
affected by the formal parameters.
Parameter passing techniques:
In c language two types of techniques are available for passing parameters to
the functions. they are

1. Call by value
2. Call by reference

1. Call by value:

➢ In this technique the values of actual arguments in the calling function are
copied into the formal arguments in the called function.
➢ Here the data transfer done in only one direction i.e. from calling function
to called function, so any changes happen in formal arguments does not
effect on the actual arguments.
➢ But if any changes will happen in the actual arguments, formal arguments
automatically effected.

Question: Write a C program to pass a parameter using call by value.


PROGRAM:
//write a program to send value by call by value
#include<stdio.h>
#include<conio.h>
void change();
void main()
{
int x,y;
clrscr();
printf("\n enter values of x and y=");
scanf("%d%d",&x,&y);
change(x,y);
printf("\n in main () x=%d, y=%d",x,y);
getch();
}
void change(int a,int b)
{
int k;
k=a;
a=b;
b=k;
printf("\n in change() a=%d,b=%d",a,b);
}
OUTPUT:
enter values of xand y=40
20
in change() a=20,b=40
in main () x=40, y=20

2. Call by reference: (Passing address to a Function)

➢ In this technique the addresses of actual arguments in the calling function


are copied into the formal arguments in the called function.
➢ Any changes happen in formal arguments does effect on the actual
arguments.
➢ But if any changes will happen in the actual arguments, formal arguments
automatically effected.

Question: Write a C program to pass a parameter using call by reference.


PROGRAM:
/* write a program swaping of two numbers by using call by reference
technique*/
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
printf("\n enter value of x,y:");
scanf("%d%d",&x,&y);
change(&x,&y);
printf("\n in main() x=%d,y=%d",x,y);
getch();
}
change(int *a,int *b)
{
int *k;
*k=*a;
*a=*b;
*b=*k;
printf("\n in change() x=%d,y=%d",*a,*b);
}
OUTPUT:
enter value of x,y:40 20
in change() x=20,y=40
in main() x=20,y=40
6.2 What are the Variable Storage Classes?
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the
scope, visibility and lifetime of a variable.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register

1. Local Variable or automatic variables:

The variables declared inside the function are automatic or local


variables.
The local variables exist only inside the function in which it is declared.
When the function exits, the local variables are destroyed.
int main() {
int n; // n is a local variable to main() function
... .. ...
}
void func() {
int n1; // n1 is local to func() function
}
In the above code, n1 is destroyed when func() exits. Likewise, n gets
destroyed when main() exits.

Question: Write a C program to implement local variable storage


classes.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void fun1()
{
int a=10;
printf(“\na=%d”,a);
}
void fun2()
{
int a=20;
printf(“\na=%d”,a);
}
void main()
{
clrscr();
int a=30;
fun1();
fun2();
printf(“\na=%d”,a);
}
OUTPUT:
a=10
a=20
a=30

2. Global Variable or external variables:

Variables that are declared outside of all functions are known as


external or global variables. They are accessible from any function inside
the program.

Question: Write a C program to implement global variable storage


classes.
PROGRAM:
#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
++n; // variable n is not declared in the main() function
display();
return 0;
}
void display()
{
++n; // variable n is not declared in the display() functio n
printf("n = %d", n);
}
OUTPUT:
n=7
❖ Suppose, a global variable is declared in file1. If you try to use that
variable in a different file file2, the compiler will complain. To solve
this problem, keyword extern is used in file2 to indicate that the
external variable is declared in another file.

3. Static Variable

A static variable is declared by using keyword static. For example;


static int i;
The value of a static variable persists until the end of the program.

Question: Write a C program to implement static variable storage classes.


PROGRAM:
//Static Variable
#include <stdio.h>
void display();
int main()
{ display();
display();
}
void display()
{
static int c = 0;
printf("%d\t ",c);
c += 5;
}
OUTPUT:
0 5
● During the first function call, the value of c is equal to 0. Then, it's value is
increased by 5.
● During the second function call, variable c is not initialized to 0 again. It's
because c is a static variable. So, 5 is displayed on the screen.

4. Register Variable

➢ The register keyword is used to declare register variables. Register


variables were supposed to be faster than local variables.
➢ However, modern compilers are very good at code optimization and there
is a rare chance that using register variables will make your program faster.
➢ Unless you are working on embedded systems where you know how to
optimize code for the given application, there is no use of register variables.

Question: Write a C program to implement register variable storage classes.


PROGRAM:
#include<stdio.h>
int exp(int a, int b);
int main()
{
int a=3, b=5, res;
res=exp(a,b);
printf(“\n %d to the power of %d=%d”,a,b,res);
return 0;
}
int exp(int a, int b)
{
register int res=1;
int i;
for(i=1;i<=b;i++)
res=res*a;
return res;
}
OUTPUT:
3 to the power of 5=243
6.3 What is Recursion?
Definition:- “ The function which calls itself is called recursive function”.
➢ Recursive functions are classified into two types:

i. Direct recursive (function calls directly)


ii. In-direct recursive (function calls indirectly)

➢ The following are the conditions(criteria ) of recursive function:


a) Base criteria and
b) Recursive criteria.
➢ The recursive function which satisfies the above two criteria is called
well-defined recursive function.
Rules for recursive function:-

i. Function should be called itself otherwise recursion does not takes


place.
ii. Only user-defined functions are involved in the recursion but not
pre-defined.
iii. To stop the recursion, the function should met the base criteria.
iv. It needs the stack memory for implementing the recursion.

Advantages of recursion:-
In the recursive program, the solution to the base case is provided and the
solution of the bigger problem is expressed in terms of smaller problems.
i) It is very flexible in data structures like stacks, queues, linked lists
and trees.
ii) Using recursion, the length of the program is reduced.
Disadvantages of recursion:-
i) It requires extra storage space(memory).
ii) Whenever there is no exit condition then program will be executed
out of memory and takes into infinite calls.
iii) It takes more time and less speed for execution.
The following are the applications(example problems ) of recursion:

1. Towers of Hanoi and


2. Fibonacci sequence(Fibonacci series) .
Question: Write a C program to find the factorial of given number using
recursion.
PROGRAM:
//factorial of given number using recursion
#include<stdio.h>
#include<conio.h>
main( )
{
int m,n;
clrscr( );
printf(“enter the n value:”);
scanf(“%d”,&n);
m=fact(n);
printf(“factorial of n is %d”,m);
getch( );
}
fact(int x)
{
if(x==1)
return 1;
else
return (x*(fact(x-1));
}
OUTPUT:
enter the n value:4
factorial of n is 24

Question: Write a C program to implement fibnoacci sequence with


recursion.
PROGRAM:
//Recursion for fibnoacci sequence
#include<stdio.h>
#inclulde<conio.h>
int fib(int val);
main( )
{
int i,j;
clrscr( );
printf(“\n enter the number of terms”);
scanf(“%d”,&i);
printf(“Fibonacci sequence for %d terms is:”,i);
for(j=0;j<=i;j++)
printf(“%d\t”,fib[j]);
getch( );
}
int fib(int val)
{
if(val<=2)
return 1;
else
return(fib(val-1)+fib(val-2));
}
OUTPUT:
enter the number of terms 6
Fibonacci sequence for 6 terms is 0 1 1 2 3 5

Question: What is Towers of Hanoi? How does it implement


recursion?
Answer:
Tower of Hanoi is a mathematical puzzle where we have three rods and n
disks. The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Approach :
Take an example for 2 disks :
Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.

Step 1 : Shift first disk from 'A' to 'B'.


Step 2 : Shift second disk from 'A' to 'C'.
Step 3 : Shift first disk from 'B' to 'C'.

The pattern here is :


Shift 'n-1' disks from 'A' to 'B'.
Shift last disk from 'A' to 'C'.
Shift 'n-1' disks from 'B' to 'C'.

Image illustration for 3 disks :


Initially all the disks are as shown below.

Step 1:

Step 2:

Step 3:

Step 4:

Step 5:

Step 6:
Step 7:

PROGRAM:
#include <stdio.h>
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B');// A, B and C are names of rods in towers of hanoi
return 0;
}
// C recursive function to solve tower of hanoi puzzle
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
Here,
For n disks, total 2n – 1 moves are required.
Example: For 4 disks 24 – 1 = 15 moves are required.
For n disks, total 2n-1 function calls are made.
Example: For 4 disks 24-1 = 8 function calls are made.

Question: What are the differences between recursion and iteration?


Answer:
RECURSION ITERATION
1) Function calls itself is called as 1) A set of instructions repeatedly
Recursion. executed is called as Iteration.
2) Functions are the applications for 2) Loops are the application for
Recursion, Iteration.
3) Termination for recursion is 3) When the termination condition for
through base case, where there will the iterator ceases to be satisfied.
be no function call.
4) Used when code size needs to be 4) Used when time complexity needs
small, and time complexity is not an to be balanced against an expanded
issue. code size.
5) Recursion has smaller code size. 5) Iteration has larger code size.

6.4 What are the Standard Library Functions?


Question: What Is Header File In C Language?
Answer:
● Header file is a file that contains function declaration and macro definition
for C in-built library functions.
● All C standard library functions are declared in many header files which
are saved as file_name.h.
● We are including these header files in our C program using “#include
<file_name.h>” command to make use of the functions those are declared in
the header files.
● We can include header files in our C program using “#include
<filename.h>” command, all C code of the header files are included in C
program. Then, this C program is compiled by compiler and executed.
● A header file is a file with extension .h which contains C function
declarations and macro definitions to be shared between several source files.
There are two types of header files:

1. The files that the programmer writes


2. The files that comes with your compiler.

● You request to use a header file in your program by including it with the C
preprocessing directive #include , like you have seen inclusion of stdio.h
header file, which comes along with your compiler.
● Including a header file is equal to copying the content of the header file but
we do not do it because it will be error-prone and it is not a good idea to
copy the content of a header file in the source files, especially if we have
multiple source files in a program.
● Both the user and the system header files are included using the
preprocessing directive #include . It has the following two forms.
#include <file>
This form is used for system header files. It searches for a file named 'file' in a
standard list of system directories.
#include "file"
It searches for a file named 'file' in the directory containing the current file.
Writing Of Single And Multiple Uses Of Header Files:
In case, when a header file needs to be included twice within your program,
your compiler will be going to process the contents inside it - twice which will
eventually lead to an error in your program. So to eliminate this, you have to use
conditional preprocessor directives.
Syntax:
#ifndef HEADER_FILE_NAME
#define HEADER_FILE_NAME
the entire header file
#endif
Multiple conditional preprocessors can be used like this:
Syntax:
#if FIRST_SYSTEM
#include "sys.h"
#elif SEC_SYSTEM
#include "sys2.h"
#elif THRID_SYSTEM
....
#endif
For example, I am calling an external function named swap in my main.c file.
Example:
#include<stdio.h>
#include"swap.h"
void main()
{
int a=10;
int b=30;
swap (&a,&b);
printf ("a=%d\n", a);
printf ("b=%d\n",b);
}

Swap method is defined in swap.h file, which is used to swap two numbers by
using a temporary variable.
Example:
void swap (int* a, int* b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}

Question: Write a about C Preprocessor?


Answer:
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. All preprocessor commands begin with a hash symbol (#).
It must be the first non blank character, and for readability, a preprocessor
directive should begin in the first column. The following section lists down all
the important preprocessor directives:
Directive Description
S.
No

1 #define Substitutes a preprocessor macro.


2 #include Inserts a particular header from
another file.
3 #undef Undefines a preprocessor macro.
4 #ifdef Returns true if this macro is defined.
5 #ifndef Returns true if this macro is not
defined
6 #if Tests if a compile time condition is
true
7 #else Alternative for #if
8 #elif #else and #if in one statement
9 #endif Ends preprocessor conditional

Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 10
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH
with 10. Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add
the text to the current source file. The next line tells CPP to get myheader.h from
the local directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 32
It tells the CPP to undefine existing FILE_SIZE and define it as 32.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
EXAMPLE C PROGRAM:
#include<stdio.h>
#define PI 3.14
void main()
{
printf(“PI value is %f”,PI);
}

Question: Write a C program to Pass One Dimensional Array to Function?


PROGRAM:
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float age[]);
int main() {
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
// age array is passed to calculateSum()
result = calculateSum(age);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float age[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += age[i];
}
return sum;
}
OUTPUT:
Result = 162.50

Question: Write a C program to Pass Two Dimensional Array to Function ?


PROGRAM:
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);
/* passing multi-dimensional array to a function*/
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2])
{
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
Output
Enter 4 numbers:
2
3
4
6
Displaying:
2
3
4
6
7. What are Pointers?
Pointers store address of variables or a memory location.
Syntax:
datatype *var_name;
Example:
int *ptr;

Fig. 7.1: Pointers working in C


To use pointers in C, we must understand below two operators.
To access address of a variable to a pointer, we use the unary
operator & (ampersand) that returns the address of that variable. For example &x
gives us address of variable x.
PROGRAM:
#include <stdio.h>
int main()
{
int x;
// Prints address of x
printf("%p", &x);
return 0;
}
To access the value stored in the address we use the unary operator (*) that
returns the value of the variable located at the address specified by its operand.
PROGRAM:
#include <stdio.h>
int main()
{
int Var = 10;
int *ptr = &Var;
printf("Value of Var = %d\n", *ptr);
printf("Address of Var = %p\n", ptr);
*ptr = 20; // Value at address is now 20
printf("After doing *ptr = 20, *ptr is %d\n", *ptr);
return 0;
}
OUTPUT:
Value of Var = 10
Address of Var = 0x7fffa057dd4
After doing *ptr = 20, *ptr is 20

Below is pictorial representation of above program:

Fig. 7.2: Pointer variable and address


Pointer Expressions and Pointer Arithmetic
A limited set of arithmetic operations can be performed on pointers. A pointer
may be:
incremented ( ++ )
decremented ( — )
an integer may be added to a pointer ( + or += )
an integer may be subtracted from a pointer ( – or -= )
Pointer arithmetic is meaningless unless performed on an array.
PROGRAM:
#include <stdio.h>
int main()
{
int v[3] = {10, 100, 200};
int *ptr;
// Assign the address of v[0] to ptr
ptr = v;
for (int i = 0; i < 3; i++)
{
printf("Value of *ptr = %d\n", *ptr);
printf("Value of ptr = %p\n\n", ptr);
ptr++;
}
}
OUTPUT:
Output:Value of *ptr = 10
Value of ptr = 0x7ffcae30c710

Value of *ptr = 100


Value of ptr = 0x7ffcae30c714
Value of *ptr = 200
Value of ptr = 0x7ffcae30c718

Fig. 7.3: Pointer Arithmetic

7.1 What are the Pointers And Function Arguments?


C programming allows passing a pointer to a function. To do so, simply
declare the function parameter as a pointer type.
Question:Write a C program to implement Pointers and Function
Arguments?
PROGRAM:
#include <stdio.h>
double getAverage(int *arr, int size);
int main ()
{
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
avg = getAverage( balance, 5 ) ;
printf("Average value is: %f\n", avg );
return 0;
}
double getAverage(int *arr, int size)
{
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = (double)sum / size;
return avg;
}
OUTPUT:
Average value is: 214.400000
PASSING ARGUMENTS BY ADDRESS:
There is one more way to pass variables to functions, and that is by address.
Passing an argument by address involves passing the address of the argument
variable rather than the argument variable itself. Because the argument is an
address, the function parameter must be a pointer. The function can then
dereference the pointer to access or change the value being pointed to.
7.2 What is Dangling Memory?
Question: What is Dangling Pointer or Dangling Memory with Cause and
How to avoid it?
Answer:
Dangling pointers in computer programming are pointers that pointing to a
memory location that has been deleted (or freed).
Dangling pointers arise during object destruction, when an object that has an
incoming reference is deleted or deallocated, without modifying the value of the
pointer, so that the pointer still points to the memory location of the deallocated
memory. The system may reallocate the previously freed memory, unpredictable
behavior may result as the memory may now contain completely different data.
Fig. 7.4: Dangling Pointer (or) Dangling Memory

Question: What is the Cause of Dangling Pointers?


Answer:
1) Return Local Variable in Function Call
2) Variable goes out of scope
3) De-allocating or free variable memory

1. Return Local Variable in Function Call


PROGRAM:
#include<stdio.h>
#include<string.h>
char *getHello()
{
char str[10];
strcpy(str,"Hello!");
return(str);
}
int main()
{
/*str falls out of scope
function call char *getHello() is now a dangling pointer */
printf("%s", getHello());
}
Here we are returning an address which was a local variable (str), which
would have gone out of scope by the time control was returned to the calling
function.
Attempts to read from the pointer may still return the correct value (Hello!)
for a while after calling function getHello(), but any functions called thereafter
will overwrite the stack storage allocated for str with other values and the pointer
would no longer work correctly. If a pointer to str must be returned, str must
have scope beyond the function—it might be declared as static.

2. Variable goes out of scope


PROGRAM:
#include<stdio.h>
int main()
{
char **strPtr
{
char *str = "Hello!";
strPtr = &str;
}
/* str falls out of scope
strPtr is now a dangling pointer*/
printf("%s", *strPtr);
}
As str character pointer is non-visible in Outer Block , then character pointer
to pointer strPtr is still pointing to same invalid memory location in Outer block ,
then character pointer to pointer strPtr becomes "Dangling Pointer".
3. De-allocating or free variable memory
PROGRAM:
#include<stdio.h>
#include<<stdlib.h>
int main()
{
char **strPtr;
char *str = "Hello!";
strPtr = &str;
free(str);
/*strPtr now becomes a dangling pointer*/
printf("%s", *strPtr);
}
Here we have declared the character pointer *str and character pointer to
pointer strPtr. After assigning the address of str to strPtr we have de-allocated
memory using free function. As soon as memory is de-allocated for character
pointer str, character pointer to pointer strPtr becomes dangling pointer.

Question:How to Avoid Dangling Pointer Errors?


Answer:
We can avoid the dangling pointer errors by initialize pointer to NULL, after
de-allocating memory, so that pointer will be no longer dangling. Assigning
NULL value means pointer is not pointing to any memory location.
char **strPtr;
char *str = "Hello!";
strPtr = &str;
free (str); /* strPtr now becomes a dangling pointer */
ptr = NULL; /* strPtr is no more dangling pointer */
ADDRESS ARITHEMATIC
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, the following
arithmetic operation on the pointer can be performed.
ptr++
Incrementing a Pointer:
The following program increments the variable pointer to access each
succeeding element of the array −
PROGRAM:
#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
Decrementing a Pointer:
The same considerations apply to decrementing a pointer, which decreases
its value by the number of bytes of its data type as shown below −
PROGRAM:
#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[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\n", i-1, ptr );
printf("Value of var[%d] = %d\n", i-1, *ptr );
/* move to the previous location */
ptr--;
}
return 0;
}
OUTPUT:
Address of var[2] = bfedbcd8
Value of var[2] = 200
Address of var[1] = bfedbcd4
Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10
7.3 What are Pointers And Function Arguments?
Consider the following example:
char array[] = "Hello World"; // array version
char ptr* = "Hello World"; // pointer version
Here are the differences:
arr is an array of 12 characters. When compiler sees the statement:
char array[] = "Hello World";
It allocates 12 consecutive bytes of memory and associates the address of
the first allocated byte with array

Fig. 7.5: Character Array Representation in Memory

On the other hand when the compiler sees the statement.


char ptr* = "Hello World";
It allocates 12 consecutive bytes for string literal "Hello World" and 4 extra
bytes for pointer variable ptr. And assigns the address of the string literal to ptr.
So, in this case, a total of 16 bytes are allocated.
Fig. 7.6: Internal Memory Representation for Pointer of an Array
If arr points to the address 2000, until the program ends it will always point to
the address 2000, we can’t change its address. This means string assignment is
not valid for strings defined as arrays.
arr = "Yellow World"; // Wrong
On the contrary, ptr is a pointer variable of type char, so it can take any other
address. As a result string, assignments are valid for pointers.
ptr = "Yellow World"; // ok
After the above assignment, ptr points to the address of "Yellow World" which is
stored somewhere in the memory.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, i;
char *ptr;
printf("Enter number of characters to store: ");
scanf("%d", &n);
ptr = (char*)malloc(n*sizeof(char));
for(i=0; i < n; i++)
{
printf("Enter ptr[%d]: ", i);
scanf(" %c", ptr+i);
}
printf("\nPrinting elements of 1-D array: \n");
for(i = 0; i < n; i++)
{
printf("%c ", ptr[i]);
}
return 0;
}
OUTPUT:
Enter number of characters to store: 6
Enter ptr[0]: a
Enter ptr[1]: b
Enter ptr[2]: c
Enter ptr[3]: d
Enter ptr[4]: e
Enter ptr[5]: f
Printing elements of 1-D array:
abcdef

How to pass a pointer to a function


The great advantage of passing a pointer to a function is that the information
that’s modified need not be returned. That’s because the function references a
memory address, not a value directly. By using that address, information can be
manipulated without being returned.
PROGRAM:
#include <stdio.h>
void discount(float *a);
int main()
{
float price = 42.99;
printf("The item costs $%.2fn",price);
discount(&price);
printf("With the discount, that's $%.2fn",price);
return(0);
}
void discount(float *a)
{
*a = *a * 0.90;
}
7.4 What is Pointer to Pointer?
A pointer to a pointer is a form of multiple indirection, or a chain of
pointers. Normally, a pointer contains the address of a variable. When we define
a pointer to a pointer, the first pointer contains the address of the second pointer,
which points to the location that contains the actual value as shown below.

Fig. 7.7: Pointer to Pointer in Memory


A variable that is a pointer to a pointer must be declared as such. This is
done by placing an additional asterisk in front of its name.
For example, the following declaration declares a pointer to a pointer of
type int.
int **var;
When a target value is indirectly pointed to by a pointer to a pointer,
accessing that value requires that the asterisk operator be applied twice, as is
shown below in the example.
PROGRAM:
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 1000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
OUTPUT:
Value of var = 1000
Value available at *ptr = 1000
Value available at **pptr = 3000
7.5 What is Pointers And Multidimensional Arrays?
Consider pointer notation for the two-dimensional numeric arrays. consider the
following declaration
int nums[2][3] = { {16, 18, 20}, {25, 26, 27} };
Creating a two dimensional array
To keep things simple we will create a two dimensional integer array num
having 3 rows and 4 columns.
int num[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

Fig. 7.8: Two dimensional array having 3 rows and 4 columns.

The compiler will allocate the memory for the above two dimensional
array row-wise meaning the first element of the second row will be placed after
the last element of the first row.
Fig. 7.9: Row Wise Memory Allocation for One Dimensional Array

Assume that the first element of the array is at address 1000 and the size of
type int is 2 bytes then the elements of the array will get the following allocated
memory locations.

Fig. 7.10: Value and Address Representation for One Dimensional Array
Create pointer for the two dimensional array.
The two dimensional integer array num so, our pointer will also be of type
int.
We will assign the address of the first element of the array num to the
pointer ptr using the address of & operator.
int *ptr = &num[0][0];
Accessing the elements of the two dimensional array via pointer
The two dimensional array num will be saved as a continuous block in the
memory. So, if we increment the value of ptr by 1 we will move to the next
block in the allocated memory.
In the following code we are printing the content of the num array using for
loop and by incrementing the value of ptr.
PROGRAM:
#include <stdio.h>
int main(void) {
// 2d array
int num[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// the pointer ptr pointing at array num
int *ptr = &num[0][0];
// the other variables
int ROWS = 3, COLS = 4, TOTAL_CELLS = ROWS * COLS, i;
/* printing the elements of the array num via pointer ptr*/
for (i = 0; i < TOTAL_CELLS; i++) {
printf("%d ", *(ptr + i)) ;
}
return 0;
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12
7.6 What is Dynamic Memory Management Functions?
❖ An array is a collection of a fixed number of values. Once the size of an
array is declared, you cannot change it.
❖ Sometimes the size of the array you declared may be insufficient. To solve
this issue, you can allocate memory manually during run-time. This is
known as dynamic memory allocation in C programming.
❖ To allocate memory dynamically, library functions are malloc(), calloc(),
realloc() and free() are used. These functions are defined in the <stdlib.h>
header file.
C malloc():
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number
of bytes. And, it returns a pointer of void which can be casted into pointers of
any form.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example:
ptr = (int*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of
float is 4 bytes. And, the pointer ptr holds the address of the first byte in the
allocated memory. The expression results in a NULL pointer if the memory
cannot be allocated.
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory
uninitialized. Whereas, the calloc() function allocates memory and initializes all
bits to zero.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of
type float.
C free()
Dynamically allocated memory created with either calloc() or malloc()
doesn't get freed on their own. You must explicitly use free() to release the
space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
PROGRAM: Using malloc() and free()
// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
Here, we have dynamically allocated the memory for n number of int.
PROGRAM: Using calloc() and free()
// Program to calculate the sum of n numbers entered by the user
#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));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
C realloc()
If the dynamically allocated memory is insufficient or more than required,
you can change the size of previously allocated memory using the realloc()
function.
Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.
PROGRAM: Using realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory: ");
for(i = 0; i < n2; ++i)
printf("%u\n", ptr + i);
free(ptr);
return 0;
}
OUTPUT:
Enter size: 2
Addresses of previously allocated memory: 26855472
26855476
Enter the new size: 4
Addresses of newly allocated memory: 26855472
26855476
26855480
26855484

COMMAND LINE ARGUMENTS:


➢ It is possible to pass some values from the command line to your C
programs when they are executed. These values are called command line
arguments and many times they are important for your program especially
when you want to control your program from outside instead of hard coding
those values inside the code.
➢ The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer
array which points to each argument passed to the program.
➢ Following is a simple example which checks if there is any argument
supplied from the command line and take action.
PROGRAM:
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Grater than two arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it
produces the following result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it
produces the following result.
$./a.out testing1 testing2
Grater than two arguments supplied.
When the above code is compiled and executed without passing any
argument, it produces the following result.
$./a.out
One argument expected.
❖ It should be noted that argv[0] holds the name of the program itself and
argv[1] is a pointer to the first command line argument supplied, and
*argv[n] is the last argument. If no arguments are supplied, argc will be one,
and if you pass one argument then argc is set at 2.
❖ All the command line arguments should be separated by a space, but if
argument itself has a space then you can pass such arguments by putting
them inside double quotes "" or single quotes ''.
PROGRAM:
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("Program name %s\n", argv[0]);
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Grater than two arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument
separated by space but inside double quotes, it produces the following result.
$./a.out "testing1 testing2"
Progranm name ./a.out
The argument supplied is testing1 testing2
8. What is an Enumerated Datatype?
Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and
maintain.

Fig. 8.1: enum in C language


EXAMPLES:
enum State {Working = 1, Failed = 0};
enum flag{constant1, constant2, constant3, ....... };
Variables of type enum can also be defined. They can be defined in two ways:
// In both of the below cases, "day" is defined as the variable of type week.
enum week{Mon, Tue, Wed};
enum week day;
// Or
enum week{Mon, Tue, Wed}day;
PROGRAM:
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Thur;
printf("%d",day);
return 0;
}
OUTPUT:
3
In the above example, we declared “day” as the variable and the value of
“Wed” is allocated to day, which is 2. So as a result, 2 is printed.
PROGRAM:
#include<stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
OUTPUT:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the value of
i is Jan which is 0 and the value of Dec is 11.
Facts about initialization of enum.
1) Two enum names can have same value. For example, in the following C
program both ‘Failed’ and ‘Freezed’ have same value 0.
PROGRAM:
#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
int main()
{
printf("Working %d, Failed %d, Freezed %d", Working, Failed, Freezed);
return 0;
}
OUTPUT:
Working 1, Failed 0, Freezed 0
2) If we do not explicitly assign values to enum names, the compiler by default
assigns values starting from 0. For example, in the following C program,
sunday gets value 0, monday gets 1, and so on.
PROGRAM:
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
OUTPUT:
The day number stored in d is 4
3) We can assign values to some name in any order. All unassigned names get
value as value of previous name plus one.
PROGRAM:
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 6, wednesday, thursday = 10, friday,
saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday,
thursday, friday, saturday);
return 0;
}
OUTPUT:
1 2 6 7 10 11 12
4) The value assigned to enum names must be some integeral constant, i.e., the
value must be in range from minimum possible integer value to maximum
possible integer value.
5) All enum constants must be unique in their scope. For example, the
following program fails in compilation.
PROGRAM:
enum state {work, failed};
enum result {failed, pass};
int main()
{
return 0;
}
OUTPUT:
Compile Error: 'failed' has a previous declaration as 'state failed'
9. What is a Structure?
Question: What are Derived Types in C Programming Language?
Answer:
There are five derived types in C:
1) Function types
2) Pointer types
3) Array types
4) Structure types
5) Union types
A derived type is formed by using one or more basic types in combination.
Using derived types, an infinite variety of new types can be formed. The array
and structure types are collectively called the aggregate types. Note that the
aggregate types do not include union types, but a union may contain an
aggregate member.
Question:What is a structure?
Answer:
A structure is a user defined data type in C/C++. A structure creates a data
type that can be used to group items of possibly different types into a single type.

Fig. 9.1: Structure definition


Arrays allow to define type of variables that can hold several data items of
the same kind. Similarly structure is another user defined data type available in
C that allows to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of
your books in a library. You might want to track the following attributes about
each book −
1) Title
2) Author
3) Subject
4) Book ID
Defining a Structure:
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member. The format of the struct
statement is as follows.
SYNTAX:
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal
variable definition, such as int i; or float f; or any other valid variable definition.
At the end of the structure's definition, before the final semicolon, you can
specify one or more structure variables but it is optional. Here is the way you
would declare the Book structure.
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
9.1 How to Initialize a Structure?
Let us discuss very familiar example of structure student , we can initialize
structure variable in different ways. They are:
Way 1 : Declare and Initialize
struct student
{
char name[20];
int roll ;
float marks;
}std1 = { "Pritesh",67,78.3 };

In the above code snippet, we have seen that structure is declared and as
soon as after declaration we have initialized the structure variable.

std1 = { "Pritesh",67,78.3 }
This is the code for initializing structure variable in C programming

Way 2 : Declaring and Initializing Multiple Variables


struct student
{
char name[20];
int roll;
float marks;
}

std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};

In this example, we have declared two structure variables in above code.


After declaration of variable we have initialized two variable.

std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};

Way 3 : Initializing Single member


struct student
{
int mark1;
int mark2;
int mark3;
} sub1={67};
Though there are three members of structure,only one is initialized , Then
remaining two members are initialized with Zero. If there are variables of other
data type then their initial values will be
Datatype Default value if not initialized
integer 0
float 0.00
char NULL
Way 4 : Initializing inside main
struct student
{
int mark1;
int mark2;
int mark3;
};
void main()
{
struct student s1 = {89,54,65};
-----
-----
};
When we declare a structure then memory won’t be allocated for the structure.
i.e only writing below declaration statement will never allocate memory
struct student
{
int mark1;
int mark2;
int mark3;
};
We need to initialize structure variable to allocate some memory to the structure.
struct student s1 = {89,54,65};
9.2 How to Access Structure Members?
To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name
and the structure member that we wish to access. You would use the keyword
struct to define variables of structure type. The following example shows how to
use a structure in a program.
PROGRAM:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Rashmi");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 649547;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Shanthi");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495709;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}
OUTPUT:
Book 1 title : C Programming
Book 1 author : Rashmi
Book 1 subject : C Programming Tutorial
Book 1 book_id : 649547
Book 2 title : Telecom Billing
Book 2 author : Shanthi
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495709
9.3 What is a Nested Structure?
Structure written inside another structure is called as nesting of two
structures. Nested Structures are allowed in C Programming Language.
We can write one Structure inside another structure as member of another
structure.
Way 1 : Declare two separate structures
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;
Accessing Nested Elements :
❖ Structure members are accessed using dot operator.
❖ ‘date‘ structure is nested within Employee Structure.
❖ Members of the ‘date‘ can be accessed using ’employee’ emp1 & doj are
two structure names (Variables)
Explanation Of Nested Structure:
Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year
Way 2 : Declare Embedded structures
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;
Accessing Nested Members:
Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year
PROGRAM:
#include <stdio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Leela",1001,1000.60,{22,6,1992}};
int main(int argc, char *argv[])
{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d",
emp.doj.date,emp.doj.month,emp.doj.year);
return 0;
}
OUTPUT:
Employee Name : Leela
Employee SSN : 1001
Employee Salary : 1000.600000
Employee DOJ : 22/6/1992
9.4 What is Arrays of Structures?
Structure is used to store the information of One particular object but if we
need to store such 1000 objects then Array of Structure is used.
Example:
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}Book[1000];
Explanation:
Here Book structure is used to Store the information of one Book.
In case if we need to store the Information of 1000 books then Array of Structure
is used.
b1[0] stores the Information of 1st Book , b1[1] stores the information of 2nd
Book and So on We can store the information of 1000 books.
Example:
We can represent the std array variable as following.
// student structure
struct student {
char id[15];
char firstname[64];
char lastname[64];
float points;
};
// student structure variable
struct student std[3];

Fig. 9.2: Internal Memory Representation for Structure student

PROGRAM:
#include <stdio.h>
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}book[3];
int main(int argc, char *argv[])
{
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Book : ");
gets(book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",book[i].price);
}
printf("\nBook Details");
for(i=0;i<3;i++)
{
printf("\nName of Book : %s",book[i].bname);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f",book[i].price);
}
return 0;
}
OUTPUT:
Enter the Name of Book :C
Enter the Number of Pages : 100
Enter the Price of Book : 200
Enter the Name of Book : CPP
Enter the Number of Pages : 200
Enter the Price of Book : 300
Enter the Name of Book : Java
Enter the Number of Pages : 300
Enter the Price of Book : 500
Book Details
Name of Book :C
Number of Pages : 100
Price of Book : 200
Name of Book : CPP
Number of Pages : 200
Price of Book : 300
Name of Book : Java
Number of Pages : 300
Price of Book : 500
9.5 How to use Structure as Function Arguments?
A structure as a function argument can be passed in the same way as you
pass any other variable or pointer.
PROGRAM:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Rashmi");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495403;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Sharmila");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495788;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
}
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
OUTPUT:
Book title : C Programming
Book author : Rashmi
Book subject : C Programming Tutorial
Book book_id : 6495403
Book title : Telecom Billing
Book author : Sharmila
Book subject : Telecom Billing Tutorial
Book book_id : 6495788
9.6 How to Use Pointers to Structures?
Defining pointers to structures in the same way as you define pointer to any
other variable.
struct Books *struct_pointer;
To find the address of a structure variable, place the '&'; operator before the
structure's name as follows:
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you
must use the → operator as follows:
struct_pointer->title;
PROGRAM:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Rashmi");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6995407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Sharma");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6995700;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
OUTPUT:
Book title : C Programming
Book author : Rashmi
Book subject : C Programming Tutorial
Book book_id : 6995407
Book title : Telecom Billing
Book author : Sharma
Book subject : Telecom Billing Tutorial
Book book_id : 6995700
9.7 What are Self Referential Structures?
Self Referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member.

Fig. 9.3: Self Referential Structures


Structures pointing to the same type of structures are self-referential in nature.
Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence,
the structure ‘node’ is a self-referential structure with ‘link’ as the referencing
pointer.
● An important point to consider is that the pointer should be initialized
properly before accessing, as by default it contains garbage value.
Types of Self Referential Structures
1) Self Referential Structure with Single Link
2) Self Referential Structure with Multiple Links
1) Self Referential Structure with Single Link
These structures can have only one self-pointer as their member. The
following example will show us how to connect the objects of a self-referential
structure with the single link and access the corresponding data members. The
connection formed is shown in the following figure.

Fig. 9.4: Self Referential Structure with Single Link


PROGRAM:
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Intialization
ob1.link = NULL;
ob1.data1 = 11;
ob1.data2 = 21;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 31;
ob2.data2 = 41;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}
OUTPUT:
31
41
2) Self Referential Structure with Multiple Links:
Self referential structures with multiple links can have more than one self-
pointers. Many complicated data structures can be easily constructed using these
structures. Such structures can easily connect to more than one nodes at a time.
The following example shows one such structure with more than one links.
The connections made in the above example can be understood using the
following figure.

Fig. 9.5: Self Referential Structure with Single Link


PROGRAM:
#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
{
struct node ob1; // Node1
// Intialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10 ;
struct node ob2; // Node2
// Intialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;
struct node ob3; // Node3
// Intialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;
// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;
// Accessing data of ob1, ob2 and ob3 by ob1
printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob2
printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data) ;
// Accessing data of ob1, ob2 and ob3 by ob3
printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
}
OUTPUT:
10 20 30
10 20 30
10 20 30
In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three
objects of the self referential structure ‘node’. And they are connected using
their links in such a way that any of them can easily access each other’s data.
This is the beauty of the self referential structures. The connections can be
manipulated according to the requirements of the programmer.
Applications of self referential structures:
Self referential structures are very useful in creation of other complex data
structures like:

1. Linked Lists
2. Stacks
3. Queues
4. Trees
5. Graphs
10. What is Union?
A union is a special data type available in C that allows to store different
data types in the same memory location. You can define a union with many
members, but only one member can contain a value at any given time. Unions
provide an efficient way of using the same memory location for multiple-
purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type with
more than one member for your program. The format of the union statement is
as follows −
Syntax:
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the
end of the union's definition, before the final semicolon, you can specify one or
more union variables but it is optional. Here is the way you would define a union
type named Data having three members i, f, and str.
Example:
union Data {
int i ;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number,
or a string of characters. It means a single variable, i.e., same memory location,
can be used to store multiple types of data. You can use any built-in or user
defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest
member of the union. For example, in the above example, Data type will occupy
20 bytes of memory space because this is the maximum space which can be
occupied by a character string. The following example program displays the total
memory size occupied by the above union.
PROGRAM:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[10];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
OUTPUT:
Memory size occupied by data : 10

Question: How to Access Union Members?


Answer:
To access any member of a union, we use the member access operator (.).
The member access operator is coded as a period between the union variable
name and the union member that we wish to access. You would use the keyword
union to define variables of union type. The following example shows how to
use unions in a program.
PROGRAM:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 221.5 ;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
OUTPUT:
data.i : 10
data.f : 221.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is
being used at a time.
PROGRAM:
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( )
{
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 649540;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
return 0;
}
OUTPUT:
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 649540
typedef and #define
#define is a C-directive which is also used to define the aliases for various
data types similar to typedef but with the following differences:
➢ typedef is limited to giving symbolic names to types only where as #define
can be used to define alias for values as well, q., you can define 1 as ONE
etc.
➢ typedef interpretation is performed by the compiler whereas #define
statements are processed by the pre-processor.

Question: Explain about bitfields.


Answer:
Suppose a C program contains a number of TRUE/FALSE variables in a
structure as follows:
struct abc
{
unsigned int a;
unsigned int b;
};
This structure requires 8 bytes of memory space but in actual we are going
to store either 0 or 1 in each of the variables. If we use such variables inside a
structure then we can define the width of a variable which specifies that we are
going to use only those number of bytes. For example, above structure can be
modified as follows:
struct abc
{
unsigned int a : 1;
unsigned int b : 1;
};
Now, the above structure will require 4 bytes of memory space for status
variable but only 2 bits will be used to store the values. If you will use up to 32
variables each one with a width of 1 bit , then also status structure will use 4
bytes, but as soon as you will have 33 variables, then it will allocate next slot of
the memory and it will start using 8 bytes.
For example:
struct abc
{
unsigned int a : 1;
unsigned int b : 1;
};
Now, the above structure will require 4 bytes of memory space for status
variable but only 2 bits will be used to store the values. If you will use up to 32
variables each one with a width of 1 bit , then also status structure will use 4
bytes, but as soon as you will have 33 variables, then it will allocate next slot of
the memory and it will start using 8 bytes.
PROGRAM:
struct abcd1
{
int a;
int b;
};
struct abcd2
{
int a : 1;
int b : 1;
};
int main( )
{
printf( "Memory size occupied by abcd1 : %zu\n", sizeof(struct abcd1));
printf( "Memory size occupied by abcd2 : %zu\n", sizeof(struct abcd2));
return 0;
}
OUTPUT:
Memory size occupied by abcd1 : 8
Memory size occupied by abcd2 : 4
11. What are File Operations?
FILE HANDLING IN C: file I/O operations:
File handling in C enables us to create, update, read, and delete the files
stored on the local file system through our C program. The following operations
can be performed on a file.
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 fgetc)
4) Writing to a file (fprintf or fputs)
5) Moving to a specific location in a file (fseek, rewind)
6) Closing a file (fclose)
The text in the brackets denotes the functions used for performing those
operations.
No. Function Description
1 fopen() Opens new or existing file
2 fprintf() Write data into file
3 fscanf() Reads data from file
4 fputc() Writes character into file
5 fgetc() Reads character from file
6 fclose() Closes the file
7 fseek() Sets the file pointer to given position
8 fputw() Writes an integer to file
9 fgetw() Reads an integer from file
10 ftell() Returns current position
11 rewind() Sets the file pointer to the beginning of file

11.1 How to Create a File?


The fopen() function is used to create a new file or to open an existing file.
Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to
the opened(or created) file. The filename is the name of the file to be opened and
mode specifies the purpose of opening the file. Mode can be of following types,
No. Mode Description
1 r Opens a text file In Reading Mode
2 w Opens or Creates a text file in Writing Mode
3 a Opens a text file in Append Mode
4 r+ Opens a text file in both Reading and Writing Mode
5 w+ Opens a text file in both Reading and Writing Mode
6 a+ Opens a text file in both Reading and Writing Mode
7 rb Opens binary file in Reading Mode
8 wb Opens or Create a binary file in Writing Mode
9 ab Opens a binary file in Append Mode
10 rb+ Opens a binary file in both Reading and Writing Mode
11 wb+ Opens a binary file in both Reading and Writing Mode
12 ab+ Opens a binary file in both Reading and Writing Mode

11.2 How to do Input/Output Operations in a File?


In the above table we have discussed about various file I/O functions to
perform reading and writing on file. getc() and putc() are the simplest functions
which can be used to read and write individual characters to a file.
C fputc() and fgetc():
Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a
character to a stream.
Syntax:
int fputc(int c, FILE *stream)
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character
from the stream. It returns EOF at the end of file.
Syntax:
int fgetc(FILE *stream)
PROGRAM:
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF)
{
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
// closing the file pointer
fclose(fp);
}
The above program prints the contents entered in file one.txt.
Closing File: fclose()
The fclose() function is used to close a file. The file must be closed after
performing all the operations on it.
The syntax of fclose() function is given below:
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if
there is an error in closing the file. This EOF is a constant defined in the header
file stdio.h.
C fputs() and fgets()
The fputs() and fgets() in C programming are used to write and read string from
stream. Let's see examples of writing and reading file using fgets() and fgets()
functions.
Writing File : fputs() function
The fputs() function writes a line of characters into file. It outputs string to a
stream.
Syntax:
int fputs(const char *s, FILE *stream)
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
clrscr();
fp=fopen("myfile2.txt","w");
fputs("hello c programming language",fp);
fclose(fp);
getch();
}
OUTPUT:
hello c programming language
Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string from a
stream.
Syntax:
char* fgets(char *s, int n, FILE *stream)
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char text[300];
clrscr();
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
getch();
}
OUTPUT:
hello c programming
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is
used to write data into file at desired location.
Syntax:
int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence:
a) SEEK_SET
b) SEEK_CUR
c) SEEK_END.
PROGRAM:
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is C program", fp);
fseek( fp, 7, SEEK_SET );
fputs("my programming language", fp);
fclose(fp);
}
OUTPUT:
This is my programming language

Question: What are the difference between Text File and Binary File
Answer:
Text File Binary File
1) Bits represent character.. 1) Bits represent a custom data.
2) Less prone to get corrupt as 2) Can easily get corrupted, even a
changes reflect as soon as the file is single bit change may corrupt the file.
opened and can easily be undone.
3) Can store only plain text in a file.
3) Can store different types of data
(image, audio, text) in a single file.
4) Widely used file format and can 4) Developed especially for an
be opened using any simple text application and may not be understood
editor. by other applications.
5) Mostly .rtf and .txt are used as 5) Can have any application defined
extension as text files. extension.

Question: What are Formatted Input/Output Operations?


Answer:
Input means to provide the program with some data to be used in the
program and Output means to display data on screen or write the data to a printer
or a file.
C programming language provides many built-in functions to read any
given input and to display data on screen when there is a need to output the
result.
scanf() and printf() functions:
The standard input-output header file, named stdio.h contains the definition
of the functions printf() and scanf(), which are used to display output on screen
and to take input from user respectively.
PROGRAM:
#include<stdio.h>
void main()
{
int i;
printf("Please enter a value...");
scanf("%d", &i);
printf( "\nYou entered: %d", i);
}
OUTPUT:
Please enter a value…
5
You entered:5
When you will compile the above code, it will ask you to enter a value.
When you will enter the value, it will display the value you have entered on
screen.
You must be wondering what is the purpose of %d inside the scanf() or
printf() functions. It is known as format string and this informs the scanf()
function, what type of input to expect and in printf() it is used to give a heads up
to the compiler, what type of output to expect.
Format String Meaning
%d Scan or Print an integer as a single decimal number
%f Scan or Print a floating point number
%c To scan or print a Character
%s To scan or print a character string. The scanning ending at
white space.

We can also limit the number of digits or characters that can be input or
output, by adding a number with the format string specifier, like "%1d" or
"%3s", the first one means a single numeric digit and the second one means 3
characters, hence if you try to input 42, while scanf() has "%1d", it will take only
4 as input. Same is the case for output.
getchar() & putchar() functions:
❖ The getchar() function reads a character from the terminal and returns it as
an integer. This function reads only single character at a time. You can use
this method in a loop in case you want to read more than one character.
❖ The putchar() function displays the character passed to it on the screen and
returns the same character. This function too displays only a single character
at a time. In case you want to display more than one characters, use
putchar() method in a loop.
PROGRAM:
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character:");
c = getchar();
printf(“Entered character:”);
putchar(c);
}
OUTPUT:
Enter a character:k
Entered character:k
gets() & puts() functions:
❖ The gets() function reads a line from stdin(standard input) into the buffer
pointed to by str pointer, until either a terminating newline or EOF (end of
file) occurs.
❖ The puts() function writes the string str and a trailing newline to stdout.
PROGRAM:
#include<stdio.h>
void main()
{
char str[100];
printf("Enter a string:");
gets( str );
printf(“Entered string:”);
puts( str );
getch();
}
OUTPUT:
Enter a string:rashmi
Entered string:rashmi
When you will compile the above code, it will ask you to enter a string.
When you will enter the string, it will display the value you have entered.
Difference between scanf() and gets():
➢ The main difference between these two functions is that scanf() stops
reading characters when it encounters a space, but gets() reads space as
character too.
➢ If you enter name as Rashmi Devi using scanf() it will only read and store
Rashmi and will leave the part after space. But gets() function will read it
completely.
OTHER BOOKS BY AUTHOR:

You might also like