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

Full PSPC Theory Complete C Programming Notes

Uploaded by

sumanta.a.390
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Full PSPC Theory Complete C Programming Notes

Uploaded by

sumanta.a.390
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

lOMoARcPSD|42959127

Full PSPC Theory - Complete C programming notes

problem solving through programming using C (Assam Engineering College)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sumanta Das ([email protected])
lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 a

Input Unit

This unit contains devices with the help of which we enter data into the computer. This unit creates a link between the user
and the computer. The input devices translate the information into a form understandable by the computer.

CPU (Central Processing Unit)

CPU is considered as the brain of the computer. CPU performs all types of data processing operations. It stores data,
intermediate results, and instructions (program). It controls the operation of all parts of the computer.

CPU itself has the following three components: ALU (Arithmetic Logic Unit), Memory Unit & Control Unit.

Output Unit

The output unit consists of devices with the help of which we get the information from the computer. This unit is a link
between the computer and the users. Output devices translate the computer's output into a form understandable by the users.

Memory is primarily of three types: Cache Memory, Primary Memory/Main Memory & Secondary Memory

Cache memory is a very high speed semiconductor memory which can speed up the CPU. It acts as a buffer between the
CPU and the main memory. It is used to hold those parts of data and program which are most frequently used by the CPU.
The parts of data and programs are transferred from the disk to cache memory by the operating system, from where the
CPU can access them.

Advantages: 1. Cache memory is faster than main memory. 2. It consumes less access time as compared to main memory.
3. It stores the program that can be executed within a short period of time. 4.It stores data for temporary use.

Disadvantages: 1. Cache memory has limited capacity. 2. It is very expensive.

Primary memory holds only those data and instructions on which the computer is currently working. It has a limited
capacity and data is lost when power is switched off. It is generally made up of semiconductor device. These memories are
not as fast as registers. The data and instruction required to be processed resides in the main memory. It is divided into two
subcategories RAM and ROM. Its Faster than secondary memories. A computer cannot run without the primary memory.

Secondary Memory: This type of memory is also known as external memory or non-volatile. It is slower than the main
memory. These are used for storing data/information permanently. CPU directly does not access these memories, instead
they are accessed via input-output routines. The contents of secondary memories are first transferred to the main memory,
and then the CPU can access it. For example, disk, CD-ROM, DVD, etc.

A processor, or "microprocessor," is a small chip that resides in computers and other electronic devices. Its basic job is to
receive input and provide the appropriate output. A processor core is a processing unit which reads in instructions to
perform specific actions. Processors go through four main steps whenever they process instructions: fetch, decode, execute,
and writeback.

For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 a


Fetch: the processor core retrieves instructions that are waiting for it, usually from some sort of memory. This could include
RAM, but in modern processor cores, the instructions are usually already waiting for the core inside the processor cache. The
processor has an area called the program counter which essentially acts as a bookmark, letting the processor know where the last
instruction ended and the next one begins.

Decode: Once it has fetched the immediate instruction, it goes on to decode it. Instructions often involve multiple areas of the
processor core — such as arithmetic — and the processor core needs to figure this out. Each part has something called an opcode
which tells the processor core what should be done with the information that follows it. Once the processor core has figured this
all out, the different areas of the core itself can get to work.

Execute: The execute step is where the processor knows what it needs to do, and actually goes ahead and does it. As an example,
the processor can do arithmetic inside the ALU, or Arithmetic Logic Unit. This unit can connect to different inputs and outputs to
crunch numbers and get the desired result.

Writeback: The final step, called writeback, simple places the result of what’s been worked on back into memory.

It’s Just One Cycle and this entire process is called an instruction cycle.

An operating system is a program that acts as an interface between the software and the
computer hardware. It is an integrated set of specialized programs used to manage overall
resources and operations of the computer. It is specialized software that controls and monitors the
execution of all other programs that reside in the computer, including application programs and
other system software.

The objectives of the operating system are :

1.To make the computer system convenient to use in an efficient manner.

2. To hide the details of the hardware resources from the users.

3. To provide users a convenient interface to use the computer system.

4. To act as an intermediary between the hardware and its users, making it easier for the
users to access and use other resources.

5. To manage the resources of a computer system.

6. To keep track of who is using which resource, granting resource requests, and
mediating conflicting requests from different programs and users.

7. To provide efficient and fair sharing of resources among users and programs.

Here is a list of some of the most prominent characteristic features of Operating Systems −

•Memory Management − Keeps track of the primary memory, i.e. what part of it is in use by whom, what part is not in use, etc.
and allocates the memory when a process or program requests it.

•Processor Management − Allocates the processor (CPU) to a process and deallocates the processor when it is no longer
required.

•Device Management − Keeps track of all the devices. This is also called I/O controller that decides which process gets the
device, when, and for how much time.

•File Management − Allocates and de-allocates the resources and decides who gets the resources.

•Security − Prevents unauthorized access to programs and data by means of passwords and other similar techniques.

•Job Accounting − Keeps track of time and resources used by various jobs and/or users.
For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 a


•Control Over System Performance − Records delays between the request for a service and from the system.

•Interaction with the Operators − Interaction may take place via the console of the computer in the form of instructions. The
Operating System acknowledges the same, does the corresponding action, and informs the operation by a display screen.

•Error-detecting Aids − Production of dumps, traces, error messages, and other debugging and error-detecting methods.

•Coordination Between Other Software and Users − Coordination and assignment of compilers, interpreters, assemblers, and
other software to the various users of the computer systems.

Software is a set of programs, which is designed to perform a well-defined function. A program is a sequence of instructions
written to solve a particular problem.

There are two types of software: System Software and Application Software

System Software: The system software is a collection of programs designed to operate, control, and extend the processing
capabilities of the computer itself. System software is generally prepared by the computer manufacturers. These software products
comprise of programs written in low-level languages, which interact with the hardware at a very basic level. System software
serves as the interface between the hardware and the end users. Some examples of system software are Operating System,
Compilers, Interpreter, Assemblers, etc.

Application Software: Application software products are designed to satisfy a particular need of a particular environment. All
software applications prepared in the computer lab can come under the category of Application software. Application software
may consist of a single program, such as Microsoft's notepad for writing and editing a simple text. It may also consist of a
collection of programs, often called a software package, which work together to accomplish a task, such as a spreadsheet package.

The most prominent features of a system software are: Close to the system,Fast in speed, Difficult to design, Difficult to
understand, Less interactive, Smaller in size, Difficult to manipulate, Generally written in low-level language. Examples:Railways
Reservation Software, Microsoft Office Suite Software etc.

Language Processors: Assembly language is machine dependent yet mnemonics that are being used to represent instructions in it
are not directly understandable by machine and high Level language is machine independent. A computer understands instructions
in machine code, i.e. in the form of 0s and 1s. It is a tedious task to write a computer program directly in machine code. The
programs are written mostly in high level languages like Java, C++, Python etc. and are called source code. These source code
cannot be executed directly by the computer and must be converted into machine language to be executed. Hence, a special
translator system software is used to translate the program written in high-level language into machine code is called Language
Processor and the program after translated into machine code (object program / object code).

The language processors can be any of the following three types: Assembler, Compiler and Interpreter

Compiler: The language processor that reads the complete source program written in high level language as a whole in one go
and translates it into an equivalent program in machine language is called as a Compiler. Example: C, C++, C#, Java.

In a compiler, the source code is translated to object code successfully if it is free of errors. The compiler specifies the errors at the
end of compilation with line numbers when there are any errors in the source code. The errors must be removed before the
compiler can successfully recompile the source code again.

For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 a


Assembler: The Assembler is used to translate the program written in Assembly language into machine code. The source program
is a input of assembler that contains assembly language instructions. The output generated by assembler is the object code or
machine code understandable by the computer.

Interpreter: The translation of single statement of source program into machine code is done by language processor and
executes it immediately before moving on to the next line is called an interpreter. If there is an error in the statement, the
interpreter terminates its translating process at that statement and displays an error message. The interpreter moves on to the next
line for execution only after removal of the error. An Interpreter directly executes instructions written in a programming or
scripting language without previously converting them to an object code or machine code.Example: Perl, Python and Matlab.

For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 b

What is an algorithm?

An algorithm is a list of rules to follow in order to solve a problem. Algorithms need to have their steps in the right
order. A computer performs many tasks exactly in the same manner as it is told to do. This places responsibility on
the user to instruct the computer in a correct and precise manner, so that the machine is able to perform the required
job in a proper way.

In order to instruct a computer correctly, the user must have clear understanding of the problem to be solved. Thus,
before attempt to write a computer program to solve a given problem. It is necessary to formulate or define the
problem in a precise manner. Once the problem is defined, the steps required to solve it, must be stated clearly in the
required order.

What are the Steps Involved in Problem Solving?

1. Understanding the problem


2. Analyzing the problem
3. Developing the solution
4. Coding and implementation

1. Understanding the problem: try to understand the problem to be solved in totally i.e. the objectives of the given
problem.

2. Analyzing the problem: try to look different ways of solving the problem and evaluate each of these methods. To
search an appropriate solution to the problem is the main criteria..

3. Developing the solution: the result of analysis stage is expanded to form a detailed step by step solution to the
problem under consideration.

4. Coding and implementation: the conversion of the detailed sequence of operations in to a language that the
Computer can understand

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 indentified first for any specified problem.

Step2: Identification of output: From an algorithm, at least one quantity is produced, called 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.

For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 b

Example: Suppose we want to find the average of three numbers, the algorithm is as follows

Step 1 Read the numbers a, b, c

Step 2 Compute the sum of a, b and c

Step 3 Divide the sum by 3

Step 4 Store the result in variable “result”

Step 5 Print the value of “result”

Step 6 End of the program

What is a Flow Chart?

A flow chart is a step by step diagrammatic representation of the logic paths to solve a given problem. Flowchart is
visual or graphical representation of an algorithm. The flowcharts are pictorial representation of the methods to be
used to solve a given problem and help a great deal to analyze the problem and plan its solution in a systematic and
orderly manner. A flowchart when translated in to a proper computer language, results in a complete program.

Symbols used in Flow-Charts: (as per conventions followed by International Standard Organization (ISO).)

1. Oval: Rectangle with rounded sides is used to indicate either START/ STOP of the program.

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

For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 b

3. Process Indicators: - Rectangle is used to indicate any set of processing operation such as for storing
arithmetic operations.

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

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

6. On- Page connectors: Circles are used to join the different parts of a flowchart and these circles are called
on-page connectors. The uses of these connectors give a neat shape to the flowcharts. Ina complicated
problems, a flowchart may run in to several pages. The parts of the flowchart on different pages are to be
joined with each other. The parts to be joined are indicated by the circle.

7. Off-page connectors: This connector represents a break in the path of flowchart which is too large to fit
on a single page. It is similar to on-page connector. The connector symbol marks where the algorithm ends
on the first page and where it continues on the second.

example 1: flowchart to add two numbers entered by user

For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 b

example 2: flowchart to find the largest among three different numbers entered by user

For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 b

What is a Pseudo code?


It’s simply an implementation of an algorithm in the form of annotations and informative text written in plain
English. It has no syntax like any of the programming language and thus can’t be compiled or interpreted by the
computer.
Examples 1:

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


Print "passed"
else
Print "failed"
End

Example 2: Add Two Numbers


BEGIN
NUMBER s1, s2, sum
OUTPUT("Input number1:")
INPUT s1
OUTPUT("Input number2:")
INPUT s2
sum=s1+s2
OUTPUT sum
END

Example 3: Calculate Area and Perimeter of Rectangle


BEGIN
NUMBER b1,b2,area,perimeter
INPUT b1
UNPUT b2
area=b1*b2
perimeter=2*(b1+b2)
OUTPUT alan
OUTPUT perimeter
END

For Reference Only. Study from Standard Books and Materials

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 c


From algorithm to program:

Example: Write an algorithm to add two numbers entered by user.

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

sum←num1+num2

Step 5: Display sum

Step 6: Stop

From algorithm to program:

Example: Write an algorithm to add two numbers entered by user.

#include<stdio.h>

#include<conio.h>

void main()

int num1, num2, add; //declaring Variables

printf("Enter first number: ");

scanf("%d",&num1); //Accepting Number one

printf("Enter second number: ");

scanf("%d",&num2); //Accepting Number two

add = num1+num2; //Adding both of them

printf("The addition of numbers %d and %d is %d",one,two,add); //Printing the Result

Object code is the output of a compiler after it processes source code.

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

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 c


Pre-processing
This phase includes:

1. Removal of Comments
2. Expansion of Macros
3. Expansion of the included files.
A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of
code is communicated to the compiler before entering into the actual coding (main () function). A macro is defined
with the preprocessor directive, #define.

Compiling
The next step is to compile the output of preprocessing and produce an intermediate compiled output file. This file is
in assembly level instructions.

Assembly
In this phase the output of compiling is taken as input and turned into “filename.o” by assembler. This file contains
machine level instructions. At this phase, only existing code is converted into machine language, the function calls
like printf() are not resolved.

Linking
This is the final phase in which all the linking of function calls with their definitions are done. Linker knows where
all these functions are implemented. Linker does some extra work also, it adds some extra code to our program which
is required when the program starts and ends. GCC by default does dynamic linking, so printf() is dynamically linked
in above program.

Errors in C
1. Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax are known as syntax
errors. This compiler error indicates something that must be fixed before the code can be compiled. All these
errors are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
 Missing Parenthesis (})
 Printing the value of variable without declaring it
 Missing semicolon like this:

2. Run-time Errors: Errors which occur during program execution(run-time) after successful compilation are
called run-time errors. One of the most common run-time error is division by zero also known as Division
error. These types of error are hard to find as the compiler doesn‟t point to the line at which the error occurs.

3. Linker Errors: These error occurs when after compilation we link the different object files with main‟s
object using Ctrl+F9 key(RUN). These are errors generated when the executable of the program cannot be
generated. This may be due to wrong function prototyping, incorrect header files. One of the most common
linker error is writing Main() instead of main().

4. Logical Errors: On compilation and execution of a program, desired output is not obtained when certain
input values are given. These types of errors which provide incorrect output but appears to be error free are
called logical errors. These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we follow the
line of execution and determine why the program takes that path of execution.

5. Semantic errors: This error occurs when the statements written in the program are not meaningful to the
compiler.
Eg: int a, b, c;
a + b = c; //semantic error
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 c

Variables
In programming, a variable is the area to hold data.
Rules for naming a variable
 A variable name can have letters (both uppercase and lowercase letters), digits and underscore only.
 The first letter of a variable should be either a letter or an underscore.
 There is no rule on how long a variable name (identifier) can be. However, problems may arise in some
compilers if variable name is longer than 31 characters.
Constants
1. Integers: a numeric constant (number) without any fractional or exponential part
2. Floating-point Numbers: a numeric constant that has either a fractional form or an exponent form. Eg. 12.2,
0.000123, 0.123E-5 (Remember: E-5 = 10-5 )
3. Character Constants: character constant is created by enclosing a single character inside single quotation
marks. Eg: 'a', 'b', 'C', '1', '{'
4. Escape Sequences: to use characters which cannot be typed or has special meaning in C programming as an
example: newline(enter), tab, question mark etc. In order to use these characters, escape sequence is used.
 \t means Horizontal tab
 \b means Backspace
 \n means Newline
 \0 means Null character
5. String Literals : a sequence of characters enclosed in double-quote marks. Eg: "mousam choudhury”
6. Enumerations : to define enumeration types. Eg.:enum colour {yellow, green, black, white};
Here, colour is a variable and yellow, green, black and white are the enumeration constants having value 0, 1,
2 and 3 respectively.

double: It is used to store decimal numbers (numbers with floating point value) with double precision.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 1 c

A C program basically consists of the following parts −

1. Preprocessor Commands
2. Functions
3. Variables
4. Statements & Expressions
5. Comments
 The Documentation Section consists of a set of comment lines giving the name of the program and other
details.
 The Link Section provides instructions to the compiler to link functions from the system library. C program
depends upon some header files for function definition that are used in the program. Each header file has
extension „.h‟. The header files are included at the beginning of the program in the C language.
 The Definition Section defines all symbolic constants.
 The Global Declaration Section: There are some variables and those variables are declared in this section
that is outside of all functions.
 main() function: Every C program must have one main() function section.
 Declaration Part declares all the variables used in the executable part. There should be at least one
statement in the executable part which contains instructions to perform certain task. The declaration and
executable part must appear between the opening and closing braces. All statements in the declaration part
should end with the semicolon.
 The Subprogram Section contains all the user defined functions that are called in the main function.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 2


Operator: The Special Symbols those have specific functions associated with them. For performing the operations it
needs some Operands.

Operands are those on which operations are performed by the Operators.

Eg: 1+2. Here, + is the Operator and 1 and 2 Operands.

Separators: These are Special Symbols used to Indicate the group of code that is either be divided or arrange into the
Block. The Separators includes Parentheses, Open Curly braces, Comma, Semicolon etc.

Identifiers: Those which are used for giving a name to a variable, class and method, packages, interfaces etc.

Remember:

1. Name of Identifier cannot be a Keyword


2. Must be Started with Alphabet and not from digit
3. Uppercase and Lowercase are treated Different
4. It can be any length
5. It should not be a reserved word.

Literals:-Literals are Sequence of Characters like Digits, alphabets, letters those are used for Representing the Value
of the Variable.

Eg: int money = 123;

'123' is a literal whose identifier is 'money'

Identifiers are tokens (also called symbols) which name language entities. Some of the kinds of entities an identifier
might denote include variables, types, labels, subroutines, and packages.

literal is a notation for representing a fixed value in source code. Literals (often referred to as constants) are data items
that never change their value during the execution of the program. Eg. Integer-Constants, Character-constants,
Floating-constants, Strings-constants

C Character Set

Letters  A-Z, a-z

Digits  0-9

Special Characters Space + - * / ^ \ ( ) [ ] { } = != <> „ “ $ , ; : % ! & ? _ # < = > = @

C uses the following types of tokens Keywords, Identifiers, Literals, Punctuators, Operators.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 2

Keywords

Punctuators in C

Operators are the symbols which tell the computer to execute certain mathematical or logical operations. C
programming offers a number of operators which are classified into 8 categories viz.

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 2

Arithmetic Operators

Modulo division is only possible with integer operands. It causes compilation error with float types.
Modulo division evaluates remainder after performing division of two numbers.

Remember: There is no exponential operator in C programming language.

^ is a bitwise XOR operator in C. (Important)

Relational Operators used when we have to make comparisons

Relational operators are most commonly used in decision statements like if, while, etc.

C represents false with 0 and true with a non-zero integer value. C standard specifies to use 1 for representing a true
value. But we can use any number as per our requirement.

Do not confuse assignment = operator with relational equals to == operator. (Important)

Arithmetic operators have higher priority than relational operators meaning that if arithmetic expressions are present
on two sides of a relational operator then arithmetic expressions will be calculated first and then the result will be
compared.

Eg. 1 > 2+3

Here 2 is added with 3 first and then compared with 1

High priority: * / %
Low priority: + -

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 2

Logical operators are used when more than one conditions are to be tested and based on that result, decisions have
to be made.

Medium Precedence

Assignment operators are used to assign result of an expression to a variable. „=‟ is the assignment operator in C.

Shorthand assignment operator Example Meaning


+= a += 1 a=a+1
- = a -= 1 a=a-1
*= a *= 1 a=a*1
/= a /= 1 a=a/1
%= a %= 1 a=a%1
&= a &= 1 a=a&1

Shorthand assignment can be used with all arithmetic operators

C programming allows the use of ++ and -- operators which are increment and decrement operators respectively.
Both the increment and decrement operators are unary operators. Thus have high precedence. The increment
operator ++ adds 1 to the operand and the decrement operator -- subtracts 1 from the operand.

Eg. a++ means a=a+1; and b-- means b=b-1.

Remember: ++m is known as prefix operator and m++ is known as postfix operator.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 2

Conditional Operator: operator pair “?” and “:” is known as conditional operator.

Eg:

Can be written as:

Remember: it is never recommended to transform a nested if...else...if or ladder if...else statement to conditional
operator expression.

Bitwise operators are used for testing the bits or shifting them left or right. Bitwise operators works on each bit of
the data.

Eg: Suppose a and b are two integer variables with initial value int a=10, b=11;

re-writing integers in 8-bit binary representation

a = 0000 1010
b = 0000 1011

For c = a & b

We get, 0000 1010 which is 10 in decimal.

a 0000 1010
b 0000 1011
-----------------
a & b 0000 1010

Remember: Do not confuse between bitwise OR | and logical OR || operator.

Eg. Bitwise XOR ^ operator. It sets each bit of the resultant value to 1 whenever the corresponding bits of the two
operands differ.

a 0000 0110
b 0000 1101
-------------------------------
a^b 0000 1011
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 2

Bitwise left shift << operator. Eg.

int a=15; Which in 8-bit binary will be represented as:

a = 0000 1111

Now, c = a << 3;

This will shifts bits of a three times to left and evaluates to 0111 1000 which is 120 in decimal.

a 0000 1111
a << 1 0001 1110
a << 2 0011 1100
a << 3 0111 1000

Bitwise right shift >> operator

a 0000 1111
a >> 1 0000 0111
a >> 2 0000 0011
a >> 3 0000 0001

Remember: Shifting bits to right is equivalent to dividing by 2. We can use bitwise right shift operator if we need to
divide a number (unsigned number) by power of 2.

Special Operators:

1. Comma Operator
The comma operator can be used to link the related expressions together. A comma linked expression is evaluated
from left to right and the value of the right most expression is the value of the combined expression.

2 .Sizeof() operator
The sizeof operator returns the number of bytes the operand occupies.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 2

High priority: * / %
Low priority: + -

Its evaluated from Left to Right

Eg: x = 1 – 4 / 2 + 3 *5 – 1

Step 1: x = 1-2 + 3 * 5 – 6
Step 2: x = 1 – 2 + 15 – 6
Step 3: x = -1 + 15 – 6
Step 4: x = 14 – 6
Step 5: x = 8

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 3


In C, both if statements and while loops rely on the idea of Boolean expressions.

The (num < 0) portion of the program is the


Boolean expression. C evaluates this expression to
decide whether or not to print the message. If the
Boolean expression evaluates to True, then C
executes the single line immediately following the if
statement.

If the Boolean expression is False, then C skips the


line or block of lines immediately following the if
statement.

Lets see another example:

"If the value in variable a equals the value in variable b and if the value in
variable c is greater than the value in variable d, then set the variable x to 1,
otherwise set the variable y to 2."

Here are all of the Boolean operators in C:

while statements:

The two lines within the braces to be executed repeatedly until a is greater
than or equal to b.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 3

if statement is used to decide whether a certain statement or block of statements will be executed or not .If a certain
condition is true then a block of statement is executed otherwise not.

Remember:
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the
first immediately below statement to be inside its block.

if(condition)
statement1;
statement2;

// Here if the condition is true, if block will consider only statement1 to be inside its block.

if- else : We can use the else statement with if statement to execute a block of code when the condition is false.

if...else if....else Statement : allows one to check for multiple test expressions and execute different statement(s).

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 3

Nested if...else : include if...else statement(s) inside the body of another if...else statement.

The initialization statement is executed only once.

Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated.

But if the test expression is true (nonzero), codes inside the body of for loop is executed and the update expression is
updated.

This process repeats until the test expression is false.

do...while loop: It is similar to the while loop with one important difference. The body of do...while loop is executed
once, before checking the test expression.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 3

break Statement: terminates the loop (for, while and do...while loop) immediately when it is encountered.

break Statement: terminates the loop (for, while and do...while loop) immediately when it is encountered.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 3

Continue statement skips statements after it inside the loop.


Its syntax is:

continue;

Syntax of switch...case

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 3

goto statement is used to alter the normal sequence of a C program

Note: try to avoid goto statement as it may make the code buggy

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 4


An array is a collection of a fixed number of values of a single type. The size and type of arrays cannot be changed
after its declaration.

Eg. int value[10]; or float data[100];

data_type array_name[array_size];

Arrays are of two types:

1. One-dimensional arrays
2. Multidimensional arrays

Can access elements of an array by indices. Eg. float data[5]; To access 3rd value use data[2]

1 2 3 4 5

[0] [1] [2] [3] [4]

Arrays have 0 as the first index not 1. If the size of an array is n, to access the last element, (n-1) index is used.

Initialize an array

int data[5] = {19, 10, 8, 17, 9};

or we can use

int data[] = {19, 10, 8, 17, 9};

Take input from the user and insert in (i+1)th element

scanf("%d", &data[i]);

Print ith element of an array

printf("%d", mark[i-1]);

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 4

Array declaration by specifying size:

int arr1[10]; or int n = 10; int arr2[n];

Array declaration by initializing elements

int arr[] = { 10, 20, 30, 40 }

Array declaration by specifying size and initializing elements

int arr[6] = { 10, 20, 30, 40 }

Initialization of a two dimensional array

int x[3][4]; Here, x is a two-dimensional (2d) array. The array can hold 12 elements.

// Different ways to initialize two dimensional array

int c[2][3] = {{1, 2, 3}, {-4, 5, 6}};

int c[][3] = {{7, 8, 9}, {-10, 11, 12}};

int c[2][3] = {13, 14, 15, -16, 17, 18};

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 4

String is a sequence of characters that is treated as a single data item and terminated by null character '\0'.
Remember:C language does not support strings as a data type. A string is actually one-dimensional array of
characters in C language. Example: The string "Mousam choudhury" contains 17 characters including '\0' character
which is automatically added by the compiler at the end of the string.

Declaring and Initializing a string variables


char name[7] = "mousam"; or we can represent as

char name[10] = {'A','b','c','d','e','f','g','\0'};

Note: In the 2nd case must supply the '\0' character explicitly.

OR
string.h library has the following most important functions:

strcat() function
strcat("mousam", "choudhury");
strcat() function will add the string "mousam" to "choudhury" i.e it will ouput mousamchoudhury.

strlen() function
strlen() function will return the length of the string passed to it.

int j;
j = strlen("mousam");
printf("%d",j);

Output will be 6

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 4


strcmp() function
strcmp() function will return the ASCII difference between first unmatching character of two strings.

int j;
j = strcmp("mousam", "choudhury");
printf("%d",j);

Note the output yourself

strcpy() function
It copies the second string argument to the first string argument.

strrev() function
It is used to reverse the given string expression.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 5

Linear search in C: Used to find whether a given number is present in an array and if it is present then at what
location it occurs. It is also known as sequential search. Here we keep on comparing each element of the array with the
element to search until it is found or the list ends.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 5

C program for binary search: can only be used for sorted arrays, but it's fast as compared to linear search. If the
array isn't sorted, then we must sort it using some sorting technique (eg. merge sort or quick sort ) and then use the
binary search algorithm to find the desired element in the list. The code below assumes that the input numbers are in
ascending order.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 5

C program for bubble sort:

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 5


Insertion sort in C: Best case complexity of insertion sort is O(n), average and the worst case complexity is O(n2).

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 5


Selection sort in C:

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 5


C program to find roots of a equation:

Notion of order of complexity:

In a data set of n items.

O(n2): ask one item and then ask that item about the status of other (n-1) item and so on.

O(n): ask each item individually

O(log n): divide group into 2 half. Select the group where element lie. Now divide this group into 2 half and go on.

Eg.1. time complexity is constant: O(1) Eg.2. time complexity is O(N)

Binary search algorithm has Average performance of O(log n).

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 6


A function is a block of code that performs a specific task. A function prototype is simply the declaration of a
function that specifies function's name, parameters and return type. It doesn't contain function body. A function
prototype gives information to the compiler that the function may later be used in the program.

C functions can be classified into two categories:

1. Library functions: Library functions are those functions which are already defined in C library, example
printf(), scanf(), strcat() etc.
2. User-defined functions: functions which are defined by the user at the time of writing program. These
functions are made for code reusability and for saving time and space.

Function declaration consists of 4 parts: returntype; function name; parameter list; terminating semicolon.

General syntax for function declaration is:

returntype functionName(type1 parameter1, type2 parameter2,...);

returntype: When a function is declared to perform some sort of calculation or any operation and is expected to
provide with some result at the end, in such cases, a return statement is added at the end of function body. Return
type specifies the type of value (int, float, char, and double) that function is expected to return to the program which
called the function. In case your function doesn't return any value, the return type would be void.

functionName: Function name is an identifier and it specifies the name of the function. The function name is any
valid C identifier and therefore must follow the same naming rules like other variables in C language.

parameter list: The parameter list declares the type and number of arguments that the function expects when it is
called. Also, the parameters in the parameter list receive the argument values when the function is called. They are
often referred as formal parameters.

The general syntax of function definition is:

returntype functionName(type1 parameter1, type2 parameter2,...)

// function body goes here

The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known as function header and the
statement(s) within curly braces is called function body. While defining a function, there is no semicolon(;) after the
parenthesis in the function header, unlike while declaring the function or calling the function.

The function body contains the declarations and the statements (algorithm) necessary for performing the required
task. The body is enclosed within curly braces { ... } and consists of three parts.

1. local variable declaration(if required).


2. function statements to perform the task inside the function.
3. a return statement to return the result evaluated by the function(if return type is void, then no return
statement is required).

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 6


Scope rules in C: A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in
C programming language :

1. Inside a function or a block which is called local variables.


2. Outside of all functions which is called global variables.
3. In the definition of function parameters which are called formal parameters.

Local Variables: Variables that are declared inside a function or block are called local variables. They can be used
only by statements that are inside that function or block of code. Local variables are not known to functions outside
their own.

Global Variables: Global variables are defined outside a function, usually on top of the program. Global variables
hold their values throughout the lifetime of your program and they can be accessed inside any of the functions
defined for the program. A global variable can be accessed by any function. That is, a global variable is available for
use throughout your entire program after its declaration

#include <stdio.h>

/* global variable declaration */

int a;

Formal Parameters: Formal parameters, are treated as local variables with-in a function and they take precedence
over global variables.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 6

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 6

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 6

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 7


Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.

Recursion makes program elegant and more readable. However, if performance is vital then, use loops
instead as recursion is usually much slower.

Note that, every recursion can be modeled into a loop.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 7

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 8


A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of
possibly different types into a single type.

How to create a structure?

‘struct’ keyword is used to create a structure. Following is an example.

When a structure is defined, it creates a user-defined type. However, no storage or memory is allocated. To allocate
memory of a given structure type and work with it, we need to create variables.

two variables student1, student2, and an array


variable v having 20 elements of type struct
Person are created.

Both represent same thing

Or

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 8

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 8

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 9


Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This
process is called preprocessing.

Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.

List of preprocessor directives :

#include ; #define ; #undef ; #ifdef ; #ifndef ; #if ; #else ; #elif ; #endif ; #error ; #pragma

1. #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-
defined and user-defined header files. If included file is not found, compiler renders error. It has three variants:

#include <file>

This variant is used for system header files. It searches for a file named file in a list of directories specified by you,
then in a standard list of system directories.

#include "file"

This variant is used for header files of your own program. It searches for a file named file first in the current directory,
then in the same directories used for system header files. The current directory is the directory of the current input file.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 9


#include anything else

This variant is called a computed #include. Any #include directive whose argument does not fit the above two forms is
a computed include.

2. Macro's (#define)

a macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive.

Syntax

#define token value

There are two types of macros:

1. Object-like Macros
2. Function-like Macros

1. Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For
example:

#define PI 3.1415

2. Function-like Macros

The function-like macro looks like function call. For example:

#define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name. Let's see an example of Function-like Macros :

#include <stdio.h>

#define MIN(a,b) ((a)<(b)?(a):(b))

void main()

printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));

3. #undef

To undefine a macro means to cancel its definition. This is done with the #undef directive.

Syntax:

#undef token

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 9


define and undefine example

#include <stdio.h>
Output:
#define PI 3.1415

#undef PI
Compile Time Error: 'PI' undeclared
main()

printf("%f",PI);

4. #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code.

5. #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code.

6. #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code.

7. #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with
#if, #elif, #ifdef and #ifndef directives.

8. #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips
further compilation process.

9. #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive
is used by the compiler to offer machine or operating-system feature.

To use conditional, #ifdef, #if, #defined, #else and #elseif directives are used.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 9

Predefined Macros

There are some predefined macros which are readily for use in C programming.

Predefined macro Value

__DATE__ String containing the current date

__FILE__ String containing the file name

__LINE__ Integer representing the current line number

__STDC__ If follows ANSI standard C, then value is a nonzero integer

__TIME__ String containing the current date.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10


Pointers are used in C program to access the memory and manipulate the address. If you have a variable var in your
program, &var will give you its address in the memory, where & is commonly called the reference operator.

In C, you can create a special variable that stores the address (rather than the value). This variable is called pointer
variable or simply a pointer.

& is called reference operator. It gives you the address of a variable.

another operator that gets you the value from the address, it is called a dereference operator *.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10

“malloc” or “memory allocation” method is used to dynamically allocate a single large block of memory with the
specified size. It returns a pointer of type void which can be cast into a pointer of any form.

“calloc” or “contiguous allocation” method is used to dynamically allocate the specified number of blocks of
memory of the specified type. It initializes each block with a default value ‘0’.

“free” method is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and
calloc() are not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation
takes place. It helps to reduce wastage of memory by freeing it.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10


a pointer points to a location in memory and thus used to store address of variables. So, In Double Pointer (Pointer to
Pointer) The first pointer is used to store the address of second pointer.

Syntax:

int **ptr; // declaring double pointers

Self Referential structures are those structures that have one or more pointers which point to the same type of
structure, as their member. In other words, structures pointing to the same type of structures are self-referential in
nature.

‘link’ is a pointer to a structure of type ‘node’. Hence, the structure


‘node’ is a self-referential structure with ‘link’ as the referencing
pointer.

An important point to consider is that the pointer should be


initialized properly before accessing, as by default it contains garbage
value.

Types of Self Referential Structures

1. Self Referential Structure with Single Link: Self Referential Structure with Single Link: These structures can
have only one self-pointer as their member.
2. Self Referential Structure with Multiple Links: Self referential structures with multiple links can have more
than one self-pointers. Many complicated data structures can be easily constructed using these structures.
Such structures can easily connect to more than one nodes at a time.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10


An array is a collection of fixed number of values of a single type. That is, you need to declare the size of an array
before you can use it.Sometimes, the size of array you declared may be insufficient. To solve this issue, you can
allocate memory manually during run-time. This is known as dynamic memory allocation in C programming.

There are 4 library functions defined under <stdlib.h> makes dynamic memory allocation in C programming. They are
malloc(), calloc(), realloc() and free().

1. The name "malloc" stands for memory allocation. The malloc() function reserves a block of memory of the
specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form.
Example:

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

Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the
address of the first byte in the allocated memory.

However, if the space is insufficient, allocation fails and returns a NULL pointer.

2. The name "calloc" stands for contiguous allocation.The malloc() function allocates a single block of memory.
Whereas, calloc() allocates multiple blocks of memory and initializes them to zero.
Example:

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each with the size of float.

3. Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must
explicitly use free() to release the space.

Syntax of free()

free(ptr);

This statement frees the space allocated in the memory pointed by ptr.

4. If the dynamically allocated memory is insufficient or more than required, you can change the size of previously
allocated memory using realloc() function

Syntax of realloc()

ptr = realloc(ptr, x);

Here, ptr is reallocated with new size x.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])


lOMoARcPSD|42959127

Problem Solving Through Programming Using C (PSPC) Module 10

Linked list is an ordered set of data elements, each containing a link to its successor. This program is to create a linked
list and display all the elements present in the created list. It is a series of connected "nodes" that contains the
"address" of the next node. Each node can store a data point which may be a number, a string or any other type of
data.

the address of the first node is called HEAD and the last node in the linked list can be identified because its next
portion points to NULL.

The power of linkedlist comes from the ability to break the chain and rejoin it. E.g. if you wanted to put an element 4
between 1 and 2, the steps would be:

A. Create a new struct node and allocate memory to it. B. Add its data value as 4. C.Point its next pointer to the
struct node containing 2 as data value D.Change next pointer of "1" to the node we just created.

For Reference Only. Study from Standard Books and Materials @Mousam Choudhury

Downloaded by Sumanta Das ([email protected])

You might also like