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

Programming in C -NOTES(1 to 5)-1

This document provides an overview of the basics of C programming, focusing on problem-solving techniques such as algorithms, flowcharts, and pseudocode. It outlines the steps involved in algorithm development, properties of algorithms, and various control structures like selection and iterative control. Additionally, it discusses building blocks of algorithms, including statements, state, control flow, and functions, along with guidelines for developing pseudocode.

Uploaded by

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

Programming in C -NOTES(1 to 5)-1

This document provides an overview of the basics of C programming, focusing on problem-solving techniques such as algorithms, flowcharts, and pseudocode. It outlines the steps involved in algorithm development, properties of algorithms, and various control structures like selection and iterative control. Additionally, it discusses building blocks of algorithms, including statements, state, control flow, and functions, along with guidelines for developing pseudocode.

Uploaded by

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

UNIT-1 I YEAR/I SEM

UNIT I BASICS OF C PROGRAMMING


Introduction to Problem Solving: Algorithm, Flowchart, Pseudocode. Programming Basics:
Applications of C Language-Structure of C program -Identifiers-Data Types – Variables-
Constants – Keywords – Operators – Input/output statements, Decision making statements -
Looping statements - Expressions-Precedence and Associativity – Expressions- Evaluation-
Type Conversions

1.1 ALGORITHMS:

Definition1:
An algorithm can be defined as “a complete, unambiguous, finite number of logical
steps for solving a specific problem”

Definition2:
An algorithm, is defined as a:“well-ordered collection of unambiguous and effectively
computable operations, that when executed, produces a result and halts in a finite amount
of time.”

Definition3:
An algorithm is defined as a finite sequence of explicit instruction that provides a set
of input values, process an output and then terminates.

Definition4:
An algorithm is a well-defined computational procedure consisting of a set of
instructions that takes some value or set of values, as input, and produces some value or
set of values, as output
algorithm
Input Output

Definition5:
An algorithm consists of a set of explicit and unambiguous finite steps which, when
carried out for a given set of initial conditions, produce the corresponding output and
terminate in a finite time. An algorithm is a step-by-step procedure for solving a problem
in a finite number of steps.

Definition6:
An algorithm is a finite number of clearly described, unambiguous “doable” steps that can be
systematically followed to produce a desired result for given input in a finite amount of time.

1
UNIT-1 I YEAR/I SEM

(STUDY ANY ONE DEFINITION WHICH IS EASY FOR

YOU) STEPS INVOLVED IN ALGORITHM DEVELOPMENT:

Step1. Identification of input: For an algorithm, there are quantities to be supplied


called input and these are fed externally. The input is to be identified first for any
specified problem.
Step2: Identification of output: From an algorithm, at least one quantity is produced, called
output for any specified problem.

Step3 : Identification the processing operations : All the calculations to be performed in order
to lead to output from the input are to be identified in an orderly manner.
Step4 : Processing Definiteness : The instructions composing the algorithm must be clear and
there should not be any ambiguity in them.
Step5 : Processing Finiteness : If we go through the algorithm, then for all cases, the algorithm
should terminate after a finite number of steps.
Step6 : Possessing Effectiveness : The instructions in the algorithm must be sufficiently basic
and in practice they can be carries out easily.
PROPERTIES OF AN ALGORITHM:
1. Finiteness: An algorithm must terminate in a finite number of steps
2. Definiteness: Each step of the algorithm must be precisely and unambiguously stated
3. Effectiveness: Each step must be effective, in the sense that it should be primitive
easily convert able into program statement) can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it can be used to solve
problems of a specific type for any input data.
5. Input/output: Each algorithm must take zero, one or more quantities
as input data produce one or more output values.

6. Well-ordered: the steps are in a clear order

7. Unambiguous: the operations described are understood by a computing agent without


further simplification
8. Effectively computable: the computing agent can actually carry out the operation

METHOD FOR DEVELOPING AN ALGORITHM


1. Define the problem: State the problem you are trying to solve in clear and concise terms.
2. List the inputs (information needed to solve the problem) and the outputs (what the
algorithm will produce as a result)
3. Describe the steps needed to convert or manipulate the inputs to produce the outputs.
Start at a high level first, and keep refining the steps until they are effectively computable

2
UNIT-1 I YEAR/I SEM
operations.
4. Test the algorithm: choose data sets and verify that your algorithm works!

APPROACHES TO ALGORITHM DESIGN:


Top down approach: In this approach, the given problem is divided into two or more
sub problems, each of which resembles the original problem. The solution of each sub
problem is taken out independently. Finally, the solution of all sub problems is combined
to obtain the solution of the main problem. The following figure shows the meaning of
top down approach.

Top down approach


Bottom-up approach : This technique is just reverse of the top down programming. In
this programming technique, the solutions of the independent sub-problems are designed
first. Then these solutions are combined or composed in a main module in order to design
the final solution of the problem. The following figure shows the bottomup approach:

Bottom up approach

Example Algorithm 1

Step 1: Start.
Step 2: Read two numbers a and b.
Step 3: Add the numbers a and b and store in sum as
sum=a+b Step 4: Display sum
3
UNIT-1 I YEAR/I SEM
Step 5: Stop

Example Algorithm 2
Step 1: Start.
Step 2: Read the three numbers A,B,C.
Step 3: Compare A and B. If A is greater, store A in MAX, else store B in MAX.
Step 4: Compare MAX and C. If MAX is greater, output “MAX is greater” else
output “C is greater”.
Step 5: Stop.

1.2 BUILDING BLOCKS OF ALGORITHMS


The building blocks of algorithm refer to the blocks such as statements, state,
control flow structures, functions, etc that are used to develop algorithms

Building blocks of algorithms:

The following are the various building blocks of algorithms:

 Statements
 State
 Control flow
 Functions
Statements

A statement is a command given to the computer that instructs the computer to


take a specific action, such as display to the screen, or collect input. A computer program
is made up of a series of statements.

Example:Statements in Python are made up of:

 Reserved words - words that have pre-defined meanings in the Java language
 Identifiers - words that are created by programmers for names of variables, functions,
classes, etc.
 Literals - literal values written in code, like strings or numbers
 Operators - special symbols that perform certain actions on their operands
 Calls to
functio
ns State
State is the information that the program manipulates to accomplish some task. It
is data or information that gets changed or manipulated throughout the runtime of a
program. The state of an algorithm is defined as its condition regarding stored data. The
stored data in an algorithm are stored as variables or constants. The state shows its
current values or contents. An instruction is a single operation, that describes a
computation. When it executed it convert one state to other. Example: state refers to the

4
UNIT-1 I YEAR/I SEM
set of variables and the values to which they refer.

Control Flow
Control flow is the order that instructions are executed in a program .A control
statement is a statement that determines the control flow of a set of instructions

Various forms of control flow:


There are three fundamental forms of control that programming languages provide-
sequential control, selection control, and iterative control.

Sequential control: It is an implicit form of control in which instructions are executed in


the order that they are written. A program consisting of only sequential control is referred
to as a “Straight-line program”. Executes statements one by one in linear order

Pseudocode Flowchart
BEGIN
statement
Statement Action1
END
Action2

Selection control: It is provided by a control statement that selectively executes


instructions. The selection structure allows the programs to make a choice between two
alternate paths, whether it is true or false. Selection control structure enables a program to
execute different statements for different conditions. These statements are known as
conditional or decision making or selection statements or branching statements
Algorithm to find biggest among 2 nos
Step1: Start
Step 2: Get two numbers as input and store it in to a and
b Step 3: If a is greater than b then
Step 4: Print a is
big Step 5: else
Step 6: Print b is
big Step 7: Stop

5
UNIT-1 I YEAR/I SEM

Conditional Statements:
The following are the conditional statements such as if, if-else,if…elif...else statement
if statement:
The if statement is used to test a condition. If the condition is true, the statements of if
block are executed otherwise the statements following the if block are executed.
Pseudocode:
IF(CONDITION)TH
EN STATEMENTS
ENDIF

Example:

6
UNIT-1 I YEAR/I SEM

if else
The if-else statement is used to execute different actions based on the condition. The if-
else statement evaluates the condition and will execute body of if only when test
condition is true. If the condition is false, body of else is executed. It is a two-way
branching statement

Pseudocode:
IF condition
THEN statement
1
ELSE
statement
2 END‐IF

Example:

7
UNIT-1 I YEAR/I SEM

if elif else

The if elif else statement is used to check multiple conditions. When series of actions are
to performed based on one-by-one decisions, then if –else-if else statements are used. It is
also called as multipath decision statement. If the condition for if is false, it checks the
condition of the next elif block. If all the conditions are false, body of else is executed.

8
UNIT-1 I YEAR/I SEM
Example

Iterative control or repetition structure: It is provided by an iterative control statement


that repeatedly executes instructions. Each is based on a given condition. Loops are used
in programming to repeat a specific block of code.
Algorithm to print first 10 natural numbers
Step1: Start
Step 2: Initailize a=0
Step 3: Check whether a<=10,then goto
step 4 Step 4: a=a+1,Print the value of a
Step 5: Else goto step 6
Step 6: stop

9
UNIT-1 I YEAR/I SEM

Looping/Iterative statements:
The following are the looping statements such as while , for
while:
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.In while loop, test expression is checked first. The body of
the loop is entered only if the test_expression evaluates to True. After one iteration, the
test expression is checked again. This process continues until the test_expression
evaluates to False.

1
0
PANIMALAR INSTITUTE OF TECHNOLOGY UNIT-1 I YEAR/I SEM

Example:

for:
The for loop in Python is used to iterate over a sequence .Iterating over a sequence is
called traversal. Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation.

11
PANIMALAR INSTITUTE OF TECHNOLOGY UNIT-1 I YEAR/I SEM

Example:

Various forms of control flow


Loop control statements:

The statements used to control or terminate from the loop are known as loop control statements.
The following are the loop control statements: break, continue

break

The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop. If break statement is inside a nested
loop (loop inside another loop), break will terminate the innermost loop. Inside the loop
body, you can use the break statement to exit the loop immediately.

12
I YEAR/I SEM

Pseudocode:
WHILE condition
Sequence of
statements BREAK
Continue
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Continue statement will be encountered, and the flow of control will leave that loop
body–but then the loop will continue with the next element in the range.

13
I YEAR/I SEM

Pseudocode:
WHILE condition
Sequence of
statements
CONTINUE
Functions
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree
of code reusing. Other Terms: methods, sub-routines, procedure.

Example:
 Function: piece of prewritten code that performs an operation
 print function: displays output on the screen
 Argument: data given to a function
Example: data that is printed to screen
Types of functions/categories of
functions:

Pre-defined functions-built in functions provided by programming languages Example: print()


in python

User-defined functions-created by user. Example fact()

Pseudocode:
BEGIN BEGIN PROCEDURE
CALL PROCEDURE statement1
END statement2
END PROCEDURE

14
I YEAR/I SEM

1.3 NOTATION

(PSEUDOCODE,FLOWCHART,PROGRAMMING

LANGUAGE)

Notation refers to the means of representing the algorithm for solving a task. The
following are the notations for representing the algorithms

 Pseudocode
 Flowchart
 Programming Languages
PSEUDOCODE
Pseudo code derived from „pseudo‟ which means imitation and „code‟ means
instruction is a generic way of describing an algorithm without using any specific
programming language related notations. Pseudocode is an artificial and informal
language that helps programmers to develop algorithms. Pseudocode can be defined as
the narrative description of the flow and logic of the intended program, written in plain
15
I YEAR/I SEM
language that expresses each step of the algorithm.The pseudocode is also called as
Program design language (PDL)

Characteristics/properties of Pseudocode:

 It is a “text based” detail (algorithmic) design tool.


 Pseudo code generally consists of short English phrases to express a specific task
 Consists of natural language-like statements that precisely describe the steps of an
algorithm or program
 Statements describe actions
 Focuses on the logic of the algorithm or program
 Avoids language-specific elements

Guidelines for developing Pseudocode:


The general guidelines for developing pseudocodes are :
• Statements should be written in English and should be programming language independent.
• Steps of the pseudocodes must be understandable.
• It should be concise.
• Each instruction should be written in a separate list and each statement in pseudocode should
express just one action for the computer.
• The keywords like READ, PRINT etc should be written in capital letter.
Pseudocode Language
Constructs The Commonly used
keywords Start:START,BEGIN
STOP:END
Input: READ, OBTAIN, GET, USERINPUT
Output: PRINT, DISPLAY, SHOW, RETURN, OUTPUT
Process/compute: COMPUTE, CALCULATE,
DETERMINE Initialise: SET, INIT
Add one: INCREMENT, BUMP
If: IF condition
THEN statement 1
ELSE
statement
2 END‐IF
While: WHILE condition
statements
END‐WHILE
For: FOR
condition
statements END‐
FOR
for subprogram BEGIN SUBPROGRAM, END SUBPROGRAM,BEGIN PROCEDURE,END
PROCEDURE
Indenting is used to show structure in the algorithm.
Advantages of Pseudocode:
 Its language independent nature helps the programmer to express the design in
16
I YEAR/I SEM
plain natural language.
 Based on the logic of a problem it can be designed without concerning the syntax or
any rule

 It can be easily translated into any programming language.


 It is compact in nature and can be easily modify.
 To develop a pseudocode it requires less time and effort than other programming tools.

Disadvantages/ Limitations of Pseudocode:


 It is unable to provide the visual presentation of the program logic.
 It has not any standard format or syntax of writing.
 It cannot be compiled or executed.
 To convert a pseudocode into flowchart is not easy
Example1: Calculate Area and Circumference of a Circle
READ radius of the circle as r
CALCULATE area== 3.14*r* r
CALCULATE circumference = 2*
3.14 *r PRINT area
PRINT circumference
Example2:Swap Two Values without Temporary Variable
READ two values say A,
B COMPUTE A=A+B
COMPUTE B= A-B
COMPUTE A= A-B
PRINT Swapped values of A, B
FLOWCHARTS
A flowchart is a pictorial representation of an algorithm that uses boxes of different
shapes to denote different types of instructions. A flowchart acts as a road map for a
programmer and guides the programmer as to how to go from the starting point to the
final point while writing a computer program. A flow chart will also helps the
programmer at the time of analyzing, debugging and testing the programs. A graphical
tool that diagrammatically depicts the steps and structure of an algorithm or program
Definition: A flowchart is a graphical representation of a program flow or an algorithm
of a problem to be solved by a computer.

Characteristics/properties of flowchart:
Flowcharts are also known as process maps to identify flow of information

 Used to identify number of steps in a process


 Used to identify branches in a process
 Used to identify inter-dependent operations
Flowchart advantages
17
I YEAR/I SEM
 Flowcharts are a graphical way of writing an algorithm.
 They are standardised: they all agree on the symbols and their meaning.
 Since a flowchart is a diagramatic representation of a program flow of a problem, it helps a
programmer to get a good visual reference of the structure of a program.

 Flowchart not only serves as a program documentation but also helps as a means
to communicate with several programmers as it is language independent.
 It serves as a useful reference or a programing aid due to its simple and efficient
method of representing the program logic of a problem.
Flowchart disadvantages
 They are hard to modify and can be time consuming.
 They need special software for symbols
 Constructing a flowchart is time-consuming
Reasons for using flowchart as a problem solving tool:
 Communication
 Effective analysis
 Proper documentation
General rules /Guidelines for drawing flowcharts

 The flowchart should be clear, neat and easy to follow.


 The flowchart should contain one Start and one Stop terminator
 Only one flow line should come out from a process symbol.

 Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.

 Only one flow line is used with a terminal symbol.

 Flowcharts are drawn so that flow generally goes from top to bottom of the page or
from left to right
 Within standard symbols, write briefly and precisely.
 Intersection of flow lines should be avoided.
 It is useful to test the validity of the flowchart with normal/unusual test data.

 The symbols of the flowcharts are always labeled

18
I YEAR/I SEM

Commonly used flowchart symbols:

Predefined process-To show process or procedure that is previously specified.

Preparation-To show for loop and set-up process

Example1:Flowchart for calculating simple interest

19
I YEAR/I SEM

Example2: Flowchart to find the largest of the two given numbers.

Finding the Largest of two Numbers

Difference between Algorithm, Pseudocode and

Flowchart:
S.no Algorithm Pseudocode Flowchart
1 An algorithm is a A tool to document and A tool to document and
sequence of instructions represent the algorithm represent the algorithm
used to solve a particularReadable, formally Graphical representation
problem styled English like of the algorithm
representation of the
algorithm
2 Provides the logic of the Uses programming Uses graphical symbols
program in steps language constructs
3 Does use symbols and Use keywords Use standardized
programming language symbols
constructs
4 Set of instructions Artificial and Informal A graphical way of
language writing pseudocode

Programming Language:

The programming language is the medium through which the problems to be solved by
computer can be represented in the form of programs or set of instructions. The computer
executes the set of instructions written in a particular language to produce the desired
result. A programming language consists of a set of characters, symbols, and usage rules
that allow the user to communicate with computers. In a simple form it can be defined as -20
any notation for the description of algorithm and data structure may be termed as a
programming language.
I YEAR/I SEM

Low Level Language:

 A low-level language is a programming language that deals with a computer's hardware


components and constraints. It has no (or only a minute level of) abstraction in
reference to a computer and works to manage a computer's operational semantics.
 A low-level language may also be referred to as a computer‟s native language.
 Machine language and assembly language are popular examples of low-level
languages.

High Level Language:


 A high-level language (HLL) is a programming language such as C, FORTRAN, or
Pascal that enables a programmer to write programs that are more or less
independent of a particular type of computer.
 Such languages are considered high-level because they are closer to human
languages and further from machine languages
There are different levels of programming language as follows :
• Machine language
• Assembly language
• High level language

i) Machine language : The machine language programs were written using the digit 0 and 1.
The instruction in machine language consists of two parts. The first part is an operation which
tells the computer what operation is to be performed. The second part of the instruction is
operand, which tells the computer where to find or store the data after applying the operation
Advantages :
Translation free : Machine language is directly understand by the computer so it does not
need any translation. Otherwise, if a program is developed in high level language then it
has to be translated into the machine language so that the computer can understand the
instructions.
High speed : The application developed in the machine language are extremely fast
because it does not require any conversion.
Disadvantages :
Machine dependent : Program developed in one computer system may not run on an
another computer system.
Complex language : This language was very difficult to understand and programming
techniques were tedious.
Error prone : Writing machine language programs, a programmer has to remember all the
opcodes and memory locations, so machine language is bound to be error prone.
ii) Assembly language : Assembly language is not a single language, but a group of language. An
assembly language provides a mnemonic instruction, usually three letters long, corresponding to
each machine instruction. The letters are usually abbreviated indicating what the instruction
does, like ADD for addition, MUL for multiplication etc. The assembly language allows the
programmer to interact directly with the hardware. Each line of assembly language program
consists of four columns called fields.
The general format of an assembly language instruction is :
[Label] <Opcode> <Operands> [; Comment]
21
e.g. BEGIN ADD A, B ; Add B to A
I YEAR/I SEM

Advantages:
Easy to understand and use : Assembly language uses mnemonics instead of using
numerical opcodes and memory locations used in machine language, so it is easy to
understand and use.
Less error prone : Assembly language is less error prone and it provides better facility to
locate errors and correct them.
Faster : It is much faster and use less memory resources than the high level language.
Disadvantage :
• Assembly language programs are machine dependent.
• Assembly language is complex to learn.
• A program written in assembly language is less efficient than machine language because every
assembly instruction has to be converted into machine language.
iii) High level language : COBOL, FORTRAN, PASCAL and C are the examples of high level
languages. High level languages are similar to English language. Programs written using these
languages may be machine independent. A single instruction of a high level language can
substitute many instructions of machine language and assembly language. Using the high level
language complex software can be design.
Advantages :
• Readability : Since high level languages are similar to English language so they are easy to
learn and understand.
• Programs written in high level languages are easy to modify and maintain.
• High level language programs are machine independent.
• Programs written in high level language are easy to error checking.
Disadvantages :
Programs written in high level language has to be compile first for execution of the
program. This step of compilation increases the execution time of an application.
Moreover, the programs occupies more memory space during the execution time.
Another main drawback of HLL programs is - its poor control on the hardwares.
Language Translators
The language translators or also called language processors are the programs which
converts the high level language programs into the machine language programs for
execution.
Types of Language Translators:
 Compiler
 Interpreter
 Assembler
Compiler : A compiler is a program that can translates an higher level language program
to its machine form. This language processor translates the complete source program as a
whole into machine code before execution. Here the source program means – the program
that is written by the programmer and the translated program is called a object program or
object code. Examples: C and C++ compilers. If there are errors in the source code, the
compiler identifies the errors at the end of compilation. Such errors must be removed to
enable the compiler to compile the source code successfully.

22
I YEAR/I SEM

Interpreter: It is a language processor whose working principle is different from


compilers. It translates each statement of source program into machine code and executes it
immediately before translating the next statement. If there is an error in the statement the
interpreter terminates its translating process at that statement and displays the error
message. The python is an example of interpreter.

Assembler : We have already known that - assembly language is the symbolic


representation of a computer‟s binary encoding – machine language . Assembly language
is more readable than machine language because it uses symbols instead of bits. A program
called an assembler that translates assembly language into binary instructions or machine
language. An assembler reads a single assembly language source file and produces an
object file containing machine instructions.

Difference between compiler and interpreter 23

S.no Compiler Interpreter


I YEAR/I SEM

1 Translates High level language Translates each instruction one by


into target language in binary form one from HLL into low level
machine language
2 Reads the whole program first and Reads each instruction one by one
then translates it into the machine and translate each instruction
language immediately one by one

3 It is a faster process It is a slow process because the


interpreter has to wait while each
instruction is being translated
4 Examples: C,C++ Examples :Python
1.4 ALGORITHMIC PROBLEM SOLVING:

Problem:
The problem can be defined as the gap between actual and desired conditions.

Steps involved in problem solving:


1. Identify the Problem:
You identify the problem before you start solving it .If you don‟t know what the problem
is, you cannot solve it.
2. Understand the Problem:
You must understand what is involved in the problem before you continue towards the
solution. You cannot solve the problem if you do not know the subject. For example solve
a problem involving accounting you must know accounting. Thus before start of solution
you understand knowledge base of the person or machine for whom you are solving the
problem.
3. Identify alternative ways to solve the problem:
Find out different alternatives for solving problem. Alternatives solutions must be
acceptable ones.
4. Select the best way to solve the problem from the list of alternative solutions:
In this step you identify and evaluate the pros and cons of each possible solution before
selecting the best one for doing this, you should have selection criteria for the evaluation
which will serve guidelines for evaluating each solution.
5. List instructions that enable you to solve the problem using the selected solution:
List step by step instruction from knowledge base for solving the problem using the
selected solution. No instruction can be used unless the individual or the machine can
understand it.
6. Evaluate the solution:
Evaluation of solution means to check its result to see if it is correct, and to see if it
satisfies the needs of the person with the problem. If the result is unsatisfactory, restart the
process. If any of these six steps are not completed well, the results may be less than
desired.

Algorithmic Problem solving: 24


Algorithmic problem solving means solving the problem by means of algorithm.
I YEAR/I SEM

Algorithmic problem solving steps:


 Understanding the problem
 Ascertain the capabilities of the computational device
 Exact /approximate solution
 Decide on the appropriate data structure
 Algorithm design techniques
 Methods of specifying an algorithm
 Proving an algorithms correctness
 Analysing an algorithm
Understanding the problem:
The problem given should be understood completely. Check if it is similar to some standard
problems & if a Known algorithm exists. Otherwise a new algorithm has to be developed
Ascertain the capabilities of the computational device:
Once a problem is understood, we need to know the capabilities of the computing device
this can be done by knowing the type of the architecture, speed & memory availability.

Exact /approximate solution:


Once algorithm is developed, it is necessary to show that it computes answer for all the
possible legal inputs. The solution is stated in two forms, exact solution or approximate
solution. Examples of problems where an exact solution cannot be obtained are i) Finding a
square root of number. ii) Solutions of nonlinear equations.
Decide on the appropriate data structure:
Some algorithms do not demand any ingenuity in representing their inputs. Some others are
in fact are predicted on ingenious data structures. A data type is a well-defined collection of
data with a well-defined set of operations on it. A data structure is an actual
implementation of a particular abstract data type.

Algorithm design techniques:


Creating an algorithm is an art which may never be fully automated. By mastering these
design strategies, it will become easier for you to develop new and useful algorithms.
Dynamic programming is one such technique.

Methods of specifying an algorithm:


There are mainly two options for specifying an algorithm: use of natural language or
pseudocode & Flowcharts. A Pseudo code is a mixture of natural language & programming
language like constructs. A flowchart is a method of expressing an algorithm by a
collection of connected geometric shapes

Proving algorithms correctness:


Once algorithm is developed, it is necessary to show that it computes answer for all the
possible legal inputs .We refer to this process as algorithm validation. The process of
validation is to assure us that this algorithm will work correctly independent of issues25
concerning programming language it will be written in.
I YEAR/I SEM

Analysing algorithms:
As an algorithm is executed, it uses the computers central processing unit to perform
operation and its memory (both immediate and auxiliary) to hold the program and data.
Analysis of algorithms and performance analysis refers to the task of determining how
much computing time and storage an algorithm requires

INTRODUCTION TO PROGRAMMING PARADIGMS:


Programming paradigms are a way to classify programming languages based on their features.
Languages can be classified into multiple paradigms.
Major programming paradigms are:
1. Imperative
2. Logical
3. Functional
4. Object-Oriented
Imperative programming paradigms:
- In imperative programming paradigm , Computations are performed through a guided
sequence of steps, in which the variables are referred to or changed.
- The order of the steps is crucial, because a given step will have different consequences
depending on the current values of variables when the step is executed.
- Popular programming languages are imperative more often than they are any other
paradigm studies in this course. There are two reasons for such popularity:
 The imperative paradigm most closely resembles the actual machine itself, so the
programmer is much closer to the machine;
 Because of such closeness, the imperative paradigm was the only one efficient
enough for widespread use until recently.
Advantages
o Efficient
o close to the machine
o Popular
o Familiar.
Disadvantages
o The semantics of a program can be complex to understand or prove.
o Side effects also make debugging harder;
o Abstraction is more limited than with some paradigms;
o Order is crucial, which doesn't always suit itself to problems.
Logical programming paradigms: 26
- The Logical Paradigm takes a declarative approach to problem-solving.
I YEAR/I SEM

- Various logical assertions about a situation are made, establishing all known facts.
- Then queries are made. The role of the computer becomes maintaining data and logical
deduction.
- A logical program is divided into three sections:
 a series of definitions/declarations that define the problem domain
 statements of relevant facts
 statement of goals in the form of a query
Advantages:
The advantages of logic oriented programming are
o The system solves the problem, so the programming steps themselves are kept to a
minimum;
o Proving the validity of a given program is simple.
3. Functional programming paradigms:
- The Functional Programming paradigm views all subprograms as functions in the
mathematical sense-informally, they take in arguments and return a single solution.
- The solution returned is based entirely on the input, and the time at which a function is
called has no relevance.
- The computational model is therefore one of function application and reduction.
Advantages:
o Higher level of abstraction
o The lack of dependence on assignment operations
o Possess referential transparency.
Disadvantages
o Perhaps less efficiency
o Problems involving many variables or a lot of sequential activity are sometimes easier
to handle imperatively or with object-oriented programming.
4. Object-Oriented
- Object Oriented Programming (OOP) is a paradigm in which real-world objects are
each viewed as separate entities having their own state which is modified only by built
inprocedures, called methods.
- Because objects operate independently, they are encapsulated into modules which
contain both local environments and methods. Communication with an object is done
by message passing.
- Objects are organized into classes, from which they inherit methods and equivalent
variables. The object-oriented paradigm provides key benefits of reusable code and
code extensibility.
Benefits and Features:
o A new class (called a derived class or subclass) may be derived from another class
(called a base class or superclass) by a mechanism called inheritance. The derived
class inherits all the features of the base class: its structure and behavior(response to
27
messages.
o Inheritance gives OOP its chief benefit over other programming paradigms - relatively
I YEAR/I SEM

easy code reuse and extension without the need to change existing source code.Also,
encapsulation and information hiding are inherent benefits of OOP.
INTRODUCTION TO C PROGRAMMING:
- C is a general-purpose computer programming language developed in 1972 by Dennis
M. Ritchie at the Bell Telephone Laboratories to develop the UNIX Operating System.
- C is also called mother Language of all programming Language. It is the most widely
use computer programming language.
- All other programming languages were derived directly or indirectly from C
programming concepts.
- This language is used for develop system software and Operating System.
Features of C:

Simplicity:
- It is very easy to understand.
Portability:
- It is the concept of carrying the instruction from one system to another system
Powerful:
- C is a very powerful programming language, it have a wide verity of data types,
functions, control statements, decision making statements, etc
Structure oriented:
- Structure oriented programming language aimed on clarity of program, reduce the
complexity of code, using this approach code is divided into sub-program/subroutines.
These programming have rich control structure.
Modularity
- In c programming we can break our code in subprogram.
Middle level language:
- C programming language can supports two level programming instructions with the
combination of low level and high level language that's why it is called middle level
programming language
28
Compiler based:
- C is a compiler based programming language that means without compilation no C
I YEAR/I SEM

program can be executed


Syntax based language
- C is a strongly tight syntax based programming language.
Efficient use of pointers
- Pointers is a variable which hold the address of another variable, pointer directly direct
access to memory address of any variable due to this performance of application is
improve
Uses(Applications) of C language:
 To Design Operating system
 To Design Language Compiler and Interpreter
 To Design Database
 Language Interpreters
 Utilities
 Network Drivers
 Assemblers
 UNIX Kernel is completely developed in C Language.

STRUCTURE OF A ‘C’ PROGRAM


Simple C Program:
/* Simple C program to display the text */
#include<stdio.h>:
int main()
{
printf(“good morning\n”);
return(0);
}
/*……..*/
A comment starts with star and asterisk /* and ends with asterisk and start */ .
comment lines used to give description and it is ignored by compiler during execution.
#include<stdio.h>
This <stdio.h> is called header file that has functions used for reading input and
generating output.
In order to use printf function, we need to include the required file in our program
using #include preprocessor.
int main()
C program consists of functions with required main() function as a entry point of
program. It is where, actual execution starts.
A program can have only one main function and any number of sub functions.
Curly brackets { …. }
Indicates block of code.
29
we can have statements inside the brackets to determine what the function does when
executed.
I YEAR/I SEM

printf(“good morning\n”);
printf is a build-in functions which is used to display output in the screen.
\n is called escape sequence to go to next line It always begin with \ (back slash).
Semicolon(;)
It is used to terminate the statement.
return(0);
- This statement terminates the main function.
- Returns the value 0 to the operating system indicating Successful completion of
program.
- Any other number indicates that the program is failed.

Fig, Structure of C program


Documentation Section
o This section consists of set of comment lines which gives the name of programmer and
other details like time and date of writing the program.
o Comment lines used to give description and it is ignored by compiler during
execution.
o Documentation section helps anyone to get an overview of the
program. There are two types of comments.
Single line comment (// program for addition)
Multiple line comment(/*...........*/)
Link Section
- The link section consists of the header files of the functions that are used in the
program.
- It provides instructions to the compiler to link functions from the system library.
- Some of the header files are,
#include<stdio.h>
#include<conio.h> 30
#include<math.h>
I YEAR/I SEM

Here, #include is the preprocessor directive.


Definition Section
All the symbolic constants are written in definition section.
Macros are known as symbolic constants.
Ex: #define PI 3.14
Global Declaration Section
The variables that are used in more than one function throughout the program are called
global variables. Global variables declared outside of all the functions.
main() Function Section
Every C program must have one main() function, which specifies the starting point of ‘C’
program.
Main function contains two parts,
i. Declaration part
ii. Executable part
 The declaration part contains all the variables that are used in executable part.
 These two parts must be written in between the opening and closing braces.
 Each statement in the declaration and executable part must end with a semicolon (;).
 The execution of program starts at opening braces“{”and ends at closing braces“}”.
Subfunction(Sub program) Section
Subprogram section contains all the user defined functions that are placed after the main
function.

‘C’ CHARACTER SET


Character set is a set of alphabets, letters and some special characters that are valid in C
language.
The basic character set of C language includes,
2 types :
(i) Source Character Set :
Uppercase letters: A, B,C….Z.
Lowercase letters: a, b, c……z.
Digits: 0 to 9.
Special characters: , . : ; “ # % & ( ) { } [ ] | \/ _ ^~ +,-,~&,!,/,\,*@,etc.
White spaces characters int age; // balnk space between int and age is ignored by
compiler. It is used to distinguish the aqw.
(ii) Execution Character set:
Horizontal tab \t
Vertical Tab \v
New line character \n
Null Character \0
31
I YEAR/I SEM

C TOKENS:
 C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.

IDENTIFIERS:
Identifiers are the name used to identify entities like variable, function, array, structure or any
other user-defined item.
Identifier must be unique.
They are created to give unique name to an entity to identify it during the execution of the
program.
Rules for naming an Identifier
 Identifier name in C can have letters, digits or underscore(_).
 The first character of an identifier name must be a alphabet (a-z, A-Z),underscore( _ ).
 The first character of an identifier cannot be a digit.
 Keywords are not allowed to be used as Identifiers.
 No special character (except underscore) blank space and comma can be used in
Identifier name.
KEYWORDS
 Keywords are reserved words that have a particular meaning in C language.
 The meaning of key word is predefined. These meaning of the keyword cannot be
changed.
 There are total 32 keywords in C language.

VARIABLES:
 It is a name given to the memory location.
 In programming, a variable is a container (storage area) to hold data.
 To indicate the storage area, each variable should be given a unique name called
identifier. 32
I YEAR/I SEM

Rules to define variable name


 Variable name in C can have letters ( A – Z ), ( a – z ), numbers and underscore (_),
Digits ( 0 – 9 )
 No Special Symbols like blank space and Commas are allowed in variable name.
 First Character should be alphabet or underscore and not a number.
 Variable name should not be keyword.
 The maximum number of character(31 characters) is allowed in a variable and it
depends on a compiler.
2 steps:
(i) variable declaration
- Declaration of variables must be done before they are used in the program.
- Declaration does two things.
It tells the compiler , the name of the variable.
It specifies what type of data the variable will hold.
Syntax:
datatype variable;
Example:
int
number;
char a;
float price;
char name[20];
(ii) variable initialization
- Initialization is done using assignment operator(=). Also, we can assign the value to the
variable during declaration itself.
If no input values are assigned(initialized) by the user , then the system will give a
default value to the allocated memory which is called garbage value.
Example,
int a=20;

L-Value: R-Value
L- Value Is An Object Locator. R-value refers to ‘Read Value’.
L-Value Stands For Left Value
The L-Value Could Legally Stand On The Left Side R-value can be anything of following:
Of An Assignment Operator. 1.Variable
For Example: Mark=20; // 2. Function
The L- Value Should Be A Variable. 3. Constant
Eg, 33

num=20; //constant R value


I YEAR/I SEM

num=20+20; //constant R value


Expression

L value cannot be a constant and cannot be a datatype.


Eg, 5=num; //Error
int=num;
Example:
Addition of two numbers: Output:
#include< stdio.h> Sum is 100
int main()
{
int a,b,c; //Variable declaration
a=50; //Assigning values to variables
b=50;
c=a+b;
printf("sum is %d",c);
return(0);
}
Variable definition=variable declaration + memory reservation

Scope of variable(Types of variable):


Variable Scope is a region in a program where a variable is declared and used.
i. Local Variable - Variables that are declared inside a function or a block are
called local variables and are said to have local scope.
We can use (or access) a local variable only in the block or function in which it is
declared. It is invalid outside it.
ii. Global Variable:- Variables that are defined outside of all the functions and are
accessible throughout the program are global variables.
It is declared above the main function.
Example:(program using local and gloab Output:
variable) Value of a : 10
#include<stdio.h> Value of b : 20
int a=10; // global variable
int main()
{
int b=20; // local variable
printf("Value of a : %d\n",a); 34
printf("Value of b : %d\n",b);return(0);}
I YEAR/I SEM

DATA TYPES :
 Data types determines the possible values that an identifier can have and the valid
operations that can be applied on it.
 The type of a data determines how much space it occupies in storage.
 In C Language, data types are broadly classified as

Basic/Primitive data types:


1. Character – char
2. Integer - int
3. Floating point – float
4. Double– double
5. No value available – void

1. Basic(Primitive) data types


Integer type:
 Integers are whole numbers that can have both positive and negative values but
no decimal values.
 Keyword for integer is int.
 Size of en integer is 2 bytes or 4 bytes.
 Size of the datatype change with respect to the processor used.
Type Size(bytes) Range
int or signed int 2 -32,768 to32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
long int or signed long int 4 -2,147,483,648to2,147,483,647
unsigned longint 4 0 to4,294,967,295
Floating type 35
 Float data type is used to store real numbers.
I YEAR/I SEM

 Key word is float. The size of floating point number is 4 bytes.


 If the accuracy is not sufficient in floating point, the double data type can be used to
define the number.
 Eg, float height=5.5
Range values are given for 16 bit processor.
Type Size(bytes) Range
Float 4 3.4E-38 to3.4E+38
Double 8 1.7E-308 to 1.7E+308
longdouble 10 3.4E-4932to1.1E+4932
Character type
- Character denotes any alphabet, digit or special symbol to represent information.
- Key word is char.
- Size of character is 1 byte. Eg, char a=‘h’;
Type Size(bytes) Range
char or signed char 1 -128 to127
unsigned char 1 0 to255
void type
- void means no value.
- This is usually used to specify the type of functions.
Data type modifiers:
It is nothing but modifying the memory space allocated to the variable.
Types:
1. Signed(signed)
2. Unsigned(unsigned)
3. Short(short)
4. Long(long)
Integers and floating point variables can hold both negative and positive values.
Sign modifiers Size modifiers
Signed Unsigned short long
signed keyword unsigned keyword In general int data type It is used to increase
accepts both negative accepts only occupies different the size of the current
or positive value. positive values. memory spaces for a data type to 2 more
.(It is the default different operating bytes.
integer data type). system;
To allocate fixed
memory space short
keyword can be used.
Example: Example: For example: For Example:
signed int number; unsigned int rate; short int a; long int a;
or 36
int number;
I YEAR/I SEM

2. User-defined Data Types


The C language provides flexibility to the user to create new data types. These newly created
data types are called user-defined data types. The use-defined data types in c can be created by
using:
1. typedef
2. Enumeration
typedef:
- typedef keyword is used to give new name to the existing data type..
Syntax:
typedef datattype
variable
In the below program, rollno is the variable name (alias)given to the existing datatype int. So,
after this type definition, roll no can be used instead of datatype int.
Example (using typedef): Output:
#include<stdio.h> Roll number1 is 4001
int main() Roll number2 is 4002
{
typedef int rollno;
rollno num1 = 4001,num2 = 4002;
printf("Roll number1 is %d\n",num1);
printf("Roll number2 is %d\n",num2); return(0); }

Enumerated data type:


- enum is a keyword used.
- It is mainly used to assign the names to integral constants ,as the names make a
program easy to read and maintain.
- The compiler assigns integer values starting from 0 and further increments by 1 for all
enum values(contants values ).
- We can also assign value to the enum constants if we need.
Syntax:
enum variable {value1, value2,.....Value n};
Default Numeric value assigned to first enum value is “0”.
Example: Example(using Example 2:
enum datatype): #include<stdio.h>
#include<stdio.h> main()
main() {
{ enum
enum month{JAN, FEB, month{JAN,FEB=5,MARCH,A
MARCH, APRIL, MAY}; PRIL=2, MAY,JUNE=3,
enum month m1; JULY}; 37
m1=APRIL; enum month m1;
I YEAR/I SEM

printf("%d",m1);} m1=MAY;printf("%d",m1);}
Output: Output:
3 3
Explanation: Explanation:
In this example, we Integers are assigned to enum
declared “m1” as the constants.
variable and the value of
“APRIL” is allocated to
m1, which is 3.
3. Derived data types
These data types are derived from the basic data types. Derived data types available in c are:
Array
Structure
Union
Pointer
Type conversion (Type casting):
- A type cast is basically a conversion from one type to another.
There are two types of type conversion:
Implicit Type Conversion (Also known as ‘automatic type conversion’):
- This Implicit conversion is done by the compiler on its own, without any
knowledge to the user.
- Generally type casting takes place when in an expression is having more than one
data type in it.
- Here, It is best practice to convert lower data type to higher data type to avoid
data loss. Because, Data will be truncated when the higher data type is converted
to lower. For example, if a float is converted to int, data which is present after
the decimal point will be lost.
- Hence, Compiler convers all operands into datatype of the largest operand.
bool-> char-> short int -> int -> unsigned int -> long -> unsigned -> long long ->float ->
double -> long double
Example 1:(implicit typecasting) Example 2: :(implicit typecasting)
#include<stdio.h> #include <stdio.h>
main() main() {
{ int i = 17;
int a=10; char c = 'c';
float b=6.1; float sum;
float c; sum = i + c; /* ascii value is 99 */
c=a+b; /*integer value 10 is converted to float value as printf("%f\n", sum );
10.0 automatically*/ }
printf("%f",c); Output:
38
} 116.000000
I YEAR/I SEM

Output:
16.100000
Explicit Conversion(Type casting):
The type conversion performed by the programmer by specifying the data type in the
expression.
Data type should be mentioned before the variable name or value.
Syntax:
(data type)expression
Example1: Example2: :(Explicit typecasting)
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int x=13, y=5 ; int x=13, y=5 ;
float z; float z;
z=x/y; // here, quotient is int datatype and it is z=(float)x/y; // int data type is converted to
stored in float variable float and float value(quotiemt) is stored in
printf("%f",z); float variable
} printf("%f",z);
Output: }
2.000000 Output:
2.600000

STORAGE CLASS:
A storage class defines the scope (visibility) and life-time of variables.
Scope - Where to store a variable (Storage area of variable)
Lifetime- How long the variable can be stored in the memory(
alive) The following storage classes are most often used in C
programming.
1.auto 2.static
3.extern 4.register
A variable should be declared in any one of these four storage class.
1. auto storage class:
- auto is the default storage class.
- It is stored in RAM(main memory)
Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It will be alive only inside the block of code where it is declared.
Default value is Garbage Value

39
Syntax: Example:
auto data_type variablename; (or) auto int a;
I YEAR/I SEM

40
I YEAR/I SEM

data_type variable; int a;


(both are same since auto is
default storage class )
To print the value using auto storage Output:
class: Value of a is: 11
#include<stdio.h> Value of a is: 11
int main() Value of a is: 11
{
increment();
increment();
increment();
}
int increment()
{
auto int a=10;
a++;
printf("Value of a is: %d\n", a);
}

2. Static Storage class:


Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It can be used throughout the program. That means, the variable will be alive
until the program completes its execution.
Default value is 0.
Syntax: Example:
static data_type variablename; static int a;
To print the value using static storage Output:
class: Value of a is: 11
#include<stdio.h> Value of a is: 12
int main() Value of a is: 13
{
increment();
increment();
increment();
}
int increment()
{
static int a=10;
a++;
printf("Value of a is: %d\n", a);
}
3. Extern Storage Class:
- This process is similar to storing global variable.
- When extern keyword is used, the compiler will come to know that somewhere in the 41
program , variable is declared or initialized(may be outside or inside the function,etc).
I YEAR/I SEM

42
I YEAR/I SEM

Scope: Variable can be accessed from anywhere in the program.


Lifetime: It can be used throughout the program. That means, the variable will be alive
until the program completes its execution.
Default Value is 0.
Note: Memory occupied by the variable will be released only after completion of the program.
Syntax: Example:
extern datatype variablename; extern a=10;
Printing the value of the variable using extern storage class.
#include<stdio.h> Output:
int main() 3
{ 10
int a=3;
extern int b;
printf("%d\n",a);
printf("%d\n",b);
}
b=10;

4. Register Storage Class:


- Register variables are also local variables, but stored in register memory.
Whereas, auto variables are stored in main CPU memory.
- These data objects will have a local life time.
- Theyhave to be initialized implicitly otherwise they will have a garbage value.
Advantages: The register variables are faster than remaining variables, because register
variable are stored in register memory in the processor and not in main memory..
Limitation: But, only limited variables can be used as register since register size is very low.
(16 bits, 32 bits or 64 bits).
Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It will be alive only inside the block of code where it is declared.
Default value is Garbage Value
Only difference between auto and register the storage place(RAM/Register)

Syntax: Example:
register data_type variablename; register int a;
Printing the value of the variable using register storage class Output:
#include<stdio.h> Value of a is 11
int main() Value of a is 11
{ Value of a is 11
increment();
increment(); 43
increment();
I YEAR/I SEM

}
int increment()
{
register int a=10; a+
+;
printf("Value of a is: %d\n", a);
}
Properties of Storage Class:

CONSTANTS (LITERALS):
Constants are the values that cannot be changed during the execution of a program.
Constant is a fixed value which may be an integer, floating point number, character or a string.
Types of constants:

 Integer constants:
- Integer constants are integer values like -1, 2, 8 without any decimal point.
- It can be either positive or negative. If no sign proceeds an integer is assumed to be
positive.
There are three types of integer constants in C language:
- Decimal constant (base 10)
- Octal constant (base 8) 44
- Hexadecimal constant (base 16)
I YEAR/I SEM

45
I YEAR/I SEM

 Floating-point constants:
- Floating point constants can be written in fractional form or exponential form. Floating
point constant are values like -23.1, 12.8, -1.8e12.
- The floating point constant in an exponential form has two parts: The mantissa part
and the exponent part. Both parts are separated by e or E.

 Character constants:
- Character constants can have one character enclosed within single quotes.
- For example: 'a', 'l', 'Y', 'A' etc.
Escape Sequences
- C supports some special character constants that are used in output functions.
- Escape sequence consists of a backward slash (\) followed by a character.

Escape Sequences Character


\n Newline
\a Alert
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
 String constants
- String constant can have group of characters enclosed within double quotes.
For example: “hai”, “welcome”
Declaring a variable as constant:
Syntax:
const datatype variable = constant
Example:
const float PI=3.14;
Program using const Output To find area of rectangle Output
keyword: error using const keyword. area : 70
#include<stdio.h> [const value #include <stdio.h>
int main() cannot be changed. int main()
{ { 46
const int a=10;
I YEAR/I SEM

printf("%d",a); const int LENGTH = 10;


a=20; const int WIDTH = 5;
return(0); int area;
} area = LENGTH * WIDTH;
printf("area : %d", area);
return(0);
}

OPERATORS IN C:
Operands:
 An operand specifies an entity on which an operation is to be performed.
 An operand can be a variable name, constant, a function call.
Operators:
 Operators are special symbol that tells the compiler to perform specific mathematical or
logical operations.
 Operator specifies the operation to be applied to its operands.
CLASSIFICATION OF OPERATORS:
The operators in c are classified on the basis of the following criteria:
1. The number of operands on which an operator operates.
2. The role of an operator.
Classification based on Number of Operands
Based upon the number of operands on which an operator operates,operators are classified
as,
Unary operator: Binary operator ternary operator
A unary operator operates Binary operator operates Ternary operator operates on three
on only one operand. on two operands. operands. (Conditional operator)
Eg, Eg: Eg,
-3. Here the – is an unary 2-3. Here (-) acts as a ?: is a ternary operator
minus operator. binary operator.
Classification based on role of operator
Based upon their role operators are classified as:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bitwise operators
6. Increment /Decrement operators
7. Conditional operator
8. Special operators
Arithmetic operators
Arithmetic operations like addition, subtraction, multiplication, divisions, etc. The arithmetic
47
operators available in c are given here.
I YEAR/I SEM

Operato Description Eg Program Output:


r
+ adds two operands a+b #include<stdio.h> 13
- subtract second operands from a-b int main() -3
first { 40
* multiply twooperand a*b int a=5,b=8; 0
/ divide numerator by denominator, a/b printf("%d\n",a+b); 40
gives quotient as result printf("%d\n",a-b);
% dividenumerator bydenominator, a%b printf("%d\n",a*b);
gives remainder asresult printf("%d\n",a/b);
printf("%d\n",a*b);
}
Assignment Operators
A variable can be assigned a value by using an assignment operator. The assignment operators
are available in c are given below.
Operator Description Example
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to a+=b is same as
left a=a+b
-= subtracts right operand from the left operand and assign the a-=bissameas a=a-b
result to left operand
*= multiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=bissameas a=a/b
result to left operand
%= calculate modulus using two operands and assign the a%=b is same as
result to left operand a=a%b
Example: Output:
#include <stdio.h> c=5
int main() c=10
{ c=5
int a = 5, c;
c=25
c = a;
printf("c=%d \n", c=5
c); c += a; c=0
printf("c=%d \n",
c); c -= a;
printf("c=%d \n", c);
c *= a;
printf("c=%d \n", c);
c /= a; 48
printf("c=%d \n", c);
I YEAR/I SEM

c %= a;
printf("c=%d \n", c); return 0;
}

Relational operators:
- Relational operators are used to check the conditions.
- If the relation is true, it returns 1; if the relation is false, it returns value 0.
- The operand may be variables, constants or expressions.
Operator Description Example program Output
:
== Check if two operand are equal #include<stdio.h> 0
!= Check if two operand are not equal. int main() 0
> Check if operand on the left is { 1
greater than operand on the right int a=5,b=8; 0
< Check operand on the left is smaller printf("%d\n",a==b); 1
than right operand printf("%d\n",a>b); 1
>= check left operand is greater than or printf("%d\n",a<b);
equal to right operand printf("%d\n",a>=b);
<= Check if operand on left is smaller printf("%d\n",a<=b);
than or equal to right operand printf("%d\n",a!=b);
}
Logical operators:
- Logical operators are used to combine the results of two or more conditions. C has the
following logical operators.
Op Description Example a=5, b=2
erator
&& Logial AND. True only if all operands are true ((a == 5) && (b > 5)) equals to 0.
|| Logical OR. True only if either one operand is true ((a == 5) || (b > 5)) equals to 1.
! Logical NOT. True only if the operand is 0 ! (a == 5) equals to 0.
Note: 1 represents true and 0 represents false.
Example: Output:
#include <stdio.h> 0
int main() 1
{ 1
int a=5,b=7,c=2;
printf("%d\n",((a==b)&&(a==c)));
printf("%d\n",((a==b)||(a>c)));
printf("%d\n",(!(a==b)));
}
Bitwise operators:
- Bitwise operators perform manipulations of data at bit level.
- It operates on individual bits of the operands.
49
- Bitwise operators are not applicable for float or double data types.
I YEAR/I SEM

- The Truth table for &, | and ^ operation.


A B A &B A| B A^B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Assume A = 60 and B = 13 .
In binary format, A= 0011 1100 and B = 0000 1101
Operator Description A= 0011 1100 and B = 0000 1101
& Bitwise AND (A & B) = 12, i.e., 0000 1100
| Bitwise OR (A | B) = 61, i.e., 0011 1101
^ Bitwise exclusive OR (A ^ B) = 49, i.e., 0011 0001
~ Bitwise Complement (~A ) = -60, i.e,. 1100 0100 in 2's
complement form.
<< left shift A << 2 = 240 i.e., 1111 0000
>> right shift A >> 2 = 15 i.e., 0000 1111

Increment operator/decrement operator:


Increment operator:
- Increment operator is used to increment the value by adding 1.
- The value of i++ is equal to i=i+1.
Syntax:

Increment operator can be classified into two types.


pre increment operator
post increment operator
Pre increment operator: Post increment operator:
First the value of operand is The value of operand is used for the
incremented by 1 and then it is used evaluation of the expression and then it
for evaluation of the expression. is incremented.
For example: ++i For example: i++.
Decrement operator:
- Decrement operator is used to decrement the value by subtracting 1.
- The value of i-- is equal to i=i-1.
Decrement operator can be classified into two types.
pre decrement operator
post decrement operator 50
I YEAR/I SEM

Pre decrement operator: .Post decrement operator:


First the value of operand is The value of operand is used for the
decremented by 1 and then it is used evaluation of the expression and then it
for evaluation of the expression. is decremented.
For example: --i For example: i--.

Example: Preincrement: Postincrement:


#include <stdio.h> #include<stdio.h> #include<stdio.h>
int main() int main() main()
{ { {
int i=10; printf("%d\ int x,i; int x,i;
n",i++); i=10; i=10;
printf("%d\n",++i); x=++i; printf("x: x=i++;
printf("%d\n",i--); %d\n",x); printf("x: %d\n",x);
printf("%d\n",--i); printf("i:%d\n",i); printf("i: %d\n",i);
} return(0); return(0);
Output: } }
10 Output Output:
12 : x:11 x: 10
12 i:11 i: 11
10

Special Operator:
Operator Description Example
Sizeof Returns the size of an variable sizeof(x);
& Returns the address of an variable &x;
* Pointer to a variable *x ;

Example: Output:
#include <stdio.h> Size of integer is 2
int main() Size of Float value is 4
{ Size of character is 1
int a;float b;char c;
printf("Size of integer is %d\n", sizeof(a));
printf("Size of Float value is %d\n", sizeof(b));
printf("Size of character is %d\n", sizeof(c));
}
Conditional operator:
Conditional operator is the ternary operator.
Syntax:
Condition? Expression 1: Expression 2
Condition: condition is checked first. This expression evaluates to 1 if it's true and evaluates51
to 0 if it's false.
I YEAR/I SEM

Expression1: If the condition is true, this expression is evaluated and return the result of
Expression1.
Expression2: If the condition is false, this expression is evaluated.
Advantages of ternary operator:
Using ?: reduce the number of line codes and improve the performance of application.
Example 1: Use of ternary Example 2: Use of ternary operator
operator
#include <stdio.h> #include<stdio.h>
int main() main()
{ {
int a=89,b; int a=10,b=20,small;
b=(a ==100?1:2); printf((a<b ? printf("a is less") : printf("a is greater")));
printf("%d\n",b);return(0); return(0);
} }
Output: Output:
2 a is less

PRECEDENCE OF OPERATORS:(Associativity)
 -. Each operator in c has a precedence associated with it..
 High precedence operator *, /,%.
 Low precedence operator +,
Precedence rule: This rule decides the order in which different operators are applied.
Associativity rule: This rule decides the order in which multiple occurrence of the same
level operators are applied.
 Several operators of the same precedence appear together, the operator are evaluated
according their associativity.
 If the operators are left-to-right associative, they are applied in left-to –right
order.
 If the operators are right-to-left associative, they are applied in right-to-left order.
 This table lists C operators in order of precedence (highest to lowest) and their
associativity.
Operator Description Associativity
() Parentheses (function call) left-to-right
[] Brackets (array subscript)
Increment right-to-left
++
decrement
--
Unary plus
+
- unary minus
& Address of operator
sizeof Determine size in bytes on this 52
implementation
I YEAR/I SEM

* Multiplication left-to-right
/ Division
% Modulus
+ Addition left-to-right
- Subtraction
< Relational less than operator left-to-right
<= less than or equal to operator
> Relational greater than
>= greater than or equal to
== Relational is equal to left-to-right
!= is not equal to
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Simple Assignment right-to-left
+= assign addition
-= Assign subtraction
*= Assign multiplication
/= Assign division
%= Assign modulus
, Comma operator left-to-right
Examples:
a=9-12/3+3*2-1 int a; a=2*3+4%5-3/2+6 int a= 5+7*4-9*(3,2)
a=? a=2*3.25+((3+6)/2) a=? a=?
a=9-4+3*2-1 a=? a=6+4-3/2+6 a= 5+7*4-9*2
a=9-4+6-1 a=2*3.25+9/2 a=6+4+1+6 a=5+28-18
a=5+6-1 a=6.50+4 a=10-1+6 a=33-18
a=11-1 a=10.50 a=9+6 a=15
a=10 a=10 a=15
(because ‘a’ is an integer)

53
I YEAR/I SEM

b=4*6+3*4<3?4:3 a=2,b=12,c=1 find m=?


b=? d=a<b>c m=-43||8&&0||-2
b=24+3*4<3?4:3 d=2<12>1 d=1>1 m=-43||0||-2
b=24+12<3?4:3 d=0 m=1||-2
b=36<3?4:3 m=1
b=3

EXPRESSIONS:
Expressions:
An expression is a sequence of operands and operators.
The meaningful expression consists of one or more operands or operators that specify
the operations to be performed on operands.
Example: a+b, a-b.
Operands:
An operand specifies an entity on which an operation is to be performed.
Operators:
Operators are special symbol that tells the compiler to perform specific mathematical or logical
operations.
Operator specifies the operation to be applied to its operands.
Based on the number of operators present in an expression, expressions are classified as
simple expression and compound expressions.
Simple expressions:
An expression that has only one operator is known as a simple expression
For example: a+2;
Compound Expressions:
An expression that has more than one operator is known as compound expressions.
For example: b= 2+3*5;
INPUT AND OUTPUT STATEMENTS:
In c language two types of input/output statements are available. They are
1. Formatted input/output statements
2. Unformatted input/output statements

54
I YEAR/I SEM

FORMATTED INPUT AND OUTPUT STATEMENTS:


Formatted input and output refers to input and output, that has been arranged in a particular
format.
It read and writes all types of data values.

scanf() statement:
 scanf() is a built-in library function in c.
 It is a standard input function used to read inputs from the user during execution of the
program.
Syntax:
scanf(“control strings”,&variable1,&variable2….&variable);
Control strings(Format Specifier):
- Control string is the type of data that the input statement going to accept, this
always preceded with a % sign.
- Each variable name must be preceded by an ampersand (&).
- & is the address of operator which gives the address of variable.
- It is built in function defined in the <stdio.h> header file.
- The given table lists some control strings with its meaning.
Format specifier Meaning
%c Single character
%s String
%d Integer
%f Float
%ld Double
scanf() for integer data type(%d)
Example:
scanf(“%d”,&a);
- here, a is a variable holding integer value.
- %d is the integer format specifier to represent integer data.
- ‘&’ symbol is used to represent the memory address of the variable.
scanf() for float data type(%f)
Example:
scanf(“%f”,&b);
- here, b is a variable holding float or fractional value.
- The format specifier %f indicates floating or fractional data.
scanf for character data
type(%c) Example: 55
scanf(“%c”,&ch);
I YEAR/I SEM

- here ch is the character datatype.


- %c is the character format specifier to represent character.
scanf for string(%s)
Example:
scanf(“%s”,name);
- here name is the string datatype.
- %s is the string format specifier to represent string data.
Rules for writing scanf function:
o scanf() statement should end with a semi colon (;). This indicates the compiler that it is
the end of the statement..
o The format specifiers should always be placed in between double quotes (“ ”).
o Separate the variables using comma (,)
o Always use a right format specifier while using scanf() function in C.
o Always use the exact data type of the variable for reading the data.
o As C is a case sensitive language, capital letters are not used while writing scanf()
function.
printf() statement:
 It is used to display the output to the screen.
 printf is used to print the message or value.
 It is builtin function defined in the stdio.h header file.
2 ways of using printf statement:
(i) printf() can print text on the screen without using any format specifier.
Syntax:
printf(“string”);
Example:
printf(“hello my dear friend”);
(ii) printf() is used to print the value of the variable and results of the expressions.Using
format specifier
Syntax:
printf(“control string”, variable1,variable2..);
Example:
printf(“my age is %d”, age)
Control strings(Format Specifier):
- Control string is the type of data that the input statement going to accept, this always
preceded with a % sign.
printf() for integer datatype:
Example:
printf(“%d%d”,a,b); // here a and b variables holding integers.
printf() for float datatype:
Example: 56

printf(“%f%f”,a,b); //here a and b are variables holding float values.


I YEAR/I SEM

printf for character datatype:


Example:
printf(“%c”,ch); //here ch is the character datatype.
printf for string:
Example:
printf(“%s”,name); //here name is the string datatype.
Rules for writing printf statement:
1. The message which is to be printed should be placed in between double quotes (“ ”).
2. The printf() function should follow a semi colon at the end.
3. Separate the format specifiers and variables using comma (,).
Use of printf() and scanf() functions in C: Output:
#include<stdio.h> Enter any character:
int main() s
{ Entered character is s
char ch; Enter any string:
char str[100]; anitha
int num; Entered string is anitha
printf("Enter any character:\n"); Enter the number
scanf("%c", &ch); 301
printf("Entered character is %c \n", ch); entered number is 301
printf("Enter any string: \n");
scanf("%s", str);
printf("Entered string is %s \n", str);
printf("Enter the number\n");
scanf("%d",&num);
printf("entered number is %d:",num);
return(0);
}
Program to add two numbers:
#include<stdio.h
int main() Output:
{ Enter two numbers:
int a,b,c; 2
printf("Enter two numbers:\n"); 2
scanf("%d%d",&a,&b); Sum of entered
c = a + b; numbers is 4
printf("Sum of entered numbers is %d\n",c);
return(0);
}
Program to print student details:
#include<stdio.h> Output:
int main() enter the roll no,mark1,
{ mark2,mark3,name
int rollno,m1,m2,m3; 1001 95 85 95 george
Roll no is 1001 57
char name[20];
float total,percentage; Name is george
I YEAR/I SEM

printf("enter the roll no,mark1,mark2,mark3,name\n"); Marks Obtained is 958595


scanf("%d%d%d%d%s",&rollno,&m1,&m2,&m3,name total marks is 275.000000
); percentage is 91.666664
total=(m1+m2+m3);
percentage=total/3;
printf("Roll no is %d\n",rollno);
printf("Name is %s\n",name);
printf("Marks Obtained is %d%d%d\n",m1,m2,m3);
printf("%total marks is %f\n",total);
printf("percentage is %f\n",percentage);
return(0);
}
Swapping of 2 values using temporary variable: Output:
#include <stdio.h> Enter the value of a and b
int main() 4
{ 5
int a,b,temp; Before Swapping value of a
printf("Enter the value of a and b\n"); and b is: 4 5
scanf("%d%d", &a, &b); After Swapping value of a
printf("Before Swapping value of a and b is: %d and b is: 5 4
%d\n",a,b);
temp=a;
a=b;
b=temp;
printf("After Swapping value of a and b is: %d
%d\n",a,b);
return(0);
}
Swapping of 2 numbers without using temporary variable: Output:
#include <stdio.h> Enter the value of a and b
int main() 4
{ 5
int a,b,temp; Before Swapping value of a
printf("Enter the value of a and b\n"); and b is: 4 5
scanf("%d%d", &a, &b); After Swapping value of a
printf("Before Swapping value of a and b is: %d and b is: 5 4
%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After Swapping value of a and b is: %d
%d\n",a,b);
return(0);
}
Program to convert Celsius to Fahrenheit: Output:
#include<stdio.h> Enter the Temperature
58
in
int main () Celcius:10
I YEAR/I SEM

{ The Temperature in
float celsius, fahrenheit; Fahrenheit is:50.000000
printf ("Enter the Temperature in Celsius:");
scanf ("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf ("The Temperature in Fahrenheit is:%f", fahrenheit);
return(0);
}
Program to find slope and midpoint of a line: Output:
#include<stdio.h> Enter the first point x1,y1:
int main () 10
{ 20
float xmp,ymp,x1,y1,x2,y2,slope; Enter the second point
printf ("Enter the first point x1,y1:\n"); x2,y2:
scanf ("%f %f", &x1,&y1); 30
printf ("Enter the second point x2,y2:\n"); 40
scanf ("%f %f", &x2,&y2); Slope is:1.000000
slope=(y2-y1)/(x2-x1); midpoint is:20.000000
xmp=(x1+x2)/2; 30.000000
ymp=(y1+y2)/2;
printf ("Slope is:%f\n", slope);
printf("midpoint is:%f %f",xmp,ymp);
return(0);
}

UNFORMATTED INPUT AND OUTPUT STATEMENTS:


Unformatted I/O functions work only with character data type (char). This is also called
character oriented I/O functions.
There are 2 different types:
o Character I/O
o String I/O
o File
I/O Various functions are,

59
I YEAR/I SEM

input.
Syntax: Syntax:
variable name=getchar(); putchar(variable_name);
Example Example:
char c; char c;
c=getchar(); putchar(c );
Program using getchar and putchar function:
#include<stdio.h>
int main()
{
char a;
printf("enter any key");
a=getchar(); // read input and store it in variable ‘a’
putchar(a); //display the output on screen
}
Output:
enter any key
s
s
getch() putch()
- getch() accepts only single character It displays any alphanumeric characters to the
from keyboard. standard output device. It displays only one
- getch() function will just wait for any character at a time.
keyboard input (and press ENTER). It won’t Syntax:
display the given input character in output putch(variable_name)
screen. Example:
Syntax: char a;
variable_name=getch(); putch(a);
Example:
char x;
x=getch();
Program using getch() function:
#include <stdio.h>
int main()
{
printf("Hello World! ");
getch();
return 0;
}
Output:
60
Hello World!
I YEAR/I SEM

getche()
Like getch(), getche() also accepts only single character, but getche() displays the entered input
character in the screen.
Syntax:
Variable_name=getche();
Example:
char x;
x=getche();
To use getch(), getche() functions, you need to include #include <conio.h> header file
which is a non-standard header file.
gets() puts()
- gets() accepts any line of string including puts displays a single / paragraph of text to the
spaces from the standard Input device standard output device.
(keyboard). Syntax:
-gets() stops reading character from keyboard puts(variable_name);
only when the enter key is pressed. Example:
Syntax: char name[25];
gets(variable_name); puts(name);
Example:
char name[25];
gets(name);
Program to read and print the string using
gets and puts:
#include<stdio.h>
main()
{ Output:
char name[20]; enter the string
printf("enter the string\n"); hello my
gets(name); friend hello my
puts(name); friend
return(0);
}

Character Build-in functions:


isalnum(ch)
isalpha(ch)
isdigit(ch)
islower(ch)
isupper(ch)
tolower(ch)
61
toupper(ch)
I YEAR/I SEM

Program to convert character from lower case to uppercase and vice versa:
#include<stdio.h> Output 1:
int main() enter the character
{ g
char a; G
printf("enter the character\n"); Output 2:
a=getchar(); enter the character
if(islower(a)) G
putchar(toupper(a)); g
}
else
{
putchar(tolower(a));
} return(0);
}
Difference Between Formatted And Unformatted Input/Output Functions:
Formatted Unformatted
1. These are standard input output library These are console input output library function.
function.
2. Formatted input and output functions can Unformatted input/output can deal with one
deals with all kind of data types. character at a time and string function for array
of characters (string).
3. Unformatted Input / Output functions Formatted Input / Output functions are several
have fixed format to give the input and standard library functions
obtain the output.

DECISION MAKING( BRANCHING STATEMENTS) IN C:


- Decision making and branching statements are used to decide the order of execution of
statements based on certain conditions.
- Decision making and branching statements are used to transfer the program control from
one point to another.
- They are categorized as
 Conditional statements
 Unconditional statements
Conditional statements:
Conditional statements also known as Selection statements. In this, the program control is
transferred from one point to another based upon the outcome of certain condition. The
following conditional statements are available in C:
1. if statement
2. if-else statement
3. nested if statement
4. else-if ladder 62
5. switch statements
I YEAR/I SEM

1. if statement
 If the condition is true, the statements inside if statement will be executed.
 If the condition is false, the control will be transferred to the statements outside of if.

Program to check the given number is positive Output


#include<stdio.h> Enter the number
int main() 6
{ number is positive
int num;
printf("Enter the number\n");scanf("%d",&num);
if(num>0)
{
printf("number is positive");
}
}
Program to find the purchase value. If >1000, price 200
will deducted from purchase. Output
#include<stdio.h> enter the purchase value50000
int main() deducted amount is 49800
{
int purchase;
printf("enter the purchase value");
scanf("%d",&purchase);
if(purchase>1000)
{
purchase=purchase-200;
}
printf("deducted amount is %d", purchase);
}
2. if...else statement
 In this, else statement can be combined with if statement.
 If Condition is checked first.
 If the condition is true, statements inside the if part is executed
 When the condition is false, statements in else part is executed. 63
I YEAR/I SEM

Program to check vote eligibility Output:


#include<stdio.h> enter your age
int main() 5
{ not eligible to vote
int age;;
printf("enter your age\n"); scanf("%d",&age);
if(age>18)
printf("eligible to vote");
else
printf("not eligible to vote");return(0);
}
Program to find odd or even number Output
#include<conio.h> enter the number
int main( ) 6
{ 6 is even
int n; enter the number
printf("enter the number\n");scanf("%d",&n); 5
if(n%2==0) 5 is odd
printf("%d is even",n);
else
printf("%d is odd",n);return(0);
}
Greatest of 2 numbers: Output
#include<stdio.h> enter the 2 numbers
int main( ) 4
{ 100
int a,b; 100 is greater
printf("enter the 2 numbers\n");scanf("%d%d",&a,&b);
if(a>b)
printf("%d is greater",a);
else
printf("%d is greater",b);return(0); 64
}
I YEAR/I SEM

Leap year or not:


#include <stdio.h> Output:
int main()
{ Enter a year
int year; 2016
printf("Enter a year\n"); leap year
scanf("%d", &year);
if ((year%4 == 0) && (year%100!=0)|| (year%400==0))
printf("leap year.\n");
else
printf("not a leap year.\n");
return(0);
}
Note:
A year is leap year if following conditions are satisfied
1) Year is multiple of 400
2) Year is multiple of 4 and not multiple of 100.
3. Nested if-else statement
 Nested if-else is used to check more than one conditions.
 If there are more than two alternatives to select, then the nested-if statements are used.
 The conditions are executed from top to bottom.
 Enclosing an if statement within another if statement is called nested-if statement.

If 'expression' is false the 'statement-3' will be executed, otherwise it continues to check the
condition for 'expression 1' .
If the 'expression 1' is true the 'statement-1' is executed otherwise 'statement-2' is executed
65
I YEAR/I SEM

Program to find greatest of three number. Output


#include<stdio.h>
int main( )
{ enter 3 numbers
int a,b,c; 6
printf("enter 3 numbers\n"); 8
scanf("%d%d%d",&a,&b,&c); 1
if(a>b) 8 is greatest
{
if( a > c)
printf("%d is greatest",a);
else
printf("c is greatest");
}
else
{
if( b> c)
printf("b is greatest");
else
printf("c is greatest");
}return(0);
}

4. else-if ladder :
 If there are more than three alternatives, we can go for else if ladder.
 Once a true condition(if) is satisfied, the other statements in the ladder will be skipped.
 When all conditions became false, then the final else part which contains default statement will
be executed.

66
I YEAR/I SEM

Program to print class obtained based on percentage of marks Output:


#include <stdio.h> Enter the percentage of marks
int main() obtained by student:
{ 53
int marks; Grade E
printf("Enter the percentage of marks obtained by student:\n");
scanf("%d",&marks);
if(marks>=90)
printf("Grade S");
else if(marks>=80)
printf("Grade A");
else if(marks>=70)
printf("Grade B");
else if(marks>=60)
printf("Grade C");
else if(marks>=55)
printf("Grade D");
else if(marks>=50)
printf("Grade E");
else
printf("Grade U");return(0);
}
Program to find Quadratic Equation: Output:
#include <stdio.h> enter the value of a,b & c
#include<math.h> -1
int main() 2
{ 4
int a,b,c,d; Both roots are real and diff
float x1,x2; First Root x1= -1.236068
printf("enter the value of a,b & c\n"); Second Root x2= 3.236068
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if(d==0)
{
printf("Both roots are equal\n");
x1=-b/(2.0*a);
x2=x1;
printf("First Root x1= %f\n",x1);
printf("Second Root x2= %f\n",x2);
}
else if(d>0)
{
printf("Both roots are real and diff-2\n");
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("First Root x1= %f\n",x1);
67
printf("Second Root x2= %f\n",x2);
I YEAR/I SEM

}
else
printf("Root are imaginary\n");
}
Program to find the entered key is an alphabet or numeric Output:
or alphanumeric(using character Build-in functions) Enter any key
#include<stdio.h> 8
int main() Entered key is number
{
char a;
printf("Enter any key\n");
a=getchar();
if(isdigit(a))
printf(" Entered key is number");
else if(isalpha(a))
printf("Entered key is alphabet");
else
printf("Entered key is alphanumeric");
return(0);
}
Program to find the entered key is an alphabet or numeric or Output:
alphanumeric(using print, scanf statements) enter a single character or
#include<stdio.h> value
int main() [
{ Alphanumeric
char ch;
printf("enter a single character or value \n"); scanf("%c",&ch);
if((ch>='a')&&(ch<='z'))
printf("Alphabet\n");
else if((ch>='0')&&(ch<='9'))
printf("Number\n");
else
printf(("Alphanumeric\n")); return(0);
}
Note:
In if statement, a single statement can be written without using curly braces { }
Eg, int x=2;
if(x > 4)
printf("welcome");
In the above case, no curly braces are required, but if we have more than one statement
inside if condition, then we must use curly braces.
Other than 0(zero), all other values are considered as true.
Eg, if(9)
printf("welcome");
In above example, hello will be printed, because the integer 9 is a non zero value. 68
I YEAR/I SEM

Switch statement:
 C provides a multi way decision statement called switch statement.
 It allows the user to make a decision from number of choices.
 The expression(condition) in switch case return an integer value or character constant,
which is compared with the values in different cases.
 When the condition matches with the case ,that block of statement is executed.
 If there is no match, then default statement is executed.

Note:
It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of
codes will get executed after the matching block.
int i = 1;
switch(i)
{
case 1:
printf("A"); // No break case 2:
printf("B"); //No break case 3:
printf("C");
break;
}
Output : A B C
- The output was supposed to be only A because only the first case matches, but as there is no break
statementaftertheblock,thenextblocksareexecuted,untilthe cursor encounters a break.
Rules for switch Statement:
o Default case is optional andcan be placed anywhere in the switch case. But Usualy we place 69
itattheend.
I YEAR/I SEM

o Case keyword must terminate with colon(:)


o Case order execution is from top to bottom.
o No two case constant should be same.
Example: To print month using switch case Output:
#include<stdio.h> Enter any number
int main() from 1 to 4 to
{ represent month
int ch; 3
printf("Enter any number from 1 to 4 to represent month\n"); March
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("january");
break;
case 2:
printf("february");
break;
case 3:
printf("march");
break;
case 4:
printf("april");
break;
}
return(0);
}
Arithmetic operations using switch: Output:
#include<stdio.h> 1.Addition
int main() 2.Subtraction
{ 3.Multiplication
int a,b,op; printf("1.Addition\n2.Subtraction\n3.Multiplication\ 4.Division
n4.Division\n"); printf("Enter the values of a & b: "); Enter the values of a
scanf("%d %d",&a,&b); & b: 20 5
printf("Enter your Choice : ");scanf("%d",&op); Enter your Choice :
switch(op) 3
{ Multiplication is :
case 1 : 100
printf("Sum is : %d",a+b);
break;
case 2 :
printf("Difference is : %d",a-b);
break;
case 3 :
printf("Multiplication is : %d",a*b);
70
I YEAR/I SEM

break;
case 4 :
printf("Division is %d : ",a/b);
break;
default :
printf(" Enter Your Correct Choice.");
break;
}
return(0);
}
Printing student GPA details using switch case:
#include<stdio.h> Output:
int main() Enter three subject
{ Marks95
int m1,m2,m3,gpa; 94
float tot, avg; 96
printf("Enter three subject Marks"); grade=A
scanf("%d%d%d",&m1,&m2,&m3);
tot=m1+m2+m3;avg=tot/3; gpa=avg/10;
switch(gpa)
{
case 10: printf("grade=S"); break;
case 9 : printf("grade=A"); break;
case 8 : printf("grade=B"); break;
case 7 : printf("grade=C"); break;
case 6 : printf("grade=D"); break;
case 5 : printf("grade=E"); break;
default : printf("grade=F");
}
return(0);
}
LOOPING STATEMENTS / ITERATIVE STATEMENTS:
 In Loop, sequence of statements are executed until a specified condition is true.
 This sequence of statements to be executed is kept inside the curly braces { } known as the
Loop body.
 After every execution of loop body, condition is verified, and if it is found to be true the loop
body is executed again. When the condition check returns false, the loop body is not executed.
 There are 3 type of Loops in C language
for loop
while loop
do-while loop
Entry controlled loop Exit controlled loop
The test condition is checked first before The loop is executed first and then condition
the loop is executed. is checked. 71
I YEAR/I SEM

Example The loop is executed at least once, even


while loop when the condition is false.
for loop Example
do-while loop

while Loop:
 It is an entry controlled looping statement.
 Statements are executed repeatedly until the while condition is true.
 It is completed in 3 steps.
 Variable initialization. ( e.g int x=0; )
 Condition Checking ( e.g while( x<=10) )
 Variable increment or decrement ( x++ or x-- or x=x+2)
Description:
Step 1: The while condition is checked first.
Step 2: If the condition is true, the statements inside the loop will be executed, then the variable
value is incremented or decremented at the end of the looping statement.
Step 3: If the condition is false, the loop body will be skipped and the statements after the while
loop will be executed.

Sum of n natural numbers using while loop Output:


#include<stdio.h> Enter a number
int main() 5
{ The sum of nos: 15
int n,i=1,sum = 0;
printf("Enter a number\n"); scanf("%d",&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf("The sum of nos: %d\n",sum);return(0);
}
72

Sum of Digits of given number using while loop: Output:


I YEAR/I SEM

#include <stdio.h> enter the number


int main() 555
{ sum of digits of given no is: 15
int n,dig,sum1=0;
printf("enter the number\n");scanf("%d",&n);
while(n>0)
{
dig=n%10;
sum1=sum1+dig;
n=n/10;
}
printf("sum of digits of given no is: %d",sum1);
return(0);
}
To reverse the given number Output:
#include <stdio.h> Enter a no to reverse
int main() 523
{ Reverse of entered no=325
int n,dig,rev=0;
printf("Enter a no to reverse\n"); scanf("%d",&n);
while(n>0)
{
dig=n%10;
rev=(rev*10)+dig;
n=n/10;
}
printf("Reverse of entered no=%d",rev); return(0);
}
To check the given number is palindrome or not: Output:
#include <stdio.h> Enter a number to check
int main() palindrome:
{ 1221
int n,rev=0,temp,dig; It is a palindrome no.
printf("Enter a number to check palindrome:\n");
scanf("%d",&n);
temp=n;
while(temp != 0 )
{
dig=temp %10;rev=rev*10 + dig; temp=temp/10;
73
I YEAR/I SEM

}
if(rev == n )
printf("It is a palindrome no.\n"); else
printf("it is not a palindrome no.\n"); return(0);
}
To Check Armstrong number or not: Output:
#include <stdio.h> Enter a number
int main() 153
{ Its an Armstrong number
int n, arm = 0, dig, temp;
printf("Enter a number\n");
scanf("%d", &n);
temp=n;
while (temp != 0)
{
dig = temp %10;arm= arm + (dig*dig*dig);
temp = temp/10;
}
if(arm==n)
printf("Its an Armstrong number"); else
printf("Its an not Armstrong number"); return(0);
}

do whileloop:
 It is an exit controlled looping statement.
 The do-while loop checks its condition at the bottom of the loop whereas for and while loops,
the loop condition is checked at the top of the loop.
 do-while loop is guaranteed to execute the statement at least one time.

74
I YEAR/I SEM

While Do while
Conditionistestedfirstandthen statements are Statements are executed at least
executed. once. then the conditions are
tested.
While loop is entry controlled loop Do wile loop is exit control
loop.

Sum of 10 natural no’s using do while loop: Output:


#include<stdio.h> Enter a number
int main() 10
{ The sum of digits: 55
int n,i=0,sum = 0;
printf("Enter a number\n"); scanf("%d",&n);
do
{
sum=sum+i;
i++;
}while(i<=n);
printf("The sum of digits: %d\n",sum);return(0);
}
Program to print multiples of 5: Output:
#include<stdio.h> 5
int main() 10
{ 15
int a=5,i=1; 20
do 25
{ 30
printf("%d\n",a*i); 35
i++; 40
} 45
while(i <= 10); 50
}
Program to print the squares of number from 1 to 10: Output:
#include<stdio.h> numbers squares
#include<math.h> 1 1
int main() 2 4
{ 3 9
int num=1,sq; 4 16
printf("numbers squares\n"); 5 25
do 6 36
{ 7 49
sq=pow(num,2); 8 64
printf("%d%20d\n",num,sq); 9 81
num++; 10 100
}while(num<=10);
return(0); 75
}
I YEAR/I SEM

for loop:
for loop is usedtoexecutea set of statements repeatedlyuntilaparticularconditionis satisfied.

Flow of Execution:
i.The initialization step is executed first, and only once. This step allows to declare and
initialize any loop control variables.
ii.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 will not be executed and flow of control jumps to the next
statement just after the for loop.
iii.After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows to update any loop control variables.
iv.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). When the
condition becomes false, the for loop terminates.
Different ways of implementing for loop:
Form Comment

for(i=0;i<10;i++)
Single Statement
Statement1;

for ( i=0 ;i <10; i++) Multiple Statements within for


{
Statement1;
Statement2;
Statement3;
}

for ( i=0 ; i < 10;i++) ; For Loop with no Body ( Carefully Look
at the Semicolon ) 76
I YEAR/I SEM

for(i=0,j=0;i<100;i++,j++) Multiple initialization & Multiple


Statement1; Update Statements Separated by Comma

for ( ; i<10 ; i++) Initialization not used

for ( ; i<10 ; ) Initialization & Update not used

for ( ; ; ) Infinite Loop, Never Terminates


Simple Programs using for loop:
Printing n natural numbers: Output:
#include <stdio.h> enter the maximum no to be
int main() printed:10
{ 1
int n,i; 2
printf("enter the maximum no to be printed:"); 3
scanf("%d",&n); 4
for(i=1;i<=n;i++) 5
{ 6
printf("%d\n",i); // 7
} 8
return(0); 9
} 10
Printing n even numbers: Output:
#include <stdio.h> Enter the number:10
int main() 0
{ 2
int n,i,sum=0; 4
6
printf("Enter the number:"); 8
scanf("%d", &n); 10
for (i = 0; i <= n; i=i+2)
printf("%d\n",i);
return(0);
}
Sum of n Odd numbers: Output:
#include <stdio.h> Enter the number
int main() 10
{ Sum of entered odd number is
int n,i,sum=0; 25
printf("Enter the number\n");scanf("%d", &n);
for (i = 1; i <= n; i=i+2)
sum = sum + i;
printf("Sum of entered odd number is %d",sum);
return(0);
} 77
I YEAR/I SEM

Sum of Squares of a number: Output:


#include <stdio.h> Enter the number:4
int main() sum is 30:
{
int n,i,sum=0;
printf("Enter the number:");scanf("%d", &n);
for (i = 1; i <= n; i=i+1)
{
sum=sum+(i*i);
}
printf("sum is %d:\n",sum);return(0);
}
To find Factorial of the given number: Output:
#include <stdio.h> Enter the number:5
int main() sum is 120:
{
int n,i,fact=1;
printf("Enter the number:");scanf("%d", &n);
for (i = 1; i <= n; i=i+1)
fact=fact*i;
printf("sum is %d:\n",fact);return(0);
}
Sum of series 1+1/2+1/3+...........+ 1/n Output:
#include <stdio.h> Enter the number
int main() 5
{ Sum of the series =2.283333
double sum=0.0,n,i;
printf("Enter the number\n"); scanf("%lf", &n);
for (i = 1; i <= n; i++)
sum = sum + (1/i);
printf("Sum of the series =%lf ",sum);return(0);
}
Sum of series 1/1!+1/2!+1/3!+...........+ 1/n! Output:
#include <stdio.h> Enter the number
int main() 5
{ Sum of the series =0.008333
double sum=0.0,n,i,fact=1;
printf("Enter the number\n"); scanf("%lf", &n);
for (i = 1; i <= n; i++)
fact=fact*i;
sum = sum + (1/fact);
printf("Sum of the series =%lf ",sum);return(0);
}
Fibonacci Series: Enter the number of terms: 10
#include <stdio.h> 0,1,1,2,3,5,8,13,21,34,
int main() 78
I YEAR/I SEM

{
int i, n, a = 0, b = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
printf("%d,",a);
next=a+b;
a=b;
b=next;
}return 0;
}
To find Factors of a given number: Output:
#include<stdio.h> Enter a number to find
int main() its factors
{ 10
int n,i; factors are: 1
printf("Enter a number to find its factors\n"); factors are: 2
scanf("%d",&n); factors are: 5
for (i=1;i<=n;i++) factors are: 10
{
if(n%i==0)
printf("factors are: %d\n",i);
}
return(0);
}
Program to check the number is prime or not: Output:
#include<stdio.h> enter the no
int main() 11
{ number is prime
int n,i,flag; printf("enter the no\n");
scanf("%d",&n);
for(i=2;i<n;i++) Note:
{ Flag is a Boolean variable that
if(n%i==0) has only 2 states (0 and 1)
{ Eg, On/Off, True/False,
flag=0; Yes/No
break;
}
}
if(flag==0)
printf("number is not prime \n");
else
printf("number is prime\n");
return(0);
}
79
I YEAR/I SEM

Nested for loop:


- One for loop inside another for loop.

Flowchart:

Program to multiply numbers using nested for: Output:


#include <stdio.h> 1
int main() 2
{ 2
int i,j; 4
for(i=1;i<3;i++)
{
for(j=1;j<3;j++)
{
printf("%d\n",i*j);
}
}
return(0);
}
80
I YEAR/I SEM

Loop Control Statements:


C language allows jumping from one statement to another within a loop as well as
jumping out of the loop.
1. break
2. continue
3. goto
4. return
1) break
statement
 When break statement is encountered inside a loop, the loop is immediately
terminated and program control comes out of the loop and executes the
statement immediately following the loop.
 It can be used in iteration only(looping statements).
 Cannot be used in conditional statements(if, else, else if).
Syntax:
break;

2) continue statement:
C Continue statement are used to skips the rest of the current iteration in a loop and returns to
the top of the loop.
Syntax:
continue;

81
I YEAR/I SEM

Example:
Use of break statement Output: Use of continue statement to Output:
to print numbers: print numbers:
#include <stdio.h> enter the enter the
int main() #include <stdio.h>
number: 10 number: 10
{ int main()
1 { 1
int i,num;
printf("enter the number: "); 2 int i,num; 2
scanf("%d",&num); 3 printf("enter the number: "); 3
for(i=1;i<=num;i++) 4 scanf("%d",&num); 4
{ for(i=1;i<=num;i++) skipped
if(i==5) { 6
{ if(i==5)
7
printf("stop"); {
printf("skipped\n"); 8
break;
} continue; 9
printf("%d\n",i); } 10
} printf("%d\n",i);
return(0); }
} return(0);
}
Break Continue
Break statement is used to transfer the Continue is used to skip some statement of
controlof the program to outside loop or the loop and moves to the next iteration in
switch case statement. the loop.
It is used in loop as well as switch case. It is used only within the loop.
Syntax: break; Syntax: continue;

3) goto statement:
 The goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
 When a goto statement is encountered in a C program, the control jumps directly to the
label mentioned in the goto statement.
 It us used when loops are deeply nested and simple break statement cannot work
effieciently.
Syntax:
goto label_name;


label_name

82
I YEAR/I SEM

Flowchart: Program to print sum


of no’s using goto
statement:
#include <stdio.h>
int main()
{
int sum=0,i;
for(i = 0; i<=10; i++)
{
sum = sum+i;
if(i==5)
{
goto addition;
}
}
addition:
printf("sum is %d",
sum);
return(0);
}
Output:
sum is 15

Preprocessor Directives:
 Preprocessor is a program which will be executed automatically before passing the source
program to compiler. This process is called pre-processing.
 The preprocessor provides the ability for the inclusion of header files, macro expansions,
conditional compilation, and line control.
 Commands used in preprocessor are called preprocessor directives.
 They begin with "#" symbol and should be not ended with (;)
 Proprocessor Directive can be place any where in the program, but generally it place top of the
program before defining the first function.
Preprocessor directives in C:
 Macro substitution directives. example: #define
 File inclusion directives. example: #include
 Conditional compilation directive. example: #if, #else, #ifdef, #undef, #endif
 Miscellaneous directive. example: #error, #line

83
I YEAR/I SEM

(i) Macro preprocessor:


Example: To print PI value
#include<stdio.h>
#define PI 3.14
int main()
{
printf("%f",PI);
}
Three types of macros are
Simple macros Augmented macros Nested macros
Define symbolic It is used to define more The macro defined within another
constants complex expressions macro is called nested macro.
Example: Example: Example:
#define A 100 #define sqr(n) (n*n) #define sq(n) (n*n)
#define tablesize 10 #define cube(n) (n*n*n)

(ii) File Inclusion:


This is used to include an external file which contains functions into the program. It enables code
reusability.
Syntax Example
#include "filename" #include"example.c"
#include <filename> #include<stdio.h>
 The filename is quoted in quotes (“ ”), then it searches that file in current directories.
 When the filename is quoted in angle brackets (< >), then it searches the file in standard
directories only.
(iii) Conditional Directives:
#if, #else and #endif:
If given condition is true, "If" clause statement is included in source file . Otherwise, else clause
statement is included in source file for compilation and execution.
84
I YEAR/I SEM

Example: Tocheck the Vote eligibility using #if, #else and #endif
#include<stdio.h> Output:
#define AGE 5 Not eligible
int main()
{
#if (AGE>=18)
{
printf("Eligible for voting");
}
#else
{
printf("\n Not eligible");
}
#endif
return(0);
}
#ifdef, #else and #endif:
- #ifdef" directive checks whether particular macro is defined or not.
- If it is defined, "If" clause statements are included in source file. Otherwise, "else" clause
statements are included in source file for compilation and execution.
- In the below example1 macro is not defined. So, else part is executed.
Example: Example:
#include<stdio.h> #include<stdio.h>
int main() #define AGE 1
{ int main()
#ifdef AGE {
{ #ifdef AGE
printf("Eligible for voting\n"); {
} printf("Eligible for voting\n");
#else }
{ #else
printf("Not eligible\n"); {
} printf("Not eligible\n");
#endif }
return(0); #endif
} return(0);
}
Output: Output:
Not eligible Eligible for voting
undef
This directive undefines existing macro in the program.
In below program we first undefine age variable and again it is defined with new value.
Example: Undefining the macro Output:
#include<stdio.h> First define value for age is:
85
#define age 20 20
I YEAR/I SEM

int main() Age after undef redefine is:


{ 30
printf("First defined value for age is: %d\n",age);
#undef age // undefining variable
#define age 30 // redefining age with new value
printf("Age after undef redefine is: %d",age);
return(0);
}

PART A:
1. What are variables? Give Examples (M/J’16)(N/D’14)
2. Define implicit type conversion (M/J’16)
3. What is an array? Give Example (M/J’16) (M/J’15)
4. Define strings. Give examples(M/J’16)
5. What is meant by linking process? (N/D’15)
6. What are the input functions and output functions in C? (N/D’15) (M/J’15)
7. Write a C program to store Fibonacci series in an array. (N/D’15)
8. List the string functions available in C. (N/D’15)
9. List some pre-processor directives. (N/D’15)
10. What are the importance of keyword in C? (M/J’15)
11. How is a character string declared? (M/J’15)
12. Give the use of pre-processor directives. (M/J’15) (N/D’14) (M/J’14)
13. Give an Example of ternary operator. (N/D’14)
14. Describe float array of size 5 and assign 5 values in it. (N/D’14)
15. Give an example for initialization of string array.
16. Define static storage class. (N/D’14)
17. List different data types available in C. (M/J’14)
18. Write a C program to find factorial of the number using iteration. (M/J’14)
19. Write an example code to declare two dimensional array. (M/J’14)
20. List any 4 string handling functions (M/J’14)

PART B:
1. Explain different types of operators in detail.(M/J’16) (M/J’15) (N/D’14)
2. Discuss basic data types in C (M/J’16)
3. Describe various input and output statements in detail. (M/J’16)
4. Write a C program for the following series 1+2+3+4+…N (M/J’16)
5. Write a C program to convert the number of vowels in your name (M/J’16)
6. Write a C program to multiply two matrices/ Write a C program for two 3*3 Matrix
(M/J’16)/(N/D’15) (N/D’14)
7. Write a C program to check whether the given string is palindrome or not (M/J’16)
8. Write a C program to arrange the given 10 numbers in descending order (M/J’16
9. Explain various storage classes in detail. (M/J’16) (N/D’15) (M/J’15) (M/J’14)
10. Describe about pre-processors with suitable examples. (M/J’16) 86
I YEAR/I SEM

11. Describe the structure of C program using ‘calculator program’ example. (N/D’15)
12. Write short notes on branching statements in C. (N/D’15)
13. Write in detail about various looping statements with suitable example.(N/D’15) (M/J’15)
(N/D’14)
14. Write a C program to find determinant of the resultant matrix. (N/D’15)
15. Write the following programs (N/D’15)
(i) To sort the given set of strings alphabetically
(ii) To print whether each word is palindrome or not
(iii) To count the length of the string
16. What are constants? Explain various types of constants in C. (M/J’15)
17. Write a C program to solve(roots of) Quadratic Equation ((M/J’15) (M/J’14)
18. Write a C program to add two matrices. (M/J’15)
19. Write a C program to search a number in an array of elements. (M/J’15) (N/D’14)
20. Write a C program to arrange the given 10 numbers in ascending order/ Write a C program to
sort array of numbers. (N/D’14) (M/J’15) (M/J’14)
21. Explain various string handling functions in C. (M/J’15)
22. Explain various string operations. Write a C program to find the length of the string without
using build in function. (N/D’14)
23. Write a short notes on (i) #include<stdio.h> (ii) ifdef.. # endif (N/D’14)
24. Write a C program to check the given number is prime or not (M/J’14)
25. Write a C program to find sum of digits of a number (M/J’14)
26. Explain entry and exit checked conditional structure with example(M/J’14)
27. Write a C program to subtract two matrices and display the resultant matrix.(M/J’14)
28. (M/J’14)

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

87
I YEAR/I SEM
UNIT II ARRAYS AND STRINGS
Arrays: Introduction – Declaration of Arrays – Storing Values in Array – Accessing elements of
the Array– Operations on Array – one dimensional arrays – Two dimensional Arrays –String:
Declaring, Initializing, Printing and reading strings, String input and output functions, String
handling functions, Arrays of strings.

INTRODUCTION TO ARRAYS:
Anarray isacollectionof similar data items that arestored undera commonname.
Array is defined as finite ordered collection of similar data, stored in contiguous
(continues) memory locations.
It is a derived data type in C.
What is the use of array?
A single variable cannot store multiple values . But an array can store multiple values of
same data type in one single name.
Example where arrays are used,
 to store roll numbers of the students in a class
 to store marks of a students
 to store list of names of employees etc..

Array can store integer, float and double values which is said to be integer array.
Array that is used to store characters are said to be Character array.
Features of array:
Array might be belonging to any of the data types
Array size must be a constant value.
Array index starts with 0 and ends with n-1.
Element of an array is accessed using index or subscript.
Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
It is a best practice to initialize an array to zero or null while declaring, if we don’t
assign any values to array.
Advantage of array:
 Code Optimization: Less code is required, one variable can store numbers of
value.
 Easy to traverse data: By using array easily retrieve the data of array.
 Easy to sort data: Easily sort the data using swapping technique.
I YEAR/I SEM
 Random Access: With the help of array index you can randomly access any
elements from array.
Types of an array:
1. Single dimensional array
2. Multi dimensional array
Single(one)dimensionalarray:
 Array having only one subscript [ ] variable is called One-Dimensional array.
 It is also called as Single Dimensional Array or Linear Array or list.
 The elements of one dimensional array is also called as linear
array Declaring Array:
data_type array_name[size];
Example:
int roll_num[100];
char name[50];
double balance[10];
Initialization of an Array:
 After an arrayis declared it must be initialized.
 An array can be initialized in 2 ways (i) Compile time initialization
(ii)Run time initialization
(i) Compile time Array initialization:
- Compiletime initialization ofarrayelementsissame as ordinaryvariableinitialization.
Syntax:
data type array_name[size] = { list of values };
Example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization
double balance[10]={1000.0,20.0,3.4,7.2,50.0}
char str[10]={‘H’,‘a’,‘i’}; // character array
Accessing Array Elements:
We can access array elements with the help of index value of element.
Example:
int marks[50]={10,20,30,15,12}
here, marks is the array name and [50] is the maximum number of elements the array can
hold.
Printing array of numbers(Compile time initialization) Output:
#include<stdio.h> the elements in the
int main() array are
{ 95
int arr[40]={95,58,45,78}; 58
I YEAR/I SEM
int i; 45
printf("the elements in the array are\n"); 78
for(i=0;i<=3;i++)
{
printf("%d\n", arr[i]);
}
return(0);
}
Note: [40] is the maximum size the array can hold.
(ii)Runtime Array initialization:
- An array can also be initialized at runtime using scanf() function.
- This approach is usually used for initializing large array elements , or to initialize
arrayby getting the input from the user.
Syntax:
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
Reading and Printing array of elements( Run Time Output:
initialization) enter the size of an
#include<stdio.h> array
int main() 5
{ enter the elements of
int arr[100],n,i; an array
printf("enter the size of an array\n"); 45
scanf("%d",&n); 45
printf("enter the elements of an array\n"); 78
for(i=0;i<=n-1;i++) 4
{ 12
scanf("%d",&arr[i]); the elements are
} 45
printf("the elements are\n"); 45
for(i=0;i<=n-1;i++) 78
{ 4
printf("%d\n",arr[i]); 12
}
return(0);
}
Operations on 1Darray:
1. Subscripting an 1D array
It is an action of selecting an element from an array.
printf(“%d”, a[5]);
2. Assigning an array to another array
I YEAR/I SEM
A variable can be assigned to another variable but array can’t be assigned to
another arraydirectly.
Output:
#include<stdio.h> //compilation error
int main()
{
int a[3],b[3]={1,2,3};
a[3]=b[3];
printf(“%d”, a[0]);eturn(0);
}

Example Programs: (using One Dimensional Array)


C program to find sum of array of elements: Output:
#include<stdio.h> Enter the size of
int main() array:
{ 4
int i, arr[20], n, sum=0; Enter the values:
printf("Enter the size of array:\n"); 2
scanf("%d",&n); 5
printf("Enter the values:\n"); 1
for(i=0;i<n;i++) 12
{
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("the sum of the array is %d",sum);
return(0);
}
C Program to find the largest element in an array: Output:
#include<stdio.h> enter the size of an
int main() array :3
{ enter the elements of
int arr[10]; an array
int large,i,n; 23
printf("enter the size of an array :"); 2
scanf("%d",&n); 15
printf("enter the elements of an array\n"); largest element is: 23
for(i=0;i<=n-1;i++)
{
scanf("%d",&arr[i]); Note:
} Can also try the size
large=arr[0]; of array and
I YEAR/I SEM
for(i=1;i<=n-1;i++) elements of array by
{ getting input from
if(arr[i]>large) user.
large=arr[i];
}
printf("largest element is: %d\n",large);
return(0);
}
Note:
(Same can be done to find the smallest element also. use < to
find smallest element)
Program to insert an element in an array at specific position Output:
#include<stdio.h> enter the position
int main() where the new
{ element to be inserted
int arr[50]={10,20,30,40,50},i,pos,element; 2
printf("enter the position where the new element to be enter the new element
inserted\n"); to be inserted
scanf("%d",&pos); 25
printf("enter the new element to be inserted\n"); after insertion
scanf("%d",&element); ,elements are
for(i=4;i>=pos;i--) 10
{ 20
arr[i+1]=arr[i]; //moving the elements 25
} 30
arr[pos]=element; 40
printf("after insertion ,elements are\n"); 50
for(i=0;i<=5;i++)
{
printf("%d\n",arr[i]);
}
return(0);
}
C program to delete an element in an array: Output:
#include<stdio.h> Enter the size of an
int main() array
{ 4
int n, a[10],i,pos; Enter the array
printf("Enter the size of an array\n"); elements
scanf("%d",&n); 23
printf("Enter the array elements\n"); 12
for(i=0;i<n;i++) 5
{ 47
scanf("%d",&a[i]); Enter the position to
} be deleted
printf("Enter the position to be deleted\n"); 1
I YEAR/I SEM
{ After deletion:
scanf("%d",&pos); 23
} 5
if(pos>=n) 47
{
printf("deletion is not possible");
}
else
{
for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}
}
printf("After deletion:\n");
for(i=0;i<n-1;i++)
{
printf("%d\n",a[i]);
}
return(0);
}
C program to display elements in Descending order: Output:
#include <stdio.h> Enter the size of
int main() array: 5
{ Enter the elements of
int arr[50],n,i,j; array:
int temp; 2
printf("Enter the size of array: "); 6
scanf("%d",&n); 8
printf("Enter the elements of array:\n"); 9
for(i=0;i<=n-1;i++) 1
scanf("%d",&arr[i]); Array elements after
sorting:
for(i=0;i<=n-1;i++) 9
{ 8
for(j=i+1;j<=n-1;j++) 6
{ 2
if(arr[i]<arr[j]) //sort array 1
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
I YEAR/I SEM
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return 0;
}

Illustrative Programs:
Searching: Searching is a process of finding a particular element in a given list.
Types:
1. Linearsearch
2. Binary search
Linear Search
- It is a process of finding an element in the list from the beginning and continues till
the end of the list.
Concept of linear Search:
i. To search an element we want, we start with the first element in the list. If this is the
required element, our search is over.
ii. Else, we take up the second element and see if this is the element we search for.
iii. If this is too not the element, we pick up the third element and compare.
iv. This process continues until the element we search for is found.
Advantages:

 The linear search is simple - It is very easy to understand and implement;


 It does not require the data in the array to be stored in any particular order.
Disadvantages:
The linear search is inefficient(takes more time) if the list has more number of elements.
C program to perform Linear Search:
#include<stdio.h> Output:
int main() Enter the number of
{ elements in array
int array[100], item, i, n, found=0; 4
printf("Enter the number of elements in array\n"); Enter the elements
scanf("%d",&n); 6
printf("Enter the elements \n", n); 12
for (i = 0; i < n; i++) 5
scanf("%d", &array[i]); 8
Enter the element to
printf("Enter the element to search\n"); search
scanf("%d", &item); 5
5 is present in array and
for (i = 0; i <=n-1; i++) position is 2
{
if (array[i] == item) // if required element found
I YEAR/I SEM
{
found=1;
break;
}
}
if (found==1)
printf("%d is present in array and position is %d\n", item,i);
else
printf("%d is not present in array.\n", item);
return 0;
}
Binary Search:
 Binary search is an algorithm used to find an element in an sorted array by using the
divide and conquer concept.
 This method can be applied only if list is in sorted order.
 Listisdividedintotwohalves separatedbymiddleelement.
Left half Middle Right half
Concept of Binary search:
i. Find the middle element
ii. Check the middle element with the element to be found
iii. If the middle element is equal to that element, then it will provide the output.
iv. If the value is not same, then it will check whether the middle element value is
less than or greater than the element to be found.
v. If the value is less than that element, then the search will start with the elements
next to the middle element.
vi. If the value is high than that element, then the search will start with the
elements before to the middle element.
vii. This process continues, until that particular element has been found.
Example: Consider the following set of elements in array where 31 is the element to be
searched.

Middle =(First+Last)/2 =>(0+9)/2 =4.5=>4

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
I YEAR/I SEM
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.

We change our low to mid + 1 and find the new mid value again.
Like this searching continues until we find the desired element.

Advantages:
 Faster than linear search.
Disadvantages :
 Binary search algorithm can work only with the sorted array (either ascending or
descending order).
 It is time consuming and waste of memory allocation.
If the element to be identified occurs more than once, then it will show the occurrence of
the first one.
Program for Binary search: Output:
#include <stdio.h>
int main() enter size of array
{ 6
int i, first, last, middle, n, item, arr[50]; enter the elements
printf("enter size of array"); 5
scanf("%d",&n); 12
printf("enter the elements\n"); 4
for (i = 0; i <=n-1; i++) 7
{ 18
scanf("%d",&arr[i]); 240
} Enter element to find
printf("Enter element to find\n"); 18
scanf("%d", &item); 18 found at location 4
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (arr[middle] < item)
{
first = middle + 1;
}
else if (arr[middle] == item)
I YEAR/I SEM
{
printf("%d found at location %d.\n", item, middle);
break;
}
else
{
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list\n", item);
return (0);
}
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.
Consider the following example:

Program to perform selection sorting (ascending order) Output:


#include <stdio.h> Enter the size of array: 5
int main() Enter the elements of array:
{ 1
int arr[50],n,i,j; 6
int temp; 4
I YEAR/I SEM
printf("Enter the size of array: "); 6
scanf("%d",&n); 1
printf("Enter the elements of array:\n"); Array elements after sorting:
for(i=0;i<=n-1;i++) 1
scanf("%d",&arr[i]); 1
4
for(i=0;i<=n-1;i++) 6
{ 6
for(j=i+1;j<=n-1;j++)
{
if(arr[i]>arr[j]) //sort array
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return (0);
}
Computing Mean, Median
Mean: The average of a set of numbers.
The mean is the usual average, so I'll add and then divide:
(13 + 18 + 13 + 14 + 13 + 16 + 14 + 21 + 13) ÷ 9 = 15
Median: The middlemost number in a set of number arranged in order.
The median is the middle value, so first I'll have to rewrite the list in numerical order:
13, 13, 13, 13, 14, 14, 16, 18, 21
There are nine numbers in the list, so the middle one will be the (9 + 1) ÷ 2 = 10 ÷ 2 = 5th
number:
13, 13, 13, 13, 14, 14, 16, 18, 21
So the median is 14.
Mode: Mode is the number that is repeated more often than any other, so 13 is the mode.

C program to create mean and median of array of Output:


elements enter size of array
#include <stdio.h> 5
int main() enter the elements
{ 6
int i,j,a[20], sum=0,n,temp,b[20]; 4
I YEAR/I SEM
float mean=0.0, median=0.0; 3
printf("enter size of array\n"); 2
scanf("%d",&n); 4
printf("enter the elements\n"); mean value is
for (i = 0; i <=n-1; i++) 3.800000median is 4.000000
{
scanf("%d",&a[i]);
sum=sum+a[i]; //Calculating mean
}
mean=(float)sum/(float)n;
printf("mean value is %f",mean);
for(i=0;i<=n-1;i++)
{
for(j=i+1;j<=n-1;j++) //calculating median
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
} if(n
%2==0)
median=(float)(a[n/2]+a[(n-1)/2])/2;
else
median=a[(n-1)/2];
printf("median is %f",median);
}

Two dimensional Arrays:( Multidimensional Arrays


- In 2-dimentional array, elements are arranged in row and column format.
- An array with two subscripts[ ][ ] is termed as two dimensional arrays.
- A two dimensional array enables us to store multiple rows of elements, in form of
matrix.
Array Declaration Syntax:
data_type arr_name [num_of_rows][num_of_column];

Example:
int arr[2][2];
- this array can hold 2*2=4 elements totally.
I YEAR/I SEM

Array Initialization:
(i) Compile time Initialization
Array Initialization Syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Example:
int arr[2][2] = {1,2, 3, 4};
int arr[2][3] = { {0,0,0}, {1,1,1} };
int arr[2][3] = { 0,0,0, 1,1,1 };
Array accessing syntax:
arr_name[index];
Example:
int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0] = 3;
arr [1] [1] = 4;
Invalid initializations:
Following initializations are wrong and invalid.
int arr[2][ ]={1,2,3,4}; // We need to mention the column size.
Otherwise compiler do not know where the first row size ends.
ii) Run Time initialization:
Syntax:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,a[i][j]);
}
}
Programs on two dimensional arrays:
C Program To read and display 2 dimensional matrix Output:
#include <stdio.h> enter the size of row and
int main() column
{ 3
int a[10][10]; 3
int i,j,m,n; enter the elements of
printf("enter the size of row and column\n"); matrix
scanf("%d%d",&m,&n); 5
printf("enter the elements of matrix\n"); 2
I YEAR/I SEM
for(i=0;i<=m-1;i++) 5
{ 2
for(j=0;j<=n-1;j++) 5
{ 2
scanf("%d",&a[i][j]); 5
} 2
} 5
printf("the elements are\n"); the elements are
for(i=0;i<=m-1;i++) 5 2 5
{ 2 5 2
for(j=0;j<=n-1;j++) 5 2 5
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return(0);
}
Program for Matrix Addition: Output:
#include <stdio.h> Enter the size of row and
int main() column
{ 2
int a[10][10], b[10][10]; // array declaration for matrix a&b 2
int c[10][10]={0}; // c matrix initialized to 0 Enter the elements of A
int i,j,m,n; matrix
printf("Enter the size of row and column\n"); 1
scanf("%d%d",&m,&n); //reading size or row and column 3
printf("Enter the elements of A matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ Enter the elements of B
for(j=0;j<=n-1;j++) matrix
{ 1
scanf("%d",&a[i][j]); //getting the elements of A matrix 5
} 5
} 6
printf("Enter the elements of B matrix\n"); Sum of two matrices:-
for(i=0;i<=m-1;i++) 2 8
{ 7 11
for(j=0;j<=n-1;j++)
{
scanf("%d", &b[i][j]); //getting the elements of B matrix
}
}
printf("Sum of two matrices:-\n");
for(i = 0;i<=m-1;i++)
{
I YEAR/I SEM
for(j=0;j<=n-1;j++)
{
c[i][j] = a[i][j] + b[i][j]; // addition of A and B matrix
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
Same program can be written for matrix subtraction with - sign c[i][j] = a[i][j] - b[i][j];

Matrix multiplication: Output:


#include<stdio.h> enter the size
int main() 2
{ 2
int i, j, k,m,n; Enter A matrix
int a[10][10], b[10][10]; 2
int c[10][10]={0}; 2
printf("enter the size"); 2
scanf("%d%d",&m,&n); 2
printf("Enter A matrix\n"); Enter B matrix
for (i = 0; i <=m-1; i++) 2
{ 2
for (j = 0; j <=n-1; j++) 2
{ 2
scanf("%d", &a[i][j]); The product of matrix is
} 8 8
} 8 8
printf("Enter B matrix\n");
for (i = 0; i <= m-1; i++)
{
for (j = 0; j <=n-1; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("The product of matrix is\n");
for (i = 0; i <=m-1; i++)
{
for (j = 0; j <=n-1; j++)
{
for (k = 0; k <=m-1; k++)
{
c[i][j] = c[i][j] + a[i][k]*b[k][j];
}
printf("%d\t", c[i][j]);
I YEAR/I SEM
}
printf("\n");
}
return(0);
}
C Program to perform scalar multiplication: Enter Rows and Columns of
#include <stdio.h> Matrix
int main() 2
{ 2
int a[50][50]; enter the elements of matrix
int m, n, i, j, scalar; 2
printf("Enter Rows and Columns of Matrix\n"); 1
scanf("%d %d", &m, &n); 3
5
printf("enter the elements of matrix\n"); Enter a scalar number to
for(i = 0; i <=m-1; i++) multiply with matrix
for(j = 0; j <=n-1; j++) 5
scanf("%d", &a[i][j]); Product Matrix is
10 5
printf("Enter a scalar number to multiply with matrix \n"); 15 25
scanf("%d", &scalar);
/* Multiply each element of matrix with scalar*/
for(i = 0; i <= m-1; i++)
{
for(j = 0; j <=n-1; j++)
{
a[i][j] = a[i][j]*scalar;
}
}

printf("Product Matrix is\n");


for(i= 0; i <=m-1; i++)
{
for(j = 0; j<=n-1; j++)
printf("%d ", a[i][j]);
}
printf("\n");
return(0);
}
C Program to TRANSPOSE a matrix: Output:
#include <stdio.h> Enter the SIZE of the matrix
int main() 2
{ 3
int a[10][10], i, j, m, n; Enter the ELEMENTS of the
printf("Enter the SIZE of the matrix \n"); matrix
scanf("%d %d", &m, &n); 2
I YEAR/I SEM
printf("Enter the ELEMENTS of the matrix\n"); 1
for (i = 0; i <= m-1; i++) 5
{ 3
for (j = 0; j<= n-1; j++) 7
{ 8
scanf("%d", &a[i][j]); The given matrix is
} 215
} 378
printf("The given matrix is \n"); Transpose of matrix is
for (i = 0; i <=m-1; ++i) 23
{ 17
for (j = 0; j <= n-1; ++j) 58
{
printf(" %d", a[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j <=n-1; j++) //interchanging rows and
columns
{
for (i = 0; i <=m-1; i++)
{
printf(" %d", a[i][j]);
}
printf("\n");
} return(0);
}
C program to find determinant of 2*2 Matrix :
#include<stdio.h>
int main()
{ Example:
int a[2][2],i,j; Output:
long determinant;
printf("Enter the elements of matrix:\n "); Enter the elements of matrix:
for(i=0;i<2;i++) 8
for(j=0;j<2;j++) 3
scanf("%d",&a[i][j]); 2
1
printf("\nThe matrix is\n"); The matrix is
for(i=0;i<2;i++) 8 3
{ 2 1
printf("\n"); for(j=0;j<2;j+ Determinant is :2
+)
printf("%d\t",a[i][j]);
}
I YEAR/I SEM
determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\nDeterminant is :%ld",determinant);
return(0);
}
Determinant of 3*3 matrix Enter the elements of
#include<stdio.h> matrix: 1
int main() 5
{ 4
int a[3][3],i,j; 2
int determinant=0; 1
printf("Enter the elements of matrix: "); 2
for(i=0;i<3;i++) 1
for(j=0;j<3;j++) 2
scanf("%d",&a[i][j]); 1
printf("\nThe First matrix is\n");
for(i=0;i<3;i++) The First matrix is
{
printf("\n"); for(j=0;j<3;j+ 1 5 4
+) 2 1 2
printf("%d\t",a[i][j]); 1 2 1
} Determinant of matrix is: 9
for(i=0;i<3;i++)
determinant = determinant + (a[0][i]*(a[1][(i+1)%3]*a[2]
[(i+2)%3] -
a[1][(i+2)%3]*a[2][(i+1)%3]));
printf("\nDeterminant of matrix is: %d",determinant);
return(0);
}
Three Dimensional array:
Total number of elements that can be stored in a multidimensional array can be calculated
by multiplying the size of all the dimensions.
Example:
int arr[5][10][20] can store total (5*10*20) = 1000 elements totally.

Disadvantages of an array:
 The elements in an array must be same data type.
 The size of an array is fixed. we can’t expand the size in run time.
 The insertion and deletion operations in an array require shifting of
elements which takes more time.
I YEAR/I SEM
INTRODUCTION TO STRINGS
Nowadays, computers are widely used for word processing applications such as creating,
inserting, updating, and modifying textual data. Besides this we need to search for a
particular pattern within a text, delete it, or replace it with another pattern. So there is
actually a lot we as users do to manipulate the textual data.

Programming Tip: Character constants are enclosed in single quotes. String constants
are enclosed in double quotes.

In C language, a string is a null-terminated character array. This means that after the last
character, a null character ('\0') is stored to signify the end of the character array. For
example, if we write

char str[] = "HELLO";

We are declaring a character array that has five usable characters namely, H, E, L, L, and
O. Apart from these characters, a null character ('\0') is stored at the end of the string. So,
the internal representation of the string becomes HELLO'\0'. To store a string of length 5,
we need 5 + 1 locations (1 extra for the null character). The name of the character array
(or the string) is a pointer to the beginning of the string. Figure 6.1 shows the difference
between character storage and string storage.

If we declare str as,

char str[5] = "HELLO";

Then the null character will not be appended automatically to the character array. This is
because str can hold only 5 characters and the characters in HELLO have already filled the
locations allocated to it.
I YEAR/I SEM
Note

When the compiler assigns a character string to a character array, it automatically


appends a null character to the end of the string. Therefore, the size of the string should
be equal to maximum number of characters in the string plus one.

Programming Tip: When allocating memory space for a character array, reserve space
to hold the null character also.

Like we use subscripts (also known as index) to access the elements of an array, similarly
subscripts are also used to access the elements of the character array. The subscript
starts with a zero (0). All the characters of a string array are stored in successive memory
locations. Figure 6.2 shows how str[] is stored in ed in memory.

Thus we see that a string is a sequence of characters. In Figure 6.2, 1000, 1001, 1002, and
so on are the memory addresses of individual characters. From the figure, we see that H
is stored at memory location 1000 but in reality the ASCII codes of characters are stored
in memory and not the character itself, i.e., at address 1000, 72 will be stored since the
ASCII code for H is 72.

char str[] = "HELLO";

The above statement declares a constant string as we have assigned value to it while
declaring the string. However, the general form of declaring a string is

char str[size];

When we declare the string in this way, we can store size -1 characters in the array
because the last character would be the null character. For example, char mesg [100]; can
store a maximum of 99 usable characters.

Till now we have seen one way of initializing strings. The other way to initialize a string is
to initialize it as an array of characters, like

char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};


I YEAR/I SEM
In this example, we have explicitly added the null character. Also observe that we have
not mentioned the size of the string (or the character array). Here, the compiler will
automatically calculate the size based on the number of elements initialized. So, in this
example 6 memory slots will be reserved to store the string variable, str.

We can also declare a string with size much larger than the number of elements that are
initialized. For example, consider the statement below:

char str [10] = "HELLO";

In such cases, the compiler creates a character array of size 10; stores the value "HELLO"
in it and finally terminates the value with a null character. Rest of the elements in the
array are automatically initialized to NULL. Figure 6.3 shows the memory representation
of such a string.

Consider the following declaration:

char str[3];

str =

"HELLO";

The above declaration is illegal in C and would generate a compile time error because of
two reasons. First, the array is initialized with more elements than it can store. Second,
initialization cannot be separated from declaration.

Note

An array name cannot be used as the left operand of an assignment operator. Therefore,
the following statement is illegal in C.

char str2, str1[]="HI";

str2 = strl;
I YEAR/I SEM

Reading Strings
If we declare a string by writing

char str[100];

Then str can be read by using three ways:

1. using scanf function

2. using gets () function

3. using getchar(), getch() or getche () function

repeatedly Strings can be read using scanf() by writing

scanf("%s", str);

Programming Tip: Using & operand with a string variable in the scanf statement is
optional as string variable is a character array and denotes the address where the array
begins.

Although the syntax of scanf() function is well known and easy to use, the main pitfall
with this function is that the function terminates as soon as it finds a blank space. For
example, if the user enters Hello World, then str will contain only Hello. This is because
the moment a blank space is encountered, the string is terminated by the scanf()
function. You may also specify a field width to indicate the maximum number of
characters that can be read in. Remember that extra characters are left unconsumed in
the input buffer.

Unlike int (%d), float (f), and char (c), %s format does not require ampersand before the
variable name.

Note

When scanf() encounters a white space character, it ter- minates reading further and
appends a null character to the string that has been read. The white space character is
left in the input stream and might be mistakenly read by the next scanf() statement. So
in order to delete the white space character from the input stream, either use a space in
the format string before the next conversion code or FLUSH the input stream by using
the fflush function by writing fflush(stdin).

The next method of reading a string is by using gets () function. The string can be read by
writing

gets (str);
I YEAR/I SEM
gets () is a simple function that overcomes the drawbacks of the scanf() function. The
gets () function takes the starting address of the string which will hold the input. The
string inputted using gets () is automatically terminated with a null character.

Last but not the least, strings can also be read by calling the getchar() function repeatedly
to read a sequence of single characters (unless a terminating character is entered) and
simultaneously storing it in a character array as shown below.

i=0;

ch = getchar(); // Get a character

while (ch != '*')

str[i] = ch;

// Store the read character in str

i++;

ch= getchar(); // Get another character

str[i] = '\0'; // terminate str with null character

Programming Tip: A compile time error will be generated if a string is assigned to a


character variable.

Note that in this method, you have to deliberately append the charac- ters with a null
character. The other two functions automatically do this.

Writing Strings
Strings can be displayed on screen using three ways:

1. using printf() function

2. using puts() function

3. using putchar () function repeatedly

A string can be displayed using printf () by writing


I YEAR/I SEM
printf("%s", str);

We use the conversion character 's' to output a string. We may also use width and
precision specifications along with %s (as discussed in Chapter 2). The width specifies the
minimum output field width. If the string is short, extra space is either left padded or right
padded. A negative width left pads short string rather than the default right justification.
The precision specifies the maximum number of characters to be displayed. If the string is
long, the extra characters are truncated. For example,

printf("%5.3s", str);

The above statement would print only the first three characters in a total field of five
characters. Also these three characters are right justified in the allocated width. To make
the string left justified, we must use a minus sign. For example,

printf("%-5.3s", str);

Note

When the field width is less than the length of the string, the entire string will be
printed. Also if the number of characters to be printed is specified as zero, then nothing
is printed on the screen.

The next method of writing a string is by using puts () function. The string can be displayed
by writing

puts (str);

puts () is a simple function that overcomes the drawbacks of the printf() function. The
puts () function writes a line of output on the screen. It terminates the line with a newline
character ('\n'). It returns an EOF (-1) if an error occurs and returns a positive number on
success. Last but not the least, strings can also be written by calling the putchar() function
repeatedly to print a sequence of single characters.

i=0;

while (str[i] != '\0')

putchar (str[i]);

// Print the character on the screen


I YEAR/I SEM
i++;

Note

Note one interesting point from the given fragment.

char str = "Hello";

printf("\n %s", str); // prints Hello

printf("\n %s", &str); // prints Hello

printf("\n %s", &str[2]); // prints llo

This is possible because a string is an array of characters.

Summary of Functions Used to Read and Write Characters


Table 6.1 contains a list of functions that are used to read characters from the keyboard
and write characters to the screen.

1. Write a program to display a string using printf().


#include <stdio.h>

#include

<conio.h> int

main()

char str[] = "Introduction to C";

clrscr();

printf("\n |%\s", str);

printf("\n |%20s|", str);

printf("\n |%-20s", str);

printf("\n %.4s", str);

printf("\n |%20.4s", str);


I YEAR/I SEM
printf("\n %-20.4s", str);

getch();

return 0;

Output

| Introduction to C |

| Introduction to C |

| Introduction to C |

| Intr |

| Intr |

| Intr |

The printf() function in UNIX supports specification of variable field width or precision, i.e.,
if we write,

printf("\n %*.s*, w, p, str);


I YEAR/I SEM
Then the printf() statement will print first p characters of str in the field width of w.

2. Write a program to print the following

pattern. H

HE

HE

HELL

H E L L

O H E L

L O H E

LL

HE

LH

EH
#include <stdio.h>

#include

<conio.h> int

main()

int i, w, p;

char str[] = "HELLO";

printf("\n");

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


I YEAR/I SEM
{

p = i+1;
I YEAR/I SEM
printf("\n %-5.*s", p, str);

printf("\n");

for (i=4;i>=0; i--)

p = i+1;

printf("\n %-5.*s", p, str);

getch();

return 0;

sprintf() Function
The library function sprintf() is similar to printf (). The only difference is that the formatted
output is written to a memory area rather than directly to a standard output
(screen). sprintf() is useful in situations when formatted strings in memory have to be
transmitted over a communication channel or to a special device. The syntax
of sprintf() can be given as

int sprintf( char * buffer, const char * format [ , argument, ..] );

Here, buffer is the place where string needs to be stored. The arguments command is an
ellipsis so you can put as many types of arguments as you want. Finally, format is the
string that contains the text to be printed. The string may contain format tags.

#include

<stdio.h> main()

char buf[100];

int num = 10;


I YEAR/I SEM
sprintf(buf, "num = %3d", num);

}
I YEAR/I SEM
UNIT III FUNCTIONS AND POINTERS

Library functions: Math functions, other miscellaneous functions such as getchar(), putchar(), malloc(),
calloc().
User defined functions - function definition, functions declaration, function call, scope of variables - local
variables, global variables.
Function parameters: Parameter passing- call by value & call by reference, Passing arguments to
Functions, Recursive functions. Storage classes-auto, register, static, extern, scope rules.

Library functions play a crucial role in programming by providing ready-made solutions to


common tasks. Here's a brief overview of some categories of library functions:

1. **Math Functions**: These functions are part of the `<math.h>` library in C and C++. Some
commonly used math functions include:
- `sin`, `cos`, `tan`: Trigonometric functions
- `exp`, `log`, `log10`: Exponential and logarithmic functions
- `sqrt`, `pow`: Square root and power functions
- `ceil`, `floor`: Ceiling and floor functions
- `abs`: Absolute value
- `round`, `trunc`: Rounding functions

Example:
```c
#include <math.h>
double result = sin(3.14);
```

2. **Character I/O Functions**: These functions handle character input and output operations. In
C, `getchar()` and `putchar()` are commonly used.
- `getchar()`: Reads a single character from standard input (usually the keyboard).
- `putchar()`: Writes a single character to standard output (usually the console).

Example:
```c
int ch = getchar();
I YEAR/I SEM
putchar(ch);
```

3. **Dynamic Memory Allocation Functions**: These functions allow dynamic memory allocation
during runtime, managed through `<stdlib.h>`.
- `malloc()`: Allocates a block of memory of a specified size in bytes.
- `calloc()`: Allocates a block of memory for an array of elements, initialized to zero.
- `realloc()`: Resizes the previously allocated block of memory.

Example:
```c
#include <stdlib.h>
int *arr = malloc(10 * sizeof(int)); // Allocates memory for an array of 10 integers
```

These functions are essential in programming as they provide efficient and tested implementations
for tasks like mathematical calculations, character input/output, and memory management, saving
developers from having to implement these functionalities from scratch.

FUNCTIONS:

o A function is a block of code or set of statements that are used toperform a particular task
which repeatedly occurs in the main program.
o By using functions, we can divide complex problem into small components that makes
program easy to understand and use.
o A function is often executed several times, from several different places(sub function) during
the execution of the program.
o After executing the subprogram, the program control return back to main function.

Functions are Classified into two types:

(i) User defined functions:


 User-defined functions are those functions which are defined(written) by the user according to
their requirements.
I YEAR/I SEM
 Users have full scope to implement their own ideas in the function.
 Examples: add (), sub (), mul()
How function works?
1. Once the function is called from main
function, it takes some data to the sub
function(called function)
2. When the program control is passed to
sub function, working of main function is
temporarily stopped.
3. Once the execution of sub function is
completed, again program control returns
back to main function(calling function).

Elements of user defined function:( Components)


1. Function declaration or prototype
2. Function definition
3. Function call
(i) Function Declaration:
- Likevariableand an array, a functionmust also bedeclaredbefore it is called.
- A function declaration tells the compiler about a function name and how to call the
function.
Syntax Example
return-type function-name (parameter-list) ; int add(int x, int y);

Return type: int, char, float, void


Function name: specifies the name of the function.
Parameter list: list of variables with data type separated by comma
(ii) Function Definition (function-body)
The function bodycontains following 3 parts.
Bodyis enclosed within curly braces {}.
 Local variable declaration.
 Execution statement that performs specific task.
 return statement that return the value evaluated by the function.

Syntax Example
return-type function-name (parameter-list) int add(int x,int y)
{ {
body of function; int z;
} z=x+y;
return(z);
}
return Statement:
return type specifies the type of value(int, float, char, double) that function is expected to return to the program
calling the function.
It may or may not present send back result to calling function.
Syntax Example
return; return;
I YEAR/I SEM
return(); return();
return(value); return(1);
return(variable); return(c);
Note:
 Default data type is int.
 Only one value can be returned to a function. Pointers are used to return more values.
 If return (a,b,c) is used, only c value is returned to the function
Example:

int add(int x, int y) // function definition


{
int z; //local declaration
z=x +y //execution statement
return(z); //returnstatement
}
Note:
If a function does not return any value, then keyword void must be used as return type while declaring
function definition.

(iii) Function Call:

Calling the function by simply specifying the function name, return value and parameters if present.
Syntax Example
return_variable= function_name(arg1, arg2, ….arg n); c=add(x,y);

Simple Program to add two numbers using function: Output:


#include<stdio.h> enter two numbers
int add(int,int); 5
int main() 6
{ The sum is 11
int a,b,c;
printf("enter two numbers\n");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The sum is %d",c);
return(0);
}
int add(int x,int y)
{
int z;
z=x+y;
return(z);
}

Types of Arguments/Parameters:

Actual parameter – Parameters transferred from calling function(main function) to called


function(function definition)
Formal Parameters - Parameters transferred to calling function(main function) from called
function(function definition)
Example:
I YEAR/I SEM

Global And Local Variable:


Local Variables: Global Variable:
 Defined within the body of the function.  Defined outside the main function.
 Other functions cannot access these  These variables can be used throughout the
variables. program.

Program using global and local variable:


#include<stdio.h>
void test();
int m = 10, n =10 ; // global
variable int main()
{
printf("globally declared values: m=%d n=%d\n", m,n);
test();
}
void test()
{
int m=20,n=20; // local variable
printf("locally declared values: m=%d n=%d\n:",m,n);
}

Output:
globally declared values: m=10 n=10
locally declared values: m=20 n=20

FUNCTION PROTOTYPES: ( CATEGORIES OF FUNCTION)

1. Without arguments and without return type


2. Without arguments and with return type
3. With arguments and without return type
4. With arguments and with return type
I YEAR/I SEM
1. Without arguments and without return type
o There is no data transfer between calling and the called function.
o The called function is used to perform any operation. They work independently.
o They read the data values and print the results in same block.
2. Without arguments and with return type
o In this type of function , no argument are passed through the main() function. But the
called function returns the values to the main function.
o Thecalledfunctionisindependent.
3. With argument and without return type:
oIn this type the arguments are passed through the function call.
o The called function operates on the values. But no result is sent back.
4. With argument and with return type( fruitful function)
o In this type the arguments are passed through the function call.
o The result is sent back to the main function.

without arguments and without return type without argument and with return type
/* Addition of two numbers */ /* Addition of two numbers */
#include<stdio.h> #include<stdio.h>
void my_add(); int my_add();
int main()
int main() {
{ int c;
int c; c=my_add();
c=my_add(); printf("sum is %d",c);
return(0); return(0);
} }

void my_add(int x,int y) int my_add(int x,int y)


{ {
int z; int z;
printf("enter the values "); printf("enter the values ");
scanf("%d\n%d",&x,&y); scanf("%d%d",&x,&y);
z=x+y; z=x+y;
printf("sum is %d",z); return(z);
} }

Output: Output:
enter the values enter the values
5 5
6 6
sum is 11 sum is 11

With argument and without return type With argument and with return type
I YEAR/I SEM
/* Addition of two numbers */ /* Addition of two numbers */
#include<stdio.h> #include<stdio.h>
void my_add(int a,int b); int my_add(int a, int b);

int main() int main()


{ {
int a,b; int a,b,c;
printf("enter the values "); printf("enter the values ");
scanf("%d%d",&a,&b); scanf("%d%d",&a,&b);
my_add(a,b); c=my_add(a,b);
return(0); printf("sum is %d",c);
} return(0);
}
void my_add(int x,int y) int my_add(int x,int y)
{ {
int z; int z;
z=x+y; z=x+y;
printf("sum is %d",z); return(z);
} }

Output: Output:
enter the values enter the values
5 5
6 6
sum is 11 sum is 11

Calculator Program: ( with argument and with return type)


#include<stdio.h> Output:
int my_add(int a,int b); enter a,b values
int my_sub(int a,int b); 4
int my_mul(int a,int b); 3
float my_div(int a,int b); the sum is: 7
the dif is: 1
int main() the product is: 12
{ the division is: 1.000000
int a,b,c;
float d;
printf("enter a,b values\n");
scanf("%d%d",&a,&b);
c=my_add(a,b);
printf("the sum is: %d\n",c);
c=my_sub(a,b);
printf("the dif is: %d\n",c);
c=my_mul(a,b);
printf("the product is: %d\n",c);
d=my_div(a,b);
printf("the division is: %f\n",d);
return(0);
}

int my_add(int x,int y)


{
int z;
I YEAR/I SEM
z=x+y;
return(z);
}
int my_sub(int x,int y)
{
int z;
z=x-y;
return(z);
}
int my_mul(int x,int y)
{
int z;
z=x*y;
return(z);
}
float my_div(int x,int y)
{
float z;
z=x/y;
return(z);
}

Benefits of Using Functions


 Reduction in code redundancy
 Enabling codereuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability
 Powerful programming tool

BUILT-IN FUNCTIONS ( STANDARD LIBRARY FUNCTIONS)


Built-in functions are nothing but predefined functions or library functions.
These functions are defined by C library.
Example printf(), scanf(), strcat() etc.
Various standard library functions and a macro defined under:
- math.h to perform mathematical operations
- String.h Perfoms All String Operations

String Built-In Functions:


String.h header file supports all the string functions in C language.
Some of the string library functions are given below.

Function Purpose Syntax


strlen Calculates the length of the string s. strlen(str1);
strcmp Compares two strings. strcmp(str1, str2);
strcmpi Compares two strings without case sensitive. Strcmpi(str1,str2);
strcat Appendsthecopyofthestringsrc totheendofthe string dest. strcat(str1, str2);
strcpy Copies the source string src to the destination string strcpy(str1,str2);
dest.
I YEAR/I SEM
strrev Reverse the content of the string s. strrev(str1);
strlwr Converts the string to lowercase. strlwr(str1);
strupr Converts the string to uppercase. strupr(str1);
strset Set all character in a string s to the character ch. strset(str1,ch);
strnset Setthefirstncharacterinastringstothecharacter ch. Strnset(str1,ch,n);
strchr Scansastringforthefirstoccurrenceofthegiven character. strchr(str1,ch);
strrchr Scansastringforthelastoccurrenceofthegiven character. strrchr(str1,ch);
strstr Scansastringforthefirstoccurrenceofthesubstring in anotherstring. strstr(str1,ch);

Return Type:
S.no Result type Function
1 Integer strlen, strcmp,strcmpi
2 String strcat, strcpy, strrev, strupr, strlwr, strset, strnset
3 Address strchr, strnchr,strstr

Math Built-In Functions:

This function returns the nearest integer which is less than or equal to the argument
floor ( ) passed to this function.

This function returns the nearest integer value that passed to this function. If
decimal value is from “.1 to .5”, it returns integer value less than the argument. If
decimal value is from “.6 to .9”, it returns the integer value greater than the
round() argument.

This function returns nearest integer value which is greater than or equal to the
ceil() argument passed to this function.

sin() This function is used to calculate sine value.

cos() This function is used to calculate cosine.

cosh() This function is used to calculate hyperbolic cosine.

exp() This function is used to calculate the exponential “e” to the xth power.

tan() This function is used to calculate tangent.

tanh() This function is used to calculate hyperbolic tangent.

sinh() This function is used to calculate hyperbolic sine.

log() This function is used to calculates natural logarithm.

log10() This function is used to calculates base 10 logarithm.

sqrt() This function is used to find square root of the argument passed to this function.

pow() This is used to find the power of the given number.

trunk() This function truncates the decimal value from floating point value and returns
I YEAR/I SEM
integer value.

Program using different math built-in functions: Output:


#include<stdio.h> floor of 5.4 is 5.000000
#include<math.h> round of 5.4 is 5.000000
int main() ceil of 5.4 is 6.000000
{ The value of sin(3.014) : 0.127247
printf("floor of 5.4 is %f\n", floor(5.4)); The value of cos(3.014) : -0.991871
printf("round of 5.4 is %f\n", round(5.4)); The value of tan(3.014) : -0.128290
printf("ceil of 5.4 is %f\n", ceil(5.4)); The value of sinh(0.25) : 0.252612
printf("The value of sin(3.014) : %f \n", sin(3.014)); The value of cosh(0.25) : 1.031413
printf("The value of cos(3.014) : %f \n", cos(3.014)); The value of tanh(0.25) : 0.244919
printf("The value of tan(3.014) : %f \n", tan(3.014)); The value of log(6.25) : 1.832581
printf("The value of sinh(0.25) : %f \n", sinh(0.25)); The value of log10(6.25) : 0.795880
printf("The value of cosh(0.25) : %f \n", cosh(0.25)); The value of exp(6.25) : 6.250000
printf("The value of tanh(0.25) : %f \n", tanh(0.25)); sqrt of 16 = 4.000000
printf("The value of log(6.25) : %f \n", log(6.25)); 5 power 3 = 125.000000
printf("The value of log10(6.25) : %f \n",log10(6.25));
printf("The value of exp(6.25) : %f \n",6.25);
printf ("sqrt of 16 = %f\n", sqrt (16) );
printf ("5 power 3 = %f\n", pow (5, 3) );
return(0);
}

RECURSION FUNCTION:
 A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
 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.
How Recursion Function Works?

The recursion continues until some condition is met .i,e it must have at least one if statement to
terminate the recursion.

A Recursion Function must have the following statements:


- A statement to test whether function is calling itself again.
- A statement that calls the function itself must be an argument
- A conditional statement( if-else)
- A return statement
Advantages of recursion:
I YEAR/I SEM
- Recursion makes program simple and ease
- All algorithms can be defined recursively which makes it easier to visualize and prove.
Disadvantages of recursion:
- Recursions use more memory and are generally slow. Instead, you can use loop.
Program Output

Program to find factorial of a given number: enter a number 5


#include<stdio.h> Factorial of a given number is
int fact(int n); 120
int main()
{
int f,n;
printf(" enter a number");
scanf("%d",&n);
f=fact(n);
printf("Factorial of a given number is %d",f);
return(0);
}
int fact(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
Program to compute GCD of two given numbers enter two integers
#include<stdio.h> 6
int gcd(int x,int y); 12
int main() gcd of two numbers is :6
{
int a,b;
printf("enter two integers\n"); scanf("%d
%d",&a,&b);
printf("gcd of two numbers is :%d %d\n",gcd(a,b));
return(0);
}
int gcd(int x,int y)
{
if(y!=0)
return gcd(y,x%y);
else
return(x);
}
To find Sum of n numbers using recursion function : Enter a positive integer: 3
#include <stdio.h> sum=6
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
} I YEAR/I SEM
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
Sum of N numbers –How Recursive Function works.

Illustrative Program:
i) Computation of Sine series
ii) Scientific calculator using built-in functions (refer book page no 5.33)
iii) Binary Search using recursive functions .

Conputation of Sine Series:


Sine Series is a series which is used to find the value of Sin(x).
where, x is the angle in degree which is converted to Radian.

The formula used to express the Sin(x) as Sine Series is


I YEAR/I SEM

Expanding the above notation, the formula of Sine Series is

For example,

Let the value of x be 30.

So, Radian value for 30 degree is 0.52359.

So, the value of Sin(30) is 0.5.

Computation of Sine Series Output


#include<stdio.h> Enter the value for x : 30
int main() Enter the value for n : 5
{ The value of Sin(0.523598) = 0.5000
int i, n;
float x, sum, t;
printf(" Enter the value for x : ");
scanf("%f",&x);
printf(" Enter the value for n : ");
scanf("%d",&n);
x=x*3.14159/180;
t=x;
sum=x;
/* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" The value of Sin(%f) = %.4f",x,sum);
}

Binary Search Using Recursion Output:


#include <stdio.h> enter the element to search
int binarySearch(int arr[], int left, int right, int x) 75
{ Element is present at index 3
if (right >= left)
{
int mid = left + (right - left)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x) I YEAR/I SEM
return binarySearch(arr, left, mid-1, x);
return binarySearch(arr, mid+1, right, x);
}
return -1;
}
int main(void)
{
int arr[]= {25,35,50,75,100};
int x, result;
int n = sizeof(arr)/ sizeof(arr[0]);
printf("enter the element to search");
scanf("%d",&x);
result = binarySearch(arr, 0, n-1, x);
if (result ==-1)
printf("Element is not present in array");
else
printf("Element is present at index %d",result);
return 0;
}
I YEAR/I SEM
UNIT IV STRUCTURES
Basics of structures-structure data types, type definition, accessing structures, Structure operations,
Complex structures-nested structures, structures containing arrays, Array of structures, Structures and
Functions, Unions. Pointers: Understanding Computer Memory –Memory Management-Dynamic
memory Allocation-Memory leaks- Introduction to Pointers – declaring Pointer Variables – Pointer
Expressions and Pointer Arithmetic – Null Pointers – Generic Pointers - Passing Arguments to Functions
using Pointer – Pointer and Arrays –Use of pointers in self-referential structures, notion of linked list.

STRUCTURES:
- Structure is a collection of various data types shares a common name.
- It is a user defined data type.
- Each element in a C structure is called member.
Example:
Student: name, roll no, mark, avg
Book: author, title, price, year
Address: door no, street name, place, state, pin
Arrays Structures

Collection of similar data types. Collection of different data types.

Static memory allocation is done in arrays Dynamic memoryallocation is done in structures.

It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to access members of
an arrayelement. structures

Array is a pointer to its first element. Structure is not a pointer.

Array is a derived data type. Structure is a user defined data type.

Accessing array element takes less time Accessingstructuremembertakesmore time.

It has no keywords. It uses keyword“struct”

Steps :
1. Declaring structure
2. Declaring structure variable
3. Initializing the members of the structure
4. Accessing the members of structure
1. Declaring structure:
Syntax: Example:

struct tag_name struct student

{ {

datatype member 1; char name[10];

datatype member2; int roll_no;

float percentage;

datatype membern; };

};

Keyword struct is used for creating a structure. Note: semicolon }; in the ending line is must.

2. Declaring structure variable

Syntax: Example:
I YEAR/I SEM
struct tag_name

{ struct student

datatype member1; {

datatype member2; char name[10];

datatype member3; int roll_no;


‘ float percentage;
‘ }
struct book s1,s2;
datatype membern;

} variable1, variable2,……. variable n; Note:


Structure variable can be declared within the structure definition or
in the main function.

3. Initializing the members of structure:


Initialization can be done in 2 ways.
 Compile time initialization:
- uses assignment operator(=) to initialize values to the members of structure.
Example:
struct student s1={“ramya”,1001,45.8};
struct student s2={“anitha”,1002,89.6};
 Run time initialization:
- uses scanf function to read the input from the user.
Example:
printf("enter s1 student details"); scanf("%s%d
%f",s1.name,&s1.roll_no,&s1.percentage); printf("enter s2
student details"); scanf("%s%d
%f",s2.name,&s2.roll_no,&s2.percentage);

4. Accessing the members of the structure:


- Members can be accessed using .operator (dot). Also pointer operator is used(->)
Syntax:
structure_variable_name . member_name;
Example:
s1.name // to access name of s1
s2.percentage // to access percentage of
s2
Program to print student details( accessing member using .dot operator): Output:
#include<stdio.h> Enter rollno, name , percentage
struct student 1001
{ ramya
int roll; 96.8
char name[10]; Student details are:
float percentage; ROLL_NO=1001 NAME=ramya
}s1; PERCENTAGE=96.80000
int main()
{
printf("Enter rollno, name , percentage\n");
scanf("%d%s%f", &s1.roll, s1.name, &s1.percentage);
printf("Student details are:\n");
printf ("ROLL_NO=%d\n NAME=%s\n PERCENTAGE=%f\n", s1.roll, s1.name,
s1.percentage);
return(0);
}
I YEAR/I SEM
NESTED STRUCTURE:
I YEAR/I SEM
A structure with in a structure is called nested structure.
The elements of nested structure are accessed using dot (.) operator.

Syntax:
structure tagname_1 Example:
{ struct Employee
data_type member1; {
data_type member2; char ename[20];
data_type member3; int empid;
.. int salary;
member n; struct date
structure tagname_2 {
{ int day;
data_type member_1; int month;
data_type member_2; int year;
data_type member_3; }doj;
... }emp;
member_n;
} var1;
} var2;

Syntax:

outrstructurevariable . innerstructure variable . innerstructuremember

To Access the Nested members,

Accessingmonth Field: emp1.doj.month

AccessingdayField : emp1.doj.day

Accessingyear Field : emp1.doj.year


I YEAR/I SEM
Program to display employee details using nested structure: Output:
#include <stdio.h>
struct Employee Employee Name : ramya
{
char ename[20];
int empid; Employee ID : 1001
int salary;
struct date Employee Salary : 25000
{
int day; Employee DOJ : 25/9/1988
int month;
int year;
}doj;
}emp;
int main()
{
struct Employee emp={"ramya",1001,25000,{25,9,1988}};
printf("\nEmployee Name : %s",emp.ename); printf("\
nEmployee ID : %d",emp.empid); printf("\
nEmployee Salary : %d",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", emp.doj.day, emp.doj.month, emp.doj.year);
return 0;
}

ARRAY OF STRUCTURES:

- Array of structures is nothing but collection of structures.


- Declaring an array of structure is same as declaring an array of fundamental types.
- This is also called as structure array in c.
I YEAR/I SEM

- Here s is an array of 5 elements where each element is of type struct student.


- We can use s to store 5 structure variables of type struct student.
- To access individual elements we will use subscript notation ([]) and to access the members of each element we will use dot (.)
operator as usual.

Accessing members of array structure:


s[0] : points to the 0th element of the array.
s[1] : points to the 1st element of the array.

s[0].name : refers to the name member of the 0th element of the array.
s[0].roll_no : refers to the roll_no member of the 0th element of the array.
s[0].marks : refers to the marks member of the 0th element of the array.

Program to print 5 student details using array of structures: Output:


#include<stdio.h>
#define MAX 5 Enter details of student 1
struct student Enter name: ravi
{ Enter roll no: 1005
char name[20]; Enter marks: 89.6
int roll_no, i;
float marks; Enter details of student 2
}; Enter name: priya
int main() Enter roll no: 1002
{ Enter marks: 89.6
struct student s[5];
int i; Enter details of student 3
for(i = 0; i < MAX; i++) Enter name: mahesh
{ Enter roll no: 1003
printf("\n Enter details of student %d\n\n", i+1); Enter marks: 56.9

printf("Enter name: "); Enter details of student 4


scanf("%s", s[i].name); Enter name: rini
Enter roll no: 1004
printf("Enter roll no: "); Enter marks: 96
scanf("%d", &s[i].roll_no);
Enter details of student 5
printf("Enter marks: "); Enter name: ram
scanf("%f", &s[i].marks); Enter roll no: 1005
} Enter marks: 36.9

printf("\n");
printf("Name\tRoll no\tMarks\n");
for(i = 0; i < MAX; i++ )
{
printf("%s\t%d\t%.2f\n",
s[i].name, s[i].roll_no, s[i].marks);
}
I YEAR/I SEM
return 0;
}
Note:
Here, array of size 5 to store information of 5 students.

How To Find the Size of Structure?


- sizeof() function is used to find the size of structure.
- sizeof can be applied to any data-type, including primitive types such as integer and floating-point
types, pointer types, or compound datatypes such as Structure, union etc.Syntax:
Example: (Sizeof() for structure)
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
};
int main()
{
printf("Size of book structure is :%d",sizeof(b1.bookname));
}
Output:
Size of book structure is :84

POINTER AND STRUCTURE:


C structure can be accessed in 2 ways in a C program. They are,
(i) Using normal structure variable
(ii) Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and
Arrow (->) is used to access the data using pointer variable.
Syntax: Example:
struct name struct product
{ {
member1; int prod_id;
member2; char prod_name[20];
. float price;
}; };
struct name *ptr; struct product *p1;

Difference between normal structure variable and pointer variable:


I YEAR/I SEM

Example:
Displaying book details using pointer to a structure:
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
float price;
};
int main()
{
struct book b1; // structure variable
declaration struct book *ptr; // pointer
variable declaration ptr=&b1; // pointer variable
initialization printf("enter the bookid\n");
scanf("%d",&ptr->bookid);
printf("enter the book name\
n"); scanf("%s",ptr-
>bookname); printf("enter
author\n"); scanf("%s",&ptr-
I YEAR/I SEM
>author);
I YEAR/I SEM
printf("Enter price");
scanf("%f",&ptr->price);
printf("book details are\n: %d\t %s\t %s\t %f\n\n",ptr->bookid,ptr->bookname,ptr->author,ptr->price);
}
Output:
enter the bookid
1001
enter the book name
python
enter author
Rossum
Enter price 450
book details are
1001 python Rossum 450.000000

DYNAMIC MEMORY ALLOCATION:


Why do we need to go for Dynamic Memory Allocation?
 We know, an array is uses static memory allocation technique because, the size of the array is fixed. So we cannot increase or
decrease the size of the array once size is declared.
 Hence, the array we declared may be insufficient or sometimes size may be more than what we required.
 To solve this issue, we can allocate memory dynamically.
Dynamic Memory Allocation:
 The process of allocating memory during program execution is called dynamic memory allocation.
 It allows us to manually handle memory space for our program.
There are 4 library functions defined under <stdlib.h> which can be used for dynamic memory allocation.
They are,
malloc()
calloc()
realloc()
free()

(i) malloc() function:


- malloc() stands for "memory allocation".
- malloc () function is used to allocate space in memory during the execution of the program.
- This function reserves a block of memory of the given size and returns a pointer of type void (that is to be typecasted)

Syntax:
Pointer_variable= (type_cast*) malloc(Size_in _bytes)
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
Here, 50 represents the total size to be allocated depending upon 16 bit or 32 bit processor. Hence given, sizeof() function irrespective of 2
byte or 4 byte integer
- If it fails to allocate enough space as specified, it returns a NULLpointer.
- malloc () does not initialize the memory allocated during execution. It carries garbage value.
Program (to copy a string to allocated memory using malloc()):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
I YEAR/I SEM
int main()
{
char *ptr;
ptr = (char*)malloc( 20 * sizeof(char) ); // memory is allocated dynamically
if( ptr== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning

(ii) calloc() function:


 The name calloc() stands for "contiguous allocation".(continues)
 calloc() is another memory allocation function that is used for allocating memory at runtime.
 This statement will allocate contiguous space in memory for an array of n elements.
 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
 calloc () initializes the allocated memory to zero. But, malloc() does not.
 If it fails to allocate enough space as specified, it returns a NULL pointer.

Syntax:
Pointer_variable= (type_cast*) calloc(n, element_size)
Example:
float *y;
y= (float*) calloc(25, sizeof(float));
Note:
This statement allocates contiguous space in memory to store 25 elements each of size of float( i.e, 4 bytes)

Program: (To copy a string to allocated memory using calloc() ):


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char*)calloc( 20,sizeof(char) ); // memory is allocated dynamically
if( ptr== NULL)
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning
I YEAR/I SEM
(iii) realloc():
- realloc() used to change the memory size that is already allocated using malloc() and calloc() functions.

Syntax:
ptr = realloc(ptr, newsize); //ptr is reallocated with size of newsize.
Example:
int *x;
x = (int*)malloc(50 * sizeof(int));
x = (int*)realloc(x,100); //allocated a new memory to variable x

Difference between malloc() and calloc():

free()
- free() to release the space that are allocated using memory by malloc (), calloc (), realloc () functions .
- It returns the memory to the system.
Syntax:
free(pointer_variable);
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable
x free(x); //releases the memory allocated to variable x

Program: ( To copy a string to allocated memory using realloc())


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char *)malloc( 20 * sizeof(char) ); //memory is allocated dynamically
if( ptr == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content : %s\n", ptr );
ptr=realloc(ptr,100*sizeof(char));
strcpy( ptr,"can store 100 characters");
printf("Resized memory : %s\n", ptr);
free(ptr);
}
I YEAR/I SEM
Output:
Dynamically allocated memory content : good morning
Resized memory : can store 100 characters

C Program to generate Salary Slip of employee( Dynamic memory allocation for Structure using pointers):
#include <stdio.h> Output:
#include<stdlib.h> enter the number of employee2
struct employee enter the nameravi
{ Enter Basic Salary (RS): 12000
char name[10];
int basic, da, hra, ta, others; Enter Hra1000
int pf,it,t;
int net_salary; Enter da500
}e[10];
int main() Enter TA500
{

int i,n; Enter Others1000


struct employee *ptr;
printf("enter the number of employee"); Enter pf500
scanf("%d",&n);
ptr=(struct employee*)malloc(n * sizeof(struct Enter IT1000
employee)); for(i=0;i<n;i++) enter the nameraja
{ Enter Basic Salary (RS): 25000
printf("enter the name");
scanf("%s",(ptr+i)->name); Enter Hra1000
printf("Enter Basic Salary (RS):
"); scanf("%d",&(ptr+i)->basic); Enter da1000
printf("\nEnter Hra");
scanf("%d",&(ptr+i)->hra); Enter TA1000
printf("\nEnter da");
scanf("%d",&(ptr+i)->da); printf("\ Enter Others500
n Enter TA");
scanf("%d",&(ptr+i)->ta); printf("\ Enter pf1000
nEnter Others");
scanf("%d",&(ptr+i)->others); Enter IT1500
printf("\nEnter pf");
scanf("%d",&(ptr+i)->pf); printf("\ Name is ravi Net Salary is:RS 13500
nEnter IT"); scanf("%d",&(ptr+i)-
>it); Name is raja Net Salary is:RS 26000

//calculate net salary


(ptr+i)->net_salary = (ptr+i)->basic + (ptr+i)->da + (ptr+i)->hra + (ptr+i)->ta
+ (ptr+i)->others - ((ptr+i)->pf+(ptr+i)->it);
}
//printing Net salary for(i=0;i<n;i+
+)
{
printf("\n Name is %s",(ptr+i)->name);
printf("\t Net Salary is:RS %d\n",(ptr+i)->net_salary);
}
return(0);

SELF REFERENTIAL STRUCTURES:

A structure that contains at least one pointers to a structure as its member along with other members is known as self-referential structure.
I YEAR/I SEM
Pointer variable declaration in structure Self-referential structure declaration
struct name { struct name {
member 1; member 1;
member 2; member 2;
... ...
member n; struct name *pointer;
}; };
struct name *pointer;

The above illustrated self referential structure prototype describes one node that comprises of two logical segments.
One segment stores data and the other segment is a pointer indicating where the next element is present.
Several such inter-connected nodes create a chain of structures(Linked List).

 A self-referential structure can dynamically be expanded or contracted.


 Operations like insertion or deletion of nodes in a self- referential structure involve simple and straight forward alteration of
pointers.
Singly Linked List(Linear List):
In linked list, elements are not stored at contiguous location; the elements are linked using pointers.
A linked list is represented by a pointer to the first node of the linked list.
The first node is called head. If the linked list is empty, then value of head is
NULL. Each node in a list consists of at least two parts:
1) data
2) pointer to the next node
In C, we can represent a node using structures.
Below is an example of a linked list node with an integer data.
Operations on Linked List:
1. Inserting a node in linked list:
A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.
i) Insertion at the front of linked list:
When a new node is added at the front, it becomes the header of the list. Here, Node E is added at the front. Hence E becomes the
header node and not A.

ii) Inserting node at a given position

iii) Inserting at the End


I YEAR/I SEM

2. Deleting a node:
If node to be deleted is root, simply delete it.
To delete a middle node, we must have pointer to the node previous to the node to be deleted. So if positions is not zero, we run a loop
position-1 times and get pointer to the previous node.
Advantages of linked list over arrays:
1) list uses Dynamic size whereas, array uses static size.
2) Easy to insert/delete element in list where as array requires shifting of elements.
Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search
with linked lists.
2) Extra memory space for a pointer is required with each element of the list.

Program to insert, delete and display the elements in singly linked list Output:

Program : enter the number of nodes


#include<stdio.h> 4
#include<stdlib.h> Enter the element
#define NULL 0 10
typedef struct list enter the element20
{ enter the element30
int no; enter the element40
struct list *next; enter ur option=
}LIST; 1.insert 2.delete 3.display 4.exit
3
LIST *p,*t,*h,*y,*ptr,*pt;
List elements are:
void create(void);
10 20 30 40
void insert(void);
Enter your option
void delet(void);
1
void display(void); enter the element to be inserted
int j,pos,k=1;count; 35
void main() enter the position to insert
{ 4
int n,i=1,opt;
printf("%d",sizeof(LIST)); Enter your option
printf("enter the number of nodes\n"); 3
scanf("%d",&n); List elements are:
count=n; 10 20 30 35 40
while(i<=n) Enter your option
{ 2
create(); enter the position to delete:
i++; 2
}
printf("enter ur option=\n"); Enter your option
printf("1.insert\t 2.delete \t 3.display\t 4.exit\n"); 3
do List elements are:
{ 10 30 35 40
scanf("%d",&opt); Enter your option
4
switch(opt)
{
case 1:
insert();
I YEAR/I SEM
count++;
break;
case 2:
delet();
count--;
if(count==0)
{
printf("\n List empty\n");
}
break;
case 3:
printf("List elements are:\n");
display();
break;
}
printf("\nEnter your option\n");
}while(opt!=4);
}
void create()
{
if(p==NULL)
{
p=(LIST*)malloc(sizeof(LIST));
printf("Enter the element\n");
scanf("%d",&p->no);
p->next=NULL;
h=p;
}
else
{
t=(LIST*)malloc(sizeof(LIST));
printf("enter the element");
scanf("%d",&t->no);
t->next=NULL;
p->next=t;
p=t;
}
}

void insert()
{
t=h;
p=(LIST*)malloc(sizeof(LIST));
printf("enter the element to be inserted\n");
scanf("%d",&p->no);
printf("enter the position to insert\n");
scanf("%d",&pos);
if(pos==1)
{
h=p;
h->next=t;
}
else
{
for(j=1;j<(pos-1);j++)
t=t->next;
p->next=t->next;
t->next=p;
t=p;
I YEAR/I SEM
I YEAR/I SEM
}
}
void delet()
{
printf("enter the position to delete:\n");
scanf("%d",&pos);
if(pos==1)
{
h=h->next;
}
else
{
t=h;
for(j=1;j<(pos-1);j++)
t=t->next;
pt=t->next->next;
free(t->next);
t->next=pt;
}
}
void display()
{
t=h;
while(t->next!=NULL)
{
printf("\t%d",t->no);
t=t->next;
}
printf("\t %d\t",t->no);
}

TYPEDEF:
- Typedef keyword is used to create a user defined name for existing data type.
- Generally typedef are use to create an alias name (nickname).
Syntax:
typedef datatype alias_name;
typedef int intdata;

Example: (Use of typedef on integer data type)


Program: - In this program, Intdata is an user defined
#include<stdio.h>
typedef int Intdata; // Intdata is alias name of int name or alias name for an integer data type.
int main()
{ - All properties of the integer will be applied
int a=10;
Intdata b=20; on Intdata also.
typedef Intdata Integerdata; // Integerdata is again alias name of Intdata
Integerdata s; - Integerdata is an alias name to existing user
s=a+b;
printf("\n Sum:= %d",s); defined name called Intdata.
return(0);
}
Output:
Sum:=30

Use of typedef on structure datatype:


Program: Output:
#include<stdio.h>
typedef struct telephone
I YEAR/I SEM
{
char name[20]; enter the name
int tel_no;
}t1;
anitha
int main()
{
enter the telephone number
t1 t11;
printf("enter the name");
scanf("%s",t11.name); 3216546531
printf("enter the telephone number");
scanf("%s",&t11.tel_no); Name:anitha
printf("Name:%s\n",t11.name);
printf("telephone number is:%d",t11.tel_no); telephone number :909193779
return(0);
}

Example Programs Using Pointer and Structure:

1. C program to read, display, add, and subtract two distances. Distance must bedefined Output
using kms and meters using structures.(typedef)
Program:
#include <stdio.h> ***MAIN MENU***
typedef struct distance 1. Read the distances
2. Display the distances
{
3. Add the distances
int kms; 4. Subtract the distances
int metres; 5. EXIT
} DISTANCE; // structure variable Enter your option: 1
DISTANCE add_distance (DISTANCE, DISTANCE);
DISTANCE Enter the first distance in kms and metres:
subtract_distance(DISTANCE,DISTANCE); 3
320
DISTANCE dl, d2, d3, d4;
Enter the second distancekms and metres:
int main() 5
{ 100
int option;
do ***MAIN MENU***
{ 1. Read the distances
2. Display the distances
printf("\n ***MAIN MENU***");
3. Add the distances
printf ("\n 1. Read the distances "); 4. Subtract the distances
printf ("\n 2. Display the distances"); 5. EXIT
printf ("\n 3. Add the distances "); Enter your option: 2
printf ("\n 4. Subtract the distances");
printf ("\n 5. EXIT"); The first distance is: 3 kms 320 metres
printf ("\n Enter your option: "); The second distance is: 5 kms 100 metres
***MAIN MENU***
scanf("%d", &option); 1. Read the distances
switch(option) 2. Display the distances
{ 3. Add the distances
case 1: 4. Subtract the distances
printf("\n Enter the first distance in kms and metres: "); 5. EXIT
scanf ("%d %d", &dl .kms, &dl .metres); Enter your option: 3
printf("\n Enter the second distancekms and metres: ");
The sum of two distances is: 8 kms 420 metres
scanf ("%d %d" , &d2 .kms, &d2 .metres); ***MAIN MENU***
break; 1. Read the distances
case 2: 2. Display the distances
printf("\n The first distance is: %d kms %d metres " , dl.kms, dl.metres); printf("\ 3. Add the distances
n The second distance is: %d kms %d metres " , d2 .kms, d2 .metres); 4. Subtract the distances
break; 5. EXIT
Enter your option: 4
case 3:
d3 = add_distance(dl, d2); The difference between two distances is: 1
I YEAR/I SEM
printf("\n The sum of two distances is: %d kms %d metres", d3.kms, d3.metres);

break; kms 780 metres


case 4: ***MAIN MENU***
d4 = subtract_distance(dl, d2); 1. Read the distances
2. Display the distances
printf("\n The difference between two distances is: %d kms %d metres ", d4.kms,
3. Add the distances
d4 .metres); 4. Subtract the distances
break; 5. EXIT
} Enter your option: 5
}
while(option != 5);
{
return 0;
}
}
DISTANCE add_distance(DISTANCE dl, DISTANCE d2)
{
DISTANCE sum;
sum.metres = dl.metres + d2. metres;
sum.kms = dl.kms + d2.kms;
if(sum.metres >= 1000)
{
sum.metres = sum.metres%1000;
sum.kms += 1;
}
return sum;
}
DISTANCE subtract_distance(DISTANCE dl,DISTANCE d2)
{
DISTANCE sub;
if(dl.kms > d2.kms)
{
sub.metres = dl.metres - d2. metres;
sub.kms = dl.kms - d2.kms;
}
else
{
sub.metres = d2.metres - dl. metres;
sub.kms = d2.kms - dl.kms;
}
if(sub.metres < 0)
{
sub.kms = sub.kms - 1;
sub.metres = sub.metres + 1000;
}
return sub;
}

2.C program to add, subtract two complex numbers using structure. Output
Program: Press 1 to add two complex numbers
#include <stdio.h> Press 2 to subtract two complex numbers
#include <stdlib.h> Press 3 to exit
struct complex Enter your choice
{ 1
int real, img; Enter a and b where a + ib is the first complex
}a,b,c; // Structure Variable number.
int main() a=3
{ b=5
Enter c and d where c + id is the second
I YEAR/I SEM
int choice; complex number.
while(1)

{ c=2
printf("Press 1 to add two complex numbers\n"); d=6
printf("Press 2 to subtract two complex numbers\n"); Sum of two complex numbers = 5 + 11i
printf("Press 3 to exit\n"); Press any key to enter choice again...
printf("Enter your choice\n");
scanf("%d",&choice); Press 1 to add two complex numbers
if( choice == 3) Press 2 to subtract two complex numbers
{ Press 3 to exit
exit(0); Enter your choice
} 2
if(choice >= 1 && choice <= 2) Enter a and b where a + ib is the first complex
{ number.
printf("Enter a and b where a + ib is the 1st complex number."); a=1
printf("\na = "); b=1
scanf("%d", &a.real); Enter c and d where c + id is the second
printf("b = "); complex number.
scanf("%d", &a.img); c=2
printf("Enter c and d where c + id is the 2nd complex number."); d=1
printf("\nc = "); Difference of two complex numbers = -1 + 0i
scanf("%d", &b.real); Press any key to enter choice again...
printf("d = "); Press 1 to add two complex numbers
scanf("%d", &b.img); Press 2 to subtract two complex numbers
} Press 3 to exit
if ( choice == 1 ) Enter your choice
{ 3
c.real = a.real + b.real;
c.img = a.img + b.img;

if ( c.img >= 0 )
printf("Sum of two complex numbers = %d + %di", c.real, c.img);
else
printf("Sum of two complex numbers = %d %di",c.real,c.img);
}
else if ( choice == 2 )
{
c.real = a.real - b.real;
c.img = a.img - b.img;

if ( c.img >= 0 )
printf("Difference of two complx no = %d + %di",c.real, c.img);
else
printf("Difference of two complex no = %d %di", c.real, c.img);
}
printf("\nPress any key to enter choice again...\n");
}
}

3. Define a structure called student that would contain name, regno and marks of five
subjects and percentage. Write a C program to read the details of name, regno and marks of five subjects for 30 students and calculate
the percentage and display the name, regno, marks of 30 subjects and percentage of each student.( AssignmentQuestion)
I YEAR/I SEM

Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting of names –
Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of two numbers and changing the value of a variable
using pass by reference.

POINTERS:

 Apointerisavariablethatholdstheaddressofavariableor afunction.
 It is a derived data type in c language.
 Onlyaddresscanbeassignedtoapointervariable
 Pointer variable is declared with * symbol.
Advantages:
 Pointer reduces the code and improves the performance, because it direct access the address of variable.
 Pointerscanbeusedtoreturnmultiple valuesfromafunctionviaarguments.
 It allowsdynamic memory allocation.

Declarationofavariable:

For pointer declaration, we use * (asterisk symbol).


Syntax Example

datatype *pointer_variable; int *p; // pointer to integer


char *b; // pointer to character
double *p;// pointer to double
float *p;//pointer to float
Initializationofapointer:
Syntax Example

Pointer_variable=&variable_name; p=&a;

Function Output

printf(“%d”,a); 50

printf(“%u”,&a); 1001

printf(“%u”,p); 1001

printf(“%u”,&p); 2047

printf(“%d”,*p); 50

Pointer Operators:
I YEAR/I SEM

Simply, To create pointer to a variable we use “*” operator and to find the address of variable we use “&” operator. Eg,

Referencing: Assigningaaddress to a pointervariable iscalled referencing.


& is a unary operator and should appear on the left side of its operand.
Example:
int a = 50;
int*p=&a;

Dereferencing: Extraction a value via pointer variable is called dereferencing.


Example:
printf(“%d”,*p);
printf(“%d”,**pptr);

Program using Referencing and Dereferencing Operator Output

#include<stdio.h> Address of a is: 37814052


int main()
{ Value of a is: 50
int a=50;
int *p;
p=&a;
printf("Address of a is: %u\n",&a);
printf("Value of a is: %d",*p);
return(0); }
POINTER ARITHMETIC:
We can perform arithmetic operations on a pointer just like we can on numeric value.
There are four arithmetic operators that can be used on pointers:
++,
--,
+,
-
Arithmetic operations that can be performed on value and address are given below.
Example:
I YEAR/I SEM

Note:
All the arithmetic operations can be performed on values. But only subtraction, increment and decrement can be performed on
address.

Addition:
 We cannot add two pointers.
 This is because pointers contain addresses, adding two addresses makes no sense, because you have no idea what address would
address it would point to. It may go beyond the limit also. Eg, p1+p2

Subtraction:
 We can subtract two pointers.
 This is because difference between two pointers gives the number of elements of its data type that can be stored between the two
pointers. Eg, p2-p1

Increment:
 If the pointer p1 points to an integer whose address is 1000 , after this increment operation, p1 will point to the location 1002
because each time p1 is incremented, it will point to the next integer location which is 2 bytes next to the current location for
integer data type.
 If p1 points to a character whose address is 1000, then the above operation will point to the location 1001 because the next
character will be available at 1001. Eg, p1++;

Decrement:
 Similarly, depending upon the size of data type, the position is decremented Eg, p1--;
Operators Arithmetic operators on value Arithmetic operators on address
Example
Subtraction(-) *p1-*p2 p2-p1(legal)
5-6=-1 1002-1000=1(2 bytes of data)

Increment(++) *p1++ p1++(legal)


p1+1=1002
Decrement(--) *p1-- P2--(legal)
1002-1=1000
Addition(+) *p1+*p2 p1+p2(illegal)
5+6=11 1000+1002=2002
(illegal)
Multiplication(*) (*p1)*(*p2) p1*p2(illegal)
5*6=30 1000*1002=1002000
(illegal)
/(division) (*p1)/(*p2) p1/p2(illegal)
5/6=0
I YEAR/I SEM

Program for pointer arithmetic Output:


#include <stdio.h> p1 = 2680014
int main() p2 = 2680012
{ *p1+*p2 = 15
int a = 5, b = 10, c = 0; p1-p2 = 1
int *p1; // pointer declaration p1++ = 2680018
int *p2; p2-- = 26800010
int *p3;
p1 = &a; // pointer initialization
p2 = &b;
printf("p1 = %u\n", p1); //printing the address of a
printf("p2 = %u\n", p2);//printing the address of b

c = *p1+*p2;
printf("*p1+*p2 = %d\n", c);

p3 = p1-p2;
printf("p1 - p2 = %u\n", p3);

p1++;
printf("p1++ = %u\n", p1);

p2--;
printf("p2-- = %u\n", p2);

//Below line will give ERROR


printf("p1+p2 = %d\n", p1+p2);
return 0;
}

POINTERS AND ARRAYS


- Pointer to an Array
- Array of Pointers
1. Pointer to an array
Elements in an array can be accessed using 2 methods:
(i) Standard array
(ii) Array using pointers
In array, the elements are stored in consecutive memory locations. So, it can be effectively accessed using pointers.
Example:
int a[5]={10,20,30,40,50}
I YEAR/I SEM
- Pointer to array simply points to base address of an array
- Base address is nothing but starting address ( address of 0th element).
- The address (memory location) of next element is dependent on size of data types( 2 bytes or 4 bytes for integer depending on the
compiler ).

Pointer initialization:
int a[5]={10,20,30,40,50};
int *p;
p=a;
here, pointer variable ‘p’ points only to the base address(starting address) of array.
So, p=a ;
is same as p=&a[0];

Program to print address and value of array using pointers: Output:


int main() 37814024
{ 37814024
int a[5]={10,20,30,40,50},i; 37814024
int *p; 37814028
p=a; 10
printf("%u\n",a); 20
printf("%u\n",p); 50
printf("%u\n",&a);
printf("%u\n",a+1);
printf("%d\n",*p);
printf("%d\n",*(a+1));
printf("%d\n",*(a+4));
}
Note:
Increment operator in pointer always increments based on the size of datatype.
Eg, if base address of a is 2000, the next address is 2002 or 2004 based on datatype size(
2 bytes or 4 bytes)
Program to access elements in an array using pointers: Output:
#include<stdio.h> address of a[0]is: 37814008
int main() value of a[0]is:10
{ address of a[1]is: 37814012
int a[10]={10,20,30,40,50},i; value of a[1]is:20
int *p; address of a[2]is: 37814016
p=a; // pointer variable points to base address value of a[2]is:30
for(i=0;i<5;i++) address of a[3]is: 37814020
{ value of a[3]is:40
printf("address of a[%d]is: %u\n",i,a+i); address of a[4]is: 37814024
printf("value of a[%d]is:%d\n",i,*(a+i)); value of a[4]is:50
}
}

(ii) Array of Pointers:


- Array of pointers is the Collection of pointers to hold different addresses
Syntax:
datatype *array_name[size];
Example:
int *a[5] ;
Here, a is an array of 5 integer pointers. (i,e), this array can hold the address of 5 integer variables.
In other words we can assign 5 pointer variables of type pointer to int to the elements of this array.
Program to print elements using array of pointers: Description:
#include<stdio.h>
int main()
{
int *arr[3];
int a = 10, b = 20, c = 30, i;
arr[0] = &a; // address of variable a to the 0th element of the of the
array
arr[1] = &b;
arr[2] = &c;
for(i = 0; i < 3; i++)
{ arr[i] gives the address of ith element of the array.
printf("Address = %d\t Value = %d\n", arr[i], *arr[i]); So arr[0] returns address of variable a, arr[1]returns address
} of b and so on.
I YEAR/I SEM
return 0; To get the value at address use indirection operator (*).
} So *arr[0] gives value at address[0], Similarly *arr[1] gives the
Output: value at address arr[1] and so on.
Address = 37814036 Value = 10
Address = 37814032 Value = 20
Address = 37814028 Value = 30

Difference between array of pointers and pointer to an array:


Array of pointers Pointer to an array
Each element of an array is an address to the memory location which It is the base address of the array
holds the data
Eg, Eg,
int *a[10]; int(*a)[10];
Each element must be accessed individually(dereferenced) Array must be dereferenced to access the value of each element.
Illustrative Program:

Sorting of names using Array of pointer:


#include<stdlib.h> Output:
#include<stdio.h> given array is
#include<string.h> ravi
int mycomp( void *a, void *b); anand
int main() chitra
{ ziya
char *arr[]={"ravi","anand","chitra","ziya"}; sorted array is
int n=sizeof(arr)/sizeof(arr[0]); anand
int i; chitra
printf("given array is\n"); ravi
for(i=0;i<n;i++) printf("%s\ ziya
n",arr[i]); sort(arr,n);
printf("sorted array is\n");
for(i=0;i<n;i++) printf("%s\
n",arr[i]); return(0);
}
int mycomp(void *a, void *b)
{
return strcmp(*(char **)a,*( char **)b); // type casting to char
}
void sort( char *arr[],int n)
{
qsort(arr,n,sizeof( char *),mycomp); // using QuickSort algorithm to sort the given array.
}

TYPES OF POINTERS:
NULL pointer:

 A NULLpointeris aspecial pointerthat doesnotpoint anywhere.


 It doesnot hold anyaddress.
 It has a numeric value 0.
Declaring NULL pointer:
Syntax Example

datatype* variable_name=0; (Or) int* a=0; (Or)


datatype* variable_name=NULL; int* a=NULL;
#define NULL 0

Points to remember about null pointer:

1. When a null pointer is compared with a pointer to any object the result of comparison is always false.
2. Two null pointers always compares equal.
I YEAR/I SEM
I YEAR/I SEM
3. Dereferencing null pointer leadsto error.

Program to print NULL value: Output:


#include <stdio.h> Value of ptr is 0
int main()
{
// Null Pointer
int *ptr = NULL;

printf("The value of ptr is %u", ptr);


return 0;
}

Void pointer:

 Voidpointerisa general purposepointer that can point to anydata type


 Thepointerusedtopointdifferentdatatypesiscalledvoiddatatype.
 If we assign address of char data type to void pointer it will become char Pointer, if int data type then int pointer and so
on. Any pointer type is convertible to a void pointer hence it can point to any value.

Declaring void pointer:


Syntax Example

void* variable_name; void* a;

Note: Typecasting is required to change void pointer to specific data type.


1. void pointers cannot be dereferenced. It can however be done using typecasting the void pointer
2. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.
Program using void pointer:
#include<stdlib.h> Output:
int main() Integer variable is = 4
{ Float variable is= 5.500000
int x = 4;
float y = 5.5;
void *ptr;
ptr = &x;
printf("Integer variable is = %d", *((int*) ptr));
ptr = &y;
printf("\nFloat variable is= %f", *((float*) ptr));
return 0;
}
Note:
(int*)ptr - does type casting of void
*((int*)ptr) dereferences(accessing the value) of the typecasted variable

NULL vs Void Pointer – Null pointer is a value, while void pointer is a type

Pointer – Pointer(Double/Chained Pointer):

- Declaring Pointer to Pointer is similar to declaring pointer in C.


- The difference is we have to place an additional ‘*’ before the name of pointer.
- When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that
contains the actual value as shown below.

Declaration:
int **ptr; // declaring double pointers
I YEAR/I SEM
Initialization:
int a= 78;
int *ptr2; // pointer for variable a
int **ptr1; // double pointer for ptr2
ptr2 = &a; // storing address of a in ptr2
ptr1 = &ptr2;

Program for pointer - pointer Output:


int main() Value of var
{ 78
int a= 78; Value of var using single
int *ptr2; // pointer for variable a pointer 78
int **ptr1; // double pointer for ptr2 Value of var using double 78
ptr2 = &a; // storing address of a in ptr2
ptr1 = &ptr2; // Storing address of ptr2 in ptr1
printf("Value of var = %d\n", a );
printf("Value of var using single pointer = %d\n", *ptr2 );
printf("Value of var using double pointer = %d\n", **ptr1);
return 0;
}

POINTERS AND FUNCTIONS:

PARAMETER PASSING METHODS:


There are two ways to pass value or data to function in C language:
i) call by value and
ii) call by reference.
Original value is not modified in call by value but it is modified in call by reference.

Call by Value:

- In call by value, original value is not modified.


- In call by value, value being passed to the function is locally stored by the function parameter.
- So, If you change the value of function parameter, it is changed for the current function only. It will not change the value of
variable inside main().

Passing the value (Call by Value): Output:


#include<stdio.h> Before function call x=10
void my_change(int num); changed value is x=15
int main() After function call x=10
{
int a=10; Note: Value is not modified in main function.
printf("Before function call x=%d \n", a);
my_change(a); //passing value in function
printf("After function call x=%d \n",a);
return 0;
}
void my_change(int num)
{
num=num+5;
I YEAR/I SEM
printf("changed value is x=%d \n",num);
}

Call by Reference(Pass by reference):

 In call by reference, original value is modified because we pass reference (address).


 Here, address of the value is passed in the function, so actual and formal arguments shares the same address space.
 Hence, value changed inside the function, is reflected inside as well as outside the function.

Passing the address( Call by Reference): Output:


#include<stdio.h> Before function call x=10
void my_change(int *num); changed value is x=20
int main() After function call x=20
{
int a=10; Note: Value is modified in main
printf("Before function call x=%d \n", a); function.
my_change(&a); //passing value in
function printf("After function call x=%d \n",a);
return(0);
}
void my_change(int *num)
{
*num=*num+10;
printf("changed value is x=%d \n",*num);
}

Difference between call by value and call by reference:


Call by value Call by reference
A copy of value is passed to the function An address of value is passed to the function
Changes made inside the function is not reflected on other Changes made inside the function is reflected outside the function.
functions

Actual and formal arguments will be created in different Actual and formal arguments will be created in same memory
memory location location

Slow processing because new address are created. Fast because existing address are used.

Illustrative Program( Swapping of two numbers and changing the value of a variable using pass by value and reference)

Swapping of 2 vaues(Exchanging) using call by reference: Swapping of 2 values(Exchanging) using call by Reference:

#include<stdio.h> #include<stdio.h>
void swap(int, int); void swap(int *x, int*y);
int main() int main()
{ {
int a=5,b=10; int a=5,b=10;
printf("Before Swap values of a and b is %d %d\n", a, b); printf("Before Swap values of a and b is %d %d\n", a, b);
swap(a, b); swap(&a, &b);
return(0); printf("After Swap values of a and b is %d %d\n", a, b);
} return(0);
}
void swap(int x, int y)
{ void swap(int *x, int *y)
int temp; {
temp = int temp;
x; x = y; temp = *x;
y = temp; *x = *y;
printf("after Swap values of a and b is %d %d\n", x, y); *y =
} temp;
Output: return;
before swap,value of an and b is 5 10 }
after swap,value of a and b is 10 5
Output:
Before Swap values of a and b is 5 10
After Swap values of a and b is 10 5
I YEAR/I SEM
I YEAR/I SEM

UNIT: 5 MACROS AND FILE PROCESSING


Preprocessor Directives: Introduction to preprocessor directives in Simple macros using `#define`, conditional
macros using `#ifdef`, `#ifndef`, `#endif`, `#else`, `#elif`.
Files: Introduction to Files – Opening a file – Reading Data from Files – Writing Data to Files –
Detecting the End-of-file –Closing a file – Sequential access file-Random Access Files – Binary Files –
Command line arguments.

Preprocessor directives are commands in C and C++ that instruct the compiler to
preprocess the source code before actual compilation begins. They begin with a `#`
symbol and are processed by the preprocessor, which is a part of the compiler.

### Simple Macros using `#define`

Macros defined using `#define` are simple text replacements performed by the
preprocessor. They are typically used to define constants or simple functions.

```c
#include <stdio.h>

#define PI 3.14159
#define SQUARE(x) ((x) * (x))

int main() {
double radius = 2.0;
double area = PI * SQUARE(radius);

printf("Area of circle: %f\n", area);

return 0;
}
```

In this example:
- `PI` is a constant macro for the value of pi.
- `SQUARE(x)` is a macro that computes the square of `x`.
I YEAR/I SEM

### Conditional Macros using `#ifdef`, `#ifndef`, `#endif`, `#else`, `#elif`

Conditional directives allow parts of the code to be included or excluded based on


conditions evaluated by the preprocessor.

```c
#include <stdio.h>

#define DEBUG 1

int main()
{ #ifdef
DEBUG
printf("Debugging information\n");
#else
printf("No debugging information\n");
#endif

return 0;
}
```

In this example:
- `#ifdef DEBUG` checks if the macro `DEBUG` is defined. If it is defined (`#ifdef`),
the code block between `#ifdef` and `#else` (or `#endif`) is included in the compiled
code.
- `#else` specifies what to do if `DEBUG` is not defined.
- `#endif` marks the end of the conditional directive block.

You can also use `#ifndef` to check if a macro is not

defined:

```c
I YEAR/I SEM

#ifndef DEBUG
printf("No debugging information\n");
I YEAR/I SEM

#else
printf("Debugging information\n");
#endif
```

Additionally, `#elif` can be used to provide an "else if" condition within a sequence of
`#ifdef` or `#ifndef` checks:

```c
#if defined(DEBUG_LEVEL) && DEBUG_LEVEL == 2
printf("Debugging level 2 information\n");
#elif defined(DEBUG_LEVEL) && DEBUG_LEVEL == 1
printf("Debugging level 1 information\n");
#else
printf("No debugging information\n");
#endif
```

### Summary

- **`#define`**: Defines macros for simple text substitution.


- **`#ifdef`, `#ifndef`**: Conditionally includes code based on whether a macro is
defined or not.
- **`#endif`**: Ends a conditional directive block.
- **`#else`**: Specifies alternative code to be included if the condition in `#ifdef` or
`#ifndef` is false.
- **`#elif`**: Provides an "else if" condition within a sequence of conditional checks.

These preprocessor directives provide flexibility and control over how the source
code is processed and compiled, allowing for conditional compilation and defining
macros for code simplification and abstraction.

File handling

File: the file is a permanent storage medium in which we can store the data
I YEAR/I SEM

permanently.
Types of file can be handled

we can handle three type of file as

(1) sequential file

(2) random access file

(3) binary file


File Operation
opening a file:
Before performing any type of operation, a file must be opened and for this
fopen() function is used.
syntax:

file-pointer=fopen(“FILE NAME ”,”Mode of open”);


example:
FILE *fp=fopen(“ar.c”,”r”);

If fopen() unable to open a file than it will return NULL to the file pointer.

File-pointer: The file pointer is a pointer variable which can be store the address
of a special file that means it is based upon the file pointer a file gets opened.
Declaration of a file pointer:-

FILE* var;

Modes of open

The file can be open in three different ways as


read mode ’ r’/rt
Write mode ’w’/wt
Appened Mode ’a’/at

Reading a character from a file

getc() is used to read a character into a file


Syntax:
character_variable=getc(file_ptr);
I YEAR/I SEM

Writing acharacter into a file

putc() is used to write a character into a file

puts(character-var,file-ptr);

CLOSING A FILE

fclose() function close a


file. fclose(file-ptr);
fcloseall () is used to close all the opened file at a time

File Operation

The following file operation carried out the file


(1)creation of a new file
(3) writing a file
(4) closing a file
Before performing any type of operation we must have to open the file.c, language
communicate with file using A new type called file pointer.
Operation with fopen()

File pointer=fopen(“FILE NAME”,”mode of open”);

If fopen() unable to open a file then it will return NULL to the file-pointer.

Reading and writing a characters from/to a file


fgetc() is used for reading a character from the file
Syntax:

character variable= fgetc(file pointer);

fputc() is used to writing a character to a file


Syntax:

fputc(character,file_pointer);

/*Program to copy a file to


another*/ #include<stdio.h>
void main()

{
I YEAR/I SEM

FILE *fs,*fd;
char ch;
If(fs=fopen(“scr.txt”,”r”)==0)

printf(“sorry….The source file cannot be opened”);


return;
}

If(fd=fopen(“dest.txt”,”w”)==0)

printf(“Sorry…..The destination file cannot be opened”);


fclose(fs);
return;
}

while(ch=fgets(fs)!=EOF)
fputc(ch,fd);
fcloseall();

Reading and writing a string from/to a file


getw() is used for reading a string from the file
Syntax:

gets(file pointer);

putw() is used to writing a character to a file

Syntax:

fputs(integer,file_pointer);
#include<stdio.h>
#include<stdlib.h>
void main()

FILE *fp;
int word;
/*place the word in a file*/
I YEAR/I SEM

fp=fopen(“dgt.txt”,”wb”);
If(fp==NULL)
{

printf(“Error opening file”);


exit(1);
}

word=94;
putw(word,fp);
If(ferror(fp))
printf(“Error writing to file\n”);
else
printf(“Successful write\n”);
fclose(fp);
/*reopen the file*/
fp=fopen(“dgt.txt”,”rb”);
If(fp==NULL)
{

printf(“Error opening file”);


exit(1);
}

/*extract the word*/


word=getw(fp);
If(ferror(fp))
printf(“Error reading file\n”);
else
printf(“Successful read:word=%d\n”,word);

/*clean up*/
fclose(fp);
}

Reading and writing a string from/to a file


fgets() is used for reading a string from the file
Syntax:
fgets(string, length, file pointer);

fputs() is used to writing a character to a file


I YEAR/I SEM

Syntax:
fputs(string,file_pointer);
#include<string.h>
#include<stdio.h>
void main(void)

{
FILE*stream;

char string[]=”This is a test”;


char msg[20];
/*open a file for update*/
stream=fopen(“DUMMY.FIL”,”w+”);

/*write a string into the file*/


fwrite(string,strlen(string),1,stream);
/*seek to the start of the file*/
fseek(stream,0,SEEK_SET);

/*read a string from the file*/


fgets(msg,strlen(string)+1,stream);
/*display the string*/
printf(“%s”,msg);
fclose(stream);
}

You might also like