Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
54 views

C Notes Final

The document describes the steps in the programming process: 1. Program definition and analysis involves defining the problem, inputs, outputs, and processing steps. 2. Program design develops the logic to solve the problem using techniques like algorithms or flowcharts. 3. Coding converts the program design into a language like C. 4. Compilation generates machine-readable code from the source code. Debugging and testing identifies and fixes any errors or bugs in the program. Documentation explains the program's logic and purpose. Implementation deploys the working program and maintenance addresses any subsequent issues.

Uploaded by

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

C Notes Final

The document describes the steps in the programming process: 1. Program definition and analysis involves defining the problem, inputs, outputs, and processing steps. 2. Program design develops the logic to solve the problem using techniques like algorithms or flowcharts. 3. Coding converts the program design into a language like C. 4. Compilation generates machine-readable code from the source code. Debugging and testing identifies and fixes any errors or bugs in the program. Documentation explains the program's logic and purpose. Implementation deploys the working program and maintenance addresses any subsequent issues.

Uploaded by

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

1.

Programming Process
Q: Explain the steps in solving a problem on the computers.(April 2009 , 2010, 2011,
2013)
or
Q: Write Steps in developing of a program.
Ans: In order to develop a program, whether it is small or complex a special procedure to be
followed which is called as program development life cycle. It is the systematic way to
developing any quality software. A computer program is a set of instructions which a
computer can use to solve a program. Program must be written in a precise way because
computer follows only instructions given to it. To solve a program efficiently, the
programmer follows the following steps referred to as the programming process.

Program definition and analysis

Program design

Coding

Compilation

Debugging and testing

Documentation

Implementation and Maintenance

Program definition and analysis


The first phase in developing program for a particular program is to identify and define the
problem by studying it thoroughly. For this programmer analyze it by using the basic steps
i.e. input, processing and output. Input is the data to solve the problem, processing is the steps
to convert input to output are the results obtained after solving problem. Firstly the problem
to be solved is exactly defined by identifying it in the beginning and agreement between the
user and the programmer at the end. Before tackling the problem logically, the nature of the
problem must be fully understood by the programmer.

Program design
The second phase of programming process is program design. In this phase, the programmer
must have a proper understanding of the behaviour of the problem to be solved. This
behaviour can be described in terms of the necessary inputs and required outputs. After this
programmer designs a process through different techniques like algorithm or flowchart or
pseudo code which will give the required outputs from the given inputs. Based on the
specification produced by the user, the best programmer designs a program which meets the
best requirements of the user.

Coding
After the successful completion of second phase i.e. selection of algorithm or flowchart, it
must be converted into a form that can be used by computer. So in third phase, the
programmer translates the steps of algorithm or flowchart in a computer program using a
language such as „C‟ and is called coding. Once a program is written in „C‟ i.e. source code is
ready to enter it into computer and store it in a disk file with extension (.C).

Compilation
Compilation is a process of generating machine code from source code. This can be done
using a compiler. The „C‟ compiler takes and process program that can be a complete
program or just a function. „C‟ compiler has in-built pre-processor which is used to process
the source code before being passed to compiler for compilation. Pre-processor directives are
used to tell the pre-processor how to process the source code. It processes the source code
and gives as a result the expanded version of source code. „C‟ compiler takes this expanded
version of source code of the same name and (.obj) extension. The process of translating the
source code into object code may generate some type of errors which are as follow.

 Compilation time errors


Compilation time errors abort the compilation process either immediately or following
the compilation phase in which they occur. These errors results from syntax errors in the
source code e.g. missing statement delimiters etc.
 Run time errors
Run time errors may be caused due to number factors like incorrect input, data type
mismatch, incorrect control flow etc. Normally rum time errors associated with coding
inadequacies.
 Logical errors
Logical errors are errors which are caused due to wrong program design and cannot be
detected by compiler. They can be detected by watching the printed output i.e.
programmer is not getting the desired result
 Syntax errors
Syntax error occurs when a program violates the rules of the grammar and expression of a
computer language. Syntax errors are usually detected by system software e.g. compilers
and it will give the output as diagnostic error messages. These errors are common but can
be found out easily. Syntax errors prevent the execution of the program from even
starting.

Debugging and testing


A bug is an error in a computer program. The process of eliminating the errors in the program
is called “Debugging”. There are various categories of errors in a program. These errors are
detected by testing a program with the data that will yield a known answer. If correct answers
are not obtained, the program contains errors and if it contains errors, it needs debugging
technique. Different errors can be eliminated by using various methods. Normally hit and
trial method is used to eliminate errors. Program is executed with all possible values for
which results are already known. If program gives the same output as required, it is declared
correct otherwise it is scanned to find out the errors.
Documentation
Documentation phase is used to enable every user to be connected with the program to
understand the logic and the purpose of the program. In this phase each instruction of the
program and its purpose is written in easily understandable form so that a lay man can also
understand the purpose of the program‟s instructions. Documentation is also used to upgrade
the program in future.

Implementation and Maintenance


In this phase of program development program which is altogether ready, is installed at the
site of the user. The user may have some errors and the programmer has to maintain all these
errors and do all necessary changes till the user gives green signal to programmer. Even after
compilation, maintenance of the program at regular interval is compulsory so that there must
not be any problem on the output of the program and it is best utilized and is fulfilling all its
objectives.

Que: what is data flow diagram? What are the advantages and disadvantages of data
flow diagram?
Ans: Data flow diagrams (DFDs) reveal relationships among and between the various
components in a program or system. DFDs are an important technique for modelling a
system‟s high-level detail by showing how input data is transformed to output results through
a sequence of functional transformations. DFDs consist of four major components: entities,
processes, data stores, and data flows. The symbols used to depict how these components
Interact in a system are simple and easy to understand; however, there are several DFD
models to work from, each having its own zymology. DFD syntax does remain constant by
using simple verb and noun constructs. Such a syntactical relationship of DFDs makes them
ideal for object-oriented analysis and parsing functional specifications into precise DFDs for
the systems analyst.
When it comes to conveying how information data flows through systems (and how
that data is transformed in the process), data flow diagrams (DFDs) are the method of choice
over technical descriptions for three principal reasons.
1. DFDs are easier to understand by technical and nontechnical audiences.
2. DFDs can provide a high level system overview, complete with boundaries and
connections to other systems.
3. DFDs can provide a detailed representation of system components.

DFDs help system designers and others during initial analysis stages visualize a current
system or one that may be necessary to meet new requirements. Systems analysts prefer
working with DFDs, particularly when they require a clear understanding of the boundary
between existing systems and postulated systems. DFDs represent the following:
1. External devices sending and receiving data.
2. Processes that change that data.
3. Data flows themselves.
4. Data storage locations.

Defining DFD Components


DFDs consist of four basic components that illustrate how data flows in a system: entity,
process, data store, and data flow.

Process Process Entity


Entity
Data flow

Data store

 Entity
An entity is the source or destination of data. The source in a DFD represents these
entities that are outside the context of the system. Entities either provide data to the
system (referred to as a source) or receive data from it (referred to as a sink). Entities are
often represented as rectangles (a diagonal line across the right-hand corner means that
this entity is represented somewhere else in the DFD). Entities are also referred to as
agents, terminators, or source/sink.

 Process
The process is the manipulation or work that transforms data, performing
computations, making decisions (logic flow), or directing data flows based on business
rules. In other words, a process receives input and generates some output. Process names
(simple verbs and dataflow names, such as “Submit Payment” or “Get Invoice”) usually
describe the transformation, which can be performed by people or machines. Processes
can be drawn as circles or a segmented rectangle on a DFD, and include a process name
and process number.

 Data Store
A data store is where a process stores data between processes for later retrieval by that
same process or another one. Files and tables are considered data stores. Data store names
(plural) are simple but meaningful, such as “customers,” “orders,” and “products.” Data
stores are usually drawn as a rectangle with the right- hand side missing and labelled by
the name of the data storage area it represents, though different notations do exist.

 Data Flow
Data flow is the movement of data between the entity, the process, and the data store.
Data flow portrays the interface between the components of the DFD. The flow of data in
a DFD is named to reflect the nature of the data used (these names should also be unique
within a specific DFD). Data flow is represented by an arrow, where the arrow is
annotated with the data name.

Example
In this example Student and Faculty are the source and destination of information (the
entities), respectively. Register 1, Exam 2, and Graduate 3 are the processes in the program.
Student Record is the data store. Register 1 performs some task on Registration Form from
Student, and the Subject Registered moves to the data store. The Class Rolls information
flows on to Faculty. Graduate 3 obtains Academic Record information from Student Record,
and Degree/Transcript information is moved to Student. Exam2 obtains exam/paper
information from Faculty, and moves the Grades to the Student Record for storage.

Here are a few other guidelines on developing DFDs:


 Data that travel together should be in the same data flow.
 Data should be sent only to the processes that need the data.
 A data store within a DFD usually needs to have an input data flow.
 Watch for Black Holes: a process with only input data flows.
 Watch for Miracles: a process with only output flows.
 Watch for Gray Holes: insufficient inputs to produce the needed output.
 A process with a single input or output may or may not be partitioned enough.
 Never label a process with an IF-THEN statement.
 Never show time dependency directly on a DFD (a process begins to perform tasks as
soon as it receives the necessary input data flows).

Advantage of DFD
As we have seen, the DFD method is an element of object- oriented analysis and is widely
used. Use of DFDs promotes quick and relatively easy project code development. DFDs are
easy to learn with their few-and- simple-to-understand symbols (once you decide on a
particular DFD model). The syntax used for designing DFDs is simple, employing English
nouns or noun- adjective-verb constructs.

Disadvantage of DFD
DFDs for large systems can become cumbersome, difficult to translate and read, and be time
consuming in their construction. Data flow can become confusing to programmers.

Que: Write a short note on decision table.


Ans: A decision table is simply a table showing the various actions to be taken for different
combinations of conditions. It is a logical procedure by means of set of conditions and related
actions. It specifies the logical rules and has nothing to say about the procedures. A decision
table is more problem oriented than a flowchart. The decision table are more useful than
flowcharts as an aid to program design.

Elements of decision table


 Condition stub.
 Condition entry.
 Action stub.
 Action entry.

Example
A bank uses the following rules to classify the new accounts. Id a depositor‟s age is 21 or
above and if deposit Rs. 100 or more classify the account type as A. If the depositor is under
21 and deposit Rs. 100 or more classify as account B. If the depositor is 21 or over but
deposit below Rs. 100 classify it as Account C. If the depositor is under 21 and deposit is
below Rs. 100 do not open account.
From the above we come to this conclusion which is as the following rules.
 Rule 1 If depositor`s age is 21 or above(condition 1)
And If deposit is Rs. 100 or more(condition 2)
Then classify in account as type A(Action 1)
 Rule 2 If depositor`s age is under 21(condition 3)
And If deposit is Rs. 100 or more(condition 2 )
Then classify in account as type B(Action 2)
 Rule 3 If depositor`s age is 21 or above(condition 1)
And If deposit is below Rs. 100(condition 4)
Then classify in account as type C(Action 3)
 Rule 1 If depositor`s age is under 21(condition 3)
And If deposit is below Rs. 100(condition 4)
Then do not open account(Action 4)
These conditions can be written as:
Condition 1 Depositor‟s age ≥ 21
Condition 2 Deposit ≥ Rs 100
Condition 3 Depositor‟s age <21
Condition 4 Deposit < Rs 100

Decision Table for this problem.


Rule1 Rule2 Rule3 Rule4
Condition C1 Depositor‟s age ≥ 21 Yes No Yes No
Condition C1 Deposit ≥ Rs 100 Yes Yes No No
Action 1 Classify as Account A × -- -- --
Action 2 Classify as Account B -- × -- --
Action 3 Classify as Account C -- -- × --
Action 4 Do not open Account -- -- -- ×
Q. What is an algorithm? In what way algorithms contribute in problem solving?
Explain with an example. (Sept. 2007)
Or
Q. Discuss advantages and disadvantages of Algorithms in detail.
Algorithm can be defined as: “A sequence of activities to be processed for getting desired
output from a given input and a formula or set of steps for solving a particular problem. To be
an algorithm, a set of rules must be unambiguous and have a clear stopping point”. There
may be more than one way to solve a problem, so there may be more than one algorithm for a
problem.
Now, if we take definition of algorithm as: “A sequence of activities to be processed for
getting desired output from a given input.” Then we can say that:

1. Getting specified output is essential after algorithm is executed.


2. One will get output only if algorithm stops after finite time.
3. Activities in an algorithm to be clearly defined in other words for it to be
unambiguous.

Before writing an algorithm for a problem, one should find out what is/are the inputs to the
algorithm and what is/are expected output after running the algorithm. Now let us take some
exercises to develop an algorithm for some simple problems: While writing algorithms we
will use following symbol for different operations:

‘+’ for Addition


‘-’ for Subtraction
‘*’ for Multiplication
‘/’ for Division and
„ ‟ for assignment. For example A X*3 means A will have a value of X*3.

Characteristics of an algorithm

 Input: There are zero or more values which are externally supplied as input.
 Output: At least one value is produced as an input
 Definiteness: Each step must be clear and unambiguous. Unambiguous means that
the same step must not be repeated again and again unnecessarily.
 Finiteness: If we trace the steps of an algorithm, then for all cases, the algorithm must
terminate after a finite number of steps
 Effectiveness: each step must be sufficiently basic that it can in principle be carried
out by a person using only paper and pencil. Each step must be not only definite but
also feasible.

Example 1: Write an algorithm to read two numbers and find their sum.

Step1: Start
Step2: Read\input the first num1.
Step3: Read\input the second num2.
Step4: Sum num1+num2 // calculation of sum
Step5: Print Sum
Step6: End

Example 2: Write an algorithm to find area of a circle.

Step1: Start
Step2: Read radius of a circle.
Step3: area 3.14*radius*radius.
Step4: Print area
Step5: End

Example 3: Write an algorithm to convert temperature Fahrenheit to Celsius.

Step1: Start
Step2: Read Fahrenheit in f.
Step3: Celsius 5/9*(f-32)
Step4: Print Celsius
Step5: End

Example 3: Write an algorithm to find greatest among two numbers.

Step1: Start
Step2: Read a and b.
Step3: If a>b
Print “a is greater”.
Else
Print “b is greater”.
Step4: End

Example 3: Write an algorithm to find greatest among three numbers.

Step 1: Start
Step 2: Read variables a, b and c.
Step 3: If a>b
If a>c
Print “a is greatest.
Else
Print “c is greatest.
Else
If b>c
Print “b is greatest.
Else
Print “c is greatest.
Step 5: Stop

Advantages of algorithm
1. It is a step-wise representation of a solution to a given problem, which makes it
easy to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps hence,
it is easier for programmer to convert it into an actual program
Disadvantages of algorithm.
1. Writing algorithm takes a long time.
2. An Algorithm is not a computer program, it is rather a concept of how a program
should be.

Q: What is Flowchart? Discuss Symbols used in flowcharts in detail. Support your


answer with suitable example. (Sept. 2007)
Or
Q. Discuss Advantages and Disadvantages in detail.
Ans: Flow Chart :- The flowchart is a diagram which visually presents the flow of data
through processing systems. This means by seeing a flow chart one can know the operations
performed and the sequence of these operations in a system. Algorithms are nothing but
sequence of steps for solving problems. So a flow chart can be used for representing an
algorithm. A flowchart, will describe the operations (and in what sequence) are required to
solve a given problem. You can see a flow chart as a blueprint of a design you h ave made for
solving a problem. For example suppose you are going for a picnic with your friends then you
plan for the activities you will do there. If you have a plan of activities then you know clearly
when you will do what activity. Similarly when you have a problem to solve using computer
or in other word you need to write a computer program for a problem then it will be good to
draw a flowchart prior to writing a computer program. Flowchart is drawn according to
defined rules.
Flowchart Symbols

There are 6 basic symbols commonly used in flowcharting of assembly language Programs:
Terminal, Process, input/output, Decision, Connector and Predefined Process. This is not a
complete list of all the possible flowcharting symbols, it is the ones used most often in the
structure of Assembly language programming

Symbol Name Function


Indicates any type of internal
Process operation inside the
Processor or Memory
Used for any Input / Output
Input / Output (I/O) operation. Indicates that
the computer is to obtain data
or output results

Used to ask a question that


Decision can be answered in a binary
format (Yes/No, True/False)

Allows the flowchart to be


Connector drawn without intersecting
lines or without a reverse
flow.

Indicates the starting or


Terminal ending of the program,
process, or interrupt program

Shows direction of flow.


Flow lines

General Rules for flowcharting


1. All boxes of the flowchart are connected with Arrows. (Not lines)

2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.

3. The Decision symbol has two exit points; these can be on the sides or the bottom and one
side.

4. Generally a flowchart will flow from top to bottom. However, an upward flow can be
shown as long as it does not exceed 3 symbols.

5. Connectors are used to connect breaks in the flowchart. Examples are:


 From one page to another page.
 From the bottom of the page to the top of the same page.
 An upward flow of more than 3 symbols

6. Subroutines and Interrupt programs have their own and independent flowcharts.

7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.

Example 1: Flow chart to find the sum of two numbers.


Example 2: Flow chart to find the area of a circle.

Example 3: Flow chart to convert temperature Fahrenheit to Celsius.


Example 4: Flow chart to find greatest among two numbers.

Example 5: Flow chart to find greatest among three numbers.


Advantages Of Using FLOWCHARTS:

1. Communication: - Flowcharts are better way of communicating the logic of a


system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analysed in more
effective way.
3. Proper documentation: - Program flowcharts serve as a good program
documentation, which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the systems
analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put efforts more
efficiently on that part

Disadvantages Of Using FLOWCHARTS: -

1. Complex logic: - Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may
require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is
done.

Q. Differentiate between Flowchart and Algorithm.

Difference Flow Chart Algorithm


Basic Form Step by Step formation Box by box formation
Usage Mostly run to complete or Can be used in general terms
manage a program to solve any problem related
implementation. to an individual or a group.
Apprehension More detailed but difficult to Less detailed but easy to
understand by a layman. understand by everyone.
Terms Specific programming Use of logics and signs is the
language used. main tool.
Connection Initiated with the help of a Based on general thoughts
flow chart and first planning ideas.

Q: Define Pseudo code.


Ans: Pseudocode is an artificial and informal language that helps programmers develop
algorithms. Pseudocode is a "text-based" detail (algorithmic) design tool.

The rules of Pseudocode are reasonably straightforward. All statements showing


"dependency" are to be indented. These include while, do, for, if, switch. Examples
below will illustrate this notion.

Examples:

1.. If student's grade is greater than or equal to 60

Print "passed"
else
Print "failed"
2. Fundamentals of C language
Q: Write a short note on history and features of ‘C’ language.
Or
Q: Discuss History of C.
or
Q: Write features of C language in detail.
Ans. C is a general-purpose, high-level language that was originally developed by Dennis M.
Ritchie to develop the UNIX operating system at Bell Labs. C was originally first
implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis
Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application
programs have been written in C. C has now become a widely used professional language for
various reasons:
 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms

Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around the early 1970s.
 The language was formalized in 1988 by the American National Standard Institute
(ANSI).
 Most of the state-of-the-art software have been implemented using C.
 Today's most popular Linux OS and RDBMS MySQL have been written in C.
 Today C is the most widely used and popular System Programming Language.

C was initially used for system development work, particularly the programs that make-up
the operating system. C was adopted as a system development language because it produces
code that runs nearly as fast as the code written in assembly language. Some examples of the
use of C might be:
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities
Features of ‘C’
C language is general purpose and high level programming language. The most important
features of „C‟ language are following.

 Modularity: modularity is one of the important characteristics of C. we can split the C


program into no. of modules instead of repeating the same logic statements (sequentially). It
allows reusability of modules.

 Middle level language: as a middle level language C combines both the advantages of low
level and high level languages. (arrays,pointers etc).

 General purpose programming language: C can be used to implement any kind of


applications such as math‟s oriented, graphics, business oriented applications.

 Portability: we can compile or execute C program in any operating system


(unix,dos,windows).

 Powerful programming language: C is very efficient and powerful programming language;


it is best used for data structures and designing system software. C is case sensitive language.

 Flexible: „C‟ can be used for a wide variety of application ranging from embedded systems
to commercial data processing techniques.

 Clarity: The keyword and library functions available in „C‟ resembles common English
words thus it helps to improve the clarity of the program.

 Versatile: „C‟ is very versatile language as it can solve problems in almost every application
area.

 Memory management: The various memory management functions available in „C‟ which
helps to save the memory and thus improve the efficiency.

 Compact code: Use of operators like ++, --, +=, ==, /=, *= in „C‟ helps to make compact
code. These features were not available in languages like COBOL and BASIC.

 Documentation: ‘C’ language allows user to add comments in the program. These
comments improve the readability of a program. Comments are written in general English
and are written using // and /*.

Que: Discuss the following.


1. ‘C’ Character Set.
2. Identifiers.
3. Keywords.
Ans:
 ‘C’ Character set
A character set defines valid character that can be used in a source program or
interpreted when program is running. A character set may include any alphabet, digit or
special symbol used to represent information. A set of character that can used to write a
source program is called source character set. The set of characters available when program is
being executed is called an execution character set. It may be possible that these two
character sets are different but most of the time these two character sets are identical.
The characters in C are grouped into the following two categories:

1.) Source character set


a. Alphabets.
b. Digits.
c. Special Characters.
d. White Spaces.

2.) Execution character set


a. Escape Sequence

Source character set

Alphabets
Uppercase letters A-Z
Lowercase letters a-z

Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Characters
~`!#@%&*()_-+=|\{}[]:;“„<>?./

Execution Character Set

Certain ASCII characters are unprintable, which means they are not displayed on the screen
or printer. Those characters perform other functions aside from displaying text. Examples are
backspacing, moving to a newline, or ringing a bell. They are used in output statements.
Escape sequence usually consists of a backslash and a letter or a combination of digits. An
escape sequence is considered as a single character but a valid character constant. These are
employed at the time of execution of the program. Execution characters set are always
represented by a backslash (\) followed by a character. Note that each one of character
constants represents one character, although they consist of two characters. These characters
combinations are called as escape sequence.

 Identifiers
A „C‟ identifier is a name used to identify a variable, function, or any other user defined
item. An identifier starts with a letter A to Z, a to z, or an underscore „_‟ followed by zero or
more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as
@, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower
and manpower are two different identifiers in C. Here are some examples of acceptable
identifiers:
For Example: student-name,
phone_no,
address
Rules for identifiers
 Identifier name can include letters, digit and underscore ( _ ) in „C‟.
 Identifier name must start with letters only.
 Keyword cannot be used as identifiers.
 The maximum number of character allowed in an identifier name is compiler
dependent, but the limit imposed by all the compilers provides enough
flexibility to create meaningful identifier name.

 Keywords
Keywords are reserved words that have a particular meaning already defined with
compiler. The keyword cannot be used as an identifier. There are 32 keywords reserved by
„C‟ programming language.
Auto double int struct
Break else long switch
Case enum register typedef
Char extern return union
Const float short unsigned
continue for signed void
Default goto sizeof volatile
Do if static while

Que: What is constant? Explain its types.


Ans: Constants refers to the fixed values that do not change during the execution of a
program. A "constant" is a number, character, or character string that can be used as a value
in a program. Use constants to represent floating-point, integer, enumeration, or character
values that cannot be modified. C supports several types of constants. There may be a
situation in programming that the value of certain variables to remain constant during
execution of a program. In doing so we can use a qualifier const at the time of initialization.
For example:
1. const float pie =3.147;
2. const int radius =4;
3. 3. const char c = 'A';
4. const char name[] = "Munish Kumar";

In C constant can also be used using pre-processor directive


For example: #define PI 3.147
Types of constant in C Language

 Integer Constant
An integer constant is an integer values number. It consists of a sequence of digits. An
integer constant can consist of any combination of digits taken from set 0 to 9. If the constant
contains two or more digits, the first digit must be something other than 0.

Rules for constructing integer constant


1. An integer must have at least one digit.
2. It must not have a decimal point.
3. It may either positive or negative. If no sign is present, it is assumed to be positive.
4. No commas or blank spaces are allowed in an integer constant.
5. Integer is used to store in 2 bytes of memory. So the value of constant cannot be
exceed a specified range i.e. -32768 to +32768.

 Floating point constant


Floating point constant can be written in two forms, fractional form and exponential
form. Floating point constant are normally represented as double precision quantities in „C‟.
Hence each floating point constant will occupy 4 bytes of memory. The precision of floating
point constant will vary from one version to other version.

Rules for constructing floating point constant


1. It must have at least one digit.
2. In floating point constant, there must be a decimal point. If it is not present it assumed
after the last digit.
3. It may be either positive or negative. Default is positive.
4. No commas or blank spaces are allowed.

 Character constant
A character constant is single character enclosed in apostrophes i.e. single quotation
marks. It may be an alphabet, digit or special character enclosed in single quotation marks.
Both quotation marks are pointing towards left. The maximum length of a character constant
is 1 character in memory.

Rules for constructing character constant


1. It must have only one character.
2. It must enclose in single quotation mark.
3. If it is other than alphabets, still it comes under character constants.

 String constant
A string constant is a constant that consist of any number of consecutive characters
i.e. a sequence of characters enclosed by double quotation marks. e.g. “Munish kumar”.

Rules for constructing character constant


1. A sequence of any number of characters enclosed in double quotation marks is string
constant.
2. There can be an empty string constant and is represented as “ ”.
3. The compiler automatically inserts a NULL character (\0) at the end of every string
constant, which is not visible when string is displayed. So “A” is a string constant
because it is a combination of characters „A‟ and „\0‟, whereas „A‟ is a character
constant.

Que: Explain the meaning and types of data type.


Ans: A programming language is proposed to help programmer to process certain kinds of
data and to provide useful output. The task of data processing is accomplished by executing
series of commands called program. A program usually contains different types of data types
(integer, float, character etc.) and need to store the values being used in the program. C
language is rich of data types. A C programmer has to employ proper data type as per his
requirements.
C has different data types for different types of data and can be broadly classified as:

Primary Data Type:


Primary data types are basically the building blocks of the data structure. These are explained
below:-
 Integer Data Types:
Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value range limited to
-32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and
rest 15 bits for number. To control the range of numbers and storage space, C has three
classes of integer storage namely short int, int and long int. All three data types have signed
and unsigned forms. A short int requires half the amount of storage than normal integer.
Unlike signed integer, unsigned integers are always positive and use all the bits for the
magnitude of the number. Therefore, the range of an unsigned integer will be from 0 to
65535. The long integers are used to declare a longer range of values and it occupies 4 bytes
of storage space.
Syntax:
int <variable name>;
int num1;
short int num2;
long int num3;

Integer Data Type Memory Allocation:

 Floating Point Data Types:


The float data type is used to store fractional numbers (real numbers) with 6 digits of
precision. Floating point numbers are denoted by the keyword float. When the accuracy of
the floating point number is insufficient, we can use the double to define the number. The
double is same as floatbut with longer precision and takes double space (8 bytes) than float.
To extend the precision further we can use long double which occupies 10 bytes of memory
space.

Syntax:
float <variable name>;
float num1;
double num2;
long double num3;
Floating Point Data Type Memory Allocation:

 Character Data Type:


Character type variable can hold a single character and are declared by using the
keyword char. As there are singed and unsigned int (either short or long), in the same way
there are signed and unsigned chars; both occupy 1 byte each, but having different ranges.
Unsigned characters have values between 0 and 255, signed characters have values from –
128 to 127.

Syntax:
char <variable name>;
char ch = „a‟;
A character data type used 1 byte memory.
 Void Type:
The void type has no values therefore we cannot declare it as variable as we did in
case of integer and float. The void data type is usually used with function to specify its
type.
Secondary Data type
Secondary data types are those data types which are derived from one or more basic data
types. In „C‟ there are following secondary data types

 Array
Array is basically a collection of same data types. Array is a group of same type of
data elements that have been given a common name. Array is used where programmer need
multiple variables of same type, in this situation array is used instead of multiple elements.

Syntax
data_type variable_name[size];
where data_type may be any of the basic data type like int, float or char. variable_name is the
name of array and size is the number of elements in array.

 Structure
Sometimes a program requires a data in terms of records. In the form of record it must
require data_type in which different types of data can be clubbed together i.e. int, float, char.
For this type of requirement program need a data type called as structure data type in which
different types of data can be clubbed together. E.g. A student could have name, roll no and
marks etc. Where name is of char and roll no and marks are integer data types.

Syntax
struct structure_name
{
data_type1 var_name1
data_type2 var_name2
.
.
.
data_typeN var_nameN
}

 Union
Unions are also the derived data types almost same as structure. They are declared in
the same way as structures. The only difference is that in structures, each variable has the
separate memory allocation for each element but in union variables use the same memory
location. The space in the memory taken by union is equal to the length of the variable that
has the maximum size.

Syntax
union union_name
{
data_type1 var_name1
data_type2 var_name2
.
.
.
data_typeN var_nameN
}

Que: Write a note on rules for constructing variables in C.

Ans:

1. A variable name can have letters (both uppercase and lowercase letters), digits and
underscore only.
2. The first letter of a variable should be either a letter or an underscore. However, it is
discouraged to start variable name with an underscore. It is because variable name that
starts with an underscore can conflict with system name and may cause error.
3. There is no rule on how long a variable can be. However, only the first 31 characters of a
variable are checked by the compiler. So, the first 31 letters of two variables in a program
should be different.

Que: Write a short note on assignment statements in C.


Ans: Once you've declared a variable you can use it, but not until it has been declared -
attempts to use a variable that has not been defined will cause a compiler error. Using a
variable means storing something in it. You can store a value in a variable using:
name = value;
For example:
a=10;
stores the value 10 in the int variable a. What could be simpler? Not much, but it isn't
actually very useful! Who wants to store a known value like 10 in a variable so you can use it
later? It is 10, always was 10 and always will be 10. What makes variables useful is that you
can use them to store the result of some arithmetic.
Consider four very simple mathematical operations: add, subtract, multiply and
divide. Let us see how C would use these operations on two float variables a and b.
add
a+b
subtract
a-b
multiply
a*b
divide
a/b
+ for add
- for subtract
* for multiply
/ for divide
BE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation?
a=10/3
The answer depends upon how a was declared. If it was declared as type int the answer will
be 3; if a is of type float then the answer will be 3.333. It is left as an exercise to the reader to
find out the answer for a of type char.
Two points to note from the above calculation:
1. C ignores fractions when doing integer division!
2. when doing float calculations integers will be converted into float.

An assignment "statement" is not really a statement (although it is typically used that way),
but is an expression. The value of the expression is the value that is assigned to the variable.
For example, the expression
i = j = k = 0;
sets all of i, j, and k to zero.

Q. Discuss the steps of compilation and execution of a C program.


Ans.
Install Turbo C++
Step 1: Locate the TC.exe file and open it. You will find it at location C:\TC\BIN\.
Step 2: File > New (as shown in above picture) and then write your C program

#include<stdio.h>
int main()
{
printf("hello World!");
return 0;
}
Step 3: Save the program using F2 (OR file > Save), remember the extension should be “.c”.
In the below screenshot I have given the name as helloworld.c.

Step 4: Compile the program using Alt + F9 OR Compile > Compile .

Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar) the C program.
Step 6: Alt+F5 to view the output of the program at the output screen.
3. Operators and Expressions
Que: Write a note on C instruction set.
Ans: There are basically three types of instructions in C:

1. Type Declaration Instruction


2. Arithmetic Instruction
3. Control Instruction

1. Type Declaration instructions in C Language


This instruction is used to declare the type of variables being used in the program. Any
variable used in the program must be declared before using it in any statement. The type
declaration statements is written at the beginning of the main() function. The main purpose of
type declaration instruction is to declare the type of variable C program.

int num;
char c; // Type Declaration
float f;
main()
{
// Statement
}
Example
int num=10, j=23;
float a=1.05, b=1-55+24;
int a, b, c, d;
int a=b=c=d=10;

2. The Arithmetic Instruction in C


A C arithmetic instruction consists of a variable name on the left hand side of = and variable
names & constants on the right hand side of = The variable and constants appearing on the
right hand side of = are connected by arithmetic operators like +, -, * and /.

Three types of C Arithmetic Statement

Integer mode arithmetic statement: This is an arithmetic statement which all operands are
either integer or integer constants.
int i, j, l, m;
i=i+1;
m=i* j +l;
Real Mode Arithmetic Statement: These are arithmetic statement in which all operands are
either real constant or real variable.
float si, roi, p, q ;
si = roi*p*q/100.0;

Mixed mode arithmetic statements: this is an arithmetic statement in which some of the
operands are integer and some of the operands are real.
int a, b, c, num ;
avg = ( a + b+ c + num)/4;

3. Control Instructions in C
The „Control Instructions‟ enable us to specify the order in which instructions in a program
are to be executed. or the control instructions determine the „flow of control‟ in a program.

There are four types of control instructions in C.

Sequence Control Instruction: The Sequence control instruction ensures that the
instructions are executed in the same order in which they appear in the program.
Selection or Decision Control Instruction: Decision instructions allow the computer to take
a decision as to which instruction is to be executed next.
Repetition or Loop Control Instruction: The Loop control instruction helps computer to
execute a group of statements repeatedly.
Switch Case.

Que: Explain various type of operators used in C programming.


Ans: An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. In C, an operators can either be unary, binary or ternary. If an operator
operates on single operand then it is termed as unary operator. If an operator operates on two
operands, it is called binary operator. An operator works with three operands is called ternary
operator. C language is rich in built-in operators and provides the following types of
operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators

Arithmetic Operators
The arithmetic operators are used to perform many of familiar mathematical operations( such
as addition, multiplication, subtraction etc) that involves calculation of numeric values
represented by variables, constants etc. They are binary operator that works with integers
numbers and even characters. Following table shows all the arithmetic operators supported by
C language. Assume variable A holds 20 and variable B holds 10 then:
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A - B = 10
∗ Multiplies both operands. A ∗ B = 200
∕ Divides numerator by de-numerator. A∕ B = 2
% Modulus Operator and remainder of after an integer A%B=0
division.

Program to demonstrate arithmetic operators

Output

Relational Operators
The relational operators are used to test the relationship between two operands. It does so by
comparing one operands against another and returns either true or false, depending upon the
status of the match. A relational expression that is interpreted by true evaluates to an integer
value 1 and if false it evaluates to an integer value of 0. Relational operators are binary
operators because they perform their operation on two operands. These operators are most
often used within conditional and looping statements such as if, while and for statements.
Following table shows all the relational operators supported by C language. Assume variable
A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands are equal or not. If yes, then (A == B)
the condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not. If values are (A != B)
not equal then the condition becomes true. is true.

> Checks if the value of left operand is greater than the value of (A > B)
right operand. If yes, then the condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right (A < B)
operand. If yes, then the condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand. If yes, then the condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the (A <= B)
value of right operand. If yes, then the condition becomes true. is true.

Program to find whether a given number is even or odd

output

Logical Operators
Logical operators are used to combine one or more relational expression that results in
formation of complex logical expression. Like relational operator, logical operator evaluate
the result of logical expression in term of Boolean values that can only be true (1) or false(0)
according to the result of the logical expression. They are generally used in an expression.
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, (A &&
then the condition becomes true. B) is
false.

|| Called Logical OR Operator. If any of the two operands is non- (A || B)


zero, then the condition becomes true. is true.

! Called Logical NOT Operator. It is used to reverse the logical !(A &&
state of its operand. If a condition is true, then Logical NOT B) is
operator will make it false. true.

Program to fine greatest among three numbers using logical operators.

Output

Bitwise operators
C provides an extensive bit manipulation operator for programming who want to write
program at machine level. These operators act directly on the bits of their operands rather
than numeral value. They are used for testing bits or shifting them either right to left or left to
right. Bitwise operators are used to manipulate the bits of integral operands such as char,
short, int and long both signed and unsigned form. Bitwise operator works on bits and
performs bit-by-bit operation. The Bitwise operators supported by C language are listed in the
following table. Assume variable A holds 60 and variable B holds 13, then:

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists in (A & B) =
both operands. 12 i.e.,
0000 1100

∣ Binary OR Operator copies a bit if it exists in either operand. (A ∣ B) = 61


i.e., 0011
1101

^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) =


but not both. 49 i.e.,
0011 0001

~ Binary Ones Complement Operator is unary and has the effect (~A ) = -61
of 'flipping' bits. i.e., 1100
0011 in 2's
complement
form.

<< Binary Left Shift Operator. The left operands value is moved A << 2 =
left by the number of bits specified by the right operand. 240 i.e.,
1111 0000

>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15
right by the number of bits specified by the right operand. i.e., 0000
1111

Assignment Operators :
The assignment operator is most common binary operator use in C language. It evaluates the
result of right hand side and then assigns the resulting value to a variable on the left hand
side. The right operand can be variable, constant, function call or expression. But in left side
it should be a variable. The following table lists the assignment operators supported by the C
language
Operator Description Example

= Simple assignment operator. Assigns values from C = A + B will assign the


right side operands to left side operand. value of A + B to C

+= Add AND assignment operator. It adds the right C += A is equivalent to


operand to the left operand and assign the result to C=C+A
the left operand.

−= Subtract AND assignment operator. It subtracts C −= A is equivalent to


the right operand from the left operand and C=C–A
assigns the result to the left operand.
*= Multiply AND assignment operator. It multiplies C *= A is equivalent to C
the right operand with the left operand and assigns =C*A
the result to the left operand.

/= Divide AND assignment operator. It divides the C /= A is equivalent to C


left operand with the right operand and assigns the =C/A
result to the left operand.

%= Modulus AND assignment operator. It takes C %= A is equivalent to


modulus using two operands and assigns the result C=C%A
to the left operand.
Que: write a short note on type conversion in ‘C’
Ans: Type conversion occurs when the expression has data of mixed data types example of
such expression include converting an integer value in to a float value, or assigning the value
of the expression to a variable with different data type. In type conversion, the data type is
promoted from lower to higher because converting higher to lower involves loss of precision
and value.
For type conversion, C following some General rules explained below:-
1. Integer types are lower than floating point types.
2. Signed types are lower than unsigned types.
3. Short whole number types are lower than long type.
4. double>float>long>int>short>char

While Programming consider the following points:-


 An arithmetic operation between an integer and integer always yields an
integer result.
 An operation between a float and float always yields a float result.
 An operation between an integer and float always yields a float result. In this
operation the integer is first promoted to a float and then the operation is
performed. the net result is a float.
int/int=int
float/int=float
int/float=float
float/float=float

 If the expression contains one operand as double data type and another
operand as some other lower data type then the other operand is also converted
to double and the result will be double.
double operator (float(or)long(or)int(or)short)=>double
 If the expression contains long and unsigned integer data types, the unsigned
integer is converted to unsigned long and the result will be unsigned long.
Character and short data are promoted to integer.
 Unsigned char and unsigned short are converted to unsigned integer.

Forced Conversion
Forced conversion occurs when we are converting the value of the larger data type to
the value of the smaller data type or smaller data type to the larger data type. For example,
consider the following assignment statement
int a;
float b;
a=5.5;
b=100;
In the first statement a=5.5, a is declared as int so the float value 5.5 cannot be stored in a. In
such a case float is demoted to an int and then its value is stored. hence 5 is stored in a.
In the second statement b=100, since b is a float variable 100 is promoted to
100.000000 and then stored in b.

In general, the value of the expression is promoted or demoted depending on the type of
variable on left hand side of =. Consider the following statement
float x,y,z;
int result;
result=x*y*z/100+32/8-3*1.5;
In the above statement some operands are of int type where as others are floats. During
evaluation of the expression the ints would be promoted to floats and the result of the
expression would be a float. But when this float value is assigned to result, it is again
demoted to an int and then stored in result.

Forced conversion may decrease the precision. Type casting is the preferred method
of forced conversion

Type Casting (or) Explicit Type conversion:


Explicit type conversions can be forced in any expression, with a unary operator called a cast.

Syntax
(type-name) expression;

Example
int n;
float x;
x=(float)n;

The above statement will convert the value of n to a float value before assigning to x. But n is
not altered. Type casting does not change the actual value of the variable but the resultant
value may be put in temporary storage. The cast operator has the same high precedence as
other unary operators. The Typecasting should not be used in some places such as
1. Type cast should not be used to override a const or volatile declaration overriding
these type modifiers can cause the program to fail to run correctly.
2. Type cast should not be used to turn a pointer to one type of structure or data type in
to another.

Q: Discuss Hierarchy of operators in C.


or
Q: Discuss Precedence of operators in C.
Ans: Operator precedence determines the grouping of terms in an expression and decides
how an expression is evaluated. CertFStructureain operators have higher precedence than
others; for example, the multiplication operator has a higher precedence than the addition
operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Que: What are formatted and unformatted statements in c? Support your answer with
suitable example.
Ans: formatted and unformatted statements in c are used for data input and output from
standard input/output devices. „C‟ language includes a number of library functions for data
input and output. These library functions are further divided into formatted and unformatted
statements which are explained below:-

Formatted statements
Formatted input/output statements allow the input to be read from the keyboard or output to
be displayed on the monitor to be formatted as per requirements. It actually deals with a
number of spaces that will be present between two values, when output will be displayed on
the screen or number of places after a decimal point. Following are formatted statements in
„C‟
 scanf()
The data can be entered into the computer from standard input device (usually
keyboard) by using a library function scanf(). The scanf() falls under the category of
formatted console I/O statement. The scanf() is used to enter all the data values with
format of that data type.
Syntax
scanf(formatstring, arg1, arg2,. . . . . . ., argN);
Here, formatstring is a string that contains required formatting information. It consists
of one or more character groups where each data group is used for each data item to
be entered.
 printf()
The data can be displayed onto the computer by standard onput device (usually
monitor) by using a library function printf(). The print() falls under the category of
formatted console I/O statement. The printf() is used to display the data values or
string with format of that data type.
Syntax
printf(formatstring, arg1, arg2,. . . . . . ., argN);
Here, formatstring is a string that contains required formatting information. It consists
of one or more character groups where each data group is used for each data item to
be displayed.
Program to demonstrate formatted statements.

Output
Unformatted statements
Unformatted I/O statements allow the input to be read from keyboard or output to be
displayed on the monitor without any format specifiers. These statements can be classified
into two categories.
 Character handling statements
The character handling statements deals with one character at a time. The character
input functions include getch(), getche(), getchar(). The character output functions
include putch(), putchar()

Function name Description of Function


getch() When the user inputs a character using this function, the user
need not to press enter nor type character is echoed on screen. It
is basically used to hide the input. This function is included in
conio.h header file.
getche() When the user inputs a character using this function, it returns a
character that has been recently typed and echoes on screen. In
this, the user is not required to press enter key to move the control
to next statement. the character type is immediately accepted.
This function is included in conio.h header file.
getcghar() When a user inputs a character using this function, it returns a
character that has been recently typed. After typing the
appropriate character, the user is required to press enter key to
shift the control to the next statement. This function is included in
stdio.h header file.
putchar() The putchar() is character output library function available in C. It
transmits a single inputted character to a standard output device.
The character being transmitted is normally represented as
character type variable. It included in the stdio.h header file.
putch() The putch() is another character type function in „C‟. This
function is included in conio.h header file. Like putchar(), it also
transmits the single character to the standard output device.

 String handling statements


The string handling functions deals with string of characters. The gets() and puts() are
string I/O library functions available in „C‟, that permit some form of data transfer
into or out of the computer. Both these functions are included in the header file
stdio.h.
Function name Description of Function
gets() The gets() function reads a string of text entered from standard
input device and terminates when it finds a newline character.
puts() The puts() function is used to print the string on the screen.
Program to demonstrate unformatted statements

Output

Q: Write a note on structure of a ‘c’ program.


Or
Q: Discuss structure of a C program in detail.
Ans: A program written in c consists of different sections. Some of them are mandatory and
some are optional. The optional section can be excluded from the program depending upon
the requirement of the programmer. Following sections are used to write a „c‟ program

Documentation section
Pre-processor directives section
Global declaration section
main() program section
{
Declaration part
Executable part
}
Subprogram section
Function_1()
Function_2()
....................
....................
Function_n()

1. Documentation section: Its includes a set of comment lines that improves the readability
of the program so that you and other programmers can understand your program. A
comment is message that exists only for the programmer and is ignored by the compiler
even if it looks like your program code. A good program should include comments that
describe the purpose of the program, author name, date and time of program creation and
other details. The documentation section is optional, however it is recommended.
Comments may appear anywhere in the program in c. It can be two type

 Single line comments : in it, a single line is enclosed within delimiters //


For example :
// program to find out sum of two numbers
 Multiline comments : in it , comments start and end with delimiters /* and */
For example :
/* Program to find
Sum of two numbers*/

2. Pre-processor Directive section: it includes various pre- processor directives. A pre-


processor directive is a message to the compiler to do something before compiling the
code and is handled by a part of compiler known as pre-processor. The pre-processor
directives are proceeds by the pre-processor before compilation actually starts. The main
function of pre-processor is to include other files in the source file, specifying symbolic
constants etc. All the pre-processor directives starts with the a pound sing(#) which
distinguishes them from other items in a C program. Some of the most common pre-
processor directives are :
 #include directive: Before using any functions provided in the standard C library in
your program, you must tell the compiler that you want to use them. This is done by
adding a header file in your program. It is a file that specify information that compiler
uses to integrate any predefined functions within a program. For example if you are
using printf() in your program then you have to use following header file
#include <stdio.h>
 #define directive: The other most often used pre-processor directives is #define
directive. It is used to specify symbolic constants. The symbolic constants allows the
programmer to define a name for constant and use that name throughout the program
as shown in following example: -
#define PI 3.14159

3. Global Declaration section: This section includes global declaration that is used to
declare global variables. They are called so because the are accessible to any part of the
program. In others words these variables are visible throughout the program. The global
variables declared before main() functions but after declaring pre-processor directives.
4. main() Program Section: The execution of the program always starts from this part of
the program. This part begins with a function named main(). It is this function from
which the execution of program starts. The body of the function is enclosed in curly
braces ( { and } ). C program may have many function but main is essential and all other
function are called within main program section. It returns the status code to the operating
system.
5. Subprogram Section : It include various user defined functions. These functions are
defined by programmer itself to write one‟s own code. These functions are called by
main() in C program.

Lets us look at a simple C program

Program to print a massage in C

Output:-

Que: what are pre-processor directives? Explain in details.


Ans The C pre-processor is a macro processor that is used automatically by the C compiler to
transform programmer defined programs before actual compilation takes place. It is called a
macro processor because it allows the user to define macros, which are short abbreviations
for longer constructs.
This functionality allows for some very useful and practical tools to design our programs.

 To include header files(Header files are files with pre defined function
definitions, user defined data types, declarations that can be included.)

 To include macro expansions. We can take random fragments of C code and


abbreviate them into smaller definitions namely macros, and once they are
defined and included via header files or directly onto the program itself it(the
user defined definition) can be used everywhere in the program. In other
words it works like a blank tile in the game scrabble, where if one player
possesses a blank tile and uses it to state a particular letter for a given word he
chose to play then that blank piece is used as that letter throughout the game. It
is pretty similar to that rule.
 Special pre processing directives can be used to, include or exclude parts of
the program according to various conditions.

To sum up, pre-processing directives occurs before program compilation. So, it can be also
be referred to as pre compiled fragments of code. Some possible actions are the inclusions of
other files in the file being compiled, definitions of symbolic constants and macros and
conditional compilation of program code and conditional execution of pre-processor
directives. All pre-processor directives has begin with the # operator.

# include preprocessor directive:


Only defined at the top of the program definition and only white space and comments may
appear before preprocessor directive line.This directive includes a copy of the specified file
or library. And is written like so-
# include <filename>
Or #include “file name”
If included inside <> then the compiler looks for the file in an implementation defined
manner (or system directory paths).
If included inside a quote “ ” statement then it searches for the file in the same
directory as the program being written.
So if we include a file named file1 while writing a program name code.c which is
being stored in a folder called test. Then inclusion like so -- #include “file1”
Will tell the compiler to look for the file inside the test folder, It looks at
neighbouring folders or subfolders too but it starts its search in the test folder.(This sub
search option is compiler dependent).

#define Preprocessor Directive : Macros


Symbolic constants and macros can be discarded by using the #undef pre-processor directive.
Directive #undef “undefines” the symbolic constant or macro name. The scope of a symbolic
constant or macro is from its definitions until it is undefined with #undef or until the end of
the file.
Example Code –
#include<stdio.h>
#include <conio.h>
#define BUFFER_SIZE 250
int maint()
{
char array[BUFFER_SIZE] = [0];
int i = 9;
printf(“%d”,i);
printf(“%s”,array);
return 0;
}//end main body
4. Decision Control Structure
Que: Explain different decision control statements?
Ans: Decision Making
Decision is a word which is normally taken in a moment where one is in a position to select
one option from the available options which are obviously more than one. While writing
programs this concept is always going to play an important role. We will have to provide the
capabilities to our program so that it can take decisions on its own depending upon the
various possible inputs from the user. When you are going to write some program it will be
always necessary that you will have to put some code which has to be executed only when a
specific condition is satisfied. These conditions are evaluated by the computer itself when
the input is given by the user. In C language there are various methods which can be used to
select an appropriate set of statements depending upon the user‟s input. On counting them,
totally there are FOUR different ways to take decisions which are as follow :

 If statement
As the word itself is clarifying its meaning, it is used to check a condition and
perform a set of statements according to the result of the condition checked.
The condition following the keyword if includes any relational or logical
expression which always enclose within a pair of parentheses. If condition is
true then block of if statement will executes its statements and if it is false then
flow will go out of if‟s block.

Syntax :

if (condition)
{
...
... // True_Block statements;
...
}
Example:

Output:
In above example user enters the marks and program will tell if one is passed. In if
statement there is a limitation of false condition, which is resolved further by if-else
statement.

 If-else statement
If-else statement is used to overcome the limitation of if statement. If statement do
have not another block to execute for false statement. But in if-else statement else
block is used for handling false statements. Else block do not need to specify any
condition. It will automatically executes its block when condition become false.

Syntax :

if (condition)
{
...
... // True_Block statements;
...
}
else
{
...
... // False_Block Statements;
...
}
In the above given syntax "condition" means any relational condition or any mathematical
expression. If the condition given in the brackets (parenthesis) is TRUE then the statements
within the BRACES executed. In case of mathematical expressions every non-zero value (i.e.
+ve or -ve) is considered to be TRUE and zero value is considered as FALSE. The
statements given in BRACES after the "else" part are executed when the condition is false.

Example: Program to check whether a student is pass or fail

Output

First run

Second run

 Else-if ladder statement

In C programming language the else if ladder is a way of putting multiple ifs together
when multipath decisions are involved. It is a one of the types of decision making and
branching statements. A multipath decision is a chain of if‟s in which the statement
associated with each else is an if. The general form of else if ladder is as follows -

if ( condition 1)
{
statement - 1;
}
else if (condtion 2)
{
statement - 2;
}
else if ( condition n)
{
statement - n;
}
else
{
default statment;
}

This construct is known as the else if ladder. The conditions are evaluated from the
top of the ladder to downwards. As soon as a true condition is found, the statement
associated with it is executed and the control is transferred to the end of else
block(skipping the rest of the ladder). When all the n conditions become false, then
the final else containing the default statement will be executed.

Example: program to find day of week

Output:

First Run
Second Run

 Nested if-else statement


It is also possible that an entire if-else block or another if statement can occur either
within the body of if statement or/ and in the body of else statement. This is known as
nested if statements.
Syntax

In nested if else inner block of if/ if-else block will execute only when outer condition
will satisfied. Nested if-else statements are used where a programmer need conditions
within conditions, these situations are handled by nested if-else statement.

Example: Program to find greatest among three numbers.


Output

Que: Explain various types of loops. Write the differences between while and do-while.
Ans: You may encounter situations when a block of code needs to be executed several
number of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on. C language provide various
control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement C language:

C programming language provides the following types of loops to handle looping


requirements.

While Loop

A while loop in C programming repeatedly executes a target statement as long as a given


condition is true. While loop Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing the loop body. While loop need a
initial value for condition to be checked as entry point. It may also possible to enter in a loop
without condition but these types of loops can stopped by only break statement.

Syntax
The syntax of a while loop in C programming language is:

while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately
following the loop.

Example: Program to find factorial using while loop.

Output:

For Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. For loop has three arguments initialization,
condition and increment / decrement. All three arguments are optional in for loop. A for loop
need only two semi-colons(;;) to execute its body.

Syntax
The syntax of a for loop in C programming language is:

for ( initialization; condition; increment/decreament )


{
statement(s);
}
Here is the flow of control in a „for‟ loop:
1. The initialisation step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and the flow of control jumps to the next
statement just after the „for‟ loop.
3. After the body of the „for‟ loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the „for‟ loop terminates.
Example: Program to find factorial using for loop.

Output:

Do while Loop

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while
loop in C programming checks its condition at the bottom of the loop. A do...while loop is
similar to a while loop, except the fact that it is guaranteed to execute at least one time.
Generally do while loop is used in menu driven programs, where menu has to display without
conditions to be checked.

Syntax
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );

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

Example: Program to find the factorial using do while loop

Output:

Difference between while and do-while loop


While Do-While
It is an entry control loop It is an exit control loop
Condition is checked before the execution of Condition is checked after the execution of
the body of loop the body of loop
There is no semicolon after while There is semicolon after do-while
It will not execute if the initial condition will It will execute ones if the initial condition
false will false
Syntax Syntax
while(condition) Do
{ {
Body of loop; Body of loop;
} } while(condition);
Flow Chart Flow chart
Que: Explain different types of jumping statements.

Ans: In programming there are some situations when a programmer wants to skip some code
of block and sometimes we want to continue executing the code of block. In C this is
achieved with the help of jumping statements. The break, goto and continue statements are
known as jump statements. These are used to transfer program control from one point in the
program to another point, at any time. Let's understand how these work?
break statement
This statement terminates the execution of loop or switch in which it appears and transfers
program control to the next statement which is placed immediately after the loop or switch.
The break statement is used inside loop or switch statement. When compiler finds the break
statement inside a loop, compiler will abort the loop and continue to execute statements
followed by loop.
Syntax
The syntax for a break statement in C is as follows:
break;
Example
#include<conio.h>
#include <stdio.h>
Void 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;
}
}
getch();
}

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
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
The syntax for a continue statement in C is as follows:
continue;

Example
#include<conio.h>
#include <stdio.h>
void main ()
{
/* local variable definition */
int a=10;
/* do loop execution */
do
{
if( a == 15)
{
/* skip the iteration */
a ++;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
getch()
}

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

goto Statement
A goto statement in C programming provides an unconditional jump from the „goto‟ to a
labeled statement in the same function. NOTE: Use of goto statement is highly discouraged
in any programming language because it makes difficult to trace the control flow of a
program, making the program hard to understand and hard to modify. Any program that uses
a goto can be rewritten to avoid them.

Syntax
The syntax for a goto statement in C is as follows:

goto label;
..
.
label: statement;

Here label can be any plain text except C keyword and it can be set anywhere in the C
program above or below to goto statement.
Example
#include<conio.h>
#include <stdio.h>
void main ()
{
/* local variable definition */
int a=10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
getch();
}

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

Que: Explain switch statement with example.


Ans. In decision making sometimes conditions becomes large and complicated; these
conditions can easily handle with switch case statement instead of if-else ladder and other if‟s
form. A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each switch
case. Switch case directly jumps on the matched case and skipped the above cases. To skip
cases followed by the executing case, a break statement is used.

Syntax
switch(expression)
{
Case expression 1:
Statement 1;
break;
Case expression 2:
Statement 2;
break;
:
:
Case expression n:
Statement n;
break;
default:
default statement;
}

The following rules apply to a switch statement:

 The expression used in a switch statement must have an integral or character type.
 You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will
fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.

Example: Program to find days of week using switch case


Output:

First Run

Second Run

NOTE: switch case can also be explain/ask in jumping control and decision making
statements.
5. Functions
Que: what is the meaning of functions? Explain user defined functions.
AnsA function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions. You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division is such that each function
performs a specific task. A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides the actual body of the function.
Functions are divided into two types as following.

Library Functions
Library functions are predefined in C compiler. These functions have their predefined task. A
user can not modified these function, one can only call these functions in one‟s code. These
functions can only accessed with their headers files. printf() is a library function with
predefined task of printing string and variables on console.

 Accessing A library function


A library function can be accessed simply by writing the function name, followed by
the list of arguments that present the information being passed to the function. The
arguments must be enclosed in parentheses and separated by commas, if any. For
example, suppose user want to calculate the square root of a number 9. For this user
can use predefined sqrt(n) available in math.h header file. Number, which would
provide to this function, is called its argument and the number that comes as output is
the return value. Some functions may have more than one argument but a function
cannot return more than one value. E.g. of this function is as follow.
x=sqrt(9);
x is a variable which is used to save the value which will be returned by the sqrt()
functions. User can use variable for further calculation. If it is not required user can
directly print it in printf() function

Some library functions


Function Return type Purpose
gets(s) Char * Input string from standard input device.
puts(s) int Sends string to the standard output device.
printf() int Sends data items to the standard output device.
scanf() int Read data items from standard output device.
getchar(void) int Read data items from standard output device.
putchar(C) int Sends single character to the standard output device.

User Defined Function


User defined functions are created by the programmer itself for their specific task. When a
user need to access a specific code many time in a program, functions are the best way to do
this task. Functions reduced the size and complexity of a code. A user defined function have
following steps to implement.
Global and local variables
A local variable is a variable that is declared inside a function. A global variable is a
variable that is declared outside all functions. A local variable can only be used in the
function where it is declared. A global variable can be used in all functions.

Defining a Function
The general form of a function definition in C programming language is as follows:

return_type function_name( parameter list )


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

Function Declarations

A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately. A function declaration has the
following parts:
return_type function_name( parameter list );

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


int max(int num1, int num2);

Parameter names are not important in function declaration, only their type is required, so the
following is also a valid declaration:
int max(int, int);

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

Calling a Function

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

For example:
maximum= max(10,20);

In above example max() is a function which have two integer arguments and it will return the
maximum number by comparing two numbers. Maximum number will return from function
and will save in variable maximum.

Note:- Return type of the function and variable used for calling function must have same data
type.

We can also use function calling direct in another functions. The above said function max()
can be called directly in printf().

For example:
Printf(“maximum number is = %d”,max(10,20));

Program to find maximum number using function.

Output
Q: differentiate between call by value and call by reference.
or
Q: Explain different methods passing arguments to the functions.
Ans. If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function. Formal
parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit. While calling a function, there are two ways in
which arguments can be passed to a function:

Call by Value

The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument. By default, C programming
uses call by value to pass arguments. In general, it means the code within a function cannot
alter the arguments used to call the function.

Call by Reference

The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. It means the changes made to the parameter affect the
passed argument. To pass a value by reference, argument pointers are passed to the functions
just like any other value. So accordingly, you need to declare the function parameters as
pointer types.

Call by value Call by reference


1. When an argument is passed by 1. When an argument is passed by
value, any modification made in the reference, any modification made to
formal arguments in the called the formal argument are reflected
function are not reflected back in the back in the actual arguments in the
actual argument in the calling calling function
function 2. User needs to specify this method of
2. It is default mechanism of argument arguments passing
passing 3. Any unintentional changes made in
3. This method prevents the the formal argument are reflected in
unintentional changes from occurring the actual argument in the calling
in actual argument as change in the function
formal argument is not reflected back 4. It is suitable for passing argument of
4. It is not suitable for passing argument large size as not separate copy made
of large size as separate copy in the called function.
consumes a lot of memory space 5. Address of the actual argument is
5. The value of the actual arguments are passed to the formal argument by
passed to the formal arguments preceding address operator before
their names in function call

Example. Program to swap two numbers using call by value

Output

Program to swap two numbers using call by reference


Output

Que: what is the meaning of recursion? Explain it with an example.


Ans. Recursion is a process when a function calls itself repeatedly, until some specified
condition is met. It is useful for writing repetitive program where each action is stated in
terms of previous result. The need of recursion arises if logic of a program is such that the
solution of the problem depends upon the repetition of certain set of statements with different
input values and end with a condition. The C programming language supports recursion, i.e.,
a function to call itself. But while using recursion, programmers need to be careful to define
an exit condition from the function, otherwise it will go into an infinite loop. Recursive
functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.

There are two basic requirements for recursion.

1. The function must call itself again and again.


2. It must have a stopping(return) condition.

To understand the concept of recursion, let us consider an example where we need to


calculate the factorial of a number recursively. The factorial of 0 is 1 and factorial of any
positive integer n is the product of n and factorial of the number(n-1). Therefore, 0!=1 and
n!=n × (n-1)! n>0.
Now the question arise what is the factorial of (n-1). It is in fact the product of (n-1)
and factorial of (n-2). This process continues till n becomes 0. In which case, factorial is 1.
So the result obtained is repeated until we compute n!.
Example. Program to find factorial using recursion.

Output

When a recursive function is executed, the recursive function calls are not executed
immediately; rather they are placed on the stack until the termination condition for recursion
is encountered. The function calls are then executed in reverse order, as they are popped of
the stack.

Advantages of Recursion

 It makes the program code compact which is easier to write and understand.
 It is suitable to be used with data structure such as linked lists, queues, stacks etc.
 Recursion is useful if a solution to a problem is in repetitive form.
 The compact code in recursion simplifies the compilation as less number of lines
needs to be compiled.

Disadvantages of Recursion

 Consumes more storage space as recursive calls automatic variables are stored in
stack.
 It is less efficient in comparison to a normal program in case of speed and execution
time.
 Special care need to be taken for stopping condition in a recursive function. If
condition is not specified it may result in an infinite recursion.
Note: A recursive function must have if statement somewhere in the function to force the
function to return a value in which recursive call is not being executed, otherwise it may fall
into infinite recursive loop.

Que: Explain storage classes available in c.


Ans: A storage class defines the scope (visibility) and life-time of variables and/or functions
within a C Program. They precede the type that they modify. Every variable in c is associated
with a storage class in addition to its data type and name. A variable‟s storage class specifiers
tell us the scope of the variable throughout the program. There are four different storage
classes available in c.

The auto Storage Class


The auto storage class is the default storage class for all local variables. The auto storage
specifier tells that a variable will exist only within the block in which it is declared. Memory
of these variables are automatic created when block of these variable are executed and freed
automatically upon exit from the block. The scope of auto variables is local to a block
(included nested blocks). Syntax of auto storage class is as follow.
{
int mount;
auto int month;
}
The example above defines two variables within the same storage class. „auto‟ can only be
used within functions, i.e., local variables.
Characteristics of auto storage class

Storage Memory
Default value Garbage value
Visibility Visible within block where variable is
declared e.g. if the variable is declared in a
function then it is only visible to that function
Life time It retains its value till control remains in the
block in which the variable is declared. E.g.
if the variable is declared in a function, it will
retain its value till the control is in that
function.

The register Storage Class

The register storage class is used to define local variables that should be stored in a register
instead of RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and can't have the unary '&' operator applied to it (as it does not have a
memory location). Register are special storage areas within a computer‟s CPU. The actual
arithmetic and logic operations that comprise a program are carried out within these registers.
Normally these operations are carried out by transferring information from computer‟s
memory to these registers, carrying out the indicated operation and then transferring the result
back to the computer‟s memory. This process is repeated many times during the execution of
a program. A programmer can declare register variable within a block by prefixing its
declaration with register storage class specifier.

Syntax:
{
register int miles;
}
The register should only be used for variables that require quick access such as counters.

Characteristics of register storage class

Storage CPU registers


Default value Garbage value
Visibility Visible within block where variable is
declared (same as auto).
Life time It retains its value till control remains in the
block in which the variable is declared (same
as auto).

The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope. Therefore, making local variables static allows them to maintain their values
between function calls. The static modifier may also be applied to global variables. When this
is done, it causes that variable's scope to be restricted to the file in which it is declared.
Programmer can declare a static variable using static storage class access specifier.

Syntax:
{
Static int i=1;
}

Unlike auto storage variable they are not created and destroyed each time the function in
which they declared is called, rather they are created once and they retain their value
throughout the life of a program. So the last value stored in the variable when the function is
exited is available within variable to the function, next time it is called. Default value for
static storage class is 0. So if a programmer does not assign initial value to a static variable,
then it automatically set to 0. Static variables are used in situations in which a programmer
wants to retain information between function calls such as number of times the function is
called etc.

Characteristics of static storage class

Storage Memory
Default value Zero (0)
Visibility Visible within block where variable is
declared (same as auto).
Life time It retains its value between different function
calls i.e. when a function is called for first
time, static variable is created with initial
value zero, and in subsequent calls it retains
its present value.

The extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL
the program files. When you use 'extern', the variable cannot be initialized; however, it points
the variable name at a storage location that has been previously defined. When you have
multiple files and you define a global variable or function, which will also be used in other
files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in
another file. The extern modifier is most commonly used when there are two or more files
sharing the same global variables or functions as explained below.

File A File B
int x; // global variable extern int x;
void main() int func2()
{ {
............................ ......................
............................ ......................
func1(); }
func2();
}
int func1()
{
.............................
.............................
}

From the files shown above , the global variables x declared in file A can be used only
by the function main() and the func1(). However, if programmer wants to use it in file B, one
needs to place the declaration statement extern in x; in file B. This declaration indicates that
global variable x in some another file. This extends the scope of x into file B so that it can be
used by func2().

Characteristics of static storage class

Storage Memory
Default value Zero (0)
Visibility Global
Life time It retains its value throughout the program so
the life time is as long as the program‟s
execution does not come to an end.

6. Arrays
Que: what is array? Explain its types.
Or
Q. Explain the concepts of Array in detail. Support your answer with suitable example.
Ans: Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type. Instead of declaring
individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.

The concept of array helps a programmer to store group of values under a single name and
refer directly to a particular value. This makes the program very simple and efficient. In C
programming arrays are in two main types.

One dimensional array


One dimensional array represented a single row of same type of elements. Each
element has its unique index number assign to it by compiler. Individual elements are
accessed with the help of these index numbers. Index numbers are started with the index 0 to
n-1.

Two dimensional array


Two dimensional array represented elements in table form. Array elements are
accessed with the help of unique row and column number. If you have M rows and N
columns in an array then you have total m×n elements in that array. Each element is accessed
with its row and column number.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows:

 One dimensional array


Data_type arrayName [ arraySize ];

Here data_type refers to the data type of array elements. arrayName is the name of
array and arraySize is refers to the maximum length of array size.

 Two dimensional array


Data_type arrayName[rowSize] [columnSize];

Same as above here data_type refers to the data type of array elements.
arrayName is the name of array. Difference is rowSize and columnSize instead of
arraySize. rowSize refers the maximum length of row whereas columnSize refers to
the maximum length of column.

Initializing Array
When an array is declared, its elements has values according to the storage class of
the array i.e. 0 value for static and extern and garbage value for auto and register. In „c‟ it is
also possible to initialize the elements of the array at the same place where they are declared
i.e. in the beginning itself.

Example
One dimensional array
int a[]={50,60,70,80,90};
In one dimensional array when it is declare and initialize at same place, then subscript is
optional.
Two dimensional array
int a[2][3]={10,20,30,40,50,60};
In this array there are two rows and three columns, so there are total six elements in the array.
Each row has three elements. First three elements belong to first row and other three belongs
to second row. The problem with this initialization is that it is not appropriate and
understandable. To resolve this problem we have another way to initialize an array.

int a[2][3]={10,20,30},{40,50,60};
The previous case was not clear to understand. But in this case programmer can easily
distinguish elements between rows. Each row is separated by curly braces({}).

Accessing Array Elements


Array elements are accessed with the help of their index numbers. This is done by
placing the index of the element within square brackets after the name of the array. Following
are examples of accessing both arrays.

 One dimensional array


Output

 Two dimensional array


Output

Q: Discuss character array in detail.


Or
Q: Discuss how strings re implemented in C.
Ans: Strings are actually one-dimensional array of characters terminated by a null character
'\0'. Thus a null-terminated string contains the characters that comprise the string followed by
a null. The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

or
char greeting[] = "Hello";

Following is the memory presentation of the above defined string in C

There is no need to place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array.

Example:
#include <stdio.h>
#include <string.h>
#include<conio.h>

void main () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );

getch();
}

Output
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Q: Discuss operations that are performed on arrays in C.
Or
Q: Explain insertion and deletion operation on arrays in C.
Ans:
Insertion operation: Insertion operation is used to insert a new element at specific position
in to array. In order to insert a new element into array we have to create space for new
element. Suppose there are N elements in an array and we want to insert a new element
between first and second element. We have to move last N-1 elements down in order to
create space for the new element.

Example:

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

void main()
{
int array[100], position, c, n, value;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d elements\n", n);

for(c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter the location where you wish to insert an element\n");


scanf("%d", &position);

printf("Enter the value to insert\n");


scanf("%d", &value);

for(c = n - 1; c >= position - 1; c--)


array[c+1] = array[c];

array[position-1] = value;

printf("Resultant array is\n");

for(c = 0; c <= n; c++)


printf("%d\n", array[c]);

getch();
}

Deletion operation: Deletion operation is used to delete an element from specific position in
to array. In order to delete an element from array we have to check whether array contains
any element or not.

Example:

#include <stdio.h>
#include <conio.h>
void main()
{
int array[100], position, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d elements\n", n);

for ( c = 0 ; c < n ; c++ )


scanf("%d", &array[c]);

printf("Enter the location where you wish to delete element\n");


scanf("%d", &position);

if ( position >= n+1 )


printf("Deletion not possible.\n");
else
{
for ( c = position - 1 ; c < n - 1 ; c++ )
array[c] = array[c+1];

printf("Resultant array is\n");

for( c = 0 ; c < n - 1 ; c++ )


printf("%d\n", array[c]);
}

getch();
}

Q: How we can search element in an array. Explain with an example.


Ans:

Linear Search: Linear search is also called as sequential search. Linear search is a method
for finding a particular value in a list, which consists of checking every one of its elements,
one at a time and in sequence, until the desired one is found.

Program to find element in array (Linear Search).


Output
First run

Second Run

Binary Search: This searching technique is applicable only for sorted array, but this
searching technique is faster than linear search.

Steps for binary search


first sort elements of array if it is not in sorted order, because binary search is only
application on sorted element.
 First find the middle element of the array.
 Compare the middle element with the item. After this step there are three cases;
1. If middle element is a desired item then search is successful
2. If middle element is less than desired item then search only the first half of the
array.
3. If middle element is greater than the desired item search in the second half of the
array.
4. Repeat same steps until element are found.

Program to find element in array (Binary Search).


Output
First Run

Second Run

Q: Discuss using matrices in arrays.


Ans. A matrix is a rectangular array of numbers or symbols arranged in rows and
columns. Matrix is also called as 2-D array.

Example:

Program to find the sum of two matrices

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

void main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter a%d%d: ", i+1, j+1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
printf("Enter b%d%d: ", i+1, j+1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


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

// Displaying the sum


printf("\nSum Of Matrix:");

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


for(j=0; j<2; ++j)
{
printf("%.1f\t", c[i][j]);

if(j==1)
printf("\n");
}
getch();
}

Que: How an entire array is passed to a function?


Ans: Just as primitive data_ type a programmer can pass the entire array to a function. If a
programmer wants to pass a single-dimension array as an argument in a function, one would
have to declare a formal parameter in one of following three ways and all three declaration
methods produce similar results because each tells the compiler that an integer pointer is
going to be received. Similarly, you can pass multi-dimensional arrays as formal parameters.

Formal parameters as a pointer:


void myFunction(int *ptr)
{
.
.
.
}

In this method initial address of the array is passed to the pointer, as we know that all
array elements are stored in contiguous memory location, all other elements can be accessed
with the help of arithmetic operation on pointer.

Formal parameters as a sized array:


void myFunction(int param[10])
{
.
.
.
}
In this method only first n elements would be passed to a function as formal
arguments. This way is not much used because a programmer may need all the elements in
the function body.

Formal parameters as an unsized array:


void myFunction(int param[], int size)
{
.
.
.
}
In this method two different elements are passed to a function. First in an entire array
and the second is size of that array. This method is used instead of passing sized array to a
function because in this a programmer has a length of an array too with another variable.

When an array is passed to a function, it is passed by reference not by value. This


means that the elements of an array are not copied to the called function but the array name is
interpreted as the address of its first element. Since the elements of the array are stored in
contiguous memory locations so the called functions can access all the elements of the
original array. Any changes made to the array elements within the called functions reflected
in the original array.

Example : Program to find prime numbers in array by passing array to a function


Output
7. Pointers
Que: what is the meaning of pointer? Explain pointers arithmetic.
Ans: pointers are extremely flexible and powerful tool for programming over a wide range of
application. The use of pointers offers a great degree of flexibility for manipulating data in
program and making programs quicker and memory efficient. Most of the learners feel that
understanding pointer is a very daunting task, but it is not so. The real power of pointers lies
in situations such as,
 To just pass the address of data instead of passing whole copy of data to functions.
 To return more than one value from the function.
 To allow two functions to work on the same data rather than a separate copy.
 Passing array and string to a function more efficiently.
 Support for dynamic memory management.
 Optimize the program to execute faster or use less memory.
 Creation of linked data structure such as linked list, trees, graphs etc.

A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, programmer must declare a pointer
before using it to store any variable address. The general form of a pointer variable
declaration is:

Data_type *var-name;

Here, data_type is the pointer's base type; it must be a valid C data type and varname is the
name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used
for multiplication. However, in this statement, the asterisk is being used to designate a
variable as a pointer.

Initialization of pointer variables

When a pointer variable is declared, it is not initialized. Uninitialized pointers will


have some unknown memory address in it i.e . will have an unknown value that will be
interpreted as memory address. Uninitialized pointers can be used but results are
unpredictable. So it is important to initialize a pointer variable with a meaningful address
before it is used in the program. You can initialize a pointer variable by assigning the address
of the variable that has already been declared.

For example
int i=5;
int *ptr;
ptr=&i;

The ‘&’ and ‘*’ operators.


The two fundamentals operators used with pointers are.
1. The address of operator (&).
2. The indirection operator or value at address operator (*).
The address operator returns the address of a variable. The indirection operator returns the
value of the variable that the pointer is pointing to.

Advantages of pointers
 Sometime it is more convenient or flexible to work with the address of a variable than
the actual variable.
 Using pointers, program can access any memory location in the computer‟s memory.
 Array and structures can be handled more efficiently with pointers.
 Low level system programming can be done through the use of pointers.
 It will become impossible to create complex data structures without pointers.

Program to demonstrate the uses of pointers

output

Pointer Arithmetic
It may be noted that pointer can also be incremented to an immediately next location of its
type e.g. if the contents of a pointer p of type integer are 1002 then the content of p++ will be
1004 instead of 1003. The reason being that an int is always of 2 bytes size and therefore
stored in two memory locations. The amount of storage taken by various types of data is
tabulated as below:-
Type Amount of storage
character 1 byte
Int 2 bytes
Float 4 bytes
Long 4 bytes
double 8 bytes

Thus a pointer of float type will point to an address of 4 bytes of locations and therefore an
increment to this pointer will increment its contents by 4 locations.

The following operations are permitted on pointers


1. Incrementing/ decrementing pointer variables.
2. Addition of a number to a pointer variable.
3. Subtraction of a number from a pointer variable.
4. Comparison between two pointers.

Incrementing/ decrementing pointer


Incrementing pointers are generally used in array because it has contiguous memory in array
and to get the content of next memory location it should incremented. Incrementing pointer
variable depends upon data type of the pointer variable.

Formula
New value= current address+ i* size_of(data type)

Addition of a number to a pointer


When an integer value is added to a pointer variable, it is not incremented by that integer
value but it is incremented by address stored currently in pointer variable plus increment
value multiplied by size of type to which pointer variable points to
e.g. int[5]={10,20,30,40,50};
int *p;
p=a;
p=p+3;
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
1002 1004 1006 1008 1010
Initially p will point to first location which is 1002, it will increment to the pointer variable to
P=1002 + 3* size of(int)= 1002+ 3*2=1008
Similarly for float current address in pointer plus increment value multiplied by size of float
i.e. 4.
Similarly for char current address in pointer plus increment value multiplied by size of char
i.e. 1.

Subtraction of a number to a pointer


Programmer can also subtract an integer value from a pointer in the same way. Suppose the
pointer variable p currently points to the 4th element a[3] i.e. 1008.
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
1002 1004 1006 1008 1010
Then p=p-3;
Will decrease the pointer by 6 bytes i.e.
P=1008 – 3* size of(int)= 1008- 3 *2=1002
Similarly for float current address in pointer minus decremented value multiplied by size of
float i.e. 4.
Similarly for char current address in pointer minus decremented value multiplied by size of
char i.e. 1.

Comparison between two pointers


Pointer comparison is valid only if the two pointers are pointing to same array. All relational
operators can be used for comparing pointers of same type. All equality and inequality
operators can be used with all pointer types.

Following operators are used in comparison


> Greater than.
< Less than.
>= Greater than and equal to.
<= Less than and equal to.
== Equals
!= Not Equal
All these operators are used only with pointers pointing to same array.

Q: Discuss the relationship between pointers and arrays.


Ans. In C programming, name of the array always points to address of the first element of an
array.

For Example:

int arr[4];

In the above example, arr and &arr[0] points to the address of the first element. &arr[0] is
equivalent to arr Since, the addresses of both are the same, the values of arr and &arr[0] are
also the same.

arr[0] is equivalent to *arr (value of an address of the pointer)


Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
.
.
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).

In C, you can declare an array and can use pointer to alter the data of an array.
Example:

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

void main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));

// *(classes + i) is equivalent to classes[i]


sum += *(classes + i);
}
printf("Sum = %d", sum);
getch();
}

Q: Discuss how 2- dimensional arrays are implemented using 2 dimensional arrays.


Ans: In order to display the elements of the two dimensional array using pointers, it is
essential to have a „&‟ operator as a prefix with the array name followed by element
numbers.

Example
#include <stdio.h>
#include <math.h>
Void main()
{
int arr [ ][3] = {{11,12,13}, {21,22,23},{31,32,33},{41,42,43},{51,52,53}};
int I , j ;
int *p , (*q) [3], *r ;
p = (int *) arr ;
q = arr;
r = (int *) q ;
printf ( " %u %u %d %d %d %d \n ", p , q , *p , *(r) , *(r+1), *(r+2));
p++ ;
q++ ;
r = (int *) q ;
printf ( " %u %u %d %d %d %d \n ", p , q , *p , *(r) , *(r+1), *(r+2));
}

In above example pointer p and a pointer array q. The first assignment statement is to make
the pointer p points to the array arr. While assigning, declare the type of the variable arr.
Note that variables on both side of this statement should have the same type. Next line is a
similar statement, now with q and arr. Since q is a pointer array, the array can be directly
assigned to it and there is no need for specifying the type of the variable. In the next line the
pointer r points to the pointer array q. Here is what we get from this,

32 21 22 33 44 32 21 22 33 44 11 11 12 13
32 21 22 33 48 32 21 22 33 56 12 21 22 23

Here we see that incrementing p make it just jump through each element of the array, where
as incrementing q, will move it from one row to another row.

Q: Discuss the concept of pointer to an array in C.


Ans. The interaction of pointers and arrays can be confusing but here are two fundamental
statements about it: A variable declared as an array of some type acts as a pointer to that type.
When used by itself, it points to the first element of the array. A pointer can be indexed like
an array name.

Example

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

void main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;

p = balance;

/* output each array element's value */


printf( "Array values using pointer\n");

for ( i = 0; i < 5; i++ ) {


printf("*(p + %d) : %f\n", i, *(p + i) );
}

printf( "Array values using balance as address\n");

for ( i = 0; i < 5; i++ ) {


printf("*(balance + %d) : %f\n", i, *(balance + i) );
}

getch();
}

Points to Note:
1) Pointer variable data type is same as the type of array.
2) Pointer has been initialized by array 1st element address(subscript 0 for e.g. &val[0]).
3) In the loop the increment operation(p++) is performed on the pointer variable to get the
next location (next element‟s location), this arithmetic is same for all types of arrays (for all
data types double, char, int etc..) even though the bytes consumed by each data type is
different.
4) we can also use p=a where a is an array (or a[ ] )This is because the array name without
braces holds the address of first element of the array. Which means below statement holds
true.

Q: Discuss the concept of array of pointers in C.


Ans. An array of pointers can be used to point to an array of data items with each element of
the pointer array pointing to an element of the data array. Data items can be accessed either
directly in the data array, or indirectly by dereferencing the elements of the pointer array. The
advantage of a pointer array is that the pointers can be reordered in any manner without
moving the data items. For example, the pointer array can be reordered so that the successive
elements of the pointer array point to data items in sorted order without moving the data
items. Reordering pointers is relatively fast compared to reordering large data items such as
data records or strings. This approach saves a lot of time, with the additional advantage that
the data items remain available in the original order.

Example

#include <stdio.h>
#include <conio.h>
main() {
clrscr();
int *array[3];
int x = 10, y = 20, z = 30;
int i;
array[0] = &x;
array[1] = &y;
array[2] = &z;
for (i=0; i< 3; i++) {
printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]),
array[i]);
}
getch();
return 0;
}

8. Dynamic Memory Allocation


Que: What is dynamic memory allocation? Explain different function available for it.
Ans: In C, the exact size of array is unknown until compile time, i.e., the time when a
compiler compiles your code into a computer understandable language. So, sometimes the
size of the array can be insufficient or more than required. Dynamic memory allocation
allows your program to obtain more memory space while running, or to release it if it's not
required. In simple terms, Dynamic memory allocation allows you to manually handle
memory space for your program.
„C‟ Standard library provides following four functions for dynamic memory
allocation.

Function Name Use of Function


malloc() Allocates requested size of bytes and returns
a pointer first byte of allocated space.
calloc() Allocates space for an array elements,
initializes to zero and then returns a pointer
to memory.
realloc() Change the size of previously allocated
space.
free() deallocate the previously allocated space

malloc()

The name malloc stands for "memory allocation". The function malloc() reserves a block of
memory of specified size and return a pointer of type void which can be casted into pointer of
any form.
Syntax of malloc()
ptr=(cast-type*) maloc(byte-size);

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.

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

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.

Example: program demonstrating uses of malloc().


Output

calloc()
The name calloc stands for "contiguous allocation". The calloc() function is another
alternative to malloc(). Just like malloc() functions it also allocates block of memory run time
but the only difference between malloc() and calloc() is that, malloc() allocates single block
of memory whereas calloc() allocates multiple blocks of memory each of same size and sets
all bytes to zero.

Syntax of calloc()
Ptr=(cast-type*)calloc(n,elements-size);

This statement will allocate contiguous space in memory for an array of n elements. For
example:
Ptr=(float* )calloc(25,sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of size
of float, i.e, 4 bytes.

Example: program demonstrating uses of calloc().


Output

realloc()

realloc() function enables you to change the size of the previously allocated memory by
malloc(), calloc() or by itself. If the previously allocated memory is insufficient or more than
required, you can change the previously allocated memory size using realloc() function.

Syntax of realloc()
ptr=realloc(ptr,newsize);

Here, ptr is reallocated with size of newsize.

Example: program demonstrating uses of realloc().


Output

free()

Memory is limited recourse. Once should allocate exactly the required piece of memory
before one need it, and release as soon as he/she don‟t need it. So that it can be reused.
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its
own. You must explicitly use free() to release the space.

syntax of free()
free(ptr);

This statement frees the space allocated in the memory pointed by ptr.
9. String Manipulation C
Que: Explain String handling functions available in c.
Ans: There are a large number of library functions available in „C‟ that allow to operate on
strings. Using these functions, the string can be compared, copied or concatenated. They all
are included in a header file string.h. String handling functions in „C‟:-

strlen(s)
The strlen(s) function take one argument s which can be string constant or a string
variable. It returns length of the string stored in the array a i.e number of characters in the
string excluding the NULL character („\0‟). If string is empty, it returns zero. If String s[]=
˝Munish˝; the statement,

x=strlen(s);
x will be assigned 6 as returned value from function.

strcpy(s1,s2)
The strcpy() function takes two arguments as string variables(second can be string
constant too) and copied the value of second string to first string variable. If first string
argument has some previous value, this function will replace it with second string argument.
Example: char s2=˝C programing˝;
strcpy(s1,s2);
s1 will have same content as s2 after calling strcpy() function.

strcmp(s1,s2)
The strcmp() function compares the contents of string s1 with the content of the
string s2 by comparing successive corresponding characters, starting with the first character
in each string. This process continues until either the corresponding characters are formed to
be different of the last character in one or both strings is reached. Characters are compared
lexicographically.
strcmp(s1,s2)
This function returns an integer value depending upon the relative order of the two strings. It
returns 0 if both strings are identical. It will return a positive value if first string is greater and
negative value if second string is greater.

strcat(s1,s2)
The strcat() function concatenates two strings together. It takes two strings i.e.
character arrays as arguments of which first arguments s1 is a string variable and the second
argument s2 can be a string variable or string constant. This function appends a copy of s2 to
the end of s1. The first character of s2 overwrites the terminating NULL character(„\0‟) of s1.
The length of the resulting string is strlen(s1) + strlen(s2). In addition string s2 to string s1
this function also returns s1. Its syntax is as follows. Concatenated
strcat(s1,s2)

strlwr(s)
The strlwr() function converts the uppercase letters in a given string s to lowercase. It
takes one argument s which is a string variable. Its takes the following form.
Strlwr(s).
After converting the string into lowercase, it stores the result back in string s and returns
string s.

strupr(s)
The strupr() function converts the lowercase letters in a given string s to uppercase. It
takes one argument s which is a string variable. Its takes the following form.
Strupr(s).
After converting the string into uppercase, it stores the result back in string s and returns
string s.

Program demonstrating string functions

Output
10. Structures and Unions
Que: Explain in detail structure in ‘C’ language?
Ans: Structure
Structure is a user defined data type , this is used to store different kind of data types in a
single block. Structures are used to represent a record. Suppose you want to keep track of the
information of students. You might want to track the following attributes about each student:
 Roll_num
 Name
 Class
 Marks

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:

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.

Initializing structure
When a structure variable is declared, its data members are not initialised and therefore
contain undefined values. Similar to simple variables and arrays, the structure variables can
also be initialized. For instance the structure can be declared and initialized as shown below:-
struct student
{
int roll_num;
char name[20];
char clas[10];
int marks;
};
struct student s1={731,”Munish Kumar”,”MCA”,77};
The values are assigned to the members of the structure in order of their appearance i.e. first
value is assigned to the first member, second to second and so on. But the thing which should
remember during assigning the values is that the data type of data members of structure and
values should be same.
Accessing 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.

Output

Q: Discuss the concepts of Array of structures.


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

Syntax for declaring structure array

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

struct struct-name obj [ size ];

Example

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

struct student
{
int rollno;
char name[10];
};
void main()
{
int i;
struct student st[5];
clrscr();
printf("Enter Records of 5 students");

for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}

printf("\nStudent Information List:");


for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}

getch();
}
Q: Write a note on nested structures in C.
Ans. The C language permits structures to be nested, in which a structure can contain
structure members. A structure may be declared inside another structure. Also, a structure
may be a data member of another structure.

Method 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:

1. Structure members are accessed using dot operator.


2. „date„ structure is nested within Employee Structure.
3. Members of the „date„ can be accessed using ‟employee‟
4. 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

Example

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

struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};

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

Q. Discuss in detail Structures with pointers in C.


Ans. Pointer to Structure in C Programming

 Address of Pointer variable can be obtained using „&‟ operator.


 Address of such Structure can be assigned to the Pointer variable.
 Pointer Variable which stores the address of Structure must be declared as Pointer to
Structure.

Pointer to Structure Syntax:

struct student_database
{
char name[10];
int roll;
int marks;
}stud1;
struct student_database *ptr;
ptr = &stud1;

How to Access Structure Members:

Method 1: Using Structure Name


Example

#include <stdio.h>
void main()
{
struct student_database
{
char name[10];
int roll;
int marks;
}stud1;

stud1.roll = 10;
stud1.marks = 90;

printf("Roll Number : %d",stud1.roll);


printf("Marks of Student : %d",stud1.marks);
}
Output :

Roll Number : 10
Marks of Student : 90

Method 2 : Using Indirection Operator and Pointer

Pointer variable is declared and pointer to structure. Whenever we declare pointer variable
,address of the structure variable is assigned to the pointer variable.

Example 2

#include <stdio.h>
void main(int argc, char *argv[])
{

struct student_database {
char name[10];
int roll;
int marks;
}stud1 = {"Pritesh",90,90};

struct student_database *ptr;


ptr = &stud1;

printf("Roll Number : %d",(*ptr).roll);


printf("Marks of Student : %d",(*ptr).marks);
}
Output of the Program :

Roll Number : 90
Marks of Student : 90

Method 3: Using Membership Operator

Example 3

#include <stdio.h>
void main(int argc, char *argv[])
{

struct student_database {
char name[10];
int roll;
int marks;
}stud1 = {"Pritesh",90,90};

struct student_database *ptr;


ptr = &stud1;

printf("Roll Number : %d",(ptr)->roll);


printf("Marks of Student : %d",(ptr)->marks);
}

Whenever we access the member of the structure using the pointer we use arrow operator to
access the member of structure.

Q: Explain in detail Unions in C language.


Ans:

Union

Like structure union are also of derived data type. Both structure and unions are used to
contain members or variables of different types in a single unit. While structures are used to
store different members at different places in memory, a union is used to store different
members at same memory location. Thus unions are used to conserve memory. In union
memory assignment is the largest memory of union whereas in structure, the memory
reserved is the total sum of members to be used by all the members of structure.

Defining a union

To define a union, one must use the union statement. The union statement defines a new data
type, with more than one member same as struct. The format of the union statement is as
follows:

union [union tag]


{
member definition;
member definition;
...
member definition;
} [one or more structure 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.

E.g.
Union sample
{
char a;
int b;
float c;
}
In this example union contains three members, each with a different data type. However
programmer can use only one of them at a time. This is because only one location is allocated
for union variables, irrespective of its size.
1004 1005 1008 1007

a
b
c
Object of a union type can be declared either at the same time of union type definition or after
the union type definition in a separate declaration statement. Objects of the union type can be
created after union definition only if the defined union type is named or tagged.

Program to demonstrate union


Output

Q: Write the difference between structure and union.


Ans.
Difference between Structure and union

Structure Union
Memory Allocation Members of structure do not A union shares the memory
share memory. So A structure space among its members so
need separate memory space no need to allocate memory to
for all its members i.e. all the all the members. Shared
members have unique storage. memory space is allocated i.e.
equivalent to the size of
member having largest
memory.
Member Access Members of structure can be At a time, only one member of
accessed individually at any union can be accessed.
time.
Keyword To define Structure, ‘struct’ To define Union, ‘union’
keyword is used. keyword is used.
Initialization All members of structure can Only the first member of Union
be initialized. can be initialized.
Size Size of the structure is > to the Size of union is equivalent to
sum of the each member’s size. the size of the member having
largest size.
Syntax struct struct_name union union_name
{ {
structure ele 1; union ele 1;
structure ele 2; union ele 2;
———- ———-
———- ———-
structure ele n; union ele n;
}struct_variable_name; }union_variable_name;
Change in Value Change in the value of one Change in the value of one
member can not affect the member can affect the value of
other in structure. other member.

11. Files in C
Que: Explain different I/O operation on files.
Ans: A file is a named section of storage, usually on disk to hold information. „C‟ views a
file as a continuous sequence of bytes, each of which can be read individually. Each file has a
start and an end. It has a current position that typically defines the number of bytes from the
start. Program can be designed to perform read write operation on a file. But before one
performs any operation on a file, he/she need to open it and once the task is finished file
should be closed.

There are two types of files,

A text file consists of sequence of characters. Each character line in a text may be
terminated by a newline character in most of the compilers. Each alphanumeric character
stored occupies one byte.

A binary file is a series of bytes exactly as it appears in memory. They are primarily
used for non-textual data, which is used to keep the exact contents of the file. To work with
these files, one has to explicitly open these files in binary mode.

To perform any I/O operation on a file, the following sequence should be followed in a
program.
 Declare a file pointer.
 Open file through program and assign a file pointer to it
 Manipulate contents of the file using file pointer i.e. perform read/ write operations.
 Close the file.

Different I/O operations

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file. This call
will initialize an object of the type FILE, which contains all the information necessary to
control the stream. The prototype of this function call is as follows:

FILE *fopen( const char * filename, const char * mode );

Here, filename is a string literal, which you will use to name your file, and access mode can
have one of the following values:
Mode Description

 r:- Opens an existing text file for reading purpose.


 w:- Opens a text file for writing. If it does not exist, then a new file is reated. Here
your program will start writing content from the beginning of the file.
 a:- Opens a text file for writing in appending mode. If it does not exist, then a new file
is created. Here your program will start appending content in the existing file content.
 r+:- Opens a text file for both reading and writing.
 w+:- Opens a text file for both reading and writing. It first truncates the file to zero
length if it exists, otherwise creates a file if it does not exist.
 a+:- Opens a text file for both reading and writing. It creates the file if it does not
exist. The reading will start from the beginning but writing can only be appended.

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is:

int fclose( FILE *fp );

The fclose() function returns zero on success, or EOF if there is an error in closing the file.
This function actually flushes any data still pending in the buffer to the file, closes the file,
and releases any memory used for the file. The EOF is a constant defined in the header file
stdio.h. There are various functions provided by C standard library to read and write a file,
character by character, or in the form of a fixed length string.

Writing a File

Following is the simplest function to write individual characters to a stream:

int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the output stream
referenced by fp. It returns the written character written on success otherwise EOF if there is
an error. You can use the following functions to write a null-terminated string to a stream:

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

The function fputs() writes the string s to the output stream referenced by fp. It returns a non-
negative value on success, otherwise EOF is returned in case of any error. You can use int
fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.

Reading a File

Given below is the simplest function to read a single character from a file:

int fgetc( FILE * fp );


The fgetc() function reads a character from the input file referenced by fp. The return value is
the character read, or in case of any error, it returns EOF. The following function allows to
read a string from a stream: char *fgets( char *buf, int n, FILE *fp ); The functions fgets()
reads up to n - 1 characters from the input stream referenced by fp. It copies the read string
into the buffer buf, appending a null character to terminate the string. If this function
encounters a newline character '\n' or the end of the file EOF before they have read the
maximum number of characters, then it returns only the characters read up to that point
including the new line character. You can also use int fscanf (FILE *fp, const char *format,
...) function to read strings from a file, but it stops reading after encountering the first space
character.
Program to accept string from user and write it to the file

Output

Program to swap to variables


Output

Program to find greatest among two numbers

output

Program to print Fibonacci series.


output

Program to find prime number.

output

Program to find reverse of a number.


Output

Program to find whether a number is palindrome or not

Output
First run

Second run
Program to find whether a given number is Armstrong or not.

Output
First run

Second run
Program to sort array elements using bubble sort.
Output

Program to find the product of two matrices.


Output
First run

Second Run

You might also like