Introduction to C
Introduction to C
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.
MEMORY
Types of
Software:
System Software
• 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.
14
Computing Environments
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
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
• 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
Start
Read A
Read B
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
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)
• 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
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
Defined constants
Memory Constants
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
Real
– Real type holds values that consists of
integral and fractional part.
– C support types float and double.
– Real type values are always signed.
float 4
double 8
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
8
8
Basic Input - Output
• printf function converts data stored in program into a text stream for
output to the monitor.
• 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.
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.
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
• 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.
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:Unary Expressions
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
Fig:Left-to-Right Associativity
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
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
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;
• 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.
―Array name
―Position number
• Syntax:
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
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
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
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.
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
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
str
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 : 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‖;
Syntax:
strncpy(dest,source,n);
Ex:
s1=―come‖;
s2=―gone‖;
strncpy(s2,s1,2);
output:
s2= ―co‖;
String Manipulation Functions
Syntax:
strcmp(string1,string2);
Ex: s1=―their‖;
s2=―there‖;
strcmp(s1,s2);
Output: -9
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
Syntax:
strstr(string1,string2);
Ex:
S1=―computer
engg‖; S2=―engg‖;
strstr(s1,s2);
Output: engg
String Manipulation Functions
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.
217
FUNCTIONS
Calling Function
Called Function
Function Definition
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;
} }
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
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.
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
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.
236
FUNCTIONS
Passing Parameters To The Function
— Call By Reference
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.
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.
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
– 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
25
4254
FUNCTIONS
Inter-function Communication
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
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
27
2
271
STORAGE CLASSES
• Object Storage Attributes
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
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:
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
Storage – Memory.
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
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
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(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 ).
Recursion
Pros:
• Recursive solutions often tend to be shorter and simpler than
non-
recursive ones.
• Code is clearer and easier to use
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
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
317
PRE-PROCESSOR
Macro Substitution
• Definition:
#define XDIM 10
318
PRE-PROCESSOR
Macro Substitution
• The replacement text spreads over more than one line a
forward
slash(\) is used to indicate continuation.
• Example:
FILE , LINE )
319
PRE-PROCESSOR
Macro Substitution
• Example
int j=100;
i= TWO_PLUS_J;
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
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
#define DEBUG 0
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:
# error message
333
It is used to print the message
Pointer
• When is * used?
*‖dereferencing operator‖ which provides the contents in the memory
location specified by a pointer.
• 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:
Syntax: datatype
*pointer_name; Example :
Call By Value:
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
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.
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
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.
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.
• Because the array‘s name is a pointer constant, its value cannot be changed.
• 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.
Dereference of Array
Name
Array Names as 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))
Dereferencing Array
Pointers
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.
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.
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;
The reference type of the pointer will not change with the null
assignment.
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;
};
•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
Example
struct
student
{
int
mar
k;
cha
r
na
me[
10];
floa
t
ave
Structur
es
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);
FIGURE Pointers in
Structures
Structur
es
•Structures and functions
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
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.
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)
Syntax:
enum identifier {value1, value2,.... Value n};
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.
• 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