0% found this document useful (0 votes)
7 views157 pages

Unit I Programminginc 161212055106

The document provides an overview of fundamental concepts in computer programming, focusing on the C programming language. It covers topics such as algorithms, flowcharts, pseudocode, programming languages, and language translators, including low-level and high-level languages. Additionally, it discusses the structure of C programs and the historical context of the language's development.

Uploaded by

rajavaishnavi.it
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views157 pages

Unit I Programminginc 161212055106

The document provides an overview of fundamental concepts in computer programming, focusing on the C programming language. It covers topics such as algorithms, flowcharts, pseudocode, programming languages, and language translators, including low-level and high-level languages. Additionally, it discusses the structure of C programs and the historical context of the language's development.

Uploaded by

rajavaishnavi.it
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 157

Fundamental of Computer

programming -206

PROGRAMMING IN C

UNIT- I
UNIT-1
 1.1- Representing Algorithms through flowchart, pseudo code
.
 1.2- Concept of Programming Languages and Language transl
ator.
 1.3- Introduction to Programming and structure of C Program.
 1.4- Identifiers, Constants, Variables.
 1.5- Basic Data Types.
 1.6- Operators, Expressions in C, type casting.
 1.7- Input Statement.
 1.8- Output Statement. 2

 1.9- Scope Rules and Storage classes.


By- Er. Indrajeet Sinha , +919509010997
REPERSENTING ALGORITHMS
THROUGH FLOWCHARTS & PSEUDO
CODE

Lecture no.- 1,
UNIT- I
1.1- INTRODUCTION
 Definition:-

 What is Program?
A computer program is a collection of instructions that
performs a specific task when executed by a computer. A
computer requires programs to function, and typically
executes the program's instructions in a central
processing unit.

 What is programming language?


A programming language is a formal computer language
designed to communicate instruction to a machine,
particularly a computer. Programming language can be
used to create programs to control the behavior of a
machine or to express algorithms.
By- Er. Indrajeet Sinha , +919509010997
DEFINITION’S
 What is an algorithm?
A process or set of rules to be followed in
calculations or other problem-solving operations,
especially by a computer.

 What is Flow Chart ?


Pictorial representation of an algorithm is known
as flow chart, it use some special symbol to
represent instruction set.
 What is Pseudocode?

 Artificial, informal language used to develop algorithms


 Similar to everyday English

By- Er. Indrajeet Sinha , +919509010997


WHY ALGORITHMS & FLOWCHARTS ?

 A typical programming task can be divided


into two phases:
 Problem solving phase
 produce an ordered sequence of steps that
describe solution of problem
 this sequence of steps is called an algorithm

 Implementation phase
 implement the program in some programming
language

By- Er. Indrajeet Sinha , +919509010997


STEPS IN PROBLEM SOLVING

 First produce a general algorithm (one can


use pseudocode)

 Refine the algorithm successively to get step


by step detailed algorithm that is very close
to a computer language.

 Pseudocode is an artificial and informal


language that helps programmers develop
algorithms. Pseudocode is very similar to
everyday English.

By- Er. Indrajeet Sinha , +919509010997


1.1.1- THE FLOWCHART

A graphical representation of the sequence of


operations in an information system or
program. Information system flowcharts show
how data flows from source documents
through the computer to final distribution to
users. Different symbols are used to draw each
type of flowchart.

By- Er. Indrajeet Sinha , +919509010997


FLOWCHART SYMBOLS
Name Symbol Use in Flowchart

Oval Denotes the beginning or end of the program

Parallelogram Denotes an input operation

Rectangle Denotes a process to be carried out


e.g. addition, subtraction, division etc.

Diamond Denotes a decision (or branch) to be made.


The program should continue along one of
two routes. (e.g. IF/THEN/ELSE)

Hybrid Denotes an output operation

Flow line Denotes the direction of logic flow in the program

By- Er. Indrajeet Sinha , +919509010997


1.1.1.1- SEQUENTIAL FLOW CHART

By- Er. Indrajeet Sinha , +919509010997


1.1.1.2- CONDITIONAL FLOW CHART

By- Er. Indrajeet Sinha , +919509010997


1.1.1.3 LOOPING FLOW CHART

By- Er. Indrajeet Sinha , +919509010997


1.1.2 PSEUDO CODE

 Definition:-

 Pseudo code is a simple way of


writing programming code in English.

 Pseudo code (pronounced SOO-doh-kohd) is a


detailed yet readable description of what a
computer program or algorithm must do, expressed
in a formally-styled natural language rather than in
a programming language.

 Pseudocode is an artificial and informal language


that helps programmers to develop algorithms.

By- Er. Indrajeet Sinha , +919509010997


PSEUDOCODE & ALGORITHM

 Example 1: Write an algorithm to determine


a student’s final grade and indicate whether
it is passing or failing. The final grade is
calculated as the average of four marks.

By- Er. Indrajeet Sinha , +919509010997


PSEUDOCODE & ALGORITHM

Pseudocode:
 Input a set of 4 marks
 Calculate their average by summing
and dividing by 4
 if average is below 50

Print “FAIL”
else
Print “PASS”

By- Er. Indrajeet Sinha , +919509010997


EXAMPLE

START

Input Step 1: Input M1,M2,M3,M4


M1,M2,M3, Step 2: GRADE 
M4
(M1+M2+M3+M4)/4
Step 3: if (GRADE <50) then
GRADE(M1+M2+M3+M4
)/4 Print “FAIL”
else
N IS Y Print “PASS”
GRADE< endif
50

PRINT PRINT
“PASS” “FAIL”

STOP

By- Er. Indrajeet Sinha , +919509010997


EXAMPLE 2

Write an algorithm and draw a flowchart to


convert the length in feet to centimeter.

Pseudocode:
 Input the length in feet (Lft)
 Calculate the length in cm (Lcm) by
multiplying LFT with 30
 Print length in cm (LCM)

By- Er. Indrajeet Sinha , +919509010997


EXAMPLE 2

Algorithm Flowchart
 Step 1: Input Lft
START
 Step 2: Lcm  Lft x 30
 Step 3: Print Lcm Input
Lft

Lcm  Lft x
30

Print
Lcm

STOP

By- Er. Indrajeet Sinha , +919509010997


CONCLUSION OF LECTURE-1

 In this lecture we knew about program,


algorithm and pseudo code.
 We also knew about different type of flow

chart.
 We also exercise on different types of example

for create flow chart and pseudo code.

19

By- Er. Indrajeet Sinha , +919509010997


CONCEPT OF PROGRAMMING
LANGUAGES AND LANGUAGE
TRANSLATORS

Lecture no. -2,


UNIT- I
1.2.1 LOW LEVEL LANGUAGE

 Definition:-
 In computer science, a low-
level programming language is a
programming language that provides little or no
abstraction from a computer's instruction set
architecture—commands or functions in
the language map closely to processor instructions.
Generally this refers to either machine code or
assembly language.

 Low-level language is a programming language that


deals with a computer's hardware components and
constraints. ...

 Low-level language may also be referred to as a


computer’s native language. ...

 Machine language and assembly language are popular


examples of low level languages.
By- Er. Indrajeet Sinha , +919509010997
1.2.2 HIGH LEVEL LANGUAGE

 Definition:

 A high-level language is a programming


language such as C, FORTRAN, or Pascal that
enables a programmer to write programs that are
more or less independent of a particular type of
computer. Such languages are considered high-
level because they are closer to
human languages and further from
machine languages.

 High-level language is any programming


language that enables development of a program
in much simpler programming ...

By- Er. Indrajeet Sinha , +919509010997


ASSEMBLY LANGUAGE

 Definition:
 A low level language that is similar to machine
language.

 Uses symbolic operation code to represent the


machine operation code.

By- Er. Indrajeet Sinha , +919509010997


1.2.3 LANGUAGE TRANSLATOR

 Definition:
 A translator is a computer program that performs
the translation of a program written in a given
programming language into a functionally
equivalent program in a different
computer language, without losing the functional or
logical structure of the original code (the "essence"
of each program).
 Programming language processor (assembler,
compiler, or interpreter) that converts a computer
program written in one language to another
language.

By- Er. Indrajeet Sinha , +919509010997


1.2.3.1 ASSEMBLER
 Definition:
 An assembler is a program that takes basic
computer instructions and converts them into a
pattern of bits that the computer's processor can
use to perform its basic operations.
 Assembler may refer to: Assembler (computing), a
computer program which translates assembly
language to an object file or machine language
format.
 Software that translates assembly language into
machine language.

Assembly language Object code


code Assembler

By- Er. Indrajeet Sinha , +919509010997


1.2.3.2 INTERPRETER
 Definition:
 Computer language processor that translates a program
line-by-line (statement-by-statement) and carries out the
specified actions.
 An interpreter translates high-level instructions into an
intermediate form, which it then executes. In contrast, a
compiler translates high-level instructions directly into
machine language.

By- Er. Indrajeet Sinha , +919509010997


1.2.3.3 COMPILER
 Definition:
 A compiler is a special program that processes
statements written in a particular programming
language and turns them into machine language or
"code" that a computer's processor uses. Typically, a
programmer writes language statements in a language
such as Pascal or C one line a
 A compiler is a computer program (or a set of programs)
that transforms source code written in a programming
language (the source language) into another computer
language (the target language), with the latter often
having a binary form known as object code.

By- Er. Indrajeet Sinha , +919509010997


SOFTWARE LANGUAGE LEVELS

 Machine Language (Binary)


 Assembly Language
 Assembler converts Assembly into machine
 High Level Languages (C, Perl, Shell)
 Compiled : C
 Interpreted : Perl, Shell

By- Er. Indrajeet Sinha , +919509010997


SOME TERMS

 Source
 The language program was written in
 Object
 The machine language equivalent of the program after
compilation
 Compiler
 A software program that translates the source code
into object code
 Assembler is a special case of compiler where the
source was written in Assembly language

By- Er. Indrajeet Sinha , +919509010997


CONVERT SOURCE TO OBJECT
 Example:
 SUM=A+B
 Compiles to Machine language of:
LDR R1, A
LDR R2, B
ADD R1, R1, R2
STR R1, C

By- Er. Indrajeet Sinha , +919509010997


STEPS FOR COMPILATION

 Create/Edit source
 Compile source

 Link object modules together

 Test executable

 If errors, Start over

 Stop

By- Er. Indrajeet Sinha , +919509010997


COMPILATION PROCESS:
 Invoke compiler on source program to generate
Machine language equivalent
 Compiler translates source to object

 Saves object output as disk file[s]

 Large Systems may have many source programs

 Each has to be compiled

By- Er. Indrajeet Sinha , +919509010997


INTERPRETATION

 No linking
 No object code generated

 Source statements executed line by line

By- Er. Indrajeet Sinha , +919509010997


STEPS IN INTERPRETATION

 Read a source line


 Parse line

 Do what the line says


 Allocate space for variables
 Execute arithmetic opts etc..
 Go to back to step 1

 Similar to instruction cycle

By- Er. Indrajeet Sinha , +919509010997


INTERPRETER ADVANTAGES

 Easier to debug
 Faster development time

 Some Interpretive Systems


 Languages
 BASIC, Perl, Lisp

 OS Interfaces
 C Shell, Bourne Shell
 WINEXEC

By- Er. Indrajeet Sinha , +919509010997


INTRODUCTION TO PROGRAMMING
AND STRUCTURE OF C PROGRAM

Lecture no. -3,


UNIT- I
1.3.1 NEED OF PROGRAMMING
LANGUAGES

 A programming language is a formal


computer Language designed to
communicate instructions to a machine,
particularly a computer. Programming
languages can be used to create programs to
control the behavior of a machine or to
express algorithms.
 For make easy work.

By- Er. Indrajeet Sinha , +919509010997


1.3.2 INTRODUCTION AND FEATURES
OF C
C is a high-
C is a high-level and level programming
general language developed by
purpose programming Dennis Ritchie at Bell
language that is ideal for Labs in the mid 1970s.
developing firmware or Although originally
portable applications. designed as a System
programming language.

C is a structured, C has proved to be a powerful


procedural programmi and flexible language that can
ng language that has be used for a variety of
been widely used both applications, from business
programs to engineering.
for operating systems
and applications
By- Er. Indrajeet Sinha , +919509010997
C - HISTORY

 Developed between 1969 and 1973 along with


Unix
 Due mostly to Dennis Ritchie
 Designed for systems programming
 Operating systems
 Utility programs
 Compilers
 Filters
 Evolved from B, which evolved from BCPL
 Designed by Martin Richards (Cambridge) in 1967
 Type less
 Everything an n-bit integer (a machine word)
 Pointers (addresses) and integers identical
 Memory is an undifferentiated array of words

By- Er. Indrajeet Sinha , +919509010997


FEATURES OF C

By- Er. Indrajeet Sinha , +919509010997


CONT…

 Low Level Features :


 C Programming provides low level features that are
generally provided by the Lower level languages. C
is Closely Related to Lower level Language such as
“Assembly Language“.
 It is easier to write assembly language codes in C
programming.

 Portability :
 C Programs are portable i.e they can be run on any
Compiler with Little or no Modification
 Compiler and Preprocessor make it Possible for C
Program to run it on Different PC

By- Er. Indrajeet Sinha , +919509010997


 Powerful:
 Provides Wide verity of ‘Data Types‘
 Provides Wide verity of ‘Functions’
 Provides useful Control & Loop Control Statements

 Bit Manipulation:
 C Programs can be manipulated using bits. We can
perform different operations at bit level. We can
manage memry representation at bit level. [Eg.
We can use Structure to manage Memory at Bit Lev
el
]
 It provides wide verity of bit manipulation
Operators. We have bitwise operators to manage
Data at bit level.
By- Er. Indrajeet Sinha , +919509010997
 High Level Features :
 It is more User friendly as compare to Previous
languages. Previous languages such as BCPL,Pascal
and other programming languages never provide such
great features to manage data.
 Previous languages have there pros and cons but C
Programming collected all useful features of previous
languages thus C become more effective language.
 Modular Programming:
 Modular programming is a software design
technique that increases the extent to which software
is composed of separate parts, called modules
 C Program Consist of Different Modules that are
integrated together to form complete program

By- Er. Indrajeet Sinha , +919509010997


1.3.3 STRUCTURE OF A C PROGRAM

Note:-

Every
C Program will have
one or more
functions and there
is one mandatory
function which is
called main()
function. ...

By- Er. Indrajeet Sinha , +919509010997


HELLO WORLD IN C
Preprocessor used to
share information among
#include <stdio.h> source files
- Clumsy
+ Cheaply implemented
void main() + Very flexible
{
printf(“Hello, world!\n”);
}

By- Er. Indrajeet Sinha , +919509010997


HELLO WORLD IN C Program mostly a
collection of functions
“main” function special:
the entry point
#include <stdio.h> “void” qualifier indicates
function does not return
anything
void main()
{
printf(“Hello, world!\n”);
}

I/O performed by a library


function: not included in the
language

By- Er. Indrajeet Sinha , +919509010997


1.3.4 COMPILATION, LINKING AND
EXECUTION OF A C PROGRAM
 Click Here for C program Compilation Process
 Understanding C program Compilation Process visit,
https://youtu.be/VDslRumKvRA

By- Er. Indrajeet Sinha , +919509010997


1.3.5 - OBJECT CODE,
INTERMEDIATE CODE, EXECUTABLE
CODE
 Definition:

 source code: In computing, source code is any


collection of computer instructions, (possibly with
comments), written using a human-readable
programming language, usually as ordinary text.

By- Er. Indrajeet Sinha , +919509010997


Definition:
 Intermediate Code: A source code can directly
be translated into its target machine code, then
why at all we need to translate the source code
into an intermediate code which is then translated
to its target code? Let us see the reasons why we
need an intermediate code.

49

By- Er. Indrajeet Sinha , +919509010997


 Object code: It is the output of a
compiler after it processes source code.
 Executable code: Software in a form

that can be run in the computer. It


typically refers to machine language,
which is the set of native instructions the
computer carries out in hardware.

50

By- Er. Indrajeet Sinha , +919509010997


51

By- Er. Indrajeet Sinha , +919509010997


IDENTIFIERS, CONSTANTS,
VARIABLES,

Lecture no.- 4,
UNIT- I
1.4.1- CONSTANTS

 Definition:-
 Constants refer to fixed values that the program
may not alter during its execution. These fixed
values are also called literals. Constants can be of
any of the basic data types like an Integer
Constant, a floating constant, a Character
Constant, or a string literal.

53

By- Er. Indrajeet Sinha , +919509010997


1.4.1.1- TYPES OF CONSTANTS

54

By- Er. Indrajeet Sinha , +919509010997


1.4.1.1.1 - NUMERICAL CONSTANTS

 Numerical Constants
 Constants like 12, 253 are stored as int type. No
decimal point.
 12L or 12l are stored as long int.
 12U or 12u are stored as unsigned int.
 12UL or 12ul are stored as unsigned long int.
 Numbers with a decimal point (12.34) are stored as
double.
 Numbers with exponent (12e-3 = 12 x 10-3 ) are stored
as double.
 12.34f or 1.234e1f are stored as float.
 These are not valid constants:

25,000 7.1e 4 $200 2.3e-3.4


etc.
By- Er. Indrajeet Sinha , +919509010997
1.4.1.1.2 - CHARACTER AND STRING

 Character and string constants


 ‘c’ , a single character in single quotes are stored as char.
Some special character are represented as two characters
in single quotes.
‘\n’ = newline, ‘\t’= tab, ‘\\’ = backlash, ‘\”’ =
double quotes.
Char constants also can be written in terms of their ASCII
code.
‘\060’ = ‘0’ (Decimal code is 48).
 A sequence of characters enclosed in double quotes is
called a string constant or string literal. For example
“Charu”
“A”
“3/9”
“x = 5”

By- Er. Indrajeet Sinha , +919509010997


1.4.1.2 - DECLARING CONSTANTS

57

By- Er. Indrajeet Sinha , +919509010997


1.4.2- IDENTIFIERS, KEYWORDS

 Definition:
 Identifiers
 An Identifier is a sequence of letters and digits,

but must start with a letter. Underscore ( _ ) is


treated as a letter. Identifiers are case sensitive.
Identifiers are used to name variables, functions
etc.
 Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If
 Invalid: 324, short, price$, My Name
 Keywords
 These are reserved words of the C language. For

example int, float, if, else, for, while


etc.
58

By- Er. Indrajeet Sinha , +919509010997


1.4.3- VARIABLES (VARIABLE
DECLARATION RULES)

 Naming a Variable
 Must be a valid identifier.
 Must not be a keyword
 Names are case sensitive.
 Variables are identified by only first 32 characters.
 Library commonly uses names beginning with _.
 Naming Styles: Uppercase style and Underscore
style
 lowerLimit lower_limit
 incomeTax income_tax

By- Er. Indrajeet Sinha , +919509010997


DECLARATIONS

 Declaring a Variable
 Each variable used must be declared.
 A form of a declaration statement is

data-type var1, var2,…;


 Declaration announces the data type of a variable
and allocates appropriate memory location. No
initial value (like 0 for integers) should be assumed.
 It is possible to assign an initial value to a variable
in the declaration itself.
data-type var = expression;
 Examples

int sum = 0;
char newLine = ‘\n’;
float epsilon = 1.0e-6;
By- Er. Indrajeet Sinha , +919509010997
BASIC DATA TYPES IN
C

Lecture no.- 5,
UNIT- I
1.5.1- DATA TYPES

 Definition
Data types in c refer to an extensive
system used for declaring variables or
functions of different types.
The type of a variable determines how much
space it occupies in storage and how the bit
pattern stored is interpreted.

62

By- Er. Indrajeet Sinha , +919509010997


1.5.1- DATA TYPES

63

By- Er. Indrajeet Sinha , +919509010997


BASIC DATA TYPES CONT..
 Integral Types
 Integers are stored in various sizes. They can be signed
or unsigned.
 Example

Suppose an integer is represented by a byte (8 bits).


Leftmost bit is sign bit. If the sign bit is 0, the number is
treated as positive.
Bit pattern 01001011 = 75 (decimal).
The largest positive number is 01111111 = 2 7 – 1 = 127.
Negative numbers are stored as two’s complement or as
one’s complement.
-75 = 10110100 (one’s complement).
-75 = 10110101 (two’s complement).

By- Er. Indrajeet Sinha , +919509010997


BASIC DATA TYPES CONT..

 Integral Types
 char Stored as 8 bits. Unsigned 0 to 255.
Signed -128 to 127.
 short int Stored as 16 bits. Unsigned 0 to
65535.
Signed -32768 to 32767.
 int Same as either short or long int.
 long int Stored as 32 bits. Unsigned 0
to 4294967295.
Signed -2147483648 to
2147483647

By- Er. Indrajeet Sinha , +919509010997


BASIC DATA TYPES CONT..

 Floating Point Numbers


 Floatingpoint numbers are rational numbers. Always
signed numbers.
 float Approximate precision of 6 decimal digits .
 Typically stored in 4 bytes with 24 bits of signed mantissa and
8 bits of signed exponent.
 double Approximate precision of 14 decimal
digits.
 Typically stored in 8 bytes with 56 bits of signed mantissa and
8 bits of signed exponent.

 One should check the file limits.h to what is


implemented on a particular machine.

By- Er. Indrajeet Sinha , +919509010997


TOKENS IN C

 Keywords
 Theseare reserved words of the C language. For
example int, float, if, else, for, while etc.
 Identifiers
 An Identifier is a sequence of letters and digits, but
must start with a letter. Underscore ( _ ) is treated as a
letter. Identifiers are case sensitive. Identifiers are used
to name variables, functions etc.
 Valid: Root, _getchar, __sin, x1, x2, x3, x_1,
If
 Invalid: 324, short, price$, My Name
 Constants
 Constants like 13, ‘a’, 1.3e-5 etc.

By- Er. Indrajeet Sinha , +919509010997


C- LITERALS

 String Literals
A sequence of characters enclosed in double quotes as
“…”. For example “13” is a string literal and not
number 13. ‘a’ and “a” are different.
 Operators
 Arithmetic operators like +, -, *, / ,% etc.
 Logical operators like ||, &&, ! etc. and so on.
 White Spaces
 Spaces, new lines, tabs, comments ( A sequence of
characters enclosed in /* and */ ) etc. These are used to
separate the adjacent identifiers, kewords and
constants.

By- Er. Indrajeet Sinha , +919509010997


OPERATORS, EXPRESSIONS IN C,
TYPE CASTING

Lecture no.- 6,
UNIT- I
1.6.1- INTRODUCTION

 Definition
 Operator: An operator is a symbol that tells the
compiler to perform certain mathematical or logical
manipulations. Operators are used in program to
manipulate data and variables.
 Expression: In programming, an exppression is
any legal combination of symbols that represents a
value. Each programming language and
application has its own rules for what is legal and
illegal. For example, in the C language x+5 is
an expression, as is the character string
"MONKEYS."

70

By- Er. Indrajeet Sinha , +919509010997


1.6.2- TYPES OF OPERATORS BASED
ON NUMBER OF OPERANDS

 1.5.2.1- Unary operators:-


 The unary operators operate on a single operand and
following are the examples of Unary operators.
 1.5.2.2 Binary operators:-
A binary operator is an operator that operates on
two operands and manipulates them to return a result.
 1.5.2.3 Ternary operators:-
 The ternary operator is an operator that takes three
arguments. The first argument is a comparison
argument, the second is the result upon a true
comparison, and the third is the result upon a false
comparison. If it helps you can think of the operatoras
shortened way of writing an if-else statement. 71

By- Er. Indrajeet Sinha , +919509010997


UNARY OPERATORS

Operator Name Type

! Logical NOT Unary


& Address-of Unary
() Cast Operator Unary
* Pointer dereference Unary
+ Unary Plus Unary
++ Increment Unary
– Unary negation Unary
–– Decrement 1 Unary
~ complement Unary

72

By- Er. Indrajeet Sinha , +919509010997


BINARY OPERATORS

Operator Name Type

!= Inequality Binary

% Modulus Binary

%= Modulus assignment Binary

& Bitwise AND Binary

&& Logical AND Binary


Bitwise AND
&= Binary
assignment
* Multiplication Binary
Multiplication
*= Binary
assignment
+ Addition Binary

+= Addition assignment Binary

– Subtraction Binary
Subtraction 73
–= Binary
assignment
–> Member selection Binary
By- Er. Indrajeet Sinha , +919509010997
Operator Name Type

–>* Pointer-to-member selection Binary


/ Division Binary
/= Division assignment Binary
< Less than Binary
<< Left shift Binary
<<= Left shift assignment Binary
<= Less than or equal to Binary

74

By- Er. Indrajeet Sinha , +919509010997


1.6.3- TYPES OF OPERATORS BASED
ON OPERATIONS

 1.6.3.1- Arithmetic Operator


 1.6.3.2 - Assignment Operator

 1.6.3.3 - + + and - - Operator

75

By- Er. Indrajeet Sinha , +919509010997


1.6.3.1- ARITHMETIC OPERATOR

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from A − B = 10


the first.

∗ Multiplies both operands. A ∗ B = 200

∕ Divides numerator by de- B∕A=2


numerator.

% Modulus Operator and B%A=0


remainder of after an integer
division.

++ Increment operator increases A++ = 11


the integer value by one.

-- Decrement operator decreases A-- = 9


the integer value by one.

76

By- Er. Indrajeet Sinha , +919509010997


1.6.3.2 - ASSIGNMENT OPERATOR

 Assignment Operator is Used to assign value


to an variable.
 Assignment Operator is denoted by equal to

sign
 Assignment Operator is binary operator

which operates on two operands.

77

By- Er. Indrajeet Sinha , +919509010997


1.6.3.3 - + + AND - - OPERATOR

 Definition:
 Increment Operators are used to increased

the value of the variable by one.


 -Pre-Increment: ++variable
 -Post- increment: variable++

 Decrement Operators are used to


decrease the value of the variable by one.
 -Pre-Increment: ++variable
 -Post- increment: variable++

NOTE: Both increment and decrement operator are used on a single


operand or variable, so it is called as a unary operator. 78

By- Er. Indrajeet Sinha , +919509010997


79

By- Er. Indrajeet Sinha , +919509010997


80

By- Er. Indrajeet Sinha , +919509010997


OPERATORS, EXPRESSIONS IN C,
TYPE CASTING

Lecture no.- 7,
UNIT- I
1.7.1- LOGICAL OPERATOR

 Logical Operators
 &&, || and ! are the three logical operators.
 expr1 && expr2 has a value 1 if expr1 and expr2
both are nonzero.
 expr1 || expr2 has a value 1 if expr1 and expr2
both are nonzero.
 !expr1 has a value 1 if expr1 is zero else 0.
 Example
 if ( marks >= 40 && attendance >= 75 )
grade = ‘P’
 If ( marks < 40 || attendance < 75 ) grade
= ‘N’

By- Er. Indrajeet Sinha , +919509010997


1.7.2 - TERNARY OPERATOR
(CONDITIONAL OPERATOR)

 Ternary operator needs exactly 3 operands to


compute the result. In C, If statement can be
written as ternary operator (?:).
1. if(a<b){
2. c=5;
3. }
4. else{
5. c=10;
6. }

 The above if block can be re-written using ternary operator


like this (below).
 c=(a<b)?5:10; 83

By- Er. Indrajeet Sinha , +919509010997


1.7.3 - RELATIONAL OPERATORS

 Relational Operators
 <, <=, > >=, ==, != are the relational operators.
The expression
operand1 relational-operator operand2
takes a value of 1(int) if the relationship is true and
0(int) if relationship is false.
 Example

int a = 25, b = 30, c, d;


c = a < b;
d = a > b;
value of c will be 1 and that of d will be 0.

By- Er. Indrajeet Sinha , +919509010997


1.7.4 - BITWISE OPERATOR

 and: & or: | xor: ^ not: ~ left shift: << right


shift: >>
 Useful for bit-field manipulations

#define MASK 0x040


if (a & MASK) { … } /* Check bits */
c |= MASK; /* Set bits */
c &= ~MASK; /* Clear bits */
d = (a & MASK) >> 4; /* Select field */

By- Er. Indrajeet Sinha , +919509010997


1.7.5 - OPERATOR PRECEDENCE AND
ASSOCIATIVITY

 Operator precedence determines which


operator is performed first in an expression
with more than one operators with different
precedence.

For example 10 + 20 * 30 is calculated as


10 + (20 * 30) and
not as (10 + 20) * 30.

Note: Please see the following precedence 86

and associativity table for reference.


By- Er. Indrajeet Sinha , +919509010997
Operator Name Associativity Operators

Primary scope left to right ::


resolution
() [ ] . -> dynamic_cast
Primary left to right typeid

+
Unary right to left
+ -- + - ! ~ & * (type_name)
sizeof new delete

C Pointer to
left to right .*->*
Member
* / %
Multiplicative left to right
+ -
Additive left to right
<< >>
Bitwise Shift left to right
< > <= >=
Relational left to right
== != 87
Equality left to right

By- Er. Indrajeet Sinha , +919509010997


CONT..

Operator Name Associativity Operators


&
Bitwise AND left to right
^
Bitwise Exclusive OR left to right
|
Bitwise Inclusive OR left to right
&&
Logical AND left to right
||
Logical OR left to right
? :
Conditional right to left
= += -= *=
Assignment right to left
/= <<= >>= %=
&= ^= |=

,
Comma left to right
88

By- Er. Indrajeet Sinha , +919509010997


1.7.6- C EXPRESSION

 arithmetic: + – * / %
 comparison: == != < <= > >=
 bitwise logical: & | ^ ~
 shifting: << >>
 lazy logical: && || !
 conditional: ? :
 assignment: = += -=
 increment/decrement: ++ --
 sequencing: ,
 pointer: * -> & []

By- Er. Indrajeet Sinha , +919509010997


C EXPRESSIONS

 Traditional mathematical expressions

y = a*x*x + b*x + c;

 Very rich set of expressions


 Able to deal with arithmetic and bit

manipulation

By- Er. Indrajeet Sinha , +919509010997


TERMS IN EXPRESSIONS

 Evaluating an expression often has side-


effects
a++ increment a afterwards
a=5 changes the value of a
a = foo() function foo may have side-
effects

By- Er. Indrajeet Sinha , +919509010997


1.7.6 - TYPE CASTING

 Type casting is a way to convert a variable


from one data type to another data type. For
example, if you want to store a long value
into a simple integer then you can type
cast long to int.

 Types of Type casting


 Implicit Conversion:- It does not required
any operator for converted
 Explicit Conversion:- In c language , Many

conversions, specially those that imply a


different interpretation of the value, require an
explicit conversion. 92

By- Er. Indrajeet Sinha , +919509010997


EXPLICIT CONVERSION EXAMPLE

#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(“implicit value is%d”,p);
getch();
}
Output :- 93
Explicit value is 20.
By- Er. Indrajeet Sinha , +919509010997
IMPLICIT CONVERSION EXAMPLE

#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(“implicit value is %d”,p);
getch();
94
} Output :-implicit value is 20.
By- Er. Indrajeet Sinha , +919509010997
INPUT STATEMENT OF C

Lecture no.- 8,
UNIT- I
1.8- INTRODUCTION OF LECTURE

 Definition
 An input/output statement or io statement is a
portion of a program that instructs a computer how to
read and process information. It pertains to gather
information from an input device, or sending
information to an output device.

 In this chapter, we discuss in depth the formatting features of


scanf and printf.
 These functions input data from the standard input stream and
output data to the standard output stream.
 Four other functions that use the standard input and standard
output—gets, puts, getchar and putchar—were discussed in
Chapter 8.
 Include the header <stdio.h> in programs that call these 96
functions.
By- Er. Indrajeet Sinha , +919509010997
1.8.1 GETCH()

Function : getch()
getch() is used to get a character from console but does
not echo to the screen.
Library: < stdio.h>
Declaration: int getch(void);

Example Declaration:
char ch;
ch = getch(); (or ) getch();
Remarks:
getch reads a single character directly from the keyboard,
without echoing to the screen.
Return Value:
This function return the character read from the keyboard. 97

By- Er. Indrajeet Sinha , +919509010997


Example Program:
void main()
{

char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
Program Explanation:
Here, declare the variable ch as char data type, and then get
a value through getch() library function and store it in the
variable ch. And then, print the value of variable ch.
During the program execution, a single character is get or
read through the getch(). The given value is not displayed
on the screen and the compiler does not wait for another
character to be typed.And then,the given character is
98
printed through the printf function.

By- Er. Indrajeet Sinha , +919509010997


1.8.2- GETC()

Description
The C library function int getc(FILE *stream) gets the next
character (an unsigned char) from the specified stream
and advances the position indicator for the stream.

Declaration
Following is the declaration for getc() function.
int getc(FILE *stream)
Parameters
stream -- This is the pointer to a FILE object that identifies
the stream on which the operation is to be performed.
Return Value
This function returns the character read as an unsigned
char cast to an int or EOF on end of file or error. 99

By- Er. Indrajeet Sinha , +919509010997


Example
#include<stdio.h>
int main()
{
char c;
printf("Enter character: ");
c = getc(stdin);
printf("Character entered: ");
putc(c, stdout);
return(0);
}
Let us compile and run the above program that will produce the
following result:
Enter character: a
100
Character entered: a

By- Er. Indrajeet Sinha , +919509010997


1.8.3- GETCHAR()

Function : getchar()
getchar() is used to get or read the input (i.e a single
character) at run time.

Library: <stdio.h>
Declaration: int getchar(void);
Example Declaration:
char ch;
ch = getchar();
Return Value:
This function return the character read from the keyboard.

101

By- Er. Indrajeet Sinha , +919509010997


Example Program:
void main()
{

char ch;
ch = getchar();
printf("Input Char Is :%c",ch);
}
Program Explanation
Here,declare the variable ch as char data type, and then get a
value through getchar()library function and store it in the
variable ch.And then,print the value of variable ch.
During the program execution, a single character is get or read
through the getchar(). The given value is displayed on the
screen and the compiler wait for another character to be typed.
If you press the enter key/any other characters and then only the
given character is printed through the printf function. 102

By- Er. Indrajeet Sinha , +919509010997


1.8.4 GETS()
Description
The C library function char *gets(char *str) reads a
line from stdin and stores it into the string pointed to
by str. It stops when either the newline character is
read or when the end-of-file is reached, whichever
comes first.
Declaration
char *gets(char *str)Parameters
str -- This is the pointer to an array of chars where the C
string is stored.
Return Value
This function returns str on success, and NULL on error
or when end of file occurs, while no characters have
been read.
103

By- Er. Indrajeet Sinha , +919509010997


Example
#include <stdio.h>
int main()
{
char str[50];
printf("Enter a string : ");
gets(str);
printf("You entered: %s", str);
return(0);
}
Result:
Enter a string : [email protected]
You entered: [email protected] 104

By- Er. Indrajeet Sinha , +919509010997


1.8.5 GETCHE()

Function : getche()
getche() is used to get a character from console, and echoes
to the screen.

Library: <Stdio.h>
Declaration:
int getche(void);
Example Declaration:
char ch;
ch = getche();
Remarks:
getche reads a single character from the keyboard and
echoes it to the current text window, using direct video or
BIOS.
Return Value:
105
This function return the character read from the keyboard.

By- Er. Indrajeet Sinha , +919509010997


Example Program:
void main()
{

char ch;
ch = getche();
printf("Input Char Is :%c",ch);
}
Program Explanation:
Here,declare the variable ch as char data type, and then get a
value through getche()library function and store it in the
variable ch.And then,print the value of variable ch.
During the program execution, a single character is get or read
through the getche(). The given value is displayed on the
screen and the compiler does not wait for another character to
be typed. Then,after wards the character is printed through 106
the printf function.

By- Er. Indrajeet Sinha , +919509010997


1.8.6- SCANF()

 In C programming language, scanf() function is used


to read character, string, numeric data from keyboard
 Consider below example program where user enters a
character. This value is assigned to the variable “ch”
and then displayed.
 Then, user enters a string and this value is assigned to
the variable “str” and then displayed.

107

By- Er. Indrajeet Sinha , +919509010997


EXAMPLE PROGRAM FOR SCANF()
#include <stdio.h> OUtPut
Enter any character
int main() a
{ Entered character is a
Enter any string ( upto 100
char ch; character )
char str[100]; hai
Entered string is hai
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}

108

By- Er. Indrajeet Sinha , +919509010997


KEY POINT OF SCANF()

 The format specifier %d is used in scanf()


statement. So that, the value entered is
received as an integer and %s for string.
 Ampersand is used before variable name “ch”

in scanf() statement as &ch.

109

By- Er. Indrajeet Sinha , +919509010997


OUTPUT STATEMENT OF
C

Lecture no.- 9,
UNIT- I
 In C programming language output functions
are the functions through which the result is
displayed on the standard output device like
monitor.
Following are the output functions of C
language –

 1.9.1- printf( ) – This function is used to print both


values of variables and messages. It can also display
the character strings. The general syntax is –
printf("Hello world");
printf(" Sum of two numbers is %d",a);
printf("%f,%d",m,a); 111

By- Er. Indrajeet Sinha , +919509010997


 1.9.2 putc() takes a character argument, and outputs
it to the specified FILE. fputc() does exactly the same
thing, and differs from putc() in implementation only.
Most people use fputc().
 Example
// print the alphabet
#include <stdio.h>
int main(void)
{
char i;
for(i = 'A'; i <= 'Z'; i++)
putchar(i);
putchar('\n'); // put a newline at the end to make it pretty
return 0; 112
}
By- Er. Indrajeet Sinha , +919509010997
 1.9.3 putchar( ) – This function displays the
character on the screen which is already inputted
by using the getchar( ) function. For ex
– putchar(ch); This will display the character which
was stored in the variable ch.

 1.9.4 puts( ) – It will display the whole string on


the screen which user has already inputted by
using the gets( ) function. It can also print the
message. After printing the string or message it
moves the cursor to the next line. It’s syntax is –
 puts("Text line or some message") we can also display
some text line or message on the screen by using this
function with the double quotes
113

By- Er. Indrajeet Sinha , +919509010997


 1.9.5 putch( ) – This function is almost similar to
putchar( ) function. It is used to display only one
character on the screen which is stored by using
getch( ) function. It’s syntax is same as the putchar
fucntion but the keyword here used is ‘ putch ‘ instead
of putchar.

114

By- Er. Indrajeet Sinha , +919509010997


SCOPE RULES AND STORAGE
CLASSES

Lecture no.- 10,


UNIT- I
INTRODUCTION OF LECTURE

 Definition:

 In C language, each variable has a storage


class which decides scope, visibility and lifetime of
that variable.

 storage class also determines


variable's storage location (memory or registers).

 There are four storage classes in C those are


automatic, register, static, and external.

116

By- Er. Indrajeet Sinha , +919509010997


1.10.1 - AUTO STORAGE CLASS

 Formal parameters and local variables of


functions are variables that are automatically
allocated on the stack when a function is
called and automatically deallocated when
the function returns.
 They are of storage class auto.

By- Er. Indrajeet Sinha , +919509010997


1.10.2 – STATIC STORAGE CLASS

 Static variable is allocated and initialized one


time, prior to program execution.
 It remains allocated until the entire program

terminates.

By- Er. Indrajeet Sinha , +919509010997


1.10.3 – EXTERN STORAGE CLASS
 Storage class of names known to the linker.
 Example:

extern int square (int x);


 Means the function will be available to the linker.

 It notifies the compiler that such a function exists

and that the linker will know where to find it.

By- Er. Indrajeet Sinha , +919509010997


1.10.4 – REGISTER STORAGE CLASS

 If you declare a variable of type register, it


simply alerts the compiler to the fact that
this memory cell will be referenced more
often than most.
 Register is a special high-speed memory

location inside the central processor.

By- Er. Indrajeet Sinha , +919509010997


Linker-visible.
C STORAGE CLASSES Allocated at fixed
location
Visible within file.
Allocated at fixed
#include <stdlib.h> location.

int global_static;
static int file_static;

void foo(int auto_param) Visible within func.


{ Allocated at fixed
static int func_static; location.

int auto_i, auto_a[10];


double *auto_d = malloc(sizeof(double)*5);
}

By- Er. Indrajeet Sinha , +919509010997


DYNAMIC STORAGE ALLOCATION

 What are malloc() and free() actually doing?


 Pool of memory segments:

Free

malloc( )

By- Er. Indrajeet Sinha , +919509010997


SIMPLE DYNAMIC STORAGE
ALLOCATION

Next Next First large-enough


free block selected
Size Size Size Free block divided
Free block Allocated block into two
Previous next
pointer updated
malloc( )
Newly-allocated
region begins with
a size value

By- Er. Indrajeet Sinha , +919509010997


SIMPLE DYNAMIC STORAGE ALLOCATION

Appropriate
position in free
free(a) list identified
Newly-freed
region added to
adjacent free
regions

By- Er. Indrajeet Sinha , +919509010997


FEW TERMS

1. Scope: the scope of a variable determines

125
over what part(s) of the program a variable
is actually available for use(active).
2. Longevity: it refers to the period during
which a variables retains a given value
during execution of a program(alive)
3. Local(internal) variables: are those which
are declared within a particular function.

4. Global(external) variables: are those which


are declared outside any function.

By- Er. Indrajeet Sinha , +919509010997


AUTOMATIC VARIABLES
 Are declare inside a function in which they are to
be utilized.

126
 Are declared using a keyword auto.

eg. auto int number;


 Are created when the function is called and
destroyed automatically when the function is
exited.

 This variable are therefore private(local) to the


function in which they are declared.

 Variables declared inside a function without


storage class specification is, by default, an
automatic variable.

By- Er. Indrajeet Sinha , +919509010997


EXAMPLE PROGRAM
int main()
{ int m=1000;
function2();

127
printf(“%d\n”,m);
}
function1()
{
int m = 10;
printf(“%d\n”,m);
}
function2()
{ int m = 100; Output
function1(); 10
printf(“%d\n”,m); 100
} 1000

By- Er. Indrajeet Sinha , +919509010997


FEW OBSERVATION ABT AUTO
VARIABLES
 Any variable local to main will normally live
throughout the whole program, although it is

128
active only in main.

 During recursion, the nested variables are unique


auto variables.

 Automatic variables can also be defined within


blocks. In that case they are meaningful only
inside the blocks where they are declared.

 If automatic variables are not initialized they will


contain garbage.

By- Er. Indrajeet Sinha , +919509010997


EXTERNAL VARIABLES
 These variables are declared outside any function.
 These variables are active and alive throughout the entire

129
program.
 Also known as global variables and default value is zero.
 Unlike local variables they are accessed by any function in
the program.

 In case local variable and global variable have the same


name, the local variable will have precedence over the
global one.
 Sometimes the keyword extern used to declare these
variable.
 It is visible only from the point of declaration to the end of
the program.

By- Er. Indrajeet Sinha , +919509010997


EXTERNAL VARIABLE (EXAMPLES)

int number; int count;


float length=7.5; main()
main()

130
{count=10;
{ . . . . . .
. . . . . .
} }
funtion1() funtion()
{. . . {int count=0;
. . . . . .
} . . .
funtion1() count=count+1;
{. . . }
. . . When the function references the
} variable count, it will be
referencing only its local
The variable number and
variable, not the global one.
length are available for use
in all three function
By- Er. Indrajeet Sinha , +919509010997
GLOBAL VARIABLE EXAMPLE

int x; int fun3()


int main() {
{ x=x+10;

131
return(x);
x=10; }
printf(“x=%d\n”,x);
printf(“x=%d\n”,fun1());
printf(“x=%d\n”,fun2());
printf(“x=%d\n”,fun3()); Once a variable has been
} declared global any function can
int fun1() use it and change its value. The
{ x=x+10; subsequent functions can then
return(x); reference only that new value.
}
int fun2() Output
{ int x
x=1; x=10
return(x); x=20
} x=1
x=30
By- Er. Indrajeet Sinha , +919509010997
EXTERNAL DECLARATION

int main()
{ • As far as main is concerned, y is not
defined. So compiler will issue an

132
y=5; error message.
. . . • There are two way out at this point
. . . 1. Define y before main.
} 2. Declare y with the storage class
int y; extern in main before using it.

func1()
{
y=y+1
}

By- Er. Indrajeet Sinha , +919509010997


EXTERNAL DECLARATION(EXAMPLES)

int main()
{

133
extern int y;
. . .
. . . Note that extern
} declaration does not
func1() allocate storage space
{ for variables
extern int y;
. . .
. . .
}
int y;

By- Er. Indrajeet Sinha , +919509010997


MULTIFILE PROGRAMS AND EXTERN
VARIABLES
file1.c file2.c

134
int main() int m;
{ function2()
extern int m; {
int i int i
. . . . . .
. . . . . .
} }
function1() function3()
{ {
int j; int count;
. . . . . .
. . . . . .
} }
By- Er. Indrajeet Sinha , +919509010997
MULTIFILE PROGRAMS AND EXTERN
VARIABLES
file1.c file2.c

135
int m; extern int m;
int main() function2()
{ {
int i; int i
. . . . . .
. . . . . .
} }
function1() function3()
{ {
int j; int count;
. . . . . .
. . . . . .
} }
By- Er. Indrajeet Sinha , +919509010997
STATIC VARIABLES

 The value of static variables persists until the


end of the program.

136
 It is declared using the keyword static like
static int x;
static float y;

 It may be of external or internal type


depending on the place of there declaration.

 Static variables are initialized only once,


when the program is compiled.

By- Er. Indrajeet Sinha , +919509010997


INTERNAL STATIC VARIABLE

 Are those which are declared inside a function.

137
 Scope of Internal static variables extend upto the
end of the program in which they are defined.

 Internal static variables are almost same as auto


variable except they remain in existence (alive)
throughout the remainder of the program.

 Internal static variables can be used to retain


values between function calls.

By- Er. Indrajeet Sinha , +919509010997


EXAMPLES (INTERNAL STATIC)

 Internal static variable can be used to count the


number of calls made to function. eg.

138
int main()
{
int I;
for(i =1; i<=3; i++)
stat();
} Output
void stat()
{ x=1
static int x=0; x=2
x = x+1;
printf(“x = %d\n”,x); x=3
}

By- Er. Indrajeet Sinha , +919509010997


EXTERNAL STATIC VARIABLES

 An external static variable is declared outside

139
of all functions and is available to all the
functions in the program.

 An external static variable seems similar


simple external variable but their difference
is that static external variable is available
only within the file where it is defined while
simple external variable can be accessed by
other files.

By- Er. Indrajeet Sinha , +919509010997


CONCEPT OF PREPROCESSOR
AND MACRO SUBSTITUTION

Lecture no.- 11,


UNIT- I
1.11.1- INTRODUCTION

 The C preprocessor is a macro processor that


is used automatically by the C compiler to
transform your program before actual
compilation.

 It is called a macro processor because it


allows you to define macros, which are brief
abbreviations for longer constructs.

 The C Preprocessor is not a part of the


compiler, but is a separate step in the 141
compilation process.
By- Er. Indrajeet Sinha , +919509010997
INTRODUCTION

 The C preprocessor executes before a program is


compiled.
 Some actions it performs are the inclusion of other files in

the file being compiled, definition of symbolic constants


and macros, conditional compilation of program code and
conditional execution of preprocessor directives.
 Preprocessor directives begin with # and only white-space

characters and comments may appear before a


preprocessor directive on a line.
#INCLUDE PREPROCESSOR
DIRECTIVE

 The #include preprocessor directive has been used


throughout this text.
 The #include directive causes a copy of a specified
file to be included in place of the directive.
 The two forms of the #include directive are:
#include<filename>
#include "filename"
 The difference between these is the location the
preprocessor begins searches for the file to be included.
 If the file name is enclosed in quotes, the preprocessor
starts searches in the same directory as the file being
compiled for the file to be included (and may search
other locations, too).
#INCLUDE PREPROCESSOR
DIRECTIVE

 This method is normally used to include programmer-


defined headers.
 If the file name is enclosed in angle brackets (< and >)—

used for standard library headers—the search is


performed in an implementation-dependent manner,
normally through predesignated compiler and system
directories.
#INCLUDE PREPROCESSOR
DIRECTIVE

 The #include directive is used to include standard


library headers such as stdio.h and stdlib.h (see
Fig. 5.6) and with programs consisting of several source
files that are to be compiled together.
 A header containing declarations common to the separate

program files is often created and included in the file.


 Examples of such declarations are structure and union

declarations, enumerations and function prototypes.


#DEFINE PREPROCESSOR
DIRECTIVE: SYMBOLIC CONSTANTS

 The #define directive creates symbolic constants—


constants represented as symbols—and macros—
operations defined as symbols.
 The #define directive format is

 #define identifier replacement-


text
 When this line appears in a file, all subsequent

occurrences of identifier that do not appear in string


literals will be replaced by replacement-text
automatically before the program is compiled.
1.11.3 - FUNCTIONS OF A
PREPROCESSOR

 For More Click Here

147

By- Er. Indrajeet Sinha , +919509010997


PREPROCESSOR

 All preprocessor directives or commands


begin with a #.
 E.g. #include <stdio.h>

By- Er. Indrajeet Sinha , +919509010997


PREPROCESSOR DIRECTIVES

 Macro definition
 #define, #undef
 File inclusion
 #include
 Conditional Compilation
 #if, #ifdef, #ifndef, #elseif, #else
 Others

By- Er. Indrajeet Sinha , +919509010997


ADVANTAGES

 Easy to
 Develop program
 Read programs
 Modify programs

 C code more transportable between different


machine architectures

By- Er. Indrajeet Sinha , +919509010997


#DEFINE

 To
define constants or any macro
substitution.
#define <macro> <replacement
name>
E.g.
#define FALSE 0
#define TRUE !FALSE
 To undefined a macro.
E.g. #undef FALSE
 A macro must be undefined before being
redefined to a different value.
By- Er. Indrajeet Sinha , +919509010997
DEFINE FUNCTIONS

 E.g. To get the maximum of two


variables:

#define max(A,B) ( (A) > (B) ? (A):(B))

 If in the C code:
x = max(q+r,s+t);
 After preprocessing:

x = ( (q+r) > (s+t) ? (q+r) : (s+t));

By- Er. Indrajeet Sinha , +919509010997


1.11.3.2 FILE INCLUSION

 #include directive
 Include the contents of another file at the point
where the directive appears.
 Why need file inclusion
 Use built-in functions
 E.g., printf(), rand();
 Reuse code

struct date{ struct date{


int day; #include “defTime.h” int day;
char → char
month[10]; struct date today; month[10];
int year; int year;
}; };
defTime.h Your code
struct date today;
By- Er. Indrajeet Sinha , +919509010997
FILE INCLUSION FORMATS

 #include <file>
 Used for system header files
 File contain function prototypes for library functions

<stdlib.h> , <math.h> , etc


 #include "file"
 Used for header files of your own program
 looks for a file in the current directory
first
 then system directories if not found

By- Er. Indrajeet Sinha , +919509010997


STANDARD C LIBRARIES

 Build-in with your compiler


 Detailed information
 http://www.utas.edu.au/infosys/info/
documentation/C/CStdLib.html
 stdio.h
 core input and output capabilities of C
 printf function
 scanf function

By- Er. Indrajeet Sinha , +919509010997


MATH LIBRARY FUNCTIONS

 Math library functions


 perform common mathematical calculations
 E.g. exp(), pow(), sqrt(), fabs(), sin(), cos().
 #include <math.h>
 Format for calling functions
 FunctionName( argument, …, argument );
 All math functions return data type double
 E.g.:printf( "%.2f", sqrt( 900.0 ) );
 Arguments may be constants, variables, or
expressions
 Compile
 gcc yourfilename.c –lm –o yourfilename.exe

By- Er. Indrajeet Sinha , +919509010997


STDLIB.H

 A variety of utility functions


 rand function
 A function to generate a pseudo-random
integer number
 Return value is in the range 0 to

RAND_MAX
 Example:
#include <stdlib.h>
int i = rand();
 memory allocation
 process control

By- Er. Indrajeet Sinha , +919509010997

You might also like