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

Introduction to C

Uploaded by

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

Introduction to C

Uploaded by

jobnavigator00
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 459

UNIT-1

INTRODUCTION TO COMPUTERS
Introduction to Computers
Objectives:
⚫ To review basic computer systems concepts
⚫ To be able to understand the different
computing environments and their components
⚫ To review the history of computer languages
⚫ To be able to list and describe the classifications of
computer languages
⚫ Tounderstand the steps in the development
of a computer program
⚫ To review the system development life cycle
 What is a Computer?
A COMPUTER is an electronic device that can:
Receive information,Perform processes,Produce output
and Store information for future use.

INPUT CPU(Processor OUTPUT


)

MEMORY

Fig: Information Processing Cycle


⚫A computer system made of two major components:
hardware and software.

• Hardware - the physical parts that make up the computer.


Eg: CPU, memory, disks, CD-ROM drives, printer.
• Software - computer programs and applications.
Eg: Operating system, word processor, games, etc.
Basic Hardware
Components
Software:

Types of
Software:
System Software

⚫ Operating system is a Software component that provides an interface


between user and system hardware.
Ex: Windows ,Linux,Unix,Solaris etc.

⚫ System support Software provides system utilities and


other operating services.
Eg: Sort programs, Formatting programs, Linkers, Loaders

⚫ System Development software includes the language translators


(Compilers, Assemblers etc.) that convert programs into machine
language for execution, debugging tools to ensure that the
programs are error-free and CASE tools for software engineering
processes
Eg: C Compiler,Java Compiler
ApplicationSoftware
⚫Application specific software can be used for a
specific intended purpose
Ex: Pay roll, Inventory Management, Library management
etc.
⚫General Purpose software is intended for use in more
than one application
Ex: Word Processors, Database Management
systems and Computer- aided Design
Systems.
Relation Ship Between System and Application Software
Components of a Computer System:
• The Primary Components of a Computer System are
1) Input devices.
2) Central Processing Unit
3) Memory.
4) Output devices.
• Input Devices: Input devices are Hardware Components
that accepts the input from the User.
Ex: Keyboard , Mouse, Scanner, Microphone etc.

• CPU:(CU+ALU):
- The central processing unit (CPU) is the ―brain‖
of the computer.
- It performs a large number of operations at a high speed.
- Control Unit Interprets Instructions to the Computer.
- ALU Performs the Arithmetic and logical Operations.
Ex: Intel Pentium, Motorola, IBM RISC.
• Memory: The function of Memory is Storing the data
and Instructions.
- Memory is Divided into two types :
1) Primary Memory(RAM)
2) Secondary Memory(ROM)
- Primary Memory is a Volatile Memory that is when
the power loss the data stored in the Memory lost.
Ex: RAM(Random Access Memory).
- Secondary Memory is a Non-Volatile Memory that
is Even if the power loss it holds the data.
Ex: Harddisk,CD-ROM,DVD-ROM,Floppy Flash Memory
etc.
• Memory Data Representation :
– Data in memory is stored as binary digits (BITS) e.g.
011100101010
– 1 BYTE = 8 bits
– 1 byte usually stores 1 text character.

• The size of memory is measured in terms of how many bytes it can


hold.
– 1 kilobyte = 210 bytes = 1024 bytes
– 1 megabyte = 220 bytes = ~1 million bytes
– 1 gigabyte = 230 bytes = ~1 billion bytes
– 1 terabyte = 240 bytes = ~1 trillion bytes

• One megabyte can hold approximately 500 pages of text


information.
13
Output devices
• Output devices make the information
resulting from the processing available for usage.
– printer - produces a hard copy
of your output
– screen - produces a visual
display of your output for browsing
– speakers, etc.

14
Computing Environments

There are four computing


environments:

1) Personal Computing Environment


2) Time-Sharing Environment
3) Client/Server Environment
4) Distributed Computing
Personal Computing
Environment
⚫ All of the computer hardware components are tied together in
the personal computer. The whole computer is available to the user.
Time-Sharing Environment
• Many users are connected to a computer system.
The terminals used are often non-programmable.
– The output devices and auxiliary storage devices
are shared by all of the users.
– Inthetime-sharing environment, all computing is
done by the central computer.
– Central computer controls the shared resources, manages
the shared data and printing.
Client/Server Environment
⚫A client /server computing environment splits the
computing
function between a central computer and users‘ computers.
⚫Some of the computational responsibility is moved from the
central computer and assigned to the client computers.
⚫The central computer called server that manages the shared
data
and does some part of the computing
⚫Because of the work sharing, the response time and monitor
display are faster and the users are more productive.
Distributed Computing
⚫ A distributed computing environment provides
integration of computing functions between different
clients and servers.
⚫ accomplishing
Distributed computing utilizes
a portion of a an
network of many
overall task, computers,
to achieveeacha
result much quickly than with a
computational more single
computer.
Computer Languages

• To write a program for a computer, we must use a computer language.


- There are three types of Computer Languages
1) Machine Languages
2) Symbolic Languages
3) High-Level Languages
Machine Languages
• Each Computer has its own machine language which is
made up of 0‖s and 1‘s.

• The instructions in machine language must be in streams of


0‘s and 1‘s because internal circuits of a computer are made
of devices that can be in one of two states: on or off.

• Machine language is highly difficult to program as it needs


the complete knowledge of the computer‘s instructions
• Difficult and Rarely used
• NOTE:
The only language understood by computer
hardware is machine language.
Symbolic Languages

• The computer operations are represented in symbols or mnemonics


to represent various machine language instructions .
Ex: Add instead of 0001
• These languages are also called Assembly Languages.
• Each assembly language instruction translates to one
machine language instruction
• Programming is easier in Assembly language
compared to
developing programs in machine language
• Symbolic languages are machine dependent
• Assemblers convert the assembly language instructions to machine
language instructions

22
High-level Languages
• The need to improve programmer efficiency and to change the focus
from the computer to the problem being solved led to the development
of high-level languages
• High level languages are portable to many different computers,
allowing the programmers to concentrate on the application problem
rather than on the computer
• Compilers are used to convert high-level language programs to
machine language programs
• The process of converting high-level language into machine language
is called compilation.
• One high-level language statement can get converted to one or more
machine language statements

23
• Example
A Statement A= A+B in Different
Languages
Machine Assembly High Level
Language Language
Language

0000 0000 CLA A= A+B

0001 0101 ADD A

0001 0110 ADD B

0011 0101 STA


A

24
Creating and Running Programs
• The steps involved in Creating and
Running Programs are:
1) Writing and Editing Programs
2) Compiling Programs
3) Linking Programs
4) Executing Programs

Writing and Editing Programs:


• To solve a particular problem a Program has to be created as a file
using text editor / word processor. This is called source file.

• The program has to be written as per the structure and rules defined by
the high-level language that is used for writing the program ( C, JAVA
Compiling Programs:
• The compiler corresponding to the high-level language will scan the
source file, checks the program for the correct grammar (syntax)
rules of the language.
• If the program is syntactically correct, the compiler generates an
output file called Object File which will be in a binary format and
consists of machine language instructions corresponding to the
computer on which the program gets executed.
• If the source program contains syntax errors, the compiler lists these
errors and will not generate the object file. The program is to be
corrected for the errors and recompiled.
• The object file contains references to other programs which will be
needed for the execution of the program. These programs are called
library functions. These programs are to be combined with the Object
File.
Linking Programs:
• Linker program combines the Object File with the required library
functions to produce another file called executable file. Object file
will be the input to the linker program.
• The executable file is created on disk. This file has to be put
into (loaded) the memory.
Executing Programs:
• Loader program loads the executable file from disk into the memory
and directs the CPU to start execution.
• The CPU will start execution of the program that is loaded into the
memory .
• During Program Execution, the program reads data for processing,
either from the user (key-board) or from a file. After the program
processes the data, it prepares the output. Output can be to the user‘s
monitor or to a file.
• When the program has finished its job, it informs the Operating
System. OS then removes the program from memory.
Fig: Building a C
Algorithm
– Precise step-by-step plan for a computational procedure
that begins with an input value and yields an output value
in a finite number of steps.
– It is an effective method which uses a list of well-defined
instructions to complete a task, starting from a given
initial state to achieve the desired end state.
– An algorithm is written in simple English and is not a
formal document.
– An algorithm must:
- Be lucid, precise and unambiguous
- Give the correct solution in all cases
- Eventually end
• it is important to use indentation when writing solution in algorithm
because it helps to differentiate between the different control
structures.
Instead of
Read n;for i=1 to n add all values of A[i] in sum;Print sum/n;
Write
Read n;
For i=1 to n add all values of A[i] in
sum; Print sum/n;
is more readable and easy to
understand.
Properties of algorithms

1) Finiteness:
- an algorithm terminates after a finite numbers of steps.
2) Definiteness:
- each step in an algorithm is unambiguous. This
means that the action specified by the step cannot be
interpreted in multiple ways & can be performed without any
confusion.
3) Input:
- An algorithm accepts zero or more inputs.
4) Output:
- It produces at least one output.
5) Effectiveness:
-It consists of basic instructions that are realizable. This
means that the instructions can be performed by using the
given inputs in a finite amount of time.
Flowcharts

– A flowchart is a type of diagram, that represents an


algorithm or process, showing the steps as boxes of
various kinds, and their order by connecting these with
arrows. This diagrammatic representation can give a
step-by-step solution to a problem.

– Data is represented in the boxes, and arrows connecting


them represent direction of flow of data.

– Flowcharts are used in designing,


documenting or analyzing, a program
various fields .managing process in
or
Common Flowchart Symbols:

Terminator: Shows the starting


and ending points of a
program

Data Input or output: Allows the


user to input data or to display
the results .
Processing: Indicates an
operation
performed by the computer, such as a
variable Assignment or mathematical
operation
• Common Flowchart Symbols:
Predefined Process. Denotes a group of
previously defined statements. Ex: ―Calculate m!
‖ Program executes the necessary Commands to
compute m factorial
Connector. Connectors avoid crossing flowlines,
Connectors come in pairs, one with a flowline in
and the other with a flowline out.

Off Page Connector: Come in Pairs, Extends


Flow charts to more than a page

Flowline. Flowlines connect the


flowchart symbols and show the sequence of
operations during the program execution.
Examples
• Example 1: Finding the sum of two numbers.
• – Variables:
– • A: First Number
– • B: Second Number
– • C: Sum (A+B)
• – Algorithm:
– • Step 1 – Start
– • Step 2 – Input A
– • Step 3 – Input B
– • Step 4 – Calculate C = A + B
– • Step 5 – Output C
– • Step 6 – Stop
Flowcharts:

Start

Read A

Read B

C= A+B Print C Stop

36
• Example 2: Find the difference and the division of two
numbers and display the results.
• – Variables: -- Algorithm:
• N1: First number * Step 1: Start
• N2: Second number * Step 2: Input N1
• D : Difference * Step 3: Input N2
• V : Division * Step 4: D=N1–N2
* Step 5: V=N1 /N2
* Step 6: Output D
* Step 7: Output V
* Step 8: Stop

37
Flow Chart

Start

Read N1

Read N2

D=N1-N2

V= N1/N2 Print D Print V Stop

38
Example 3:
Work on the algorithm and the flow chart of the problem of
calculating the roots of the equation Ax2 + Bx + C = 0

• Variables:

– A: Coefficient of X2
– B: Coefficient of X
– C: Constant term
– delta: Discriminant of the equation
– X1: First root of the equation
– X2: Second root of the equation

39
• Algorithm:
- Step 1: Start
– Step 2: Input A, B and C
– Step 3: Calculate delta = B2 – 4AC
– Step 4:
If delta<0 go to step 6, otherwise go to 5
– Step 5:
If delta>0 go to step 7, otherwise go to 8
– Step 6:
Output ―complex roots‖. Go to step 13
– Step 7: Output ―real roots‖. Go to step 9
– Step 8:
Output ―equal roots‖. Go to step 9
– Step 9: Calculate X1=(-b+√delta)/(2A)
– Step 10: Calculate X2=(-b-√delta)/(2A)
– Step 11: Output X1
– Step 12: Output X2
– Step 13: Stop 42
Flowcharts:

Read
Start Delta=B*B- 4*A*C

A,B,C Yes No
Delta < 0
Yes
“Complex Roots” Delta>0
No

“Equal Roots”
“Real Roots”

X1=(-b+√delta)/(2*A)

X2=(-b-√delta)/(2*A)

Print X1 Print X2 Stop


43
Intoduction to C :
• A high-level programming language developed in 1972 by
Dennis
Ritchie at AT&T Bell Labs.
• C is a structured Language
• It was designed as a language to develop UNIX operating system
• American National Standards Institute (ANSI) approved first version
of C in 1989 which called C89
• Major changes were made in 1995 and is known as C95
• Another update was made in 1999 and is known as C99
Characteristics of C
• A high level programming language .
• Small size. C has only 32 keywords. This makes it relatively easy
to learn.
• Makes extensive use of function calls.
• C is a structured programming.
• It supports loose typing (as a character can be treated as an integer
and vice versa).
• Facilitates low level (bitwise) programming
• Supports pointers to refer computer memory, array, structures and
functions.
• C is a Portable language.
• C is a core language
• C is an extensible language
Uses of C Language:
• C language is primarily used for system programming. The
portability, efficiency, the ability to access specific hardware
addresses and low runtime demand on system resources makes it a
good choice for implementing operating systems and embedded
system applications.
• C has been so widely accepted by professionals that compilers,
libraries, and interpreters of other programming languages are often
implemented in C.
• For portability and convenience reasons, C is sometimes used as an
intermediate language by implementations of other languages.
Example of compilers which use C this way are BitC, Gambit, the
Glasgow Haskell Compiler, Squeak, and Vala.
• C is widely used to implement end-user applications
• C Programs
Structure Of C Program:
Preprocessor directives:
• Every C program is made of one or more
Preprocessor directives or commands.
• They are special instructions to the preprocessor that

tell it how to prepare the program for compilation.


• The preprocessor directives are commands that
give instructions to the C preprocessor.
• A preprocessor directive begins with a number
symbol (#) as its first non-blank character.
• A common preprocessor command is
• ―include: The include command tells
the preprocessor that information
is needed from selected libraries
known as header files.
• Preprocessor commands can start in any column, but they
traditionally start in column 1.
Ex: #include <stdio.h>
• This command tells the preprocessor that definitions from the
library file in the brackets < > is included in the program. The
name of the header file is ―stdio.h. This is an abbreviation
for ―standard input / output header file.
• C requires that certain standard libraries be provided in every
ANSI C implementation.
Global Declaration Section :
• Contains declarations that are visible to all parts of the
program
Declaration section :
• It is at the beginning of the function. It describes the data that
will be used in the function. Declarations in a function are
known as local declarations as they are visible only to the
function that contains them.
Statements:
• Statements follows the declaration section. It
contains the instructions to the computer.
• Every statement ends with a semi colon.
Comments:
• Comment about the program should be enclosed within /* */.
• Any number of comments can be written at any place in the program.
• Comments in the code helps to understand the code
o Comments cannot be nested.
o For example, /* Cal of SI /* Author sam date 01/01/2002 */ */ is
invalid.
o − A comment can be split over more than one line, as
/* This is
a jazzy
comment
*/
• main( ):
• The executable part of the program begins with the function main. All statements
that belong to main are enclosed in a pair of braces { }.

• First C Program
• #include <stdio.h>
• void main ()
{
printf ("Hello World:\n");
}
• The main function contains single statement to print the message.
• The print statement use a library function to do the printing.
C TOKENS

C TOKENS

KEYWORDS CONSTANTS STRINGS OPERATORS

IDENTIFIERS SPECIAL SYMBOLS


KEYWORDS

• Keywords are predefined, reserved words


used in programming that have special
meaning. Keywords are part of the syntax and
they cannot be used as an identifier. For
example:
int money;
• Here, int is a keyword that indicates 'money' is
a variable of type integer.
Keyword List
Identifiers
⚫Identifiers are names given to program elements such as
variables, arrays and functions.
⚫ Each identified object in the computer x stored at a unique address.
⚫ If we didn‘t have identifiers that we could use to symbolically
represent data locations, we would have to know and use object‘s
addresses. Instead, we simply give data identifiers and let the compiler
keep track of where they are physically located.
Rules for Identifiers:
•A variable can have alphabets, digits, and underscore.
•A variable name can start with the alphabet, and underscore only. It can't
start with a digit.
•No whitespace is allowed within the variable name.
•A variable name must not be any reserved word or keyword, e.g. int, float,
etc.
Examples of Valid and Invalid Names:
Constants:
• Constants are data values that cannot be changed during the
execution of a program.
• C constants can be divided into two
major categories:
Constants

Secondary
Primary Constants
Constants

Array
Pointer
Boolean Constants Structure
Integer Constants Union
Real Constants Enum etc..
Character Constants
• Boolean constants

A Boolean data type can take only two values. The values are true and false.
• Integer Constants
Rules for Constructing Integer Constants
• An integer constant must have at least one digit.
• It must not have a decimal point.
• It can be either positive or negative.
• If no sign precedes an integer constant it is
assumed to be positive.
• No commas or blanks are allowed within an integer constant.
Example of Integer Constans
Real Constants:
• Rules for Constructing Real Constants
• Real constants are often called Floating Point constants. It
consists of integral part and fractional part. The real constants
can be in
– Fractional form
– Exponential form.
• In Fractional Form
– A real constant must have at least one digit.
– It must have a decimal point.
– It could be either positive or negative.
– Default sign is positive.
– No commas or blanks are allowed within a real constant.
Examples of Real Constants
• Exponential Form
• In exponential form of representation, the real constant is represented in two
parts. The part appearing before "e" is called mantissa, whereas the part
following "e" is called exponent.
 Rules for constructing real constants expressed
in exponential form:
• The mantissa part and the exponential part should be separated by a letter e.
• The mantissa and exponent part may have a positive or negative sign.
• Default sign of mantissa part is positive.
• The exponent must have at least one digit, which
must be a positive or negative integer. Default sign is positive.
Ex: 1.23 x 105 = 123000.0 is written as 1.23e5 or 1.23E5
0.34e-4 = 0.000034
Character Constants

• A character constant is a single alphabet, a single digit or a single special


symbol enclosed within two single quotes (apostrophes).
• The maximum length of a character constant can be 1 character.
• The character in the character constant comes from the character supported by
the computer.

Ex: `A` `I` `5` `=` `a`


Fi Symbolic Names for Control
Coding constants
Literal Constant
• A literal is an unnamed constant used to specify
data. Ex: a=b+5;
hear 5 is a literal constant.

Defined constants

• A defined constant uses the preprocessor command


#define
Ex: #define rate 0.85
Preprocessor replaces each defined name, rate with
the value
0.85 wherever it is found in the source program

Memory Constants

• Memory constant use a C type qualifier, const to indicate that


STRINGS
• A string in C is merely an array of characters.
The length of a string is determined by a
terminating null character: '\0' .
• So, a string with the contents, say, "abc"
has four characters: 'a' , 'b' , 'c' , and the
terminating null character. The terminating
null character has the value zero.
SPECIAL SYMBOLS
• The following special symbols are used in C having some
special meaning and thus, cannot be used for some other
purpose.
• *+ () ,- , ; : * … = #
• Braces{}: These opening and ending curly braces marks the
start and end of a block of code containing more than one
executable statement.
• Parentheses(): These special symbols are used to indicate
function calls and function parameters.
• Brackets[]: Opening and closing brackets are used as array
element reference. These indicate single and
multidimensional subscripts.
Variables
: locations that have a type, such as
⚫ Variables are named memory
integer or character, which is inherited from their type.
⚫ The type determines the values that a variable may contain and
the operations that may be used with its values.
⚫ To declare a variable specify data type of the variable followed by
its
name. Variable declaration always ends with a semicolon
⚫ Variable names should always be meaningful and must reflect the
purpose of their usage in the program.
Variable Declaration
Synatax: Type
var_name; Ex: alary; int
float
char emp_num;
grade;
double balance_ amount;
unsigned short int
Variable Initialization
– When a variable is defined, it contains unknown value.
The variable has to be initialized with a known value
– If a variable is not initialized, the value of variable may be either
0 or garbage depending on the storage class of the variable.
– We must initialize any variable with known data before executing
the function

Fig: Variable Initialization


Type
⚫ A type defines a set of values andsa set of operations that can be applied on
those values.

Ex: – Type - light switch


Values –‘ON‘ or 'OFF‘
Operations – 'turn on‘ and 'turn off‘

Fig:Data Types
Void
Type:
– Is identified by the key word 'void‘ and no operations.
– It is used to designate that a function has no parameters.
– It can also be used to define that a function has no return
value.

Integral
Type:
Character:
–A character is any value that can be
represented in the computer‘s alphabet
– It is referred by the keyword char
– One byte is used to store char. With 8 bits, 256 different
values can be possible for the char type
– Character can be signed or unsigned.
Integer
– An integer type is a number without a fraction part
– C supports four different sizes of the integer type and
is denoted by the keywordint
» short int
» int sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof
(long long)
» long int
» long long int

– Each integer size can be signed or unsigned integer. If


the integer is signed, one bit is used for signed( 0 is plus, 1
is minus). An unsigned integer can store a positive number
that is twice as large as the signed integer of the same size.

Fig: Integer Types


Floating-point type:

Real
– Real type holds values that consists of
integral and fractional part.
– C support types float and double.
– Real type values are always signed.

Fig : Floating-Point Types


sizeof (float) ≤ sizeof (double) ≤ sizeof (long
double)
• Data
Types
Data Type Abbreviation Size Range
(byte)

char char 1 -128 ~ 127


unsigned char 1 0 ~ 255
int 2 or 4 -215 ~ 215-1 or -231 ~ 231-1
unsigned int unsigned 2 or 4 0 ~ 65535 or 0 ~ 232-1
int
short int short 2 -32768 ~ 32767
unsigned short unsigned 2 0 ~ 65535
int short
long int long 4 -231 ~ 231-1
unsigned long unsigned 4 0 ~ 232-1
int long

float 4
double 8

Not 27 = 128, 215 =32768, 231 = 7


e: 2147483648 3
Operators in C
• C language supports a lot of operators to be used in expressions.
These operators can be categorized into the following major
groups:
1) Arithmetic operators
2) Relational Operators
3) Equality Operators
4) Logical Operators
5) Unary Operators
6) Conditional Operators
7) Bitwise Operators
8) Assignment operators
9) Comma Operator
10) Sizeof Operator
Operators in C
Arithmetic operators
• Assume the values a=9 and b=3

OPERATION OPERATOR SYNTAX COMMENT RESULT


Addition + a+b result = a + b 12

Subtraction - a-b result = a – b 6

Multiply * a*b result = a * b 27

Divide / a/b result = a / b 3

Modulus % a%b result = a % b 0


Operators in C

Relational Operators
• Thease operators compares two values so also
called Comparison operators.
• Relational operators return true or false value,
depending on the conditional relationship
the two
between perands
oOPERATOR . MEANING EXAMPLE
< LESS THAN 3 < 5 GIVES 1
> GREATER THAN 7 > 9 GIVES 0
<= 100 <=
LESS THAN OR EQUAL TO
100 GIVES 1
>= GREATER THAN EQUAL TO 50 >=100 GIVES 0
Operators in C
Equality Operators
• C language supports two kinds of equality operators to compare
their operands for strict equality or inequality. They are equal to
(==) and not equal to (!=) operator.

OPERATOR MEANING
== RETURNS 1 IF BOTH OPERANDS ARE
EQUAL, 0 OTHERWISE
!= RETURNS 1 IF OPERANDS DO
NOT HAVE THE SAME VALUE, 0
OTHERWISE
Operators in C
Logical Operators
• C language supports three logical
operators. They are 1) Logical AND
(&&)
2) Logical OR (||)
3) Logical NOT (!)
• In case of arithmetic expressions, the logical expressions are
evaluated
A B from
A &&Bleft to right.
A B A || B A !A
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1
Operators in C
Unary Operators
⚫ Unary operators act on single operands.
⚫ C language supports three unary
operators. They are :
1) Unary minus(-)
2) Increment (++)
3) Decrement(--)
⚫ When an operand is preceded by a minus sign, the unary
operator negates its value.
Ex: int x=5; int y= -x; then y store the value -5.
⚫ The increment operator increases the value of its operand by
Ex: int x=3,y; 1.
printf(―x=%d―,x++);
x=3 y=x; y=4;
printf(―y=%d‖,++y); y=5;
Operators in C
Unary Operators
• The decrement operator decreases the value of its operand by
1.
Ex: int x=3,y;
printf(―x=%d―,x--); x=3
y=x; y=2;
printf(―y=%d‖,--y); y=1;
Conditional Operator or Ternary Operator
• The conditional operator (?:) is just like
an if .. else statement.
• The syntax of the conditional operator is
exp1 ? exp2 : exp3
Ex: a=10 b=5
large = ( a > b) ? a : b
Operators in C
Bitwise Operators
• Bitwise operators perform operations at bit
level. They are : 1) Bitwise AND(&)
2) Bitwise OR (|)
3) Bitwise XOR (^)
4) Bitwise Shift (<< and >>)
5) Bitwise NOT (~)
• The bitwise AND operator (&) is a small version of the boolean
AND (&&) as it performs operation on bits instead of bytes, chars,
integers, etc.
A B A&B Ex: x=2 y=3 x&y
0 0 0 0010
0 1 0
0011
1 0 0
x&y= 0 0 1 0
1 1 1
Operators in C
• The bitwise OR operator (|) is a small version of the boolean OR (||)
as
it performs operation on bits instead of bytes, chars, integers, etc.
A B A|B
0 0 Ex:
0 x=2 y=3 x|y
0 1 1 0010
1 0 1
0011
1 1 1
x|y= 0011

• the
Theoperands.
bitwise XOR operator (^)
Ex: x=2 operation
performs y=3 on individual bits
ofA B A^B x^y
0 0 0 0 0 01 10 1
0 1 1
1 0 1
1 1 0 x^y= 0001
Operators in C
• In bitwise Shift operations, the digits are moved, or shifted, to the left
or right.
• The CPU registers have a fixed number of available bits for storing
numerals, so when we perform shift operations; some bits will be
"shifted out" of the register at one end, while the same number of bits
are "shifted in" from the other end.

Ex:
In a left arithmetic shift,the right side end filled with 0‘s.
int x = 11000101;
Then x << 2 = 00010100
In a right arithmetic shift,the left side end filled with 0‘s.
int x = 11000101;
Then x >> 2 = 00110001
Operators in C

• The bitwise NOT (~), or complement, is a unary operation


that performs logical negation on each bit of the operand.

• Byperforming negation of each bit, it actually produces the


1‗s complement of the given binary value.
Ex: int
x=4,y;
y=(~x); Hear x is 0 1 0 0
y=11 ~x is 1 0 1 1
Operators in C
Assignment operators
• The assignment operator is responsible for assigning values to the variables.
• The equal sign (=) is the fundamental assignment operator.
• C supports other assignment operators that provide
shorthand
(Compact)ways to represent
OPERATOR SYNTAX
common variable assignments.
EQUIVALENT TO
/= variable /= expression variable = variable / expression
\= variable \= expression variable = variable \ expression
*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount
Operators in C
Comma operator
• The Comma operator in C takes two operands. It works by evaluating
the first and discarding its value, and then evaluates the second and
returns the value as the result of the expression.
• Comma separated operands when chained together are evaluated in
left-to-right sequence with the right-most value yielding the result of
the expression.
• Among all the operators, the comma operator has the lowest
precedence.
Ex: int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x =
6.
Operators in C
Sizeof Operator
• Sizeof operator used to calculate the sizes of data types.
• It can be applied to all data types.
• The operator returns the size of the variable, data type or expression
in bytes.
Ex:
 sizeof(char) returns 1 byte, that is the size of a character data
type. If we have,
int a = 10;
unsigned int result;
result = sizeof(a);
then result =
2 bytes.
Basic Input - Output
• Data is input to and output from a stream. A stream is a source of or
destination for data.
• Stream is Associated with a Physical devices such as Terminals
or with a file stored in auxiliary memory.
• C language uses two types of Streams:
1) Text Stream
2) Binary Stream
• Text Stream: Text Stream is a sequence of Characters divided
into lines with each line terminated by a new line.
• Binary Stream: Binary Stream is a Sequence of data values such
as integer,real,or complex using their memory representation.
• In C language standard input device is a Keyboard and the out
put device is a Monitor.

8
8
Basic Input - Output

Fig: Stream Physical Devices


Basic Input - Output

• C language provides two formatting functions


– printf for output formatting
– scanf for input formatting

• printf function converts data stored in program into a text stream for
output to the monitor.

• scanf converts the text stream coming from the keyboard to


data values and stores them in program variables .

• Printf and scanf functions are data to text stream and text stream to
data converters.
Basic Input - Output
Output Formatting:printf
• The printf function takes a set of data values ,converts them to a
text stream using formatting instructions contained in a format
control string and sends the resulting text stream to the standard
output.

• In the above diagram an Integer 234 stored in


the program is converted to a text stream of
Basic Input – Output
• The following information is passed to the Printf Function:
1)The format control string including any textual data to be inserted
into the text stream.
2) A set of zero or more data values to be formatted.
Basic Input – Output
• In the above first diagram shows the format
string and the data values as parameters for the
print function.

• With in the control string we have specified


quantity(Qty:) and total(Tot:) as textual data and two
converstion specifications(%d and %f).

• In the Second diagram shows the


formatting operation and the resulting text
stream.
Basic Input – Output
Format Control String Text
⚫ The control string also contains text to be printed such as instructions to the
user,captions or identifiers and other text intended to make the output more
readable.
⚫ It also prints control characters like(\t,\n).

Conversion Specification
⚫To insert the data into the stream we use the conversion
specification .
⚫It contains a start token(%),a conversion code and
four optional modifiers.

Fig: Conversion Specification


Basic Input – Output
Code
• Approximately there are 30 different codes are available in
C language to describe data types.
• Hear we concern only three code like character(c),Integer(d),Floating
point(f).
Size
• The size modifier is used to modify the type specified by
the conversion code.
• There are four different sizes: h,l(el),ll(el,el) and L.
• The h is used with the integer codes to indicate a short
integer value.
• The l is used to indicate a long integer value.
• The ll is used to indicate a long long integer value.
• The L is used with floating point numbers to indicate a long
Basic Input – Output

Fig:Format Codes for Output


Basic Input – Output

Precision
• The precision modifier is used if a floating point number is being
printed then we may specify the number of decimal places to be
printed.
The format of precision modifier is .m
Hear m is the number of decimal digits.
• If precision is not specified printf prints
six decimal positions.
Width
• Width modifier is used to specify the minimum number of positions in
the output.
• This is very useful to align output in columns.
• If we don‘t use a width modifier each output value will take
just enough room for the data.
Basic Input – Output

Flag
• The flag modifier is used with four print modifications:
1. Justification 2. Padding 3. sign 4.numaric conversion
1.Justification
• It controls the placement of a value when it is shorter than
the specified width.
• By default the justification is right.
• To left justify a value the flag is set to minus(-).
2. Padding
• It defines the character that fills the unused space when the value
is smaller than the print width.
• It can be a space or zero.
• By default the unused width is filled with spaces.
• If the flag is 0 the unused width is filled with zeros.
Basic Input – Output
Sign
• The sign flag defines the use or absence of a sign in numeric value.
• There are three formats to specify the sign
1. default formatting inserts a sign when the value is negative.
2. When the flag is set to plus(+) signs are printed for both positive
and negative.
3. If the flag is space the positive numbers are printed with a leading
space and negative numbers with a minus sign.
Numeric conversions
• Prefix o to the output value when used with the octal
conversion specifier.
• Prefix 0x or 0X to the output value when used with the
hexadecimal conversion specifiers x or X.
Basic Input – Output

Fig: Flag Formatting Options


Basic Input – Output
Input formatting : scanf
• The standard input formatting function scanf takes a text stream
from the keyboard.
• Extracts and formats data from the stream according to a
format control string.
• Then stores the data in specified program variables.

Fig: Formatting Text from an Input Stream


• In the above diagram the stream of 5 characters ‗2‘,‘3‘,‘4‘,‘.‘,‘2‘
Basic Input – Output

• General syntax of Scanf function is:


scanf (―control string‖, arg1, arg2, ………….argn);

• The control string specifies the type and format of the data that has
to be obtained from the keyboard and stored in the memory
locations pointed by the arguments arg1, arg2,…, argn.

• With the exception of character specification , leading white


spaces are discarded.
Basic Input – Output

Fig: Input Stream Formatting


Basic Input – Output

Format Control String


• Like printf formatting string scanf is also enclosed with in a set
of quotation marks.
• It contains on or more conversion specifications that describe the
data
type and indicate any special formatting rules and characters.
Conversion Specification
• To format input data stream we use a conversion specification that
contains a start token(%) , conversion code and three optional
modifiers.

Fig: Conversion Specification


Basic Input – Output

• There are three differences between the conversion codes for


input and output formatting:
1) There is no precision in an input conversion specification.
-It is an error to include a precision

2)There is only one flag for input formatting , the


assignment suppression flag(*).
-The assignment suppression flag tells the scanf the next input field
is to be read but not store.
Ex: scanf(―%d %*c %f‖,&x, &y);

3)The width modifier specifies the maximum number of characters that


are to be read for one format code.
Basic Input – Output
Input Parameters
• Every conversion specification there must be a matching variable
in the address list.
• The address of a variable is indicated by prefixing the variable
name with an ampersand (&).
• In C language & is known as address operator.
• The first conversion specification matches the first variable
address , the second conversion specification matches the second
variable address and so on.
• The variable type match the conversion type.
• The c compiler does not verify that they match . If they don‘t
match the input data will not be formatted properly when they are
stored in the variables.
Basic Input – Output

End of File and Errors

• The scanf terminate input process when the user


signal that there is no more input by keying end
of file(EOF).
Ex: Ctrl+Z

• If scanf encounters an invalid character when it is


trying to convert the input to the stored data
type ,it stops.
Ex: Character is trying to read a numeric .
Expressions
• An Expression is a sequence of operands and operators that reduces
to a single value.
• An expression is a simple or complex.
• A simple expression contain only one
operator. Ex: 3+6,-a
• A complex operator contains more than one
operator.
Ex: 2*5+7-8
• An expression contains operator and operand.
• An operator is a syntactical token that requires
an action to be taken.
• An operand is an object on which an operator
is performed.
• An Expression always reduces to a
Expressions
• A Simple Expression is divided into Six Categories
based on the number of operands , relative position
of the operand and operator and the precedence of
operator.

Fig: Expression Categories


Expressions

Primary Expressions
• A primary Expression Consists of only one operand with no
operation.
• The operand in a primary expression can be a name, constant or
a parenthesized expression.
•A primary expression is evaluated first in a complex expressions.
Name
• Name is any identifier for a variable , a function , or any
other object .
Ex: a b12 price calc
INT_MAX SIZE Literal Constant
• A constant is a piece of data whose value can‘t
change during the
execution of the program.
Ex: 5 123.98 ‗A‘ ―Welcome‖
Expressions
Parenthetical Expressions
• Any value enclosed in a parentheses must be reducible to a
single value and is therefore a primary expression.
• A complex expression enclosed with in parentheses to make a
primary expression.
Ex: (2*3+4) (a=23+b*6)
Postfix Expression
• Postfix Expression consists of one operand followed by one operator.

Fig: Postfix Expressions

• Some of the operators that create a postfix expression are


function call,
Expressions
Function Call
⚫ Function calls are postfix expressions.
⚫ The function name is the operand and the operator is the
parentheses that follow the name.
⚫ The parentheses may contain arguments or be empty.
Ex: printf(―Hello World‖); or printf( );
Postfix Increment/Decrement
⚫ Postfix increment and decrement are also postfix operators.
⚫ Postfix increment the variable is incremented by
1. Ex: int a=5,x;
x=a++;
x=6;
⚫ Hear the
effect of
operation is
same as
Expressions
Ex:
int a=5,x;
x=a--;
x=4;
Prefix
Expression
s
⚫In prefix expression the operator comes before
the operand.
Fig:Prefix Expression
Prefix Increment and Decrement
⚫Similar to postfix increment and decrement the
prefix increment and decrement operators are
shorthand notations for adding or subtracting 1from
the value.
Expressions
Ex: int a=5,x; int a=5,x;
x=a++; x=a--;
x=6; x=4;
Postfix Postfix
Increment Decrement

Fig:Result of Prefix ++a


• When we need the value of the expression to be the current value
of
the variable we use the postfix operator.
• When we need the value to be the new value of the variable we
Expressions
Unary Expression
• It is like a prefix expression consists of one operator and one
operand.
• Prefix expression need a variable as the operand.
• Unary Expression can have an expression or variable as the operand.

Fig:Unary Expressions

• Some of Unary expressions are sizeofoperator, plus/minus


operator
the and the cast operator.
Expressions
Sizeof
• The size of operator tells the size , in bytes , of a type or a
primary expression.
• By specifying the size of an object during execution , we make
our program more portable to other hardware.
Syntax : sizeof(type);

Unary plus/Minus
• These two operators are use to compute the arithmetic value of
an operand.
• The plus operator does not change the value of an expression.
• The minus operator change the sign of a value algebraically.i.e to
change it from plus to minus and minus to plus.
Expressions
Cast Operator
• The cast operator converts one expression type to
another. Ex: To Convert integer type to float we use
cast operator.
int x;
float y=float(x);
Binary Expressions
• Binary Expressions are formed by an operand-operator-
operand
combination.

Fig:Binary Expressions
Expressions

Multiplicative Expressions
• Name of the expression takes from the first operator , include
the multiply , divide , and modulus operator.
• These operators have the highest priority among other
binary operators.
• Multiply operator is the product of the two operands.
Ex: 10*3 //result=30
true*4 //result=4
‗A‘* //result=2
2 //result=44.6
• The 22.3
type of the result depends on the conversion rules.
- if both operands are Integers result is Integer.
-if any one of the operand is floating point the result is floating
point.
Expressions

• The result of divide operator depends on the type of


operand.
Ex: 10/3 //result=3
true/4 //result=0
‗A‘/2 //result=32
• The modulus(%) operator divides the first operator by the
second operator and returns the reminder rather than quotient.
Ex: 10%3 // result=1
true%4 // result=1
‗A‘%1 // result=5
0 // result=Error because modulo can not be float.
• Both 22.3%2operands must be integral types and operator returns
the
remainder as an integer type.
Expressions
Additive Expressions
• In this type of Expressions the second operand is added to
or subtracted from the first operand , depending on the operator
used.
Ex: 3+7 // result=10
3-7 // result=-4
Assignment Expressions
• The assignment expression evaluates the operand on the right side of
the operator(=) and places its value in the variable on the left.
• The assignment expression has a value and a side effect.
• The value of the total expression is the value of the expression on the
right of the assignment operator(=).
• The side effect places the expression value in the variable on the left
of the assignment operator.
• There are two forms of Assignment
Expressions
1.Simple Expressions
• Simple assignment is found in algebraic expressions.
Ex: a=5 ; b=x+1 i=i+1
• The left variable must be able to receive the effect.
• That is it must be a variable , not a constant.
• If the left operand cannot receive a value and we assign a value
we get a compile time error.
2.Compound Assignment
• A compound assignment is a shorthand notation for a
simple assignment.
• It requires that the left operand be repeated as a part of the
right
expression.
• To evaluate the compound expression first change it to simple
Expressions
• The left operand in an assignment expression must be a
single
variable.

Fig: Expansion of Compound Expressions

Ex: x*=y+3 evaluated as x=x*(y+3).


Precedence and Associativity
Precedence
• To determine the order in which different operators in a complex
expression are evaluated.
Ex: 1 ) 2+3*4 is evaluated as (2+(3*4)) =(2+12)=14.
In the above example + having the precedence 12 and *
having the precedence 13 so first multiply 3*4 then add 2+12.
2) -6++ is evaluated as (-(6++))=-7.
Associativity
• Associativity is applied when we have more than one operator of
the same precedence level in an expression.
• Associativity can be left-to-right or right-to-left.
• Left-to-right associativity evaluates the expression by starting on
the left and moving to the right.
• Right-to-left associativity evaluates the expression by
Operator Type Operator Associativity
Primary
() [] . -> expr++ expr-- left-to-right
Expression
Operators
* & + - ! ~ ++expr --expr
Unary Operators right-to-left
(typecast) sizeof
*/%
+-
>> <<
< > <= >=
== !=
Binary Operators left-to-right
&
^
|
&&
||
Ternary Operator ?: right-to-left
= += -= *= /= %= >>= <<=
Assignment Operators right-to-left
Precedence and Associativity
Ex: (LTR)
1. 3*8/4%4*5
((((3*8)/4)%4)*5) value is 10.

Fig:Left-to-Right Associativity

• Hear all the operators having the same precedence so the


associativity is Left to Right.
Precedence and Associativity
Ex:(RTL)
1. a += b *= c -= 5
( a += ( b *= ( c -= 5)))
(a = a + (b = b * (c = c-5)))
if a has initial value of 3 , b has initial value of 5 , and c has
initial value of 8 then expression becomes
(a = 3 + (b = 5 * (c =8-
5))) (a = 3 + (b = 5 * 3))
(a = 3 + 15)
a=18
Side Effects
• A side effect is an action that results from the evaluation of an
expression.
• C language evaluates the expression from right of the
assignment operator and place result in left variable.
• Changing the value of left variable is a side effect.
Ex: x=x+3 expression has three parts . Assume x=3
1. the value of right of the right of the assignment operator
is 6
2. the value of hole expression is also 6
3. the side effect x receives the value 6.
• In c language six operators generate side effect.
– prefix increment and decrement
– postfix increment and decrement
– Assignment
– Function call
Expression Evaluation
Expressions Without Side Effects

Ex: 1. a * 4 + b / 2 – c * b
Assume the values for a=3 , b=4 , c=5
Substitute the values in the
Expression
3*4+4/2–5*4
Evaluate expression based on their
precedence
(3 * 4) + (4 / 2) – (5 * 4)
12 + 2 - 20
the value is -6.
• In the above expression there is no side effect , all the variables
Expression Evaluation
Expression With Side Effects

Ex: 1. --a * (3 + b) / 2 – c+
+ * b Assume the values a=3 , b=4
, c=5
calculate the value of Parenthesized
expression first
--a * 7 / 2 – c++ * b
--a * 7 / 2 – 5 * b
2*7/2–5*b
14 /2 – 5 * b
7–5*4
7 – 20
-13
Type Conversion
• Converting one type of data to another type of data is called type
conversion.
• There are two types of Conversions .
1. Implicit type conversion
2. Explicit Type Conversion
Implicit Type Conversion
• When the two types of a binary expression are
different then the c compiler automatically
converts one type to another. This is known
implicit type casting.
• We can assign the conversion ranks to the
integral and floating point arithmetic types.
Type Conversion

Fig: Conversion Rank


Type Conversion
Conversion in Assignment Statements
• In a simple assignment expression involve an assignment operator
and two operands.
• Depending on the rank of right expression the left variable takes
promotion or demotion.
• Promotion occurs if the right expression has lower rank.
• Demotion occurs if the right expression has higher rank.
Promotion
• The rank of the right expression is evaluated to the rank of the
left variable.
• Generally no problem with the n.
promotio
i=c //value of i is 65
Ex: char c=‗A‘;
int i=1234; d=i // value of d is
1234.0
Type Conversion
Demotion
• If the right expression having the higher rank than the left
variable then the right expression value is demoted to the left
variable.
• When the integer or real is stored into a char , the least significant
byte is converted to a char and stored.
• When a real is stored in a int the fraction part is dropped.

Ex:char c=‗A‘;
bool b= false;
int k=65;
b=c; // value of b is 1(true)
c=k+1; // value of c is B.
Type Conversion

Explicit Type Conversion

• In Explicit type conversion the programmer convert data from one


type to another.
• It uses Unary cast operator.
• To convert the data from one type to another , specify the new type in
parentheses before the value to be converted.
Ex: int a;
float f=(float) a;
Statements
• A statement causes an action to be performed by the
program.
• Most of the statements ends with semicolon , some do not.
• There are 11 types of statements.
Statements
Null Statement
• The null statement is just a
semicolon.
Syntax: ; //null statement
• null statement is used where we must have a statement but no action
is required.
Expression Statement
• An expression is turned into a statement by placing a semicolon after
the expression.
Syantax: expression ;
Return Statement
• A return statement terminates a function.
• All functions , including main , must have a return statement.
• When there is no return statement at the end of the function , the
Statements
Syntax: return statement;
• The return statement returns a value to the calling function.
• The main function returns 0 to the operating system.
• A return value of zero tells the operating system that the
program executed successfully.

Compound Statement
• A compound statement is a unit of code consisting of zero or
more statements.
• It is also called block.
• All the c functions contain a compound statement known as the
function body.
• A compound statement consists of an opening brace , an optional
declaration and definition section and an optional statement
Statements

Fig:Compound Statement
Statements
• A compound statement does not need a semicolon.
• If we put semicolon after the compound statement the compiler thinks
that we have put an extra null statement.
The Role of Semicolon
• Semicolon is used in two different situations
1. Every declaration in c is terminated by a semicolon.
2. Most statements in c are terminated by a semicolon.
• Semicolon should not be used with a preprocessor directive such
as the include and define.
UNIT-II
CONTROL STRUCTURES, ARRAYS AND STRINGS
Conditional or Decision
Statements
• Decision control statements are used to alter the flow of a sequence
of instructions.
• These statements help to jump from one part of the program to
another depending on whether a particular condition is satisfied or
not.
• The decision is described to the computer as a conditional
statement that can be answered either true or false.
• Different types of control statements are:
1 . if statement
2 . if – else statement 3
. nested if Statement
4 . else if ladder
5 . Switch statement
Statements
1.If statement or Null Else Statement
• If statement is the simplest form of decision control statements that
is frequently used in decision making.
Syntax:
if (test expression)
{
statement 1;
..............
statement n;
}
statement x;

Fig: If Statement flow chart


Statements
• First the test expression is evaluated. If the test expression is true, the
statements of if block (statement 1 to n) are executed otherwise these
statements will be skipped and the execution will jump to statement x.
• In this case the else statement is not required.

2.If- else Statement


• In the if-else construct, first the test expression is evaluated.
• If the expression is true, statement block 1 is executed and statement
block 2 is skipped.
• Otherwise, if the expression is false, statement block 2 is executed and
statement block 1 is ignored.
• In any case after the statement block 1 or 2 gets executed the control
will pass to statement x.
Statements

Fig:if...else Logic Flow


Statements

Fig : Syntactical Rules for if…else Statements


Statements
• In the first rule the expression must be enclosed in parentheses.
• The second rule no semicolon for if else statement and statement 1
and statement 2 ends with semi colon.
Ex:

• The third rule it is common in c code expressions that have side


effect. Ex: if(++lineCnt > 10){
pritf(―\n‖);
lineCnt=0;
}
else printf(….);
Statements
• Rules 4 and 5 are related .the multiple
statements can be used through the braces.
• The sixth rule states that the true and false
statements can be exchanged by complementing
the expression.
Statements
3 . Nested if Statement
• An if else is included within an if else is called nested if statement.
• There is no limit to how many level can be nested , but if the
number of levels are increased it becomes more difficult.
Statements

Dangling Else Problem


• when there is no matching else for every
if .

Fig : Dangling else


Statements
Solution to Dangling else Problem
• Always pair an else to the most recent un paired if in the
current block.
• By using a compound statement , we simply enclose the true
actions in braces to make the second if a compound statement .
Statements
Conditional Expressions
• An alternative for traditional if –else for two way selection.
• The conditional expression has three operands and a two
token operator.
Syntax: expression1 ? expression2 : expression3
• It first evaluates the left most expression1. If the expression1 is true ,
then the value of the conditional expression is the value of
expression2.
• If the expression1 is false , then the value of the conditional
expression is the value of expression3.
Ex:
a == b ? c++ : d++ ;
Statements
Else if ladder
⚫ To make a multi way decision on the basis of a value that not
an integral. We go for else if .
⚫ Else if is not a c construct ,it is a style of coding to make a multi
way selection based on a value that is not integral.
Syntax: if( expression)
{
Statements;
}
else if(expression2)
{
Statements;
}
else
{
S
t
Statements

Fig : Flow chart for else if ladder


Statements
Switch
• Switch is a composite statement used to make a decision
between many alternatives.
• The switch statement can be used only when the selection condition
is reduced to an integral expression.
Statements
switch (expression)
{
case value-1:
block-1
break;
…………
…………
default:
default-block
break;
}
statement-x;

Fig : switch Statement Syntax


Statements

• The switch expression can use any expression that reduces to


an integral value.
• The selection alternatives known as case labels must be integral types.
• Every possible value in the switch expression a separate case label is
defined.
• Every thing from a case label to the next case label is sequence.
• Case label simply provides an entry point to start the execution of the
code.
• The default label is a special form of the case label . It is executed
none of the other case values matches the value in the switch
expression.
• Once the program enters into a case it executes the code for all the
following cases until the end .
Statements

Switch Statement Rules


Statements
Loop
• To repeat an operation or a series of operation many times is
called looping .
• The loop must terminate when the work is completed.
• Design the loop to check condition before or after the loop.
Statements
Pretest Loops
• In each iteration, the control expression is tested first. If it is true, the
loop continues; otherwise, the loop is terminated.
Posttest Loops
• In each iteration, the loop action(s) are executed. Then the control
expression is tested. If it is true, a new iteration is started; otherwise,
the loop terminates.
Statements
Loop Initialization
• Initialization is the process of set the stage for the loop actions.
• It is done before the first execution of the loop body.
• Initialization may be explicit or implicit.
• In an explicit initialization we include code to set the beginning values
of key loop variables.
• In an implicit initialization there is no direct initialization
code ,it relies on preexisting situation to control the loop.
Loop Update
• The action that causes when the loop is executed is known as loop
update.
• Update is done in each iteration , usually in the last action.
• The body of the loop is repeated n times , then the updating is also
done n times.
Statements
Event Controlled Loops
• An event changes the control expression from true or false.
Ex : when Reading data , reaching the end of the data changes
the expression from true to false.
Statements
Counter – Controlled Loops
• When we know the number of times an action is to be repeated
then we use counter controlled loops.
• We must initialize , update , and test the counter.
Statements
• There are three loop statements in c language
1) do..while loop
2) while loop
3) for loop

• The first one is post test loop and remaining two are pretest loops.
• All the three loops support event and counter controlled loops.
• While and do while are commonly used for event controlled and for
is used for counter controlled.
Statements
Do…while loop
• The do while statement is a pretest loop.
• Do while statement test the expression after the execution of the body.
• Do while is concluded with a semicolon.

Fig : do…while Statement


Statements
While loop
• The while loop is a pretest loop.
• It test the expression before every iteration of
the loop.
• No semicolon is needed at the end of the
while statement.
• Hear the body of the loop must be only
one statement.
Statements
• To include multiple statements in the body , we must put them in a
compound statement.
Statements
For Loop
• It is a pretest loop.
• It uses three expressions.
• The first expression any initialization
contains
statements , the second contains
Updating
the limit-test
Initialization
expression , and the third contains the updating
expression.
Syntax: condition
for( exp1 ; exp2 ; exp3 )
Statements
• The body of the for loop must be one and only one statement.
• To include more statements in the body we must code them in a
compound statement.

Fig : Compound for Statement


• A for loop is used when a loop is to be executed a known number of
times .
• The same thing can be implemented with a while loop but the for
loop is easier to read and more natural for counting loops.

Fig : Comparing for and while Loops


Statements
Nested For Loops
• Including the for loop with in the body of another for loop.
• By using nested for loops we create looping applications.
The comma Expression
• The comma expression is a complex expression made up of two
expressions separated by a comma.
• The expressions are evaluated left to right.
• The value and type of the expression are the value and type of
the right expression.
• The comma expression has the lowest priority of all expressions ,
i.e is 1.
Ex:
for( sum=0,i=1; i<=20; i++)
Fig : Nested Comma Expression
sum=sum+i;
Statements
Break
• The break statement causes a loop to terminate.
• The break statement can be used in any of the loop statements
like while , do-while , for and in the selection switch
statement.

Fig : break and Inner Loops


Statements

The for and while as Perpetual Loops


Statements

Using a break Flag


Statements
Continue
• The continue statement does not terminate the loop.
• It simply transfer to the testing expression in while and do-
while statements and transfer to the updating expression in a for
statement.

Fig : The continue Statement


Statements
goto

• The goto statement is used to transfer control to a specified label.


• Label is an identifier that specifies the place where the branch is to be
made. Label can be any valid variable name that is followed by a
colon (:).
• label can be placed anywhere in the program either before or after the
goto statement. Whenever the goto statement is encountered the
control is immediately transferred to the statements following the
label.
• If the label is placed after the goto statement then it is called a forward
jump and in case it is located before the goto statement, it is said to be
a backward jump.
ARRAY
S same type stored contiguously in
• A collection of objects of the
memory under one name.
―May be type of any kind of variable
―May even be collection of arrays!
• The elements of the array are stored in consecutive
memory locations and are referenced by an index (subscript).
• To refer to an element, specify

―Array name
―Position number
• Syntax:

array_name[ position number ]


175
ARRAY
Array Declaration S
• When declaring arrays
– Name
– Type of data elements
– Number of elements
• Syntax
Data_Type array_Name[ Number_Of_Elements ];
• Examples:
int c[ 10 ];
float myArray[ 3284 ];
• Declaring multiple arrays of same type
– Format similar to regular variables
– Example:
int b[ 100 ], x[ 27 ];
176
ARRAY Name of array (Note
that all elements of
• int c[12] S this array have the
• An array of ten integers same name, c)

• c[0], c[1], …, c[11]


• double B[20] c[0] -45
c[1] 6
•An array of twenty long floating c[2] 0
point numbers c[3] 72
c[4] 1543
• B[0], B[1], …, B[19] c[5] -89
-89
0
• Arrays of structs, c[6]
c[7] 62
unions, , etc., are also allowed c[8]
pointers
-3
11
c[9]
6453
• Array indexes always c[10]
c[11] 78

start at zero in C
Position number of
the element 178
within array c
ARRAY
Two Dimensional Array S
• Syntax
Data_Type array_Name[ Row_Elements ][Column_Elements];
• Example
int D[10][20]
– An array of ten rows, each of which is an array of twenty
integers
– D[0][0], D[0][1], …, D[1][0], D[1][1], …, D[9][19]
– Not used so often as arrays of pointers

178
ARRAY
Two Dimensional Array S
• Multiple subscripted arrays as
– Tables with rows and columns (m×n array)
– Like matrices: specify row, then column

Column 0 Column 1 Column 2 Column 3

Row 0 a[ 0 ] a[ 0 ] a[ 0 ] a[ 0 ]
Row 1 [ 0 ] [ 1 ] [ 2 ] [ 3 ]
a[ 1 ] a[ 1 ] a[ 1 ] a[ 1 ]
Row 2 [ 0 ] [ 1 ] [ 2 ] [ 3 ]
a[ 2 ] a[ 2 ] a[ 2 ] a[ 2 ]
[ 0 ] [ 1 ] [ 2 ] [ 3 ]

Column subscript
Array name
Row subscript
179
ARRAY
Multi Dimensional Arrays S
• Array declarations read right-to-left
• Syntax
Data_Type array_Name[ Size ][Size][Size] … Size];
• Example
int a[10][3][2];
―an array of ten arrays of three arrays of two
elements‖
• In memory 3 3 3

...

2 2 2 2 2 2 2 2 2

10
180
ARRAY
Array initialization
S
• Example
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
– Values must be compile-time constants (for static arrays)
– Values may be run-time expressions (for automatic arrays)
int A[5] = {2, 4, 8, 16, 32};
–Static or automatic
int B[20] = {2, 4, 8, 16, 32};
– Unspecified
elements are
guaranteed to be
zero
int C[4] = {2, 4, 8, 16, 32};
–Error — compiler detects too many initial values
int D[5] = {2*n, 4*n, 8*n, 16*n, 32*n}; 181
ARRAY
Array initialization
S
• Example
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become
0 int n[ 5 ] = { 0 }
– All elements 0
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore 5 element array
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 2
– Initializers grouped by row in braces 3 4

–If not enough, unspecified elements set to zero


int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 1 0
3 4

182
STRINGS
String is a series of characters treated as a unit.
All string implementations treat a string as a variable length
piece of data.
Strings can vary in size.
Length of strings-Strings can be of fixed length or variable length.
FIGURE String Taxonomy
FIGURE String Formats
Length of the Strings

Fixed length:
Fixed length strings have their length controlled. Their
length fixed once cannot be changed.
There are disadvantages with fixed length because if the length is
fixed small all the data may not be stored.
If the length is made big memory gets wasted.
Variable length:
The size of the string can be either by length controlled
or delimited.
If it is length controlled string of variable length the number of
characters in the string are represented before the string.
Length of the Strings

If it is delimiter controlled string of variable length then a ‗\0‘ is


filled in after the string completes.
C O N F U S I O N \0

C strings
C String is a variable length array of characters that is
delimited by the null character.
1) Storing strings:
Strings are stored in an array of characters.
It is terminated by the null character(\0).
e.g. H E L L O \0
C strings
 for the above characters the memory locations required are 6.
 A character requires only one memory location.

 e.g. ‗H‘ this requires only one memory location.

 A character string requires memory locations based on number of

characters and a null character.


e.g. H \0 requires 2 memory locations.
 An empty string is shown as \0.

2) String delimiter
 A string is not a data type but is a data structure since delimiter is

used.
 The physical structure of a string is an array but logically it should be

stored with delimiter including.


C strings
h e l l \0

the above is a string.

h e l l o
This is a array.
g o o d b Y e \0

19
0
C strings
3) string literal:
String literal also known as string constant.
It is a sequence of characters enclosed in double quotes.
e.g. “C is a high-level language.”
“hello” , “abcd”
A string is stored in memory just like an object is stored. It has an
address.
Using pointers string literals can be referred.
C Strings

Example program

H HELLO[0]
#include<stdio.h> E HELLO[1]
int main(void) L HELLO[2]
{ L HELLO[3]
Printf(―%c\ O HELLO[4]
n‖,‖hello‖[1]); Return 0; \O HELLO[5]

}
O/P: E
C strings
4)Declaring strings
C has no string type.
As strings are sequence of characters char data type is
used for string declaring.
e.g. Char str[9];
The size of the string declared should be one memory space
more than the data size.
If the size of the data is 6 then including delimeter it is
7.
So char str[7];
C STRINGS

To declare a string pointer:


data type is followed by *p and the string name.
e.g. Char *pstr;
This allows in pointing to the first location of the string by a pointer.
Memory of the string must be allocated before the string can be
used.
FIGURE Defining
Strings
C strings
5)initializing strings:

a) Char str[9]=“good day”;


g o o d d a y \0

str

In the above counting with the characters, space and


delimeter there are totally 9 characters which are been
specified in the array.

19
6
C STRINGS
b) Char month[]=―Januar‖;
In the above compiler will create an array of 8 bytes
including delimeter .
c) Char *pstr=―good day‖;
―good day‖
d)Char str[9]={‗G‘,‘O‘,‘O‘,‘D‘,‘ ‗,‘D‘,‘A‘,‘Y‘,‘\O‘}
The method is not used too often because it is so tedious to code.
String Input/Output Functions
• C provides two basic ways to read and write strings.
1)We can read and write strings with the formatted input/
output functions, scanf/fscanf and printf/fprintf.
2)We can use a special set of string-only functions, get
string (gets/fgets) and put string ( puts/fputs ).

Fig : gets and fgets


String Input/Output Functions

Fig : puts and fputs


String Input/Output Functions

Fig : Array of
Strings
String Manipulation Functions
• strcpy()---- copies one string over another.

Syntax:
strcpy(destination,source);

Ex: s1=―bombay‖;
s2=―delhi‖; strcpy(s1,s2);

output: s1=―delhi‖;

• The string 1 should large enough to hold the characters of


string 2 or else the no. of letters sufficient in the
available string will be taken.
String Manipulation Functions

Fig : String Copy


String Manipulation Functions

• strncpy()---copy characters of a string to another string with


the given number of characters in a string.

Syntax:
strncpy(dest,source,n);

Ex:
s1=―come‖;

s2=―gone‖;
strncpy(s2,s1,2);
output:
s2= ―co‖;
String Manipulation Functions

Fig : String-number Copy


String Manipulation Functions

• strcmp()----- compares two strings

Syntax:
strcmp(string1,string2);

Ex: s1=―their‖;
s2=―there‖;
strcmp(s1,s2);

Output: -9

• The result will be ASCII code


of ‗i‘ minus(-) ASCII code of
‗r‘
=
-9
String Manipulation Functions

Fig : String Compares


String Manipulation Functions

• stricmp() ---- doesn't discriminate between small and capital


letters. syntax:
Stricmp(source , destination);
Ex :
S1=―come‖ s2=―COME‖
Stricmp(s1,s2);
output: 0
• Compares both string with out considering the case of the
string.

• strncmp()---- compares characters of two strings up to


specified length
syntax:
strncmp(source,destination,length);
Strncmp(s1,s2,2);
Ex: S1=―come‖ s2=―computer‖
Output: 1
String Manipulation Functions
• strlen()----finds the length of a string
syntax:
strlen(string);
Ex: string=―
computer‖ n=
Output: strlen(string1);
8
• No. of characters in a string.
• strlwr(): converts uppercase characters of a string to lower
case syntax: strlwr(string);
Ex : s2=―COMPUTER‖
Strlwr(s2);
output: s2= computer;
• strupr() --- converts lower case to characters of a string
to a upper case.
Syntax: strupr(string);
Ex: s1=―computer
‖ strupr(s1);
Output: s1=―COMPUTER‖;
String Manipulation Functions
• C library supports a large of
number manipulation functions string
• Strcat() -----concatenates two strings

Syntax:
strcat(string1, string2);
Ex:
string1=―very‖; s2=―good‖;
strcat(s1,s2);
Output:
s1=―verygood‖;
• The string 1 should large enough to hold the characters of string
2.
String Manipulation Functions

Fig : String Concatenation


String Manipulation Functions
• strchr() — determines the first occurrence of a given character in a string.
Syntax:
strchr(string,character);
Ex:
Char c=‗p‘;
S1=‗computer‘;
int i=
strchr(s1,c);
Output:
i=3
• strrchr() ----- determines the last occurrence of
the given character in string.

Syntax: strrchr(string, character);


String Manipulation Functions

Fig : Character in String


(strchr)
String Manipulation Functions
• strstr() – determines the first occurance of a given string in
another string.

Syntax:
strstr(string1,string2);
Ex:
S1=―computer
engg‖; S2=―engg‖;
strstr(s1,s2);

Output: engg
String Manipulation Functions

Fig : String in String


String Manipulation Functions

Fig : String Span


String Manipulation Functions
• strrev(): reverses all characters of a
string.

Syntax: strrev(source);
Ex :
S1=―madam‖
Strrev(s1)
Output: S1=madam
• strdup(): these
function duplicates
Ex:string. Char s1[10],c[10];
the
Syntax: S1=―raju‘
C=strdup(s1)
strdup(
Output: source
C=raju
);
UNIT-3
FUNCTIONS AND
POINTERS
• Breaking up a program into segments commonly known as functions.

• Each function can be written more or less independently of the others.

• The purpose of a function is to receive zero or more pieces of data, operate on


them, and return at most one piece of data.
• The side effect of a function is an action that results in a change in the state of a
program. If occurs, it effects while the function is executing and before the
function returns.

217
FUNCTIONS
Calling Function
Called Function

main() Formal arguments


{
………….. Function Call
………….. int func1(int x,
f=func1(a,b); int y)
………… {
……….. Statement Block;
return 0; Actual Arguments return z;
} }

Function Definition

Fig: Terminology of Functions


218
FUNCTIONS
Terminology
• main() calls another function, func1() to perform a well defined
task. main() is known as the calling function and func1() is
known as the called function.
• When the compiler encounters a function call, instead of
executing the next statement in the calling function, the control
jumps to the statements that are a part of the called function.
• After the called function is executed, the control is returned
back to the calling program.
• The inputs that the function takes are known as arguments .
220
FUNCTIONS
Terminology
• When a called function returns some result back to the calling
function, it is said to return that result.
• Main() is the function that is called by the operating system
and therefore, it is supposed to return the result of its
processing to the operating system.
• The arguments in function call referred as actual arguments.

• The arguments in function definition call referred as formal


arguments.

220
FUNCTIONS
• main() can call as many functions as it wants and as many
times as it wants.
• It is not that only the main() can call another
functions. Any function can call any other function.

func2()
func1()
{ func3()
main() {
{
{ ………..
………… ………..
………….. ………..
………….. func2();
……….. …………
func1(); …………
………… ……….
func3();
……….. ………..
return 0; return;
……….. ……….
} }
……….
return; return;
} }

Fig: Multi function call


illustration 221
FUNCTIONS
Advantages of functions
• Each function to be written and tested separately.
This simplifies the process of getting the total program to
work.
• Understanding, coding and testing multiple
separate functions are easier than one huge function.
• Provide a way to reuse code that is required in more than
one place in a program.
• A library of functions can be built to carry out repetitive
work like math library, standard I/O library. 22
2
223
FUNCTIONS
• Advantages of functions
• Functions can protect the data.
• Functions can have local data described within a
function. These data are available only to the function and
only while the function is executing. When the function is not
active, the data are not accessible.
• With local data, data in one function cannot be seen or
changed by a function outside of its scope.

22
3
223
FUNCTIONS
Function Declaration / Prototype
• Function declaration identifies a function with its name, a list of
arguments that it accepts and the type of data it returns.
• Syntax:
return_type function_name(data_type variable1, data_type
variable2,..);
• No function can declared within the body of
be
function. another

Eg: float avg( int , int );

224
FUNCTIONS
Function Definition
• Function definition consists of a function header that identifies the
function, followed by the function body containing the executable
code for that function.
• Syntax:
return_type function_name(data_type variable1, data_type variable2,..)
{ //function body
………….
statements
………….
return( va
} riable);

225
FUNCTIONS

Function Definition
• When a function defined, space is allocated for that function in
the memory.
• The number of and the order of arguments in the function
header must be same as that given in function declaration
statement.

226
FUNCTIONS
Function call
• The function call statement invokes the function.

• When a function is invoked the compiler jumps to the called


function to execute the statements that are a part of that
function.
• Once the called function is executed, the program control
passes back to the calling function.
• Syntax:

function_name(variable1, variable2, …);

227
FUNCTIONS
Function Call
• Names (not the types) of variables in function
declaration, function call and function definition may vary.
• Arguments may be passed in the form of expressions to
the
called function.
• In such a case, arguments are first evaluated and converted to
the type of formal parameter and then the body of the function
gets executed.
• If the return type of the function is not void, then the value
returned by the called function may be assigned to some
variable as given below.
variable_name = function_name(variable1, variable2, …);
228
FUNCTIONS
Function Call

Fig: Declaring, Calling, and Defining 230


Functions
FUNCTIONS
Multiple Function Call
#include<stdio.h> void a() void d()
void y(); { {
void y() printf(“ a ”); printf(“ d ”);
{ y(); c();
printf(“y”); } b();
} a();
void main() void b() }
{ {
void a(), b(), c(), printf(“ b ”);
d(); a();
clrscr(); }
y();
a(); void c()
b(); {
c(); a();
d(); b();
} printf(“ c ”);
}

230
FUNCTIONS
Multiple Function Call
#include<stdio.h> void a() void d()
void y(); { {
void y() printf(“ a ”); printf(“ d ”);
{ y(); c();
printf(“y”); } b();
} a();
void main() void b() }
{ {
void a(), b(), c(), printf(“ b ”); OUTPUT:
d(); a(); yayb ayayb ayc
clrscr(); } d ayb ayc b ayay
y();
a(); void c()
b(); {
c(); a();
d(); b();
} printf(“ c ”);
}

231
FUNCTIONS
Return Statement
• The return statement is used to terminate the execution of a
function and return control to the calling function.
• When the return statement is encountered, the program execution
resumes in the calling function at the point immediately following
the function call.
• A return statement may or may not return a value to the calling
function.
• Syntax:

return <expression> ;
232
FUNCTIONS
Return Statement
• The value of expression, if present, is returned to the calling
function. However, in case expression is omitted, the return value
of the function is undefined.
• Programmer may or may not place the expression within
parentheses ( , ).
• By default, the return type of a function is int.

• Functions that has no return statement, the control automatically


returns to the calling function after the last statement of the called
function is executed.
233
FUNCTIONS
Passing Parameters To The Function
• There are two ways in which arguments(parameters) can
be passed to the called function.
Passing parameters to function

Call by value Call by reference

• Call by value in which values of the variables are passed by the


calling function to the called function.
• Call by reference in which address of the variables are passed by
the calling function to the called function.
234
FUNCTIONS
Passing Parameters To The Function
― Call By Value:
• The called function creates new variables (formal arguments) to
store the value of the arguments passed to it. Therefore, the
called function uses a separate copy of the actual arguments
(formal arguments) to perform its intended task.
• If the called function is supposed to modify the value of the
parameters passed to it, then the change will be reflected only in
the called function. In the calling function no change will be
made to the value of the variables.
235
FUNCTIONS
Passing Parameters To The Function – Call By Value
#include<stdio.h> void add(int n) OUTPUT :
void add( int n); {
int main() The value of num before
n = n + 10;
calling the function = 2
{ printf("\n The
int num = 2; printf("\ value of num in the The value of num in
n The value of num called function = the called function =
before calling the %d", n); 12
function = %d", }
num); The value of num
add(num); after calling the
printf("\n The value of function = 2
num after calling the
function = %d", num);
return 0;
}

236
FUNCTIONS
Passing Parameters To The Function

— Call By Reference

• In call by value method, the only way to return the modified


value of the argument to the caller is explicitly using the return
statement.
• The better option when a function can modify the value of the
argument is to pass arguments using call by reference technique.
• In call by reference, we declare the function parameters as
references rather than normal variables.

237
FUNCTIONS
Passing Parameters To The Function

― Call By Reference
• Any changes made by the function to the arguments it received
are visible by the calling program.
• To indicate that an argument is passed using call by reference, an
ampersand sign (&) is placed after the type in the parameter
list.

238
FUNCTIONS
Passing Parameters To The Function --Call By References
#include<stdio.h> void add( int *n) Output:
void add( int {
*n); int main() The value of num before
{ *n = *n + 10; calling the function = 2
printf("\n The value
int num = 2; printf("\ of num in the called The value of num in
n The value of function = %d", the called function =
*n); 12
num before calling the }
function = %d", The value of num after
num); calling the function =
add(&num); 12
printf("\n The value of
num after calling the
function = %d",
num);
return 0;
}

239
FUNCTIONS
User Defined Functions
Five types of functions are possible:
• Functions with no arguments and no return values.

• Functions with arguments and no return values.

• Functions with arguments and return values.

• Functions with no arguments and return values.

• Functions that return multiple values.

24
0
245
FUNCTIONS
User Defined Functions
• Functions with no arguments and no return value
(void functions without parameters)
– Function without any arguments means data is passed
no
(values like int, char, etc..) to the called function.
– Similarly, function with no return type does not pass
back data to the calling function.
– This type of function which does not return any value cannot
be used in an expression.
– It can be used only as independent statement.

24
1
245
FUNCTIONS
User Defined Functions
• Functions with no arguments and no return value
(void functions without parameters) ― Example
#include<stdio.h> void printline()
#include<conio.h> {
void printline(); int i; printf("\
void main() n");
{ for(i=0;i<30;i++)
clrscr(); {
printf("Welcome to function in printf("-");
C"); }
printline(); printf("\n");
printf("Function easy to learn."); }
printline();
getch();
}

24
2
245
FUNCTIONS
User Defined Functions
• Functions with arguments and no return
value (void functions with parameters)
– Function with arguments can perform much better
than a function without arguments.
– This type of function can accept data from calling function.

– Data can be sent to the called function from calling function


but you cannot send result data back to the calling function.
– Output of function can be controlled by providing
various values as arguments.

24
3
245
FUNCTIONS
User Defined Functions
• Functions with arguments and no return
value (void functions with parameters) ―
Example
#include<stdio.h> void add(int x, int y)
#include<conio.h> {
void add(int ,
int ); void main() int result;
{ result = x+y;
clrscr(); printf("Sum of %d and %d is
add(30,15); %d.\n\n",x,y,result);
add(63,49);
add(952,321); }
getch();
}

24
4
245
FUNCTIONS
User Defined Functions
• Functions with no arguments but returns value
(non-void functions without parameters)
– Function does not take any argument
but only returns
#include<stdio.h> void main()
values to the calling function
{
#include<conio.h> int z;
int send() clrscr();
{ z = send();
int no1; printf("\nYou entered : %d.", z);
printf("Enter a no : "); getch();
scanf("%d",&no1); }
return(no1);
}

24
5
245
FUNCTIONS
User Defined Functions
• Functions with arguments and return value
(non-void functions with parameters)
– This type of function can send arguments (data) from the
calling function to the called function and wait for the result
to be returned back from the called function back to the
calling function.
– The data returned by the function can be used later in the
program for further calculations.

24
6
245
FUNCTIONS
User Defined Functions
• Functions with arguments and return value
(non-void functions with parameters) ― Example
#include<stdio.h> int add(int x, int y)
{
#include<conio.h> int result;
int add(int , int ); result = x+y;
void main() return(result)
{ ;
int z; }
clrscr();
z=
add(952
,321);
printf("
Result 2
4
%d.\n\
FUNCTIONS
User Defined Functions
• Functions that return multiple values ― Example
#include<stdio.h> void main()
#include<conio.h> {
void calc(int x, int y, int *add, int *sub) int a=20, b=11, p,q;
{ clrscr();
*add = x+y; calc(a,b,&p,&q);
*sub = x-y; printf("Sum =%d,
} Sub=%d", p, q);
getch();
}

24
8
248
FUNCTIONS
Inter-function Communication
– Functions have to communicate between them to exchange
data
– The data flow between the calling and called functions can
be divided into
• A downward flow – from the calling to the called
function
• An upward flow from the called to the calling function
• A bi-directional flow in both directions

24
9
248
FUNCTIONS
Inter-function Communication
– Downward flow
• In downward communication, the calling function sends data
to the called function
• No data flows in the opposite direction
• Copies of data items are passed from the calling function to
the called function.
• The called function may change the values passed, but
the
original values in the calling function remain untouched

25
0
248
FUNCTIONS
Inter-function Communication

Fig: Downward Communication


251
FUNCTIONS
Inter-function Communication

– Upward flow
• Upward communication occurs when the called function
sends data back to the calling function without receiving any
data from it

25
2252
FUNCTIONS
Inter-function Communication

Fig: Upward Communication


253
FUNCTIONS
Inter-function Communication
– Bi-directional flow

• Bi-directional occurs when the


communication calling
function sends data down to the called function.
• During or at the end of its processing, the called function
then sends data up to the calling function

25
4254
FUNCTIONS
Inter-function Communication

Fig: Bi-directional Communication


255
FUNCTIONS
Standard Functions
– C provides a large set of functions whose definitions have been
written and are ready to be used in user programs.
– To use these functions, we include
(#include<math.h> or
#include<stdlib.h>) in programs.
– Thefunction declarations of these functions are
grouped together and collected in several header files.

256
25
FUNCTIONS
Standard Functions
– The header files are included in the program instead of adding
the individual function declarations.
– The include statement causes the header file of the function to
be copied into the program.
– When the program is linked, the object code for the function is
combined with the program code to build the complete
program.

257
25
FUNCTIONS
Standard Functions

Fig: Library functions and the linker


258
25
FUNCTIONS
Standard Functions
– Math Functions
• These are collections of functions for
mathematical calculations. These include
– Absolute value functions – abs – returns the positive
value regardless of sign
int abs ( int number);
abs (3)
– Complex Number
functions – cabs, creal,
cimag
– Ceiling functions – ceil -returns smallest
integral value greater than or equal to a number
float ceil ( float number)
ceil ( -1.9) returns -1.0 259
FUNCTIONS
Standard Functions
• Math Functions
– Floor functions – floor – returns the largest
integral value that is equal to or less than a number
float floor ( float
number) floor ( -1.1 )
returns -2.0
floor ( 1.9) returns 1.0
– Truncate functions – trunc –
returnsthe integral in the
direction of 0
double trunc (double number)
trunc (-1.1) returns -1.0
trunc ( 1.9) returns 1.0 26
0
FUNCTIONS
Standard Functions
– Math Functions
– Floor functions – floor – returns the largest
integral value that is equal to or less than a number
float floor ( float
number); floor ( -1.1 )
returns -2.0
floor ( 1.9) returns 1.0
– Truncate functions – trunc –
returnsthe integral inthe
direction of 0
double trunc (double number);
trunc (-1.1) returns -1.0
trunc ( 1.9) returns 1.0 26
1
FUNCTIONS
Standard Functions
– Math Functions
– Round functions – round – nearest integral
returns the value
double round ( double number);
round ( -1.1) returns -1.0
round ( 1.9) returns 2.0
round (-1.5) returns -2.0
– Power functions – pow – returns the value of the x raised
to the power y. Error occurs if the base(x) is negative and
the exponent (y) is not an integer or if the base is zero and
the exponent is not positive
double power ( double n1, double n2);
pow (3.0, 4.0) returns 81.0
26
2
FUNCTIONS
Standard Functions
– Math Functions
– Square root functions – sqrt – returns the non-negative
square root of a number. Error occurs if the number is
negative.
double sqrt ( double n1);
sqrt (25) returns 5.0

26
3
FUNCTIONS
Standard Functions
• Random numbers
– A random number is a number selected from a set in
which all members have the same probability of being
selected.
– C provides two functions to build a random number series
seed random (srand) and random (rand).
– These functions are found in stdlib.h
srand (997)

26
4
FUNCTIONS
Standard Functions

265
STORAGE CLASSES
•Scope
– Scope determines the region of the program in which a
defined object is visible in the part of the program in
which we can use the object‘s name.
– Scope pertains to any object that can be declared like a
variable or a function declaration.
– A block is zero or more statements enclosed in a set of
braces.
– A block has a declarations section and a statement section.

26
6
268
STORAGE CLASSES
•Scope
– Blocks can be nested within the body of a function and
each block will be an independent group of statements
with its own isolated definitions.
– Global area of a program consists of all statements that
are outside functions.
– An objects scope extends from its declaration until the end
of the its block.
– Variables are in scope from their point of declaration until
the end of their block.
26
7
268
STORAGE CLASSES
• Scope ― Example
#include<stdio.h> int fun ( int i, int j)
int fun (int , int ); //Global area {
int p; //Global int a;
variable int main (void) int
{ y;
int x; //main‘s area
float y; //Local //
variables funct
{ // beginning of nested block ion
float a = y /2; area
float y; …
//Nested block area float z; } //
…. function
z= a * b; block
….
} // end of nested block
}
26
8
268
STORAGE CLASSES
•Scope
– Global Scope
•Any object defined in the global are of a program is visible
from its definition until the end of the program.
•The function declaration for fun is a global definition.
•It is visible everywhere in the program.

26
9
268
•Scope STORAGE CLASSES
– Local
Scope
•Variables defined within a block have local scope.
•They exist only from the point of their declaration until the
end of the block in which they are declared
•Outside the block they are invisible
– There are two blocks in main.
– The first block is all of main.
– The second block is nested within main.
– All definitions in main are visible to the second
block unless local variables with an identical name are
defined.
– In
typethe
is inner
float. block a local version of ‗a‘ is defined and
27
its 0270
STORAGE CLASSES
• Storage Class

– The storage class of a variable defines the scope (visibility)


and life time of variables and/or functions declared within
a C Program.
– To fully define a variable it is necessary to define its ‗type‘
and also its ‗storage class‘.
– If we don‘t specify the storage class of a variable in its
declaration, the compiler will assume a storage class
depending on the context in which the variable is used.
Thus, variables have certain default storage classes.
27
1
271
STORAGE CLASSES
• Storage Class

– A variable name identifies some physical location within


the computer where the string of bits representing the
variable‘s value is stored.
– There are basically two kinds of locations in a computer
where such a value may be kept— Memory and CPU
registers.
– It is the variable‘s storage class that determines in which of
these two locations the value is stored.

27
2
271
STORAGE CLASSES
• Object Storage Attributes

Storage class specifiers control three


attributes of an object‘s storage.
– Scope
– Extent
– Linkage

27
3
271
STORAGE CLASSES
• Object Storage
Attributes

27
4
271
STORAGE CLASSES
• Object Storage
Attributes
– Scope
• Scope defines the visibility of an object.
• It defines where an object can be referenced.

• Scope can be

— Block Scope

— Global(File) Scope.

27
5
271
STORAGE CLASSES
• Object Storage Attributes

– Scope

– Block (Local) Scope


» When the scope of an object is block, it is visible only in
the block in which it is defined. This object is called a
local object.
» Example – A variable declared in the formal parameter
list of a function has block scope.
» A variable declared in the initialization section of a for
loop also has a block scope, but only within the for
statement.
27
6
271
STORAGE CLASSES
• Object Storage
Attributes
– Scope
– File (Global) Scope
» File scope includes the entire source file for a program,
including any files included in it.
» An object with file scope has visibility through the whole
source file in which it is declared.
» Objects within block scope are excluded from file scope
unless specifically declared to have file scope i.e. block
scope hides objects from file scope.
» File scope includes all declarations outside a function and
all function headers.
277
» An object with file scope is referred as Global .277
STORAGE CLASSES
• Object Storage Attributes
– Extent
• The extent of an object defines the duration for which the
computer allocated memory for it.
• Extent can be
– Automatic extent
– Static Extent
– Dynamic Extent

27
8
278
STORAGE CLASSES
• Object Storage Attributes
– Extent
– Automatic extent
» An object with automatic extent is created each time its
declaration is encountered and is destroyed each time its
block is exited.
» Example– a variable declared in the body of a loop is created
and destroyed in each iteration.
» Declarations in a function are not destroyed until the
function is complete.
» When a function calls a function, they are out of scope but
not destroyed.
27
9
278
STORAGE CLASSES
• Object Storage Attributes
– Extent
– Static extent
» A variable with a static extent is created when the program
is loaded for execution and is destroyed when the execution
stops.
– Dynamic extent
» Dynamic extent is created by the program through
malloc() library functions.

28
0
278
STORAGE CLASSES
• Object Storage Attributes
– Linkage
• When a program is divided into modules, these module are
to be linked for the whole program to function.
• Linkage can be
– Internal
– External

28
1
278
STORAGE CLASSES
• Object Storage Attributes
– Linkage
– Internal
» An object with internal linkage is declared and visible
only in one module. Other modules cannot refer to this
object.
– External
» An object with an external linkage is declared in one
module but is visible in all other modules that declare it
with a special keyword, extern.

28
2
278
STORAGE CLASSES
• Types of Storage Classes
There are four storage classes in C:

– Automatic storage class

– Register storage class

– Static storage class

– External storage class

28
3
278
STORAGE CLASSES
STORAGE CLASS
FEATURE
Auto Extern Register Static
Local:
Accessible
within the
Accessible Accessible function or
Accessible block in which
within the within all
within the it is declared
function or program files
Accessibility block in function or Global:
that are a
block in which Accessible
which it is part of the
it is declared within the
declared program
program in
which it is
declared

Main Main
Storage CPU Register Main Memory
Memory Memory

Table: Storage Classes Features


284
STORAGE CLASSES
STORAGE CLASS
FEATURE
Auto Extern Register Static

Exists when Exists when the


the function or function or Local:
block in block in which Retains value
which it is it is declared is between
declared is Exists entered. Ceases function calls
entered. throughout to exist when or block
Existence Ceases to exist the execution the control entries
when the of the returns from Global:
control returns program the function or Preserves
from the the block in value in
function or the which it was program files
block in which declared
it was
declared
Defaul
Garbage Zero Garbage Zero
t value
Table: Storage Classes Features
285
STORAGE CLASSES
• Automatic Storage Class
Keyword -- auto

Storage – Memory.

Default value – An unpredictable value, which is


often called a garbage value.

Scope – Local to the block in which the


variable is defined.

Life – Till the control remains within the


block in which the variable is
defined.
28
6
286
STORAGE CLASSES
•Automatic Storage Class
Example:
#include<stdio.h> void call1()
void call1(); {
void call2(); int v=20;
main() printf(―\n v=
{ %d‖,v);
int v=10; }
call1(); void call2()
call2(); {
printf(― int v=30;
\n v= printf(―\n v=
%d‖,v); %d‖,v);
} }
28
7
286
STORAGE CLASSES
• Register storage class
The features of a variable defined to have an automatic storage
class , declaration includes a recommendation to the compiler to
use a CPU register for the variable:
Keyword -- register
Storage – Register /
Memory.
Default initial value − Garbage
value.
Scope – Local to the block in which the
variable is defined.
Life – Till the control remains within the
block in which the variable is
defined.

28
8
286
STORAGE CLASSES
• Register storage class
Example:
#include<stdio.h>
main()
{
register int m=1;
for(;m<=5;m++)
printf(―
%d‖,m);
}

28
9
286
STORAGE CLASSES
• Static storage class (Block scope)
The features of a variable defined to have static storage class
are as under:
Key word -- static

Storage – Memory.
Default value -- only one time initialization ,
if not initialized it will be zero .
Scope – Local to the block in which the
variable is defined.
Life –is created when the program is
loaded for execution and is
destroyed when the execution stops.
29
0
286
STORAGE CLASSES
• Static storage class
(Block scope)
Example:
void call1()
#include<stdio.h> {
void call1();
static int v;
void call2(); v=v+10;
main() printf(―\n
{ in
call1(); call
call2(); 1()v
call1(); =
call2(); %d
} ‖,v)
;
}
void
} call2() 29
1
291
STORAGE CLASSES
• Static storage class (File scope)
The features of a variable defined to have static storage class
are as under:
Key word -- static

Storage – Memory.
Default value -- only one time initialization ,
if not initialized it will be zero .
Scope – visible to the whole source file
in which the variable is defined.
Life – is created when the
program is loaded
for execution and is
destroyed when the execution 29
stops. 2
292
STORAGE CLASSES
• Static storage class
(File scope)
Example:
#include<stdio.h> void call1()
void call1();
{
void call2(); v=v+10;
static int v; printf(―\n in call1()v=
main() %d‖,v);
{ }
call1(); void call2()
call2(); {
call1(); static int v;
call2(); v=v+15;
} printf(―\n
in call2() =
%d‖,v); 29
3
292
STORAGE CLASSES
• External storage class
The features of a variable defined to have extern storage class
are as under:
Key word -- extern
Storage − Memory
Default value -- initialized with zero
Scope − visible to the whole source file in which
the variable is defined

Life − is created when the program is loaded


for execution and is destroyed when
execution stops the

29
4
292
STORAGE CLASSES
• External storage class
Example:
void void call2()
call1(); void {
extern int v;
call2(); int printf(―in call2() =
v=10; %d‖,v);
main() }
{
call1();
call2();
printf(―in
main() =
%d‖,v);
}
void call1() 29
5295
{
RECURSION

• A recursive function is a function that calls itself to solve a


smaller version of its task until a final call is made which does
not require a call to itself.
• Every recursive solution has two major cases, they are:
– Base Case
– Recursive Case
Base case:
• The problem is simple enough to be solved directly without
making any further calls to the same function.

296
RECURSION
Recursive case:
• first, the problem is divided into simpler sub parts.
• Second, the function calls itself but with sub parts of the problem
obtained in the first step.
• Third, the result is obtained by combining the solutions of simpler
sub-parts.
• Therefore, recursion is defining large and complex problems
in terms of a smaller and more easily solvable problem.
• In recursive function, complicated problem is defined in terms of
simpler problems and the simplest problem is given explicitly.

297
RECURSION
Factorial of A Number Using
Recursion
PROBLEM SOLUTION
5! 5 X 4 X 3 X 2 X 1!
= 5X = 5X4X3X2X1
4! = 5X4X3X2
= 5X = 5X4X6
4 X 3! = 5 X 24
= 5X = 120
4 X 3 X 2!
= 5X
4X3X2X
• Base case is when n=1, because if n = 1, the result is known to be 1
1!
• Recursive case of the factorial function will call itself but with a
smaller value of n, this case can be given as
factorial(n) = n × factorial (n-1)
298
RECURSION
Factorial of A Number Using Recursion ― Example
#include<stdio.h>
int Fact(int)
{if(n==1)
retrun 1;
return (n *
Fact(n-1));
}
main()
{int num; scanf(―
%d‖, &num);
printf(―\n Factorial
of %d = %d‖, num,
Fact(num)); 299
RECURSION
Factorial of A Number Using Recursion ―
Illustration

300
RECURSION
Fibonacci Series Using Recursion
• The Fibonacci series can be given as:

0 1 1 2 3 5 8 13 21 34 55……
• The third term of the series is the sum of the first and
second terms.
• On similar grounds, fourth term is the sum of second and third
terms, so on and so forth.
• Now we will design a recursive solution to find the nth term of the
Fibonacci series. The general formula to do so can be given as
1, if n<=2
FIB(n) =
FIB (n - 1) + FIB (n – 2),
otherwise
301
RECURSION
Fibonacci Series Using Recursion

FIB(7)

FIB(6) FIB(5)

FIB(5) FIB(4) FIB(4) FIB(3)

FIB(4) FIB(3) FIB(3) FIB(2) FIB(3) FIB(2) FIB(2) FIB(1)

FIB(3) FIB(2) FIB(2) FIB(1) FIB(2) FIB(1) FIB(2) FIB(1)

FIB(2) FIB(1)

302
RECURSION
Fibonacci Series Using Recursion ― Program
int Fibonacci(int num)
{ if(num <= 2)
return 1;
return ( Fibonacci (num - 1) + Fibonacci(num – 2));
}
main()
{
int n;
printf(―\n Enter the number of terms in the series :
―); scanf(―%d‖, &n);
for(i=0;i<n;i++)
printf(―\n Fibonacci (%d) = %d―, i, Fibonacci(i));
} 303
RECURSION
Types Of Recursion
• Any recursive function can be characterized based on:
– whether the function calls itself indirectly
directly or (direct or indirect ).

– whether any operation is pending at each recursive


call (tail-recursive or not).

– the structure of the calling pattern (linear or tree-recursive).

Recursion

Direct Indirect Linear Tree Tail


304
RECURSION
Types of Recursion
– Direct Recursion
•A function is said to be directly recursive if it explicitly
calls itself.
•Example
int Func( int n)
{
if(n==0)
retrun n;
return
(Func(n-
1));
} 305
RECURSION
Types of Recursion
– Indirect Recursion
•A function is said to be indirectly recursive if it contains a call
to another function which ultimately calls it.
•Example
int Func1(int n) int Func2(int x)
{ {
if(n==0) return Func1(x-1);
return n; }
return
Func2(n);
}

•These two functions are indirectly recursive as they both call


each other.
306
RECURSION
• Types of Recursion
– Tail Recursion
• A recursive function is said to be tail recursive if no operations
are pending to be performed when the recursive function
returns to its caller.
• That is, when the called function returns, the returned value is
immediately returned from the calling function.
• Tail recursive functions are highly desirable because they are
much more efficient to use as in their case, the amount of
information that has to be stored on the system stack is
independent of the number of recursive calls.
RECURSION
• Types of Recursion
– Tail Recursion
• Example

int Fact(n) int Fact1(int n, int res)


{ {
return Fact1(n, 1); if (n==1)
} return res;
return
Fact1(n-1,
n*res);
}
RECURSION
• Types of Recursion
– Linear Recursion
• A recursive function is said to be linearly recursive when no
pending operation involves another recursive call to the
function.
• For example, the factorial function is linearly recursive as
the pending operation involves only multiplication to be
performed and does not involve another call to Fact.
int Fact(int)
{ if(n==1)
retrun 1;
return (n * Fact(n-
1));
}
RECURSION
• Types of Recursion
– Tree Recursion
• A recursive function is said to be tree recursive (or non-
linearly recursive) if the pending operation makes another
recursive call to the function.
• For example, the Fibonacci function Fib in which the
pending operations recursively calls the Fib function.
int Fibonacci(int num)
{
if(num <= 2)
return 1;
return ( Fibonacci (num - 1) +
Fibonacci(num – 2));
}
RECURSION
Pros and Cons of Recursion

Pros:
• Recursive solutions often tend to be shorter and simpler than
non-
recursive ones.
• Code is clearer and easier to use

• Recursion represents like the original formula to solve a problem.

• Follows a divide and conquer technique to solve problems

• In some (limited) instances, recursion may be more efficient

311
RECURSION
Pros and Cons of Recursion
Cons:
• Recursion is implemented using system stack. If the stack
space on the system is limited, recursion to a deeper level will
be difficult to implement.
• Aborting a recursive process in midstream is slow
sometimes nasty.
and
• Using a recursive function takes more memory and time
to execute as compared to its non-recursive counter part.
• It is difficult to find bugs, particularly when using
global variables

312
RECURSION
Limitations Of Recursion
• Recursive solutions may involve extensive overhead because
they use function calls.
• Each function call requires push of return memory address,
parameters, returned results, etc. and every function return
requires that many pops.
• Each time we make a call we use up some of our memory
allocation. If the recursion is deep that is, if there are many
recursive calls then we may run out of memory.

313
RECURSION
Towers Of Hanoi
• Tower of Hanoi is one of the main applications of a recursion. It says, "if
you can solve n-1 cases, then you can easily solve the nth case?"

A B C A B C

If there is only one ring, then move the ring from source to the
Destination

A B C
A B C A B C

If there are two rings, then first move ring 1 to the


spare pole and then move ring 2 from source to the
A B C
destination. Finally move ring 1 from the source to the
314
destination
RECURSION
Towers Of Hanoi
• Consider the working with three rings.

A B C A B C
A B C

A B C A B C A B C

A B C
A B C

315
PRE-PROCESSOR
• There are many steps involved in turning a C program into an
executable program. The first step is called pre-processing.
• The pre-processor performs textual manipulation on the source
code before it is compiled. There are a number of major parts to
this:
1. Deleting comments
2. Inserting the contents of files mentioned in #include directives
3. Defining and substituting symbols from #define directives
4. Deciding which code should be compiled depending on
conditional compiler directives
5. To act on recognized #pragma statements, which
are implementation dependent.
316
PRE-PROCESSOR
Predefined Symbols

_ _DATE_ _ provides a string constant in the form ―mm dd yyyy‖

_ _FILE_ _ provides a string constant containing the


name of the source file.

_ _LINE_ _ provides a string constant containing the current


statement number in the source file.

_ _TIME_ _ provides a string constant in the form hh:mm:ss

_ _STDC_ _ provides a integer constant with value 1 if and only


if the compiler confirms with ISO implementation.

317
PRE-PROCESSOR
Macro Substitution
• Definition:

#define name replacement text

This causes a simple macro substitution, each occurrence


of
name is replaced by replacement text.
• Example:

#define XDIM 10

causes all occurrences of XDIM to be replaced by the literal 10.

318
PRE-PROCESSOR

Macro Substitution
• The replacement text spreads over more than one line a
forward
slash(\) is used to indicate continuation.
• Example:

#define WHERE_AM_I printf("In file %s at line %d", \

FILE , LINE )

319
PRE-PROCESSOR
Macro Substitution
• Example

#define TWO_PLUS_J 2+j

Such substitutions should be undertaken with care as there may be


more than one j in scope.

If the following were to appear in the program:

int j=100;
i= TWO_PLUS_J;

After pre-processing, it would be:

int j=100;
i= 2+j;
320
PRE-PROCESSOR
Macro Substitution
• Example
#define TWO_PLUS_J 2+j
Such substitutions should be undertaken with care as there may
be more than one j in scope.
The programmer must realize that the replacement text is used
exactly.
5* TWO_PLUS_J
will after pre-processing be:
5* 2+j
which might not be what the programmer expected?
321
PRE-PROCESSOR
Macros
• A macro allows parameters to be used in substitution text.
• Syntax

#define name(parameters) code


The bracket of the parameter list must be next to the
name, otherwise it will be part of the code substituted.
• Example
#define SQUARE(x) x*x
x= SQUARE(5); → x= 5*5;
y= SQUARE(x); → y=
z= SQUARE(2.5); → x*x;
10+SQUARE(5); z=
10+5*5 322
PRE-PROCESSOR
Conditional Compilation

• Conditional compilation provides a way where by code can be


selectively included into the compilation - depending on values
available at pre-processing.
• Syntax:
#if constant expression
…..
statements
......
#endif

323
PRE-PROCESSOR
Conditional Compilation:
— The pre-processor evaluates the constant expression if it is
zero (false) the statements are deleted from the code passed to
the compiler, if the constant expression is non-zero (true) the
statements are passed to the compiler.
— The constant expression is made up of literals and variables
that have been defined using a #define.
— It is illegal to use anything where the value will not be known
until execution time, as the compiler is unable to predict the
values.
324
PRE-PROCESSOR
Conditional Compilation
• A simple example is to bracket the code used for debugging in
the following manner:
#if DEBUG
printf("At line %d: a=%d, b=%d\n", LINE ,a,b);
#endif
• Therefore, the listing may contain many instances of this
conditional inclusion, protecting the printing of interesting
variables.

325
PRE-PROCESSOR
Conditional Compilation
— If the following is present:

#define DEBUG 1

then at compile time, all the debugging print statements will


be included in the object code produced.
— Whereas if the definition is:

#define DEBUG 0

none of the debug statements will be included in the


object code generated.

326
PRE-PROCESSOR

Conditional Compilation
• Conditional compilation is also useful if developing a software
product that has different functionality depending on whether
the user has purchased the full version, the economy version or
is trying a cover disc sample.
•A single set of code can exist for all versions. Where there is
functionality, that is available, differs between versions then
the code can be delimited within a conditional inclusion.
• This can be achieved using this enumeration and definition.

327
PRE-PROCESSOR

Conditional Compilation
• Example
enum VERSION {FULL, ECONOMY, SAMPLE};
#define VERSION FULL
in conjunction with conditional compilations of the
following sort:
#if (VERSION == FULL) \\statements for full
implementation
#elif(VERSION == ECONOMY) \\statements for
economy implementation
#else \\statements for sample implementation
#endif

328
PRE-PROCESSOR
Conditional Definitions
•The #ifdef command conditionally includes code if a symbol
is defined.
•If the symbol is not defined, the code is not included.
•The opposite command is #ifndef which includes code only if the
symbol is not defined.
•For example, if the program includes a library file that, in some
implementations, does not define a symbol.

329
PRE-PROCESSOR
Conditional Definitions
• MAXLINES, then the program may have a fragment like this:
1: #include <somelib.h>
2: #ifndef MAXLINES
3: #define MAXLINES 100
4: #endif
– Line 1 includes the library, which may vary between
machines.
– Line 2 checks if MAXLINES is already defined. If it isn't
defined then Line 3 defines it.
– Line 4 is the end of the conditional definition.
330
PRE-PROCESSOR
Conditional Definitions
• This is necessary as it is not possible to define the
same symbol twice.
• Analternative would be to undefined the symbol and
then redefine it, for example:
#undef MAXCHARS
#define MAXCHARS 60

331
PRE-PROCESSOR
Pragma
• The #pragma command is a mechanism that
supports implementation dependent directives.
• An environment may provide pragma to allow special options.
Where a pragma is not recognized, it is ignored.
• Program with pragma will run on different machines.
• The actions of the pragma may not be the same
across
machines, so the program is not truly portable.
• Pragma is used in a number of ways by C++ Builder.

332
PRE-PROCESSOR

Pragma
• Example:

when generating forms, the corresponding unit will contain code


like:

#pragma resource "*.dfm"

This is equivalent to: {$R

*.DFM} Error command

The error command is of the form

# error message
333
It is used to print the message
Pointer

• A pointer is a constant or variable that contains an address that can be used


to access data.
(or)
A pointer is a variable that contains the memory location of another variable.

• Pointers deals with memory address, it can be used to access manipulate


and data stored in memory.
‗*‘ And ‗&‘
Operators

• When is * used?
*‖dereferencing operator‖ which provides the contents in the memory
location specified by a pointer.

• when is & used?


&‖address operator‖ which gives or produces the memory address of a data
variable.

• verify the following declaration


int x=10;
• In the above statement the c compiler reserve the memory space for the integer
value
Use of & and *

Name this memory location as x.

Store the value 10 at the location 65325.


Use of & and *
• When we declared an integer variable x and assigned value 10
then compiler occupied a 2 byte memory space at memory
address 65325 and stored value 10 at that location.
• Compiler named this address x so that we can use x
instead of 65325 in our program
address of variable example
Line 1: #include<stdio.h>
Line 2: #include<conio.h>
Line 3: void main()
Line 4: {
Line 5: int i=9;
Line 6: clrscr();
Line 7: printf("
Line 8: Value of
Line 9: i : %d\
Line 10: n",i);
printf("
Address
of i :
%u",&i
);
Use of & and *
• This is a very simple c program which prints value and address of an integer.

• But did you notice line no. 8 in above program?

• This line output the address of i variable and to get address of i variable we
have used ampersand (&) operator.
• This operator is known as "Address of" operator and we already used this
operator many times in our program, just recall scanf statement which is used
to accept input from computer keyboard.
• So when we use ampersand operator (&i) before any variable then we are
instructing c compiler to return its address instead of value.
• Another operator is "*" called "Value at address" operator. It is the same
operator which we use for multiplication of numbers.
Use of & and *
• As the name suggest, "value at address" operator returns value
stored at particular address.
• The "value at address" operator also called indirection operator.
• Following example extends above C program and puts "value at
address" operator in action.
Value at address (*) example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=9;
clrscr();
printf("Value of i : %d\n",i);
printf("Address of i : %u\n",&i);
printf("Value at address of i : %d",*(&i));
getch();
}
Benefits of using Pointer in C Program
• Pointer is one of the most exciting features of C language and it has
added power and flexibility to the language.
• Pointer is in C language because it offers following benefits to the
programmers:

1. Pointers can handle arrays and data table efficiently.


2.Pointers support dynamic memory management.
3. Pointer helps to return multiple values from a function through function
argument.
4. Pointer increases program execution speed.
5. Pointer is an efficient tool for manipulating structures, linked lists, queues
stacks etc
Pointer Declaration

Example on how we can use pointer in our C


program.

Syntax: datatype

*pointer_name; Example :

int *iPtr; float *fPtr;


float *fPtr;
Pointers for inter function communication

There are two ways to be discussed with pointers, for inter


function communication among pointers.
1. call by value
2. call by reference

Call By Value:

In this mechanism a variable is declared and defined in the called function


for each value to the called function.
It means it is one –way communication.
The calling function can send data to the called function, ut the called
function cannot send data to the calling function.
Explanation:
• In the above program, two data items are passed from main to the
down function.
• One data value is a literal, the other is the value of a variable.
• Downward communication or the call by value is the one way
communication.

Call by reference:
• This method is also called as pass by reference or upward
communication.
• Here in this method instead of passing the values of the variables to the
called
• Function.
• We pass their addresses so that the called function can change the
values stored
• In the calling routine.
Fig : An Unworkable Exchange
Fig: Exchange Using Pointers
Pointers to Pointers
Pointers to pointers is using of pointers that point to other
pointers

Fig: Pointers to Pointers


Fig: Using Pointers to
Pointers
Explanation:
• Each level of pointer indirection requires a separate indirection operator
when it is dereference.
• In the above example, to refer to variable a using the pointer p, we have to
dereference it once. i.e.*p.
• To refer to variable a using the pointer q, we have to dereference it twice to
get the integer a because
• There are two levels of indirection (pointers) invoked. i.e.**q.
Compatibility:
• Pointer have a type associate with it.
• They are not just pointer types but rather are pointers to a specific type
• Such as character.
• Each pointer therefore takes on the attributes of the type to which it refers
• in addition to its own attributes.
Types Of Compatibility:

• Pointer Size Compatibility.


• Déréférence Type Compatibility.
• Dereference Level Compatibility.
Pointer size compatibility:
The size of all pointers is same.
Every pointer holds the address of one memory location in the computer.
Size of the variable that the pointer references can be different.

Trace the following example:


int a;
int *p; printf(―
%d‖,sizeof(a)); printf(―
%d‖,sizeof(p)); printf(―
%d‖,sizeof(*p));
Dereference type compatibility:
• The dereference type compatibility is the type of the variable that the
pointer is referencing.
• In C, we can‘t use the assignment operator with pointers to different types;
• If we try to, we get a compile error.
• We cannot assign one type of pointer to another type of pointer.
• A pointer to a char is only compatible with a pointer to a char
• And a pointer to an int is only compatible with a pointer to an int.
• We cannot assign a pointer to a char to a pointer to an int.
Construct an example in which we have two variables:
one int and one char
We also define one pointer to char and one pointer to int as shown in the
below Figure.

char
c; char*
pc;

int a;
int *
pa;
pc=&c; //are valid
//are valid
pa=&a;
type: pointer to char

123450
123450 z
pc c
type: pointer to int

234560 58
234560
pa a
pc=&a; //error: different types
//error: different levels
pa=&a;
The first pair of assignments are valid, we store the address of a
character variable in a pointer to character variable.

In the second assignment, we store the address of an integer(int)


variable in a pointer to an integer(int) variable.

There is an error in the third assignment because we try to store


the address of a character variable into a pointer variable
whose type is pointer to pointer to integer(int).

We also get an error in the fourth assignment.


Dereference level compatibility

Compatibility also includes dereference level compatibility.

For example, a pointer to int is not compatible with a pointer-to-


pointer to int.

The pointer to int has a reference type of int, while a pointer-to-


pointer to int has a reference type of pointer to int.
• The following figure shows two pointers declared at different
levels.
The pointer pa is a pointer to
• int;
The pointer ppa is a pointer-to-pointer to
int.

a
ppa pa

int a; //type int

int b; //type int

int* pa; //type pointer to int

int** ppa;// type pointer to pointer to int

pa=&a;//valid : same level



ppa=&pa; //valid : same level

b=**pa; //valid : same level

pa=&a;//invalid: different level



ppa=pa ;//invalid: different level

b=*ppa; //invalid: different level
Pointer to void

The exception to the reference type compatibility rule is the pointer to void.

A pointer to void is a generic type that is not associated with a reference type;
that is, it is not the address of a character , an integer, a real, or any other
type.

One restriction, void pointer has no object type, it cannot be


dereferenced unless it is cast.

The following declaration shows how we can declare a variable of pointer


to
void type.
void* pvoid;

It is important to understand the difference between a null pointer and a


variable pointer to void.
A null pointer is a pointer of any type that is assigned the constant NULL.

The reference type of the pointer will not change with the null assignment.

A variable of pointer to void is a pointer with no reference type that can store
only the address of any variable.

The following example shows the difference

void* pvoid; //pointer to void type

int* pint=NULL; //NULL pointer of type int

char* pchar=NULL; //NULL pointer of type

char A void pointer cannot be dereferenced.


• Casting pointers

The problem of type incompatibility can be solved by using casting.

For example, if we need to use the char pointer, pc in the previous example,
to
point to an int(a), we could cast it as shown below

int* pc;

pc=(char*)&a;
• Lvalue and rvalue
• Every expression has a value.
• The value of the expression after evaluation can be used in two
ways:
(i) lvalue
(ii) rvalue
• Lvalue: It is used whenever the object is receiving a value,
it is being modified.
• Rvalue: it is used to supply a value for further use.
• What does=(equal to) really
mean? int f(void)
{
int
s=1; int
t=1;
t=s;
t=2;
• Left side of = is an ―lvalue‖
• it evaluates to a location(address)!
• Right side of= is an ―rvalue‖
• it evaluates to a value
• There is an implicit * when a variable is used as an
rvalue!
Arrays and Pointers

• The name of an array is a pointer constant to the first element.

• Because the array‘s name is a pointer constant, its value cannot be changed.

• Since the array name is a pointer constant to the first element,

• the address of the first element and the name of the array both represent
the same location in memory.
Pointers to
Arrays

FIGURE Pointers to
Arrays
Pointers to
Arrays
same
a &a[0]
• a is a pointer only to the first element—not the whole array.

The name of an array is a pointer it cannot be used as an


constant; lvalue.
Dereference of Array
Name

Dereference of Array
Name
Array Names as Pointers

Array Names as Pointers


Multiple Array
Pointers

Multiple Array Pointers

To access an array, any pointer to the first element can be used instead of the
name of the array.
Pointer Arithmetic and
Arrays
• Given pointer, p, p ± n is a pointer to the value n elements away.

Pointer
Arithmetic
Pointer
Arithmetic a+n

a + n * (sizeof (one element))

Pointer Arithmetic and Different


Types
Dereferencing Array Pointers

Dereferencing Array
Pointers

The following expressions are identical.*(a + and


n) a[n]
Arithmetic Operations on Pointers

Pointers and Relational Operators


FIGURE (Part I) Find
Smallest
FIGURE (Part II) Find Smallest
Pointers And Two-dimensional
Arrays
POINTERS AND TWO DIMENSIONAL
ARRAY
• Individual elements of the array mat can be accessed
using either: mat[i][j] or *(*(mat + i) + j) or*(mat[i]+j);
• See pointer to a one dimensional array can be declared as,
int arr[]={1,2,3,4,5};
int *parr;

parr=arr;
• Similarly, pointer to a two dimensional array can be declared as,
int arr[2][2]={{1,2},{3,4}};
int (*parr)[2];
parr=arr;
• Look at the code given below which illustrates the use
of a pointer to a two dimensional array.
• #include<stdio.h>
main()
{ int arr[2]
[2]={{1,2}.{3,4}};
int i, (*parr)[2];
parr=arr;
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
printf(" %d", (*(parr+i))[j]);
}
}
OUTPUT
1234
Passing an Array to a
Function
• The name of an array is actually a pointer to the first element,
we can send the array name to a function for processing.
• When we pass the array, we do not use the address operator.
• Remember, the array name is a pointer constant, so the name is
already the address of the first element in the array.
FIGURE Variables for Multiply Array Elements
By 2
Memory Allocation Functions
C gives us two choices when we want to reserve memory locations
for an object: static allocation and dynamic allocation.
Static memory allocation:
• It requires that the declaration and definition of memory be
fully
• specified in the source program.
The number of bytes reserved cannot be changed during runtime.

Dynamic memory allocation:


• It uses predefined function to allocate and release memory for
data while the program is running.
• It effectively postpones the data definition, but not the data
declaration, to run time.
FIGURE Accessing Dynamic
Memory
MEMORY
We can refer to memory allocated in the heap only through a
USAGE
pointer.

Dynamic memory allocation has no identifier associated with it;


it has only an address that must be used to access it.

To access data in dynamic memory, therefore, we must use a


pointer.

FIGURE A Conceptual View of


Memory
Memory management functions
There are four memory management functions used with dynamic
memory.
They are:
(i) malloc(
)
(ii)calloc()
(iii)realloc(
) (iv)free()

Malloc():
• Block
memory
allocatio
n is
Malloc
function.
• The Malloc function allocates a block of memory that contains
FIGURE malloc
The malloc function declaration is as shown below.
Void* malloc(size_t size);
the type, size_t, is defined in several header files including
stdio.h. The processed data finds a place in a heap rather than
stack.
The contents of the heap should be free immediately after
operation.
For example:
void* malloc(size_t
size); main()
{
int *p;
p=(int*)malloc(sizeof(int)
);
*p=60;

printf(―*p=%d‖,*p);
printf(―*p=%u‖,p);
calloc(): It is contiguous memory allocation function.
It is primarily used to allocate memory for arrays.
• It differs from malloc only in that it sets memory to null
characters. The calloc function declaration is shown below.
void *calloc(size_t element_count,size_t element_size);
• The result is the same for both malloc() and calloc() when
overflow occurs and when a zero size is given.

• Realloc(): realloc is the reallocation of


memory . The operation of realloc() is as shown
below:
void *realloc(void*
ptr,size_t,newsize); realloc() is highly
inefficient.
It changes the size of the block by deleting or extending the
memory at the end of the block.
• If the memory cannot be extended because of other
allocations, realloc() allocates a completely new block, copies
the existing memory allocation to the new allocation, and
deletes the old allocation.
• For example:
ptr=realloc(ptr,15*sizeof(int))
;
Free():
it is used for releasing memory.
It is an error:
(1) To free memory with a NULL pointer.
(2) A pointer to other than the first element of an allocated
block. (3)A pointer that is different type than the pointer that
allocated the memory.
(4)Referring to a memory after releasing it, which is a logical
error.
void free(void* ptr);

Releasing memory doesn't change the value in a pointer.


It still contains the address in a heap.
Immediately after freeing the memory, the pointer should be
cleared by setting it to NULL.
The pointer used to free memory must be of the same type as a
pointer used to allocate the memory.
• Array of pointers
Array name itself is an address or pointer.
• Name of an array indicates the address of the first cell.
• The address of the first byte is often known as base
address. Arrays are stored in contiguous memory location.
• This structure is especially helpful when the number of
elements in
the array is variable.
Syntax declaration:
<type> *variable_name[size];

Example:
int *pa[5];

Here, pa is a 5 element array of pointers to integer


quantities.
FIGURE A Ragged
Array
• #include<stdio.h>
void main()
{
double a,b,c;
double
*pa[5];
clrscr();
a=2.3;
b=6.7;
c=1.3;
pa[0]=&a;
pa[1]=&b;
pa[2]=&c;
printf("\n a=%lf",a);
printf("\n b=%lf",b);
printf("\n c=
%lf",c);}
PROGRAMMING APPLICATIONS
pointers can be used with:
(i)arrays
(ii)functions
(iii)pointers
(iv)structures
(v)dynamic
memory
allocation

POINTER
TO VOID
• The
exception to
the reference
type
compatibility
• The following declaration shows how we can declare a variable
of pointer to void type.
void* pvoid;

It is important to understand the difference between a null pointer


and a variable pointer to void.
• A null pointer is a pointer of any type that is assigned the
constant NULL.

The reference type of the pointer will not change with the null
assignment.

A variable of pointer to void is a pointer with no reference type


that can store only the address of any variable.
• The following example shows the difference

void* pvoid; //pointer to void type

int* pint=NULL; //NULL pointer of type

int char*pchar=NULL; //NULL pointer of type

char A void pointer cannot be dereference.


UNIT-4
Structures and Unions
Definition

A structure is a collection of related elements, possibly of


different types, having a single name.

Syntax:

struct tag_name
{
data type
var_name1; data
type var_name2;
data type
var_name3;
};
Structur
Example:
struct student
es
{
int id;
char
name[10];
float
gradepoint;
};

•struct introduces the


definition for structure
student

•student is the
structure name and is
used to declare
variables of the
structure type
Structur
es
Note
Elements in a structure can be of the same or different types.
However, all elements in the structure
should be logically related.
Structur
es

FIGURE Tagged Structure


Format
Structur
es
Initializing a Structure
Example:
struct student
{
int mark;
char
name[10];
float
average;
} struct student
report;

struct student report


= {100, “Mani”,
99.5};
Structur
es
Accessing structures
•Dot operator is used to access members of a
structure.

Example
struct
student
{
int
mar
k;
cha
r
na
me[
10];
floa
t
ave
Structur
es

FIGURE Structure Direct Selection


Operator
Example
Structur
#include
<stdio.h> es
#include
{
<string.h>
int id;
struct student
char
name[20];
float
} record;
int percentage;
{main() record.id=1;
strcpy(record.name,
"Raju"); record.percentage
= 86.5; printf(" Id is: %d \
n", record.id);
printf(" Name is: %s \n",
record.name);
} printf(" Percentage is: %f \n",
record.percentage); return 0;
PROGRAM 12- Multiply
2 Fractions
Structur

es
Operations on Structures

•Assigning a structure to a structure of the same type

•Taking the address (&) of a structure

•Accessing the members of a structure

•Using the sizeof operator to determine the size of a


structure
Structur
Nested
es
structures
• Nested structure in C is nothing but structure within structure.

• One structurecan be declared inside other structureas we declare


structure
members inside a structure.

• The structure variables can be a normal structure variable or a pointer


variable to access the data.

1.Structure within structure in C using normal


variable

2.Structure within structure in C using pointer


variable
#include <stdio.h>
#include <string.h>

struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail
clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,
"Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);

printf(" College Id is: %d \n", stu_data.clg_data.college_id);


printf(" College Name is: %s \n",
stu_data.clg_data.college_name); return 0;
}
Structur
es
Pointers in a structures

• Structure may contain the pointer variable as


member

•Pointer are used to store address of memory


location

•They can be derefenced by the „*‟ operator


Structur
Pointers in a
structures
es

FIGURE Pointers in
Structures
Structur
es
•Structures and functions

•Structure can be passed to a function as a


parameter

•Functions can also have a structure as return


type
Structur
•Structures and es
functions

FIGURE Passing Structure Members to


Functions
PROGRAM 12-5 Passing and Returning
Structures
PROGRAM 12-5 Passing and Returning
Structures
PROGRAM 12-5 Passing and Returning
Structures
PROGRAM 12-5 Passing and Returning
Structures
PROGRAM Passing and Returning
Structures
Structur
•Structures and es
functions

FIGURE Passing Structures Through


Pointers
Structur
es
Pointer s to structures

Dot(.) operator is used to access the data using normal structure


variable and arrow (->) is used to access the data using pointer
variable.

Note

(*pointerName).fieldName  pointerName->fieldName.
Structur
Pointer s to es
structures
Example:
struct student
{
int mark;
char
name[10];
float
average;
};
struct student *report, rep;
struct student rep = {100, “Mani”,
99.5}; report = &rep;
report -> mark
report ->
name report -
> average
FIGURE Interpretation of Invalid Pointer
Use
#include
<stdio.h>
#include
<string.h>
struct student
{
int id;
char
name[30];
float
percentage;
};
int main()
{int i;
struct student record1 = {1, "Raju",
90.5}; struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \
n"); printf(" Id is: %d \n",
ptr->id);
printf(" Name is: %s \n",
ptr->name);
printf(" Percentage is: %f \n\n", ptr-
>percentage); return 0;
PROGRAM Clock Simulation with
Pointers
PROGRAM Clock Simulation with
Pointers
PROGRAM Clock Simulation with
Pointers
Complex Structures

 Nested Structures
 Self referential
structures
 A structure may have

Data variables

Internal
structures/unions

Pointer links

Function pointers
Structur
es
Self-Referential Structures

• Self-referential structures contain a pointer member that


points to a structure of the same structure type.
Example:
struct node {
int data;
struct
node
*nextPt
r;
}
• nextPtr
– is a pointer member that points to a structure of the
same type as the one being declared.
– is referred to as a link. Links can tie one node to
Union
Definition:
s
The union is a construct that allows memory to be shared by
different types of data. This redefinition can be as simple as
redeclaring an integer as four characters or as complex as
redeclaring an entire structure.

Syntax:
union tag_name
{
data type
var_name1; data
type var_name2;
data type
var_name3;
};
Union
s

FIGURE A Name
Union
PROGRAM 12- Demonstrate Effect of
7 Union
Bit
Field
• The variables defined with a predefined width are called
bit fields.

• A bit field can hold more than a single bit.

•for example if you need a variable to store a value


from 0 to 7 only then you can define a bit field with a
width of 3 bits .

Bit Field Declaration


the declaration of a bit-field has the form inside a
structure:
struct
{
type [member_name] : width ;
};
Bit
Field
Below the description of variable elements of a
bit field:

Elements Description
type An integer type that determines how the bit-field's value is
interpreted. The type may be int, signed int, unsigned int.
member_nam The name of the bit-field.
e
width The number of bits in the bit-field. The width must be less than or
equal to the bit width of the specified type.

Bitfi led.t
xt
Structur
es
 Type Definition (typedef)

A type definition, typedef, gives a name to a data type by


creating a new type that can then be used anywhere a type is
permitted.
Structur
es
Enumerated Types
The enumerated type is a user-defined type based on the
standard integer type. In an enumerated type, each integer value is
given an identifier called an enumeration constant.

Syntax:
enum identifier {value1, value2,.... Value n};

•enum is Enumerated Data


Type . enum is user defined
data type
•In the above example
“identifier” is nothing but the
user defined data type .
•Value1,Value2,Value3….. etc
creates one set of enum
values. Enum.t
xt
Memory Allocation Functions

C gives us two choices when we want to reserve memory locations


for
an object: static allocation and dynamic allocation.
static memory allocation:
It requires that the declaration and definition of memory be fully
specified in the source program.
The number of bytes reserved cannot be changed during runtime.
Dynamic memory allocation:
It uses predefined function to allocate and release memory for
data while the program is running.

It effectively postpones the data definition, but not the data


declaration, to run time.
MEMORY USAGE
We can refer to memory allocated in the heap only through a pointer.

Dynamic memory allocation has no identifier associated with it; it


has only an address that must be used to access it.

To access data in dynamic memory, therefore, we must use a pointer.


Memory management functions
There are four memory management functions used with dynamic
memory.
They are:
(i) malloc
()
(ii)calloc()
(iii)realloc(
) (iv)free()

Malloc():
Block
memory
allocation is
Malloc
function.
The Malloc function allocates a block of memory that contains
the number of bytes specified in its parameter.
The malloc function declaration is as shown below.
Void* malloc(size_t size);
the type, size_t, is defined in several header files including
stdio.h. The processed data finds a place in a heap rather than
stack.
The contents of the heap should be free immediately after
operation.
For example:
void* malloc(size_t
size); main()
{
int *p;
p=(int*)malloc(sizeof(int)
);
*p=60;

printf(―*p=%d‖,*p);
printf(―*p=%u‖,p);
calloc(): It is contiguous memory allocation function.
It is primarily used to allocate memory for arrays.
• It differs from malloc only in that it sets memory to null
characters. The calloc function declaration is shown below.
void *calloc(size_t element_count,size_t element_size);
• The result is the same for both malloc() and calloc() when
overflow occurs and when a zero size is given.

• Realloc(): realloc is the reallocation of


memory . The operation of realloc() is as shown
below:
void *realloc(void*
ptr,size_t,newsize); realloc() is highly
inefficient.
It changes the size of the block by deleting or extending the
memory at the end of the block.
• If the memory cannot be extended because of other
allocations, realloc() allocates a completely new block, copies
the existing memory allocation to the new allocation, and
deletes the old allocation.
• For example:
ptr=realloc(ptr,15*sizeof(int))
;
Free():
it is used for releasing memory.
It is an error:
(1) To free memory with a NULL pointer.
(2) A pointer to other than the first element of an allocated
block. (3)A pointer that is different type than the pointer that
allocated the memory.
(4)Referring to a memory after releasing it, which is a logical
error.
void free(void* ptr);

Releasing memory doesn't change the value in a pointer.


It still contains the address in a heap.
Immediately after freeing the memory, the pointer should be
cleared by setting it to NULL.
The pointer used to free memory must be of the same type as a
pointer used to allocate the memory.
UNIT-5
FILES
File:
A file represents a sequence of bytes on the
disk where a group of related data is stored.
File is created for permanent storage of data.
It is a ready made structure.
File I/O Streams in C Programming Language :

• In C all input and output is done with streams


• Stream is nothing but the sequence of bytes of data
• A sequence of bytes flowing into program is called input
stream
• A sequence of bytes flowing out of the program is called
output stream
• Use of Stream make I/O machine independent.
Basic File Operations

• Creating a new file


• Opening an existing file
• Reading from and writing information to a file
• Closing a file
CREATING A FILE

• Working with file


• While working with file, you need to declare a
pointer of type file. This declaration is needed
for communication between file and
program.
• FILE *ptr;
Opening a file

• Opening a file is performed using library


function fopen(). The syntax for opening a file
in standard I/O is:
• ptr=fopen("fileopen","mode") For Example:
fopen("E:\\cprogram\program.txt","w");
Closing a File

• The file should be closed after reading/writing


of a file. Closing a file is performed using
library function fclose().
• fclose(ptr); //ptr is the file pointer associated
with file to be closed.
Reading and writing of a binary file.

• Functions fread() and fwrite() are used for reading from and
writing to a file on the disk respectively in case of binary files.
• Function fwrite() takes four arguments, address of data to be
written in disk, size of data to be written in disk, number of
such type of data and pointer to the file where you want to
write.
• fwrite(address_data,size_data,numbers_data,pointer_to_file
);
File Types

• 1) Ordinary Files or Simple File


• 2) Directory files
• 3) Special Files
• 4) FIFO Files:
FILE OPENING MODES
FILE INPUT AND OUTPUT
FUNCTIONS
FILE STATUS FUNCTIONS

• stat, fstat, lstat - get file status


• These functions return information about a file. No
permissions are required on the file itself, but-in the case of
stat() and lstat() - execute (search) permission is required on
all of the directories in path that lead to the file.
• stat() stats the file pointed to by path and fills in buf.
• lstat() is identical to stat(), except that if path is a symbolic
link, then the link itself is stat-ed, not the file that it refers to.
• fstat() is identical to stat(), except that the file to be stat-ed is
specified by the file descriptor fd.
FILE POSITIONING FUNCTIONS
• The C library function int fseek(FILE *stream, long int offset, int whence) sets the
file position of the stream to the given offset.
• Declaration
• Following is the declaration for fseek() function.
• int fseek(FILE *stream, long int offset, int whence) Parameters
• stream − This is the pointer to a FILE object that identifies the stream.
• offset − This is the number of bytes to offset from whence.
• whence − This is the position from where offset is added. It is specified by one of
the following constants −
• Constant Description SEEK_SET Beginning of file SEEK_CUR Current position of the
file pointer SEEK_END End of file
Command Line Argument
• Command line argument is a parameter supplied to the
program when it is invoked. Command line argument is an
important concept in C programming. It is mostly used when
you need to control your program from outside. command
line arguments are passed to main() method.
• Syntax :
• int main( int argc, char *argv[]) Here argc counts the number
of arguments on the command line and argv[ ] is a pointer
array which holds pointers of type char which points to the
arguments passed to the program.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy