Algorithmic Problem Solving Techniques
Algorithmic Problem Solving Techniques
INTRODUCTION
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of
solutions.
The problem solving process starts with the problem specifications and ends with a
correct program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in providing logic for solving a
problem.
Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
[Link]
It is defined as a sequence of instructions that describe a method for solving a problem.
In other words it is a step by step procedure for solving a problem
The following are the primary factors that are often used to judge the quality of the
algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser
is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and such algorithms may be
suitable
2
Statements
Statements are simple sentences written in algorithm for specific purpose. Statements may
consists of assignment statements, input/output statements, comment statements
Example:
• Read the value of ‘a’ //This is input statement
• Calculate c=a+b //This is assignment statement
• Print the value of c // This is output statement
Comment statements are given after // symbol, which is used to tell the purpose of the line.
States
An algorithm is deterministic automation for accomplishing a goal which, given an initial
state, will terminate in a defined end-state.
An algorithm will definitely have start state and end state.
Control Flow
Control flow which is also stated as flow of control, determines what section of code is to
run in program at a given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow
3
3. Read b
4. If a>b then
4.1. Print a is greater
else
4.2. Print b is greater
5. Stop
4.1. Print i
5. Stop
Function
A function is a block of organized, reusable code that is used to perform a single, related
action. Function is also named as methods, sub-routines.
Elements of functions:
1. Name for declaration of function
2. Body consisting local declaration and statements
3. Formal parameter
4. Optional result type.
Basic Syntax
function_name(parameters)
function statements
end function
4
Step2:Geta,bValues
Step 3: add c=a+b
Step 4: Printc
Step 5: Return
[Link] OF AN ALGORITHM
Algorithm can be expressed in many different notations, including Natural Language,
Pseudo code, flowcharts and programming languages. Natural language tends to be verbose
and ambiguous. Pseudocode and flowcharts are represented through structured human language.
A notation is a system of characters, expressions, graphics or symbols designs used among
each others in problem solving to represent technical facts, created to facilitate the best result for a
program
Pseudocode
Pseudocode is an informal high-level description of the operating principle of a
computer program or algorithm. It uses the basic structure of a normal programming language,
but is intended for human reading rather than machine reading.
It is text based detail design tool. Pseudo means false and code refers to instructions
written in programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax
rules. The pseudocode is written in normal English language which cannot be understood by the
computer.
Example:
Pseudocode: To find sum of two numbers
READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to read the
input, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF, ELSE,
ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:
5
Pseudocode: Find greatest of two numbers
READ a, b
IF a>b then
PRINT a is greater
ELSE
PRINT b is greater
ENDIF
5. Keep statements language independent.
Pesudocode must never written or use any syntax of any programming language.
Advantages of Pseudocode
• Can be done easily on a word processor
• Easily modified
• Implements structured concepts well
• It can be written easily
• It can be read and understood easily
• Converting pseudocode to programming language is easy as compared with
flowchart
Disadvantages of Pseudocode
• It is not visual
• There is no standardized style or format
Flowchart
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes,
diamonds, and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols
[Link] Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.
6
6. Connector Circle A connector symbol is
represented by a circle
and a letter or digit is
placed in the circle to
specify the link. This
symbol is used to
connect flowcharts.
4. Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, cap leave the decision symbol.
Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for various
purposes.
Efficient Coding
7
The flowcharts act as a guide or blue print during the system analysis and program
development phase.
Systematic Testing and Debugging
The flowchart helps in testing and debugging the program
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart. It
helps the programmer to put efforts more efficiently on that part.
Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart
becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re-
drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
Control Structures using flowcharts and Pseudocode
Sequence Structure
Pseudocode Flow Chart
General Structure
Process 1
…. Process 1
Process 2
…
Process 2
Process 3
Process 3
Example
READ a
Start
READ b
Result c=a+b
PRINT c a=10,b=20
c=a+b
print c
Stop
8
Conditional Structure
• Conditional structure is used to check the condition. It will be having two outputs only (True or False)
• IF and IF…ELSE are the conditional structures used in Python language.
• CASE is the structure used to select multi way selection control. It is not supported in Python.
Process 1 No
Process 2
Example
READ a
READ b Start
IF a>b THEN
PRINT a is greater a=10,b=20
Yes if (a>b)
Print a is greater No
Stop
IF… ELSE
IF…THEN…ELSE is the structure used to specify, if the condition is true, then execute Process1,
else, that is condition is false then execute Process2
Process 2
Example
9
READ a Start
READ b
IF a>b THEN
a=10,b=20
PRINT a is greater
Yes if (a>b)
Print a is greater
No
Print b is greater
Stop
Yes
Body of the loop
Example
• DO…WHILE is exit checked loop, so the loop will be executed at least once.
10
INITIALIZE a=1 Start
Yes
Stop
Print a
a=a+1
Programming Language
• A programming language is a vocabulary and set of grammatical rules for instructing a computer
or computing device to perform specific tasks. In other word it is set of instructions for the
computer to solve the problem.
• Programming Language is a formal language with set of instruction, to the computer to solve a
problem. The program will accept the data to perform computation.
Program= Algorithm +Data
Need for Programming Languages
• Programming languages are also used to organize the computation
• Using Programming language we can solve different problems
• To improve the efficiency of the programs.
Types of Programming Language
In general Programming languages are classified into three types. They are
• Low – level or Machine Language
• Intermediate or Assembly Language
• High – level Programming language
Machine Language:
Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode). Machine languages are the only languages understood by computers. It is also
called as low level language.
Example code:100110011
111001100
Assembly Language:
An assembly language contains the same instructions as a machine language, but the instructions
and variables have names instead of being just numbers. An assembler language consists of mnemonics,
mnemonics that corresponds unique machine instruction.
Example code: start
addx,y
subx,y
11
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. Ultimately, programs written in a high-level language must be translated
into machine language by a compiler or interpreter.
Example code: print(“Hello World!”)
High level programming languages are further divided as mentioned below.
Figure : Interpreter
Compiled Programming Languages
Compile is to transform a program written in a high-level programming language from source
code into object code. This can be done by using a tool called compiler.
A compiler reads the whole source code and translates it into a complete machine code program to
perform the required tasks which is output as a new file.
Figure: Compiler
12
Interpreted vs. Compiled Programming Language
Interpreted Programming Language Compile Programming Language
Translates one statement at a time Scans entire program and translates it as whole
into machine code
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
slower comparatively faster
No intermediate object code is generated, Generates intermediate object code which
hence are memory efficient further requires linking, hence requires more
memory
Continues translating the program until first It generates the error message only after
error is met, in which case it stops. Hence scanning the whole program. Hence debugging
debugging is easy. is comparatively hard.
Eg: Python, Ruby Eg: C,C++,Java
13
Ascertaining the Capabilities of the Computational Device
If the instructions are executed one after another, it is called sequential algorithm
• Programming language can be fed into an electronic computer directly. Instead, it needs to be
converted into a computer program written in a particular computer language. We can look at such
a program as yet another way of specifying the algorithm, although it is preferable to consider it as
the algorithm’s implementation.
• Once an algorithm has been specified, you have to prove its correctness. That is, you have to
prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.
• It might be worth mentioning that although tracing the algorithm’s performance for a few specific
inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness conclusively.
But in order to show that an algorithm is incorrect, you need just one instance of its input for
which the algorithm fails.
Analyzing an Algorithm
1. Efficiency.
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses
14
2. simplicity.
An algorithm should be precisely defined and investigated with mathematical
expressions.
Simpler algorithms are easier to understand and easier to program.
Simple algorithms usually contain fewer bugs.
Coding an Algorithm
Most algorithms are destined to be ultimately implemented as computer programs.
Programming an algorithm presents both a peril and an opportunity.
A working program provides an additional opportunity in allowing an empirical analysis
of the underlying algorithm. Such an analysis is based on timing the program on several
inputs and then analyzing the results obtained.
15
Recursions:
A function that calls itself is known as recursion.
Recursion is a process by which a function calls itself repeatedly until some specified condition has
beensatisfied.
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
16
FLOW CHART
Main function:
BEGIN
GET n
CALL
factorial(n)
PRINT fact
BIN
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
17
5. ILLUSTRATIVE PROBLEMS
1. Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare n, guess
Step 3: Compute guess=input
Step 4: Read guess
Step 5: If guess>n, then
Print your guess is too high
Else
Step6:If guess<n, then
Print your guess is too low
Else
Step 7:If guess==n,then
Print Good job
Else
Nope
Step 6: Stop
Pseudocode:
BEGIN
COMPUTE guess=input
READ guess,
IF guess>n
PRINT Guess is high
ELSE
IF guess<n
PRINT Guess is low
ELSE
IF guess=n
PRINT Good job
ELSE
Nope
END
18
Flowchart:
Start
Read n
Read
Guess number
Guess=input
If Guess>n
If Guess<n
Good job
Stop
19
[Link] minimum in a list
Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Compute min=a[0]
Step 6: Initialize i=1
Step 7: If i<n, then go to step 8 else goto step 10
Step 8: If a[i]<min, then goto step 8.1,8.2 else goto 8.2
Step 8.1: min=a[i]
Step 8.2: i=i+1 goto 7
Step 9: Print min
Step 10: Stop
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
20
Flowchart:
21
3. Insert a card in a list of sorted cards
Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Read item
Step 6: Calculate i=n-1
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
Step 8: Compute a[i+1]=item
Step 9: Compute n=n+1
Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11
Step10.1: Print a[i]
Step10.2: i=i+1 goto step 10
Step 11: Stop
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
22
Flowchart:
23
[Link] of Hanoi
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more
than one rings.
Tower of Hanoi is one of the best example for recursive problem solving.
Pre-condition:
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller
one sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.
Post-condition:
All the disk should be moved to the last pole and placed only in ascending order as shown
below.
Rules
The mission is to move all the disks to some another tower without violating the sequence
of arrangement. A few rules to be followed for Tower of Hanoi are
• Only one disk can be moved among the towers at any given time.
• Only the "top" disk can be removed.
• No large disk can sit over a small disk.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation
shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with
lesser amount of disks, say → 1 or 2. We mark three towers with name, source, aux (only to help
moving the disks) and destination.
Input: one disk
If we have only one disk, then it can easily be moved from source to destination peg.
Input: two disks
If we have 2 disks −
• First, we move the smaller (top) disk to aux peg.
• Then, we move the larger (bottom) disk to destination peg.
• And finally, we move the smaller disk from aux to destination peg.
Input: more than two disks
• So now, we are in a position to design an algorithm for Tower of Hanoi with more than
two disks. We divide the stack of disks in two parts. The largest disk (n th disk) is in one
part and all other (n-1) disks are in the second part.
24
• Our ultimate aim is to move disk n from source to destination and then put all other (n1)
disks onto it. We can imagine to apply the same in a recursive way for all given set of
disks.
• The steps to follow are –
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest
25
FLOW CHART Start
Stop
If disk==1?
Return
26
5. Draw a flow chart to find greatest among three numbers.(AU 2018)
27
2 MARKS
1. What is an algorithm?
An algorithm is a finite number of clearly described, unambiguous do able steps that
can be systematically followed to produce a desired results for given input in the given amount
of time. In other word, an algorithm is a step by step procedure to solve a problem with finite
number of steps.
Algorithm Program
1. Systematic logical approach which is a It is exact code written for
well-defined, step-by-step procedure that problem following all the rules of the
allows a computer to solve a problem. programming language.
2. An algorithm is a finite number of clearly The program will accept the data to
described, unambiguous do able steps that perform computation.
can be systematically followed to produce
a desired results for given input in the Program=Algorithm + Data
given amount of time.
6. Write an algorithm to accept two numbers, compute the sum and print the result.
Step 1: Start
Step 2: Declare variables num1,num2 and sum,
Step 3: Read values num 1 and num2.
Step 4: Add and assign the result to sum.
Sum←num1+num2
Step 5: Display sum
28
7. Differentiate between iteration and recursion.
29
[Link] a flow chart to find whether the given number is leap year or not.
Start
Read year
If
(year%4==0)
Stop
30
CS3251 PROGRAMMING IN C L
COURSE OBJECTIVES:
• To understand the constructs of C Language.
• To develop C Programs using basic programming constructs
• To develop C programs using arrays and strings
• To develop modular applications in C using functions
• To develop applications in C using pointers and structures
• To do input/output and file handling in C
TOTAL : 45 PERIODS
TEXT BOOKS:
1. ReemaThareja, “Programming in C”, Oxford University Press, Second Edition, 2016.
2. Kernighan, B.W and Ritchie,D.M, “The C Programming language”, Second Edition, Pearson
Education, 2015.
REFERENCES:
1. Paul Deitel and Harvey Deitel, “C How to Program with an Introduction to C++”, Eighth edition,
Pearson Education, 2018.
2. Yashwant Kanetkar, Let us C, 17th Edition, BPB Publications, 2020.
3. Byron S. Gottfried, “Schaum’s Outline of Theory and Problems of Programming with C”,
McGraw-Hill Education, 1996.
4. Pradip Dey, Manas Ghosh, “Computer Fundamentals and Programming in C”, Second Edition,
Oxford University Press, 2013.
5. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, 1st Edition,
Pearson Education, 2013.
UNIT 1
BASICS OF C PROGRAMMING
Introduction to programming paradigms – Applications of C Language - Structure of C program - C
programming: Data Types - Constants – Enumeration Constants - Keywords – Operators: Precedence and
Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Preprocessor directives - Compilation process .
PROGRAMMING PARADIGMS:
In computing, a program is a specific set of ordered operation for a computer to [Link] process
of developing and implementing various sets of instruction to enable a computer to perform a certain task
is called PROGRAMMING.
PROGRAMMING PARADIGMS INCLUDE:
1. IMPERATIVE PROGRAMMING PARADIGMS:
Command show how the computation takes place, step by step. Each step affects the global
state of the computation.
2. STRUCTURED PROGRAMMING PARADIGMS:
It is a kind of imperative programming where the control flow is defined by nested loops,
conditionals, and subroutines, rather than via gotos. Variables generally local to blocks.
3. OBJECT ORIENTED PROGRAMMING(OOP) PARADIGMS:
It is a programming paradigms based on the concepts of objects, which may contain data, in the
form of fields, often known as attributes, and code, in the form of procedures, often known as
methods.
4. DECLARATIVE PROGRAMMING PARADIGMS:
The programmer states only what the results should look like , not how to obtain it. No loops,
no assignments, etc. Whatever engines that interprets this code is just supposed go gets the
desired information and can use whatever approach its wants.
5. FUNCTIONAL PROGRAMMING PARADIGMS:
In functional programming, control flow is expressed by combining functional calls, rather than
by assigning values to variables.
6. PROCEDURAL PROGRAMMING PARADIGMS:
This paradigms includes imperative programming with procedure calls.
7. EVENT DRIVEN PROGRAMMING PARADIGMS:
In which the flow of the program is determined by events such as user action(mouse clicks, key
presses), sensor output, or message from other program/threads. It is the dominant paradigms
used in GUI and other applications that are centred on performing certain action in response to
user input.
8. FLOW DRIVEN PROGRAMMING PARADIGMS:
Programming processes communicating with each other over predefined channels.
9. LOGIC PROGRAMMING PARADIGMS:
Here programming is done by specifying a set of facts and rules. An engine infers the answer
to question.
10. CONSTRAINTS PROGRAMMING PARADIGMS:
An engine finds the value that meet the constraints.
One of the characteristics of a language is its support for particular programming
paradigms. For example: small talks has direct support for programming in the object oriented
way, so it might called an object oriented language.
Very few language implement a paradigms 100%, when they do, they are “PURE”. It is
incredibly rare to have a “pure OOP language” or a “pure functional language”.
A lot of language will facilitate programming in one or more paradigms. If a language is
purposely designed to allow programming in many paradigms is called a “multi paradigms
language”.
APPLICATION OF C:
1. OPERATING SYSTEM
2. EMBEDDED SYSTEM
3. GUI(GRAPHICAL USER INTERFACE)
4. NEW PROGRAMMING PLATFORMS
5. GOOGLE
6. MOZILLA FIREBOX AND THUNDERBIRD
7. MYSQL
8. COMPILER DESIGN
9. ASSEMBLERS
10. TEXT EDITORS
11. DRIVERS
12. NETWORK DEVICES
13. GAMING AND ANIMATION
FEATURES OF C PROGRAMMING/ADVANTAGES:
• C is a robust language with rich set of built in function.
• Programs written in c are efficient and fast.
• C is highly portable, programs once written in c can be run on another machine with minor or no
modification.
• C is basically a collection of c library functions, we can also create our own function and add it to
the c library.
• C is easily extensible.
DISADVANTAGE OF C:
• C doesnot provide OOP.
• There is no concepts of namespace in c.
• C doesnot provides binding or wrapping up of a single unit.
• C doesnot provide constructor and destructor.
STRUCTURE OF C:
Documentation section:
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details, which the programmer would like to use later.
Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include directive.
Definition section: The definition section defines all symbolic constants such using the
#define directive.
Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section that
is outside of all the functions. This section also declares all the user-defined functions.
Main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part.
Declaration part:
The declaration part declares all the variables used in the executable part.
Executable part:
There is at least one statement in the executable part. These two parts must appear between
the opening and closing braces. The program execution begins at the opening brace and ends at
the closing brace. The closing brace of the main function is the logical end of the program. All
statements in the declaration and executable part end with a semicolon.
Subprogram section:
If the program is a multi-function program then the subprogram section contains all the
user-defined functions that are called in the main () function. User-defined functions are
generally placed immediately after the main () function, although they may appear in any order.
All section, except the main () function section may be absent when they are not required.
C PROGRAMMING: DATA-TYPES
A data-type in C programming is a set of values and is determined to act on those
values. C provides various types of data-types which allow the programmer to select the
appropriate typefor the variable to set its value.
The data-type in a programming language is the collection of data with values having
fixed meaning as well as characteristics. Some of them are integer, floating point, character etc.
Usually, programming languages specify the range values for given data-type.
C Data Types are used to:
Pointers These are powerful C features which are used to access the
memory and deal with their addresses.
C allows the feature called type definition which allows programmers to define their own
identifier that would represent an existing data type. There are three such types:
Structure It is a package of variables of different types under a single name. This is done
to handle data efficiently. “struct” keyword is used to define a structure.
Union These allow storing various data types in the same memory location. Programmers
can define a union with different members but only a single member can contain
a value at given time.
Enum Enumeration is a special data type that consists of integral constants and each of them
is assigned with a specific name. “enum” keyword is used to define the enumerated data
type.
int a = 4000; // positive integer data type float b = 5.2324; // float data type
char c = 'Z'; // char data type
long d = 41657; // long positive integer data type long e = -21556; // long -ve integer data type
int f = -185; // -ve integer data type
short g = 130; // short +ve integer data type short h = -130; // short -ve integer data type
double i = 4.1234567890; // double float data type float j = -3.55; // float data type
}
Let's see the basic data types. Its size is given according to 32 bit architecture.
Data Types Memory Size Range
float 4 byte
double 8 byte
long double 10 byte
The storage representation and machine instructions differ from machine to Machine.
sizeof operator can use to get the exact size of a type or a variable on a particular platform.
Example: #include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int is: %d \n", sizeof(int));
printf("Storage size for char is: %d \n", sizeof(char)); return 0
}
CONSTANTS
A constant is a value or variable that can't be changed in the program, for example: 10,
20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
C const keyword:
The const keyword is used to define constant in C programming.
Example:
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
The value of PI is: 3.140000
If you try to change the value of PI, it will render compile time error.
#include<stdio.h>
int main(){
const float PI=3.14; PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
Compile Time Error: Cannot modify a const object.
C #define preprocessor
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.
Syntax: #define token value
Let's see an example of #define to define a constant.
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output:
3.140000
Backslash character constant:
C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as “Escape
Sequence”.
Example:
\t is used to give a tab
\n is used to give new line
Constants Meaning Constants Meaning
\a beep sound \n newline
\v vertical tab \\ backslash
\b backspace \r carriage return
\’ single quote \0 null
\f form feed \t horizontal tab
\” double quote
ENUMERATION CONSTANTS:
An enum is a keyword, it is an user defined data type. All properties of integer are
applied on Enumeration data type so size of the enumerator data type is 2 byte . It work like
the Integer. It is used for creating an user defined data type of integer. Using enum we can
create sequence of integer constant value.
• In above syntax tagname is our own variable. tagname is any variable name.
It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list. If constant one value is not initialized then by default sequence will be start
from zero and next to generated value should be previous constant value one.
Example:
• In above code first line is create user defined data type called week.
Example:
#include<stdio.h>
#include<conio.h>
enum abc{x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf(“sum: %d”,a);
getch();
}
Output:
Sum: 3
KEYWORDS:
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are
only 32 reserved words (keywords) in C language.
A list of 32 keywords in c language is given below:
OPERATORS :
Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Ternary or Conditional Operators
Arithmetic Operators:
Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A
hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators:
Which can be used to check the Condition, it always return true or false. Lets suppose variable
hold 8 and B hold 3.
Logical Operator:
Which can be used to combine more than one Condition?. Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is
Logical Operator.
Assignment operators:
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
Ternary Operator:
If any operator is used on three operands or variable is known as Ternary Operator. It can be
represented with ? : . It is also called as conditional operator
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of application.
Syntax:
In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
value Or variable or statement or any mathematical expression. If condition will be true expression-2 will
be execute otherwise expression-3 will be executed.
Conditional Operator flow diagram
Example:
Special Operators:
C supports some special operators
Operator Description
* Pointer to a variable.
Expression evaluation
In C language expression evaluation is mainly depends on priority and associativity.
Priority
This represents the evaluation of expression starts from "what" operator.
Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.
Precedence of operators :
The precedence rule is used to determine the order of application of operators in evaluating sub
expressions. Each operator in C has a precedence associated with it. The operator with the highest
precedence is operated first.
Associativity of operators :
The associativity rule is applied when two or more operators are having same precedence in the sub
expression. An operator can be left-to-right associative or right-to-left associative.
Rules for evaluation of expression:
•First parenthesized sub expressions are evaluated first.
•If parentheses are nested, the evaluation begins with the innermost sub expression.
•The precedence rule is applied to determine the order of application of operators in evaluating
sub expressions.
•The associability rule is applied when two or more operators are having same precedence in the sub
expression.
EXPRESSION:
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
An expression that has only one operator is known as a simple expression. E.g: a+2
An expression that involves more than one operator is called a compound expression.
E.g: b=2+3*5.
IO STATEMENT:
• Formatted Functions
• Unformatted functions
FORMATTED INPUT FUNCTION:
SCANF():
It is used to get data in a specified format. It can accept different data types.
Syntax:
scanf(“Control String”, var1address, var2address, …);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
scanf(“%d %d”,&a,&b);
sum= a+b;
}
sum= a+b;
printf(“sum is:%d”,sum);
}
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> j
void main()
{
Char ch;
ch=getchar();
Printf(“%c”,ch);
}
getch():
getch() accepts only a single character from keyboard. The character entered through getch() is not
displayed in the screen (monitor).
Syntax:
variable_name = getch();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ Ch=a
Char ch;
ch=getch();
Printf(“ch=%c”,ch);
}
getche():
getche() also accepts only single character, but getche() displays the entered character in the
screen.
Syntax:
variable_name = getche();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ a
Ch=a
Char ch;
ch=getche();
Printf(“ch=%c”,ch);
}
gets():
This function is used for accepting any string through stdin (keyboard) until enter key
is pressed.
Syntax:
gets(variable_name);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Char ch[10]; OUTPUT:
cprogram
gets(ch); Ch=cprogram
Printf(“ch=%s”,ch);
getch();
}
UNFORMATTED OUTPUT FUNCTION:
• putchar()
• putch()
• puts()
putchar():
This function prints one character on the screen at a time.
Syntax :
putchar(variable name);
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> enter a character: j
j
void main()
{
Char ch;
printf(“enter a character:”);
ch=getchar();
putchar(ch);
getch();
}
putch():
putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.
Syntax:
putch(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Press any character:
char ch; Pressed character is: e
clrscr();
printf(“Press any character: ”);
ch = getch();
printf(“\nPressed character is:”);
putch(ch);
getch();
}
puts():
This function prints the string or character array.
Syntax:
puts(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Enter a string: cprogramming
char ch[20]; cprogramming
clrscr();
puts(“enter a string”);
gets(ch);
puts(ch);
}
ASSIGNMENT STATEMENT:
The assignment statement has the following form:
Syntax:
variable = expression/constant/variable;
Its purpose is saving the result of the expression to the right of the assignment operator to the
variable on the left. Here are some rules:
• If the type of the expression is identical to that of the variable, the result is saved in the variable.
• Otherwise, the result is converted to the type of the variable and saved there.
❖ If the type of the variable is integer while the type of the result is real, the fractional
part, including the decimal point, is removed making it an integer result.
❖ If the type of the variable is real while the type of the result is integer, then a decimal
point is appended to the integer making it a real number.
• Once the variable receives a new value, the original one disappears and is no more available.
Examples of assignment statements,
b = c ; /* b is assigned the value of c */
a = 9 ; /* a is assigned the value 9*/
b = c+5; /* b is assigned the value of expr c+5 */
• The expression on the right hand side of the assignment statement can be: An arithmetic
expression;
❖ A relational expression;
❖ A logical expression;
❖ A mixed expression.
For example,
int a;
float b,c ,avg, t;
avg = (b+c) / 2; /*arithmetic expression */
a = b && c; /*logical expression*/
a = (b+c) && (b<c); /* mixed expression*/
DECISION MAKING STATEMENTS:
Decision making statement is depending on the condition block need to be executed or not which
is decided by condition.
If the condition is "true" statement block will be executed, if condition is "false" then statement
block will not be executed.
In this section we are discuss about if-then (if), if-then-else (if else), and switch statement. In C
language there are three types of decision making statement.
• if
• if-else
• switch
if Statement:
if-then is most basic statement of Decision making statement. It tells to program to execute a
certain part of code only if particular condition is true.
Syntax:
if(condition)
{
Statements executed if the condition is true
}
FLOWCHART:
Constructing the body of "if" statement is always optional, Create the body when we are having multiple
statements.
For a single statement, it is not required to specify the body.
If the body is not specified, then automatically condition part will be terminated with next semicolon ( ; ).
Example:
#include<stdio.h>
int main()
{
int num=0;
printf(“enter a number:”); OUTPUT:
scanf(“%d”,&num); Enter a number: 4
4 is even number
if(num%2==0)
{
printf(“%d is even number”,num);
}
return 0;
}
if-else statement:
In general it can be used to execute one block of statement among two blocks, in C language if
and else are the keyword in C.
Syntax:
if(expression)
{
else
Flowchar
t:
In the above syntax whenever condition is true all the if block statement are executed remaining
statement of the program by neglecting else block statement. If the condition is false else block statement
remaining statement of the program are executed by neglecting if block statements.
Example:
#include<stdio.h>
void main()
{
int age;
printf(“enter age:”)
scanf(“%d”,&age);
Output:
if(age>=18) Enter age: 18
Eligible to vote
{ Enter age: 17
Not eligible to vote
printf(“age:%d”,age);
printf(“eligible to vote” );
}
else
{
printf(“age:%d”,age);
printf(“not eligible to vote” );
}
Nested if:
When an if else statement is present inside the body of another “if” or “else” then this is called
nested if else.
Syntax of Nested if else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Flowchart:
EXAMPLE:
#include<stdio.h>
void main() Output:
Enter age and salary: 55 55000
{ 65000
int age, salary;
printf(“enter age and salary”);
scanf(%d %d”, &age,&salary);
if(age>50)
{
if(salary<60000)
{
salary=salary+10000
;printf(“%d”,salary);
}
else
{
salary=
salary+5000;
printf(“%d”,salary);
}
}
else
{
salary=salary+1000;
printf(“%d”,salary);
}
printf(“end of program”);
getch();
}
Switch:
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax:
switch(expression/variable)
{
case value1:
statements;
break;//optional
case value2:
statements;
break;//optional
default:
statements;
break;//optional
}
Rules for apply switch:
1. With switch statement use only byte, short, int, char data type.
2. You can use any number of case statements within a switch.
3. Value for a case must be same as the variable in switch
Flowchart:
Example:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
// declaration of local variable op;
int op, n1, n2;
printf (" enter 2 number: ");
scanf(%d %d”,&n1,&n2);
printf (" \n 1 Addition \t \t 2 Subtraction \n 3 Multiplication \t 4 Division \n 5 Exit \n \n Please,
Make a choice ");
scanf ("%d", &op); // accepts a numeric input to choose the operation
switch (op)
{
case 1:
printf ("sum is :%d ",n1+n2);
break;
case 2:
printf ("difference is :%d ",n1-n2);
break;
case 3:
printf ("multiplication :%d ",n1*n2);
break;
case 4:
printf ("division :%d ",n1/n2);
break;
case 5:
printf ("exit”);
break;
default:
printf(“enter the number between 1 to 5:”);
}
}
LOOPING STATEMENTS
Sometimes it is necessary for the program to execute the statement several times, and C loops
execute a block of commands a specified number of times until a condition is met.
What is Loop?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do a task
tens of thousands of times. Every programming language has the feature to instruct to do such repetitive
tasks with the help of certain form of statements. The process of repeatedly executing a collection of
statement is called looping . The statements get executed many numbers of times based on the condition.
But if the condition is given in such a logic that the repetition continues any number of times with no
fixed condition to stop looping those statements, then this type of looping is called infinite looping.
C supports following types of loops:
• while loops
• do while loops
• for loops
while loops:
C while loops statement allows to repeatedly run the same block of code until a condition is met.
while loop is a most basic loop in C programming. while loop has one control condition, and executes as
long the condition is true.
The condition of the loop is tested before the body of the loop is executed, hence it is called an
entry-controlled loop.
Syntax:
while (condition)
{
statement(s); Increment statement;
}
Flowchart:
Flowchart:
Output:
1 2 3 4 5 6 7 8 9 10
Do..while loops:
C do while loops are very similar to the while loops, but it always executes the code block at least
once and furthermore as long as the condition remains true. This is an exit- controlled loop.
Syntax:
do{
statement(s);
}while( condition );
Flowchart:
EXAMPLE:
#include<stdio.h>
void main ()
{ Output:
int i=1; 1 2 3 4 5 6 7 8 9 10
clrscr();
do
{
printf(“%d”,i);
i++;
} while(i<=10);
getch();
}
For loop:
C for loops is very similar to a while loops in that it continues to process a block of code until a
statement becomes false, and everything is defined in a single line. The for loop is also entry-controlled
loop.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Flowchart:
Example:
#include<stdio.h>
void main ()
{ Output:
int i; 1 2 3 4 5 6 7 8 9 10
clrscr();
for(i=1;i<=10;i++)
{
printf(“%d”,i);
getch();
}
PRE-PROCESSOR DIRECTIVES
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros. Preprocessor directives are
executed before compilation.
• We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
compile it using below command.
$ gcc –Wall filename.c –o filename
The option -Wall enables all compiler’s warning messages. This option is recommended to generate
bettercode. The option -o is used to specify output file name. If we do not use this option, then an output
file with name [Link] is generated.
After compilation executable is generated and we run the generated executable using below
command.
$ ./filename
What goes inside the compilation process?
Compiler converts a C program into an executable. There are four phases for a C program to
become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
By executing below command, We get the all intermediate files in the current directory along with the
executable.
$gcc –Wall –save-temps filename.c –o filename
The following screenshot shows all generated intermediate files.
Let us one by one see what these intermediate files contain
Pre-processing:
This is the first phase through which source code is passed. This phase include:
• Removal of Comments
• Expansion of Macros
• Expansion of the included files.
The preprocessed output is stored in the filename.i. Let’s see what’s inside
filename.i:using $vi filename.i
In the above output, source file is filled with lots and lots of info, but at the end our code is
preserved.
Analysis:
• printf contains now a + b rather than add(a, b) that’s because macros have expanded.
• Comments are stripped off.
• #include<stdio.h> is missing instead we see lots of code. So header files has been
expanded andincluded in our source file.
Compiling:
The next step is to compile filename.i and produce an; intermediate compiled output file
filename.s.
This file is in assembly level instructions. Let’s see through this file using $vi filename.s
Assembly:
In this phase the filename.s is taken as input and turned into filename.o by assembler.
This file contain machine level instructions. At this phase, only existing code is converted into
machine language, the function calls like printf() are not resolved. Let’s view this file using $vi
filename.o
Linking:
This is the final phase in which all the linking of function calls with their definitions are
done. Linkerknows where all these functions are implemented.
Linker does some extra work also, it adds some extra code to our program which is
required whenthe program starts and ends.
For example, there is a code which is required for setting up the environment like passing
commandline arguments. This task can be easily verified by using $size filename.o and $size
filename.
Through these commands, we know that how output file increases from an object file to
an executable file. This is because of the extra code that linker adds with our program.
UNIT II
ARRAYS AND STRINGS
Introduction to Arrays: Declaration, Initialization – One dimensional array –
Two dimensional arrays - String operations: length, compare, concatenate, copy –
Selection sort, linear and binary search.
DIMENSIONAL ARRAYS:
Array in C language is a collection or group of elements (data). All the elements of c
array are homogeneous (similar). It has contiguous memory location.
C array is beneficial if you have to store similar elements. Suppose you have to store
marks of 50 students, one way to do this is allotting 50 variables.
So it will be typical and hard to manage.
For example we cannot access the value of these variables with only 1 or 2 lines of
code.
Another way to do this is array. By using array, we can access the elements easily. Only
few lines of code is required to access the elements of array.
Advantage of C Array:
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array:
1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't
exceed the limit. So, it doesn't grow the size dynamically like Linked List.
Declaration of C Array:
We can declare an array in the c language in the following way.
Syntax:
data_type array_name[array_size];
Initialization of C Array:
A simple way to initialize array is by index. Notice that array index starts from 0 and
ends with [SIZE - 1].
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Example:
#include<stdio.h>
int main()
{ Output:
int i=0; 80
int marks[5];//declaration of array 60
marks[0]=80;//initialization of array 70
marks[1]=60; 85
marks[2]=70; 75
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop return 0;
}
C Array: Declaration with Initialization:
We can initialize the c array at the time of declaration. Let's see the code. int
marks[5]={20,30,40,50,60};
In such case, there is no requirement to define size. So it can also be written as the
following code
.
Example: int marks[]={20,30,40,50,60};
Programs:
#include<stdio.h> Output:
int main() 20
{ 30
int i=0; 40
int marks[5]={20,30,40,50,60};//declaration and initialization of array 50
//traversal of array 60
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
return 0;
}
TWO DIMENSIONAL ARRAYS (2 D arrays):
The two dimensional array in C language is represented in the form of rows and
columns, also known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.
Declaration of two dimensional Array in C:
We can declare an array in the c language in the following way.
Syntax:
data_type array_name[size1][size2];
#include<stdio.h> Output:
int main() arr[0][0] = 1
{ arr[0][1] = 2
int i=0,j=0; arr[0][2] = 3
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[1][0] = 2
//traversing 2D array arr[1][1] = 3
for(i=0;i<4;i++) arr[1][2] = 4
{ arr[2][0] = 3
for(j=0;j<3;j++) arr[2][1] = 4
{ arr[2][2] = 5
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); arr[3][0] = 4
}//end of j arr[3][1] = 5
}//end of i return 0; arr[3][2] = 6
}
STRING OPERATION:
What is meant by String?
String in C language is an array of characters that is terminated by \0 (null character).
There are two ways to declare string in c language.
1. By char array
2. By string literal
char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
You can also define string by string literal in C language.
For example: char ch[]="javatpoint";
In such case, '\0' will be appended at the end of string by the compiler.
The strrev(string) function returns reverse of the given string. Let's see a simple example
of strrev() function.
Programs:
#include<stdio.h>
#include <string.h>int
main() Output:
{ Enter string: javatpoint
char str[20]; String is: javatpoint
printf("Enter string: "); Reverse String is: tnioptavaj
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Introduction to functions: Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion – Example Program: Computation of Sine series,
Scientific calculator using built-in functions, Binary Search using recursive functions – 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.
FUNCTIONS
Definition
C enables its programmers to break up a program into segments commonly known as functions
Every function in the program is supposed to perform a well-defined task. Therefore, the programcode of
one function is completely insulated from the other functions.
main() calls a function named func1(). Therefore, main() is known as the calling function
andfunc1() is known as the called function.
Need For Functions:
Functions are used because of following reasons –
a) To improve the readability of code.
b) Improves the reusability of the code, same function can be used in any program rather than
writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by function calls.
Terminologies In Functions
• A function f that uses another function g is known as the calling function, and g is known as the
called function.
• The inputs that a function takes are known as arguments.
• When a called function returns some result back to the calling function, it is said to
returnthat result.
• The calling function may or may not pass parameters to the called function. If the
called function accepts arguments, the calling function will pass parameters, else not.
➢ Function declaration is a declaration statement that identifies a function’s name, a
list ofarguments that it accepts, and the type of data it returns.
➢ Function definition consists of a function header that identifies the function, followed
by the bodyof the function containing the executable code for that function.
Function Declaration
The general format for declaring a function that accepts arguments and returns a value as result
can be given as:
o function_name - is a valid name for the function. Naming a function follows the
same rules that are followed while naming variables. A function should have a
meaningful name that must specify the task that the function will perform.
o return_data_type - the data type of the value that will be returned to the calling
function asa result of the processing performed by the called function.
o (data_type variable1, data_type variable2, ...) - is a list of variables of specified
data types. These variables are passed from the calling function to the called
function. They are also known as arguments or parameters that the called
function accepts to perform its task.
Function Definition
When a function is defined, space is allocated for that function in the memory. A functiondefinition
comprises of two parts:
• Function header
• Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
.............
return(variable);
}
Function Call
The function call statement invokes the function. When a function is invoked, the compiler jumps to the
called function to execute the statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function. A function call statement has the
following syntax:
function_name(variable1, variable2, ...);
If the return type of the function is not void, then the value returned by the
called functionmay be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Eg:// program to find whether a number is even or odd using functions.
#include <stdio.h>
int evenodd(int); //FUNCTION DECLARATION
int main()
{
int num, flag;
printf("\n Enter the number : ");
scanf("%d",&num);
flag = evenodd(num); //FUNCTION CALL
if (flag == 1)
printf("\n %d is EVEN", num);
else
printf("\n %d is ODD", num);
return 0;
}
int evenodd(int a) // FUNCTION HEADER
{
if(a%2 == 0)
return 1;
else
return 0;
}
Output:
Enter the number : 7878 is EVEN
PASSING PARAMETERS TO FUNCTIONS
There are two ways in which arguments or parameters can be passed to the called function.
1. Call by value - The values of the variables are passed by the calling function to
the calledfunction.
2. Call by reference - The addresses of the variables are passed by the calling
function to thecalled function.
1. Call by Value
• In call by value method, the value of the actual parameters is copied into the formal
parameters.
• In call by value method, we cannot modify the value of the actual parameter by
the formalparameter.
• In call by value, different memory is allocated for actual and formal parameters.
• The actual parameter is the argument which is used in the function call whereas formal
parameter isthe argument which is used in the function definition.
Eg://Program for call by value
#include<stdio.h>
int main()
{
int x,y;
void swap(int,int); printf("Enter two
numbers:");scanf("%d%d",&x,&y);
printf("\n\nBefore Swapping: x = %d\ty =
%d",x,y);
swap(x,y);
printf("\n\nAfter Swapping: x = %d\ty = %d",x,y);
}
Output:
1. Its main drawback is that copying data consumes additional storage space. In addition, it can take
alot of time to copy, thereby resulting in performance penalty, especially if the function is called
many times.
Call By Reference:
• The method of passing arguments by address or reference is also known as call by address or call
by reference. Here, the addresses of the actual arguments are passed to the formal parameters of
the function.
• If the arguments are passed by reference, changes in the formal parameters also make changes on
actual parameters.
#include<stdio.h>
int main()
{
int x ,y;
void swap (int*,int*);
printf(“enter the two numbers”);
scanf(“%d%d”,&x,&y);
printf("\n\nBefore Swapping:\n\nx = %d\ty = %d",x,y);
swap(&x,&y);
printf("\n\nAfter Swapping:\n\nx = %d\ty = %d\n\n",x,y);
}
void swap(int *a, int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
printf("\n\nIn swap function: x = %d\ty = %d\n\n",a,b);
}
Output:
3.A function can return only one value. In case we need to return multiple values, we can pass those
arguments by reference, so that the modified values are visible in the calling function.
Disadvantage:
1. if inadvertent changes are caused to variables in called function then these changes would
bereflected in calling function as original values would have been overwritten.
RECURSIVE FUNCTION
Output:
Types of Recursion
1. Direct Recursion
A function is said to be directly recursive if it explicitly calls itself.
2. Indirect Recursion
A function is said to be indirectly recursive if it contains a call to another function which
ultimately calls it
3. Tail Recursion
A recursive function is said to be tail recursive if no operations are pending to be performed when
the recursive function returns to its caller.
4. Non Tail Recursion:
A recursive function is said to be non tail recursive if operations are pending to be performed when
the recursive function returns to its caller.
int Fact(int n)
{
if(n==1)
return 1;else
return (n * Fact(n–1));
}
Advantages
➢ Recursive solutions often tend to be shorter and simpler than non-recursive ones.
➢ Code is clearer and easier to use.
➢ Recursion works similar to the original formula to solve a problem.
➢ Recursion follows a divide and conquer technique to solve problems.
disadvantages
➢ Recursion is implemented using system stack. If the stack space on the system is limited,
recursion to a deeper level will be difficult to implement.
#include<stdio.h>
#define size 10
int binsearch(int[], int, int, int);
int main()
{
int num, i, key, position;
int low, high, list[size];
printf("\nEnter the total number of elements");
scanf("%d", &num);
printf("\nEnter the elements of list :");
for (i = 0; i < num; i++)
{
scanf("%d", &list[i]);
}
low = 0;
high = num - 1;
printf("\nEnter element to be searched : ");
scanf("%d", &key);
position = binsearch(list, key, low, high);
if (position != -1)
{
printf("\nNumber present at %d", (position + 1));
}
else
printf("\n The number is not present in the list");
return (0);
}
{
return (mid);
}
else if (x < a[mid])
{
binsearch(a, x, low, mid - 1);
}
else
{
}
Output:
Enter the total number of elements : 5
Enter the elements of list : 11 22 33 44 55
POINTERS
A pointer is a variable that contains the memory location of another variable.
#include<stdio.h>
int main()
{
int num,*pnum;
pnum=#
printf(“enter the number”);
scanf(“%d”,&num);
printf(“the no that was entered is %d”,*pnum);
return 0;
}
Output
Enter the number : 10
The number that was entered is : 10
Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, and –
Valid Pointer Arithmetic Invalid Pointer Arithmetic
Operations Operations
✓ Adding a number to pointer. ➢ Addition of two pointers.
✓ Subtracting a number form a ➢ Division of two pointers.
pointer.
✓ Incrementing a pointer.
✓ Decrementing a pointer.
✓ Subtracting two pointers.
#include <stdio.h>int main()
{
int m = 5, n = 10, q = 0;
int *p1;
int *p2;
int *p3;
OUTPUT: p1
p1 = &m; //printing the address of m
= 2680016
p2 = &n; //printing the address of n
p2 = 2680012
printf("p1 = %d\n", p1);
*p1+*p2 = 15
printf("p2 = %d\n", p2);
p1-p2 = 1
q = *p1+*p2;
p1++ = 2680020
printf("*p1+*p2 = %d\n", q);//point 1
p2-- = 2680008
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2
p1++;
printf("p1++ = %d\n", p1); //point 3
p2--;
printf("p2-- = %d\n", p2); //point 4
//Below line will give ERROR
printf("p1+p2 = %d\n", p1+p2); //point 5return 0;
}
NULL POINTER
null pointer which is a special pointer value and does not point to any value. This means that a
nullpointer does not point to any valid memory address.
int *ptr = NULL;
The null pointer is used in three ways,
[Link] stop indirection in a recursive data structure.
[Link] an error value
[Link] a sentinel value
#include <stdio.h>
int main()
{
int *ptr = NULL;
printf("The value of ptr is %u",ptr);
return 0;
}
Output :
The value of ptr is 0
#include <stdio.h>
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int *ptr1, *ptr2;
ptr1 = arr;
ptr2 = &arr[8];
Output
while(ptr1<=ptr2) 1234567
{
printf("%d", *ptr1);
ptr1++;
}
return 0;
}
ARRAY OF POINTERS:
Eg:int *ptr[10];
The above statement declares an array of 10 pointers where each of the pointer points to aninteger variable.
Example 2://Program on Array of Pointers
int main()
{
int *ptr[10];
int p = 1, q = 2, r = 3, s = 4, t = 5;
ptr[0] = &p;
ptr[1] = &q; OUTPUT:4
ptr[2] = &r;
ptr[3] = &s;
ptr[4] = &t;
printf("\n %d", *ptr[3]);
return 0;
}
1. Write a program to calculate the GCD of two numbers using recursive functions.#include
<stdio.h>
int GCD(int, int);
int main()
{
int num1, num2, res;
printf("\n Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
res = GCD(num1, num2);
printf("\n GCD of %d and %d = %d", num1, num2, res);
return 0;
}
int GCD(int x, int y)
{
int rem;
rem = x%y;
if(rem==0)
return y;
else
return (GCD(y, rem));
}
Output
Enter the two numbers : 8 12
GCD of 8 and 12 = 4
int Fibonacci(int n)
{ output:
if ( n == 0 ) enter the terms of Fibonacci series 01123
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n–1) + Fibonacci(n–2) ))
}
3. Write a program to add two integers using pointers and functions.
#include <stdio.h>
void sum (int*, int*, int*);int
main()
{
int num1, num2, total;
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
sum(&num1, &num2, &total);
printf("\n Total = %d", total);
return 0;
}
void sum (int *a, int *b, int *t)
{
*t = *a + *b;
}
Output
Enter the first number : 23
Enter the second number : 34
Total = 57
UNIT 4 STRUCTURES AND UNION
STRUCTURES:
• A structure is a user-defined data type that can store related information together. A
structure is acollection of variables under a single name.
• the major difference between a structure and an array is that, an array contains
related informationof the same data type.
• The variables within a structure are of different data types and each has a name that is
used to selectit from the structure.
Features of structures
• Structures can store more than one different data type data under a
single variable.
• Structure elements are stored in successive memory locations.
• Nesting of structure is possible.
• Structure elements can be passed as argument to the function.
Syntax:
//Structure creation
struct structurename
{
Datatype1
variablename;Datatype2
variablename;
.
.
};
//Object Creation
#include<stdio.h>struct point
int x,y;
};
void main()
Output:
{ (2,3)
printf(“(%d,%d)”,p1.x,p1.y);
Initialization of structures:
Syntax:
struct struct_name
datatype membername1;
datatype membername2;
datatype membername3;
}sturct_var={constant1,constant2,constant3,….};
Example:
struct student
{
int rno;
char name[20];
char course[20];
float fees;
}stud1={01,”Rahul”,”BCA”,45000};
or
Fig. illustrates how the values will be assigned to individual fields of the structure
Example:
[Link]=01; [Link]=”Rahul”;[Link]=”BCA”;[Link]=45000;
scanf(“%d”,&[Link]);
scanf(“%s”,[Link]);
Displaying output:
printf(“Roll No:%d”,[Link]);printf(“Name:%s”,[Link]);
TYPEDEF DECLARATION:
The typedef keyword enables the programmer to create a new data type name
from an existing data
type.
Syntax:
typedef existingdatatype newdatatype;
Example 1:
Example 2:
int rno;
char name[20]; char course[20];float fees;
};
Copy
Compare:
if([Link]==[Link])
printf(“Fees of s2 and s1 are equal”);
STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES) :
• Structures can be placed within another structures ie., a structure may contain another
structure as itsmember. A structure that contains another structure as its member is
called as nested structures.
ARRAYS OF STRUCTURES.
In the above examples, we have seen how to declare a structure and assign
values to its datamembers.
PASSING STRUCTURES THROUGH POINTERS:
• Passing large structures to functions using the call by value method is very inefficient.
Therefore, it is preferred to pass structures through pointers. It is possible to create a
pointer to almost any type in C, including the user-defined types.
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
}*ptr;
Or
#include <conio.h>
struct student
{
int r_no; Output
char name[20]; Enter the details of the student:
SELF-REFERENTIAL STRUCTURES
Self-referential structures are those structures that contain a reference to the data
of its same type. That is, a self-referential structure, in addition to other data, contains a pointer to
a data that is of the sametype as that of the structure. For example, consider the structure node given
below.
struct node
{
int val;
struct node *next;
};
Here, the structure node will contain two types of data: an integer val and a pointer
next. You must be wondering why we need such a structure. Actually, self-referential
structure is the foundation of other data structures. We will be using them throughout this
book and their purpose will be clearer to you when we discuss linked lists, trees, and graphs.
LINKED LISTS
Array is a linear collection of data elements in which the elements are stored in
consecutive memorylocations. Its size is fixed.
A linked list does not store its elements in consecutive memory locations and the user can
add anynumber of elements to it.
However, unlike an array, a linked list does not allow random access of data. Elements in a
linked listcan be accessed only in a sequential manner. But like an array, insertions and deletions
can be done at any point in the list in a constant time.
A linked list can be perceived as a train or a sequence of nodes in which each node contains one
ormore data fields and a pointer to the next node
Start
Since in a linked list, every node contains a pointer to another node which is of the same type, it is
also called a self-referential data type.
Declaration of node:
struct node
{
int data;
struct node *next;
}
START
.
struct node *insert_beg(struct node *start)
{
struct node *new_node;int num;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = num;
new_node -> next = start;
start = new_node;
return start;
}
Programming Example
Declare a structure to store information of a particular date.
struct date
{
int day;
int month;
int year;
};
Write a program, using an array of pointers to a structure, to read and display the data of
students.
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct student
int r_no;
char name[20];
char course[20];
int fees;
};
int main()
int i, n;
scanf("%d", &n);
for(i=0;i<n;i++)
{
ptr_stud[i] = (struct student *)malloc(sizeof(struct student));
printf("\nEnter the data for student %d ", i+1);
printf("\n ROLL NO.: ");
scanf("%d", &ptr_stud[i]–>r_no);
printf("\n NAME: ");
gets(ptr_stud[i]->name);
printf(“\ncourse”);
gets(ptr->stud[i]->course);
printf(“/n FEES”);
scanf(“%d”,&ptr_stud[i]->fees);
}
printf(“\n DETAILS OF STUDENT”);
for(i=0;i<n;i++)
{
printf((“\n ROLL NO=%d”,[Link][i]->[Link]);
printf(“\n NAME=%s,ptr->stud[i]->name);
printf(“\n COURSE=%s,ptr->stud[i]->course);
printf(“n FEES=%d”,ptr->stud[i]->fees);
}
return 0;
}
Output
Enter the number ofstudents : 1
Enter the data forstudent 1
ROLL NO.: 01
NAME: Rahul
COURSE:BCA
FEES: 45000
DETAILS OF STUDENT
SROLL NO. = 01
NAME = Rahul
COURSE = BCA
FEES = 45000
scanf("%d", &ptr–>fees);
display(ptr);
getch();
return
}
ROLL NO.: 01
NAME: Rahul
COURSE: BCA
FEES: 45000
DETAILS OF STUDENT
ROLL NO. = 01
NAME = Rahul
COURSE = BCA
FEES = 45000
[Link]
CS3251 Programming in C - UNIT V
5.1 Introduction
Named means that a particular collection of data on a disk has a name, like
[Link] and access to the collection is done by using its name.
A file represents a sequence of bytes on the disk where a group of related data
is stored. File is created for permanent storage of data. It is a readymade structure.
1. Text files
2. Binary files
1. Text Files [Link]
A text file consists of consecutive characters, which are interpreted by the
library functions used to access them and by format specifiers used in functions.
Text files are the normal .txt files that you can easily create using Notepad or
any simple text editors.
They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.
2. Binary files
A binary file consists of bytes of data arranged in continuous block. A separate
set of library functions is there to process such data files.
Binary files are mostly the .bin files in your computer. Instead of storing data in
plain text, they store it in the binary form (0's and 1's). They can hold higher amount
of data, are not readable easily and provides a better security than text files.
In C, you can perform four major operations on the file, either text or binary:
3. Closing a file
Function description
[Link]
fseek() - set the position to desire point
Opening a file means creating a new file with specified file name and with accessing
mode.
The fopen() function is used to create a new file or to open an existing file.
Syntax:
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the
opened(or created) file.
filename is the name of the file to be opened and mode specifies the purpose of
opening the file.
Mode Description
Mode Purpose
ab+ [Link]
opens a binary file in both reading and writing mode
2. Closing a File
A file must be closed after all the operation of the file have been completed. The
fclose() function is used to close an already opened file.
Syntax:
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.
The ‘fgetc’ function is used to read a character from a file which is opened in read
mode.
Syntax:
c=fgetc(p1);
The fscanf function is used to read data from a file. It is similar to the scanf function
except that fscanf() is used to read data from the disk.
Syntax:
where fb refers to the file pointer. v1, v2, … vn refers variables whose values are read
from the disk “format string” refers the control string which represents the conversion
specification.
The function ‘fputc’ is used to write a character variable x to the file opened in write
mode. [Link]
Syntax:
fputc(x,fp1);
fprintf() function is used to write data to a file. It is similar to the printf() function
except that fprintf() is used to write data to the disk.
Syntax:
1. Sequential Access — In this type of file, the data are kept sequentially. To read last
record of the file, it is expected to read all the records before that particular record. It
takes more time for accessing the records.
2. Random Access — In this type of file, the data can be read and modified
randomly. If it is desired to read the last record of a file, directly the same record can
be read. Due to random access of data, it takes less access time as compared to the
sequential file.
A Sequential file is characterized by the fact that individual data items are
arranged serially in a sequence, one after another. They can only be processed in serial
order from the beginning. In other words, the records can be accessed in the same
manner in which they have been stored. It is not possible to start reading or writing a
sequential file from anywhere except at the beginning.
The second and better method of arranging records of a file is called direct
access or random access. In this arrangement one can have access to any record which
is situated at the middle of the file without reading or passing through other records in
the file.
[Link]
5.3 Reading Sequential Access file
Data is stored in files so that the data can be retrieved for processing when needed
Example:
Program:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
exit(0);
} // end while
} // end main
Output:
/* Program to read from the [Link] file and find the average of the numbers */
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fp;
int n[50], i = 0;
float sum = 0;
exit(0); [Link]
}
while (!feof(fp)) {
sum += n[i];
i++;
fclose(fp);
if (i == 0)
return 0;
Output:
} byte offsets
}
}
}
}
}
}
The functions used to randomly access a record stored in a file are fseek(), ftell(),
rewind(), fgetpos(), and fsetpos().
1. fseek()
• fseek() is used to set the file position pointer for the given stream. Offset is an
integer value that gives the number of bytes to move forward or backward in
the file. Offset may be positive or negative, provided it makes sense. For
example, you cannot specify a negative offset if you are starting at the
beginning of the file. The origin value should have one of the following values
(defined in stdio.h):
• SEEK_SET: to perform input or output on offset bytes from start of the file
• [Link]
SEEK_END: to perform input or output on offset bytes from the end of the file
• fseek() can be used to move the file pointer beyond a file, but not before the
beginning.
Example: Write a program to print the records in reverse order. The file must be
opened in binary mode. Use fseek()
#include<stdio.h>
#include<conio.h>
main()
{ int emp_code;
char name[20];
int hra;
int da;
int ta;
};
FILE *fp;
struct employee e;
int result, i;
fp = fopen("[Link]", "rb");
if(fp==NULL)
exit(1);
} [Link]
for(i=5;i>=0;i--)
fclose(fp);
getch();
return 0;
2. rewind()
10
• rewind() is used to adjust the position of file pointer so that the next I/O
operation will take place at the beginning of the file. It’s prototype can be given
as
3. fgetpos()
• The fgetpos() is used to determine the current position of the stream. It’s
prototype can be given as
• Here, stream is the file whose current file pointer position has to be determined.
pos is used to point to the location where fgetpos() can store the position
information. The pos variable is of type fops_t which is defined in stdio.h and
is basically an object that can hold every possible position in a FILE.
[Link]
the fsetpos() to return to this same position.
4. fsetpos()
• The fsetpos() is used to move the file position indicator of a stream to the
location indicated by the information obtained in "pos" by making a call to the
fgetpos(). Its prototype is
• Here, stream points to the file whose file pointer indicator has to be re-
positioned. pos points to positioning information as returned by "fgetpos".
• On success, fsetpos() returns a zero and clears the end-of-file indicator. In case
of failure it returns a non-zero value
The program opens a file and reads bytes at several different locations.
#include <stdio.h>
main()
11
FILE *fp;
fpos_t pos;
char feedback[20];
fp = fopen(“[Link]”, “rb”);
if(fp == NULL)
exit(1);
[Link]
printf(“\n Error in fgetpos()");
exit(1);
pos = 90;
exit(1);
12
fclose(fp);
5. ftell()
The ftell function is used to know the current position of file pointer. It is at this
position at which the next I/O will be performed. The syntax of the ftell() defined in
stdio.h can be given as:
On successful, ftell() function returns the current file position (in bytes) for stream.
However, in case of error, ftell() returns -1.
When using ftell(), error can occur either because of two reasons:
First, using ftell() with a device that cannot store data (for example, keyboard)
Second, when the position is larger than that can be represented in a long integer. This
will usually happen when dealing with very large files
FILE *fp;
char c;
[Link]
int n;
fp=fopen("abc","w");
if(fp==NULL)
exit(1);
while((c=getchar())!=EOF)
putc(c,fp);
n = ftell(fp);
fclose(fp);
fp=fopen("abc","r");
13
if(fp==NULL)
exit(1);
while(ftell(fp)<n)
{ c= fgetc(fp);
printf('%c", c);
fclose(fp);
Option 1
calls function textFile to store a formatted list of all the accounts (typically called a
report) in a text file called [Link] that may be printed later. The function
uses fread and the sequential file access techniques used in the program of Section
below.
14
Option 2
calls the function updateRecord to update an account. The function will update only
a record that already exists, so the function first checks whether the record specified
by the user is empty. The record is read into structure client with fread, then member
acctNum is compared to 0. If it’s 0, the record contains no information, and a message
is printed stating that the record is empty. Then the menu choices are displayed. If the
record contains information, function updateRecord inputs the transaction amount,
calculates the new balance and rewrites the record to the file.
Option 3
calls the function newRecord to add a new account to the file. If the user enters an
account number for an existing account, newRecord displays an error message
indicating that the record already contains information, and the menu choices are
[Link]
printed again
Option 4
calls function deleteRecord to delete a record from the file. Deletion is accomplished
by asking the user for the account number and re-initialising the record. If the account
contains no information, deleteRecord displays an error message indicating that the
account does not exist.
Option 5
Example Program:
15
#include <stdio.h>
#include <stdlib.h>
struct clientData {
// prototypes
exit(-1);
16
switch (choice) {
case 1:
textFile(cfPtr); break;
// update record
case 2:
updateRecord(cfPtr); break;
// create record
case 3:
newRecord(cfPtr); break;
[Link]
// delete existing record
case 4:
deleteRecord(cfPtr); break;
default:
} // end switch
} // end while
} // end main
17
} // end if
else {
while (!feof(readPtr)) {
} // end if
} // end while
} // end else
18
scanf("%d", &account);
if ([Link] == 0) {
[Link]
printf("Account #%d has no information.\n", account);
[Link], [Link]);
scanf("%lf", &transaction);
19
} // end else
if ([Link] == 0) {
} // end if
20
} // end else
scanf("%d", &accountNum);
[Link]
// move file pointer to correct record in file
if ([Link] != 0) {
} // end if
else { // create record user enters last name, first name and balance
[Link] = accountNum;
21
} // end else
[Link]
" \"[Link]\" for printing\n"
return menuChoice;
Output
22
[Link]
Syntax:
23
Here argc counts the number of arguments on the command line and argv[ ] is a
pointer array which holds pointers of type char which points to the arguments passed
to the program
Example:
#include <stdio.h>
#include <conio.h>
int i;
else
return 0;
Remember that argv[0] holds the name of the program and argv[1] points to the first
command line argument and argv[n] gives the last argument. If no argument is
24
A. Buffer
B. Stream
C. File
Answer: File
2. If the mode includes b after the initial letter, what does it indicates?
a) text file
b) big text file
c) binary file
Answer: binary file
[Link]
3. What is the function of the mode ‘ w+’?
a) create text file for writing, discard previous contents if any
b) create text file for update, discard previous contents if any
c) create text file for writing, do not discard previous contents if any
d) create text file for update, do not discard previous contents if any
Answer: create text file for update, discard previous contents if any
25
B) FILE
C) FILEFP
D) filefp
Answer: FILE
B. fprintf()
26
C. fputc()
D. fputs()
Answer: fwrite()
A. stdin
B. stdout
C. stderr
D. all of these
A. Stdin
B. stdout [Link]
C. stderr
D. all of these
Answer: stderr
A. file pointer
B. buffer
C. stdout
D. stdin
Answer: buffer
A. fread()
27
B. fopen()
C. floes()
D. fflush()
Answer: fopen()
14. Which function returns the next character from stream, EOF if the end of file
is reached, or if there is an error?
A. fgetc()
B. fgets()
C. fputs()
D. fwrite()
Answer: fgetc()
[Link]
28