Full PSPC Theory Complete C Programming Notes
Full PSPC Theory Complete C Programming Notes
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 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.
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.
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.
4. To act as an intermediary between the hardware and its users, making it easier for the
users to access and use other resources.
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
•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.
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.
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.
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
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.
Example: Suppose we want to find the average of three numbers, the algorithm is as follows
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.
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 2: flowchart to find the largest among three different numbers entered by user
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
#include<stdio.h>
#include<conio.h>
void main()
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
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
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
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
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:
Literals:-Literals are Sequence of Characters like Digits, alphabets, letters those are used for Representing the Value
of the Variable.
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
Digits 0-9
C uses the following types of tokens Keywords, Identifiers, Literals, Punctuators, Operators.
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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
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.
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.
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.
High priority: * / %
Low priority: + -
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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.
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.
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
Conditional Operator: operator pair “?” and “:” is known as conditional operator.
Eg:
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;
a = 0000 1010
b = 0000 1011
For c = a & b
a 0000 1010
b 0000 1011
-----------------
a & b 0000 1010
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
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
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
High priority: * / %
Low priority: + -
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
"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."
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
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
Nested if...else : include if...else statement(s) inside the body of another if...else statement.
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.
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
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
continue;
Syntax of switch...case
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
Note: try to avoid goto statement as it may make the code buggy
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
data_type array_name[array_size];
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
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
or we can use
scanf("%d", &data[i]);
printf("%d", mark[i-1]);
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
int x[3][4]; Here, x is a two-dimensional (2d) array. The array can hold 12 elements.
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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.
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
int j;
j = strcmp("mousam", "choudhury");
printf("%d",j);
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
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
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
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
O(n2): ask one item and then ask that item about the status of other (n-1) item and so on.
O(log n): divide group into 2 half. Select the group where element lie. Now divide this group into 2 half and go on.
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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.
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 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.
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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>
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
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
Recursion makes program elegant and more readable. However, if performance is vital then, use loops
instead as recursion is usually much slower.
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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.
Or
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.
#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
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
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
Here, MIN is the macro name. Let's see an example of Function-like Macros :
#include <stdio.h>
void main()
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
#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
Predefined Macros
There are some predefined macros which are readily for use in C programming.
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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.
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
“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
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
Syntax:
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.
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
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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:
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:
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()
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
For Reference Only. Study from Standard Books and Materials @Mousam Choudhury
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