PPS-course Notes
PPS-course Notes
UNIT –I
Introduction to computers and Problem Solving: Components of a computer, Operating system,
compilers, Program Development Environments, steps to solve problems, Algorithm, Flowchart /
Pseudocode with examples.Introduction to programming: Programming languages and generations,
categorization of high-level languages.Introduction to C: Introduction, structure of C program,
keywords, identifiers, Variables, constants, I/O statements, operators, precedence, and associativity.
UNIT –II
Introduction to decision control statements: Selective, looping, and nested statements.Functions:
Introduction, uses of functions, Function definition, declaration, passing parameters to functions,
recursion, scope of variables and storage classes, Case study using functions and control statements.
UNIT –III
Arrays: Introduction, declaration of arrays, accessing and storage of array elements, 1-dimensional
array, Searching (linear and binary search algorithms) and sorting (Selection and Bubble)
algorithms, 2-D arrays, matrix operations.Strings: Introduction, strings representation, string
operations withexamples. Case study using arrays.
UNIT –IV
Pointers: Understanding computer’s memory, introduction to pointers, declaration pointer variables,
pointer arithmetic, pointers and strings, array of pointers, dynamic memory allocation, advantages,
and drawbacks of pointers.Structures: Structure definition, initialization and accessing the members
of a structure, nested structures, structures and functions, self-referential structures, unions, and
enumerated data types.
UNIT-V
Files: Introduction to files, file operations, reading data from files, writing data to files, error
handing during file operations.Preprocessor Directives: Types of preprocessor directives, examples.
1
Text Books:
1.M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India Learning Private
Limited 2018
2.Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall ofIndia.
Online Resources:
1.https://www.tutorialspoint.com/cprogramming/index.htm.
2.https://onlinecourses.nptel.ac.in/noc18-cs10/preview
Syllabus:https://www.cbit.ac.in/wp-content/uploads/2019/04/CBIT-CSE-R20-I-and-II-Semesters-
Syllabus-2020-21.pdf
2
UNIT I
COMPONENTS OF A COMPUTER
o Input Devices
o CPU
o Output Devices
o Primary Memory
o Secondary Memory
1) Inputting: It is the process of entering raw data, instructions and information into the
computer. It is performed with the help of input devices.
2) Storing: The computer has primary memory and secondary storage to store data and
instructions. It stores the data before sending it to CPU for processing and also stores the
processed data before displaying it as output.
3) Processing: It is the process of converting the raw data into useful information. This process
is performed by the CPU of the computer. It takes the raw data from storage, processes it and
then sends back the processed data to storage.
4) Outputting: It is the process of presenting the processed data through output devices like
monitor, printer and speakers.
5) Controlling: This operation is performed by the control unit that is part of CPU. The control
unit ensures that all basic operations are executed in a right manner and sequence.
Operatingsystem:
3
In the Computer System (comprises of Hardware and software), Hardware can only understand
machine code (in the form of 0 and 1) which doesn't make any sense to a naive user.
We need a system which can act as an intermediary and manage all the processes and resources
present in the system.
The purpose of an operating system is to provide an environment in which a user can execute
programs in convenient and efficient manner.
Compilers:
o A compiler is a translator that converts the high-level language into the machine
language.
o High-level language is written by a developer and machine language can be understood
by the processor.
o Compiler is used to show errors to the programmer.
o The main purpose of compiler is to change the code written in one language without
changing the meaning of the program.
o When you execute a program which is written in HLL programming language then it
executes into two parts.
o In the first part, the source program compiled and translated into the object program (low
level language).
o In the second part, object program translated into the target program through the
assembler.
4
Compilation Process in C:
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into an
executable form:
o Preprocessor
o Compiler
o Assembler
o Linker
5
Preprocessor
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file in
DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the
name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code of
our program. Sometimes the situation arises when our program refers to the functions defined in
other files; then linker plays a very important role in this. It links the object code of these files to
our program. Therefore, we conclude that the job of the linker is to link the object code of our
6
program with the object code of the library files and other files. The output of the linker is the
executable file. The name of the executable file is the same as the source file but differs only in
their extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the
executable file can be named as 'a.out'. For example, if we are using printf() function in a
program, then the linker adds its associated code in an output file.
ProgramDevelopmentEnvironments:
The development environment helps the developers to develop the application or product using
a set of processes and programming tools.
An development environment provides developers an interface and convenient view of the
development process which includes writing code, testing the same and packaging the build so
that it can be deployed.
Ex:
Microsoft Visual Studio
Turbo C/C++
Dev C/C++
Flowchart:
Flowchart is a diagrammatic representation of sequence of logical steps of a program.
Flowcharts use simple geometric shapes to depict processes and arrows to show relationships
and process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
7
Stands for decision statements in a program,
where answer is usually Yes or No.
Decision
Examples:
Here is a flowchart to calculate the average of two numbers.
What is Language?
Language is a mode of communication that is used to share ideas, opinions with each other.
For example, if we want to teach someone, we need a language that is understandable by both
communicators.
Low-level language is machine-dependent (0s and 1s) programming language. The processor
runs low- level programs directly without the need of a compiler or interpreter, so the programs
written in low-level language can be run very fast.
9
Low-level language is further divided into two parts -
i. Machine Language
The advantage of machine language is that it helps the programmer to execute the programs
faster than the high-level programming language.
Assembly language (ASM) is also a type of low-level programming language that is designed for
specific processors. It represents the set of instructions in a symbolic and human-
understandable form. It uses an assembler to convert the assembly language to machine
language.
The advantage of assembly language is that it requires less memory and less execution time to
execute a program.
The main advantage of a high-level language is that it is easy to read, write, and maintain.
High-level programming language includes Python, Java, JavaScript, PHP, C#, C++,
Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.
Procedural Oriented Programming (POP) language is derived from structured programming and
based upon the procedure call concept. It divides a program into small procedures
called routines or functions.
The advantage of POP language is that it helps programmers to easily track the program flow
and code can be reused in different parts of the program.
The advantage of POP language is that it helps programmers to easily track the program flow
10
and code can be reused in different parts of the program.
The main advantage of object-oriented programming is that OOP is faster and easier to execute,
maintain, modify, as well as debug.
Natural language is a part of human languages such as English, Russian, German, and
Japanese. It is used by machines to understand, manipulate, and interpret human's language. It is
used by developers to perform tasks such as translation, automatic summarization, Named
Entity Recognition (NER), relationship extraction, and topic segmentation.
The main advantage of natural language is that it helps users to ask questions in any subject and
directly respond within seconds.
Middle-level programming language lies between the low-level programming language and
high-level programming language. It is also known as the intermediate programming language
and pseudo-language.
A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human
language.
Introduction to C:
The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is
known as mother language.
11
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
structure of C program:
Documentation Section :
This section consists of a set of comment lines useful for documentation. Though comments are
not necessary in a program, they help users to understand the program better.
Braces :
All C programs incorporate a set of curly braces { }. Execution of the program begins at the
opening brace { of the main( ) function and ends at its closing brace }.
12
Declaration Part:
This part is used to declare all the variables, arrays functions etc. used in the C program.
Initialization along with declaration can also be done here.
Executable Part :
This part of the program consists of a set of executable statements such as Input/ Output
statements, arithmetic statements, control statements etc. It can also include comment statements
which are ignored by the compiler (non-executable). The declaration part and the executable part
must be within opening and closing braces.
Every statement in the declaration part and executable part ends with a semicolon.
Subroutine Section:
This section is optional and consists of all the user-defined functions called in the main( )
function.
Example:
/*Program to find the area of a square*/
#include <stdio.h>
main()
{
float side, area ;
side=5;
area=side*side;
printf(“\nArea of a square=%f’,area);
}
Output:
Area of a square = 25.0
C KEYWORDS:
There are some reserved words in C, called keywords. All the keywords have standard pre-
defined meanings and can be used only for the purpose intended. All keywords must be written
in lowercase. They cannot be used as user-defined identifiers. The standard keywords are listed
below
auto break case char const continue default do double else
enum extern float for goto if int longregister return
short signed sizeof static struct switch typedef union unsigned void
volatile while
IDENTIFIERS:
• Identifiers refer to the names of program elements such as variables, functions and arrays.
• Identifiers are sequence of characters chosen from the set A–Z, a–z, 0–9, and _
(underscore).
• C is a case sensitive language so that ALFA and Alfa are different.
• The underscore symbol _ is generally in the middle of an identifier (embedded).
• Identifiers may be of reasonable length of 8–10 characters though certain computers
allow up to 32 characters.
• Identifier names must start with an alphabet or underscore followed by letters, digit or a
combination of both.
• C has a list of keywords that cannot be used anywhere other than that predefined in the
13
language i.e., you can’t have a variable named int. Also one must follow the practice of
choosing names for variables which indicate the roles of those variables in the program.
VARIABLES:
A variable is an identifier used to store a single data item. This data could be a numerical
quantity or a character constant. During execution of the program, data must be assigned to the
variable. Therefore a variable can take different values at different times during the execution of
the program. The data stored in the variable can be accessed any time, by referring to the
variable name.
The rules for naming a variable are the same as those for an identifier.
They are :
1. Variable names generally begin with a letter followed by letters, digits underscore or a
combination of all.
2. No special character except the underscore symbol ( _ ) is allowed. Underscore is generally
embedded in a variable name to make it more readable.
3. Maximum length of a variable name should not exceed 32 characters. Normally the length
must not exceed 8 characters since many compilers treat the first 8 characters as significant.
4. C variables are case sensitive, so that Counter, counter and COUNTER are 3 different
variables.
5. C keywords cannot be used as variable names.
6. White spaces are not allowed in a variable name.
7. Appropriate variable names must be chosen to indicate their role in the program.
CONSTANTS:
Any fixed value that does not change during the execution of a program is known as a constant.
C consists of several types of constants.
Types of C constants:
C constants can be divided into two categories :
• Primary Constants
• Secondary Constants
14
Integer Constants :
Integers and real constants are numbers and are generally referred to as numeric constants.
An integer constant consists of a sequence of digits and is an integer-valued number. There are 3
types of integer constants depending on the number system.
They are:
• Decimal (base 10)
• Octal (base 8)
• Hexadecimal (base 16)
Real Constants:
Quantities which are represented by numbers with fractional part are called real or floating point
constants.
(a) A real constant must have at least 1 digit.
(b) It must have a decimal point.
(c) It can be either positive or negative.
(d) No commas or blanks are allowed within a real constant.
Character Constants:
(a) A character constant is a single character within single quotes.
(b) The maximum length of a character constant is 1.
(c) Arithmetic operations are possible on character constant since they too represent integer
values.
(d) C also recognizes all the backlash character constants (Escape sequences) available.
Note that the character constant ‘2’ is not the same as the number 2. Every character has an
equivalent integer value known as the ASCII code. Some character constant & their equivalent
ASCII values are as below :
‘A’ = 65
‘B’ = 66
‘a’ = 97
‘0’ = 48
‘1’ = 49
String Constants:
A string constant consists of zero or more number of characters enclosed within double quotes.
The characters within quotes could be digits, characters, special characters and blank spaces.
Ex: "Red", "Rs.20.25", " "
Note that ‘A’ is not equal to “A” since a string constant containing a single character does not
have a corresponding integer value. In fact it contains two characters, the specified character
followed by a null character represents by \0.
Coding constants:
There are 3 types of code constants used in programs:
• Literal constants
• Defined constants
• Memory constants
15
Literal constants: are used to specify data, which cannot be changed.
For example: x = y + 1 ;
In this statement 1 is a literal constant.
Defined Constants: are constants that can be defined using a preprocessor command #define.
This constant is placed at the beginning of a program since it is a preprocessor command.
For example :
# define MAX 30
The defined constants make the program easily modifiable and enhance the understandability of
the program.
Memory Constants: use a c type qualifier called const, to indicate that the data specified is a
constant and that it cannot be changed.
Its general format is :
const Datatype identifier = value ;
For example :
const float pi = 3.14159 ;
defines a memory constant pi of float type with a value of 3.14159.
I/O statements:
In C programming you can use scanf() and printf() predefined function to read and print data.
i) printf
This function is used for displaying the output on the screen i.e the data is moved from the
computer memory to the output device.
Syntax:
printf(“format string”, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted. They are the
general characters which will be displayed as they are .
arg1, arg2 are the output data items.
Syntax:
scanf (“format string”, &arg1, &arg2, …..);
16
The number of items which are successful are returned.
Format string consists of the conversion specifier. Arguments can be variables or array name and
represent the address of the variable. Each variable must be preceded by an ampersand (&).
Array names should never begin with an ampersand.
scanf works totally opposite to printf. The input is read, interpret using the conversion specifier
and stores it in the given variable.
The conversion specifier for scanf is the same as printf.
scanf reads the characters from the input as long as the characters match or it will terminate.
The order of the characters that are entered are not important.
It requires an enter key in order to accept an input.
OPERATORS IN C :
C provides several operators for elementary arithmetic operations like addition, subtraction,
multiplication, division, residue-modulo (the operation that gives the remainder after division of
one integer by another) and logical manipulations.
An operator is a symbol used for certain type of manipulations, logical or mathematical. The
data on which the operators act are called operands. An expression is a valid combination of
operators and operands that results in a value.
For example in the expression : 12*5
* is the multiplication operator,
12 and 5 are the operands.
Binary Operators:
Binary operators operate on two operands. They are classified into five categories as follows:
(i) Arithmetic
(ii) Relational
(iii) Logical
(iv) Assignment
(v) Bitwise
Ternary Operators:
Ternary operators act on three data elements. The conditional operator (?:) is a ternary operator
Special Operators:
Special operators include operators such as comma (,) and sizeof.
ARITHMETIC OPERATORS:
C supports five arithmetic operators.
Operator Purpose
+ Addition
– Subtraction or (unary)
* Multiplication
/ Division
% Remainder after integer division
Dividing one integer by another integer is called as integer division, which truncates, the
fractional part. The % operator gives the remainder of such a division.
For example, consider a = 10, b = 3.
a % b gives 10% 3 giving the result 1
and a/b gives 10/3 giving the result 3
Mixed-mode Arithmetic operations consists of a real and an integer operand. If one of the
18
operand is real, the result is also real.
For example :
15/2.0 = 7.5
However 15/2 = 7
RELATIONAL OPERATORS:
The relational operators are used to form relational expressions, representing conditions that are
either true or false. The result of the expression is an integer. Further, false is represented by zero
value and true in represented by non-zero value. For example expressions
50<200
x>y
are called relational expressions whose value can be either true or false i.e., 50<200 is true.
when x = 10 and y = 5, x > y is true. There are 6 relational operators in C.
They are:
Operator Meaning
> greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
In the 4th and 5th example given above the expressions contain arithmetic expression. Thus in
the relational expression (i+j)>=k, the arithmetic expression i+j will be evaluated and then the
result is compared with k. These arithmetic operators have higher priority over relational
operators. The relational operators are used to compare two quantities in decision statements.
LOGICAL OPERATORS:
Logical operators are used to combine two or more logical expressions. There are 3 logical
operators in C. They are logical AND, logical OR and logical NOT
Operator Meaning
! logical NOT
&& logical AND
|| logical OR
• The result of a logical AND is true only if both operands are true. The result is false if
either operand is false.
• The result of a logical OR is false only if both operands are false. The result is true if
either operand is true.
19
• C also consists of the unary operator ! (not) that negates the value of a logical expression
i.e., it causes true expression to become false and vice-versa. This operator is known as
logical NOT operator. Further like relational operators, a logical expression results in
zero or non-zero value depending on whether it is false or true.
Consider i = 8, x = 5.1, c = ‘a’ where i is an integer variable, x is a floating point variable and c
is a char variable.
Expression Logical value Integer value
(i>6)&&(c==’a’) true 1 (or non-zero)
i<=6||(c==’b’) false 0
i>=6&&(c==97) true 1
!(i<=4) true 1
ASSIGNMENTOPERATORS
The assignment operator ‘=’ is used to assign the value of a variable, constant or
expression to a variable. The syntax is :
variable=variable/constant/expression;
For example :
x=10; /*x is assigned a value 10 */
sum=a+b; /*Thesumofa&bwhichis20isassignedtosum*/
Where += is the abbreviated or compound operator. In the above case + = means add
5ton.Thedifferentshorthandassignmentoperatorsare:
The priority of the above operators + =, –=, *=, /= and % = is the same as theassignment
operator.
Difference between = = and = operator
1. == is an equality or relational operator, used for comparison = is an
assignmentoperator which assigns the resultant value on its right hand side to the
variableon its left hand side.
2. == operator does not change the value of the variable on the left hand side.However
= operator does change the value of the variable on the left hand side of the
assignmentstatement.
INCREMENT/DECREMENTOPERATOR
Theincrement and decrement operators are specifically used in C or C++.
They are not generally available in other languages.
Increment operator ++ is used to increment the value of the variable by 1.Decrement
operator – – is used to decrement the value of the variable by 1.
They are also called as unary operators Fig. 2.14. Since they operate on only one
dataelement.
int a, b;
:
a = 5;
b = --a;
will result in the value of a and b to be 4.
Post-increment operator ++ is written to the right of its operand as in n ++; which is the
21
same as n = n + 1;
Post-decrement operator – – is also written to the right of its operand as in n—
, and is equivalent to n = n – 1;
Pre-increment and pre-decrement operators ++ and – – are always placed to theleft of the
operand as follows :
++n; /* same as n =n+1*/
––n; /* same as n =n–1*/
The behavior of post and pre–increment or decrement operators are the same when used
with a single operand. However, they behave differently when the operand is embedded in an
expression.
Difference between postfix & prefixoperators
(i) The pre-increment or decrement operator first increments or decrements the value
of its operand by 1 and then assigns the resulting value to the variable onthe left
hand side. For example,consider
int a, b; a =
15;
b = ++a;
In this example, the value of a is incremented by 1 and then this value 16 is assigned
tob.
(ii) The post increment or decrement operator first assigns the value to the variable on
the left hand side and then increments or decrements the operand by 1. Consider the
following program segment:
intm,n; n =
2;
m = n– –;
The value of n is first assigned to m and then it is decremented i.e., n becomes 1, but
value of m is 2.
In subscripted variables.
a[j++]=5;
is equivalent to a[j]=5;
j++;
Similarly, a[++i]=5;
is equivalent to i = i+1;
a[i] = 5;
Consider the statement
x = n++/2;
where n = 5. After execution, n is 6 but x gets the value 5/2 which is 2.
22
TERNARY OPERATOR (CONDITIONALOPERATOR)
C consists of a very special operator known as ternary or conditional operator and
isrepresented by ? : The syntax is
expression1 ?expression2 : expression3;
SPECIALOPERATORS
C consists of some special operators. The operators, , &,*,.and , are called special
operators in C.
Operator Description
, Comma operator
sizeof size in bytes
23
& address of operand
* accessing value at that address
. dot operator
arrow operator
The CommaOperator
(i) The comma operator is used to separate a list of expressions given as a single
expression.
(ii) Thelistswithcommasarealwaysevaluatedfromlefttoright.
(iii) The value of the right most expression becomes the final value of the combined
expression.
(iv) The syntax is of the form:
variable =exp1,exp2, .................. expn;
sizeof(n)
24
(iv) The size of operator is used to determine the size of an array or a structure. It is
alsousedfordynamicmemoryallocationofvariables.
Example 2.30
/* Program to show usage of sizeof operator
*/ #define STRING “Usage of sizeof
Operator” #include <stdio.h>
main()
{
char a = ‘p’;
clrscr();
printf(“\n The size ofcharis : %d \n”,sizeof(char));
printf(“\n Therefore the size of char ais : %d \n”,sizeof(a));
printf(“\n However the size of‘p’is : %d \n”,sizeof(‘p’));
printf(“\nSTRING : \”%s\”
\n”,STRING); printf(“\n The number of bytes in STRINGis : %d
\n”,sizeof STRING); printf(“\n The size ofshortis : %d\n”,sizeof(short));
printf(“\n The size ofintis : %d\n”,sizeof(int));
printf(“\n The size oflongis : %d\n”,sizeof(long));
printf(“\n The size offloatis : %d\n”,sizeof(float));
printf(“\n The size ofdoubleis : %d
\n”,sizeof(double)); getch();
}
Output
The size ofcharis 1
Therefore the size of charais 1
However the size of‘p’is 2
STRING : “Usage of sizeof
Operator” The number of bytes inSTRINGis 25
The size ofshortis 2
The size ofintis 2
The size oflongis 4
The size offloatis 4
25
The size ofdoubleis 8
BITWISEOPERATORS:
C supports a powerful set of operators known as bitwise operators. The bitwise
operatorsare used for controlling and interacting with hardware and also for
manipulating data at the bit level.
The Bitwise operators are as shown below table.
Operator Description
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ one’s complement
(i) Bitwise operators cannot be applied to float or double. They can be applied to
integersonly.
(ii) All except ~ operator are used in binary operations. Tilde (~) is a unaryoperator.
(iii) Bitwise operators perform bitwise logical AND, bitwise logical OR,
bitwiseexclusiveOR,bitwiseshiftleftandshiftright.
(iv) Bitwise operators work on their operands bit by bit starting from the least
significant bit. The truth table for logical bitwise operations is as shown in below
table.Trueistakentobe1andfalseaszero.
Bitwise ANDOperator:
TheBitwise AND operator is represented by the symbol & (ampersand). The
result of AND operation is 1 if both operand bits are 1, otherwise, the result is zero.
Further,theANDoperationisdoneonthebinaryrepresentationoftheoperands.
4 & 5 results in 4
i.e., binary value of4is 0100
binary value of5is 0101
AfterANDoperation 0100 i.e.,4
Bitwise & operator is used to check whether a particular bit is 0 or 1. Consider the
number 21. Its bit pattern is represented by
0001 0101
To check whether the fourth bit is 0 or 1, AND operation must be done withanother
operand whose value must be 24 i.e., 16, which can be represented as00010000.
Therefore, 00010101
0001 0000 & mask
0001 0000
Consider x = 4, y = 9
xis 00000100 4
yis 00001001 9
x|yis 00001101 i.e.,13
The bitwise OR is used to set a particular bit on (set to 1).
27
x^yis 00001101 i.e.,13
Bitiwse ComplementOperator
The complement operator is represented by ~(tilde) and is also known as one’s
complement operator. It inverts all the bits. Thus all the zeros become 1 and all the ones
become 0.
Consider x = 4
x is 00000100
~x is 11111011
Bitwise ShiftOperator
The shift operators are used to push the bit patterns to the right or left by thenumber of bits given
by theirright operand
The Right shift operator is of the form :
expression>>n
where n is the number of bit positions to be shifted. However the rightmost n bitsare
lost. Further the left most n bits which are vacant will be filled with zero. For
examplex>>4shiftsallbitsby4placestotheright.
The Left shift operator is of the form
expression<<n
where n is the number of bit positions to be shifted. The left most n bits are lost andthe
rightmost n bits are vacated and filled with zeros.
Shift operators are used for multiplication and division by 2. For example, the statement
x = y << 2;
shifts two bit to the left in y. Further the value of x is equal to y multiplied by 22.
Similarly, the statement
x = y >> 2;
shifts the bits in y to the right by 2. Also the value of x is equal to y divided by 22.
PRECEDENCE OF ARITHMETICOPERATORS:
28
Precedence level Operators Associativity
1 () Left to right
2 unary Right to left
3 *,/,% Left to right
4 +, – Left to right
where a = 20, b = 1.
The order of evaluation will be as follows.
(i) Since + operator has the highest priority in the expression, addition is computed first:
a < 10 && 21 > 15
(ii) Both the relational operators have higher priority compared to the logical operator &&.
Here the associativity of relational operators has to be considered which is leftto right.
Thus:
20 <10 && 21 > 15
False && True
(iii) Theresultoflogical&&isfalseor0.
29
A complete operator precedence summary is listed in Fig. 2.20, from highest to lowest.
30
UNIT II
Simple if statement
1. Simple if statement is used to make a decision “yes or no”, based on the available choice. It
has the following form:
Syntax:
if ( condition )
{
stmt block;
}
stmt-x;
In this syntax,
• if is the keyword.
• <condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses and no terminator (;) at the end.
• The stmt block can be a simple statement or a compound statement or a null statement.
• stmt-x is any valid C statement.
31
2. flow chart for simple if.
Whenever simple if statement is encountered, first the condition is tested. It returns either
true or false. If the condition is false, the control transfers directly to stmt-x without considering
the stmt block. If the condition is true, the control enters into the stmt block. Once, the end of
stmt block is reached, the control transfers to stmt-x
Output:
enter a number
12
Even number
if - else statement
if…else statement is used to make a decision based on two choices. It has the following
form:
1. Syntax:
if(condition)
{
true stmt block;
}
else
{
false stmt block;
}
Stmt-x;
In this syntax,
• if and else are the keywords.
32
• <condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses .
• The true stmt block and falsestmtblock are simple statements or compound statements or null
statements.
• stmt-x is any valid C statement.
2. Flow chart:
If the condition is false, the control enters into the false stmt block by skipping true stmt
block.
Once, the end of false stmt block is reached, the control transfers to stmt-x.
#include <stdio.h>
main()
{
int x;
printf("Enter a number\n");
scanf("%d",&x);
if(x%2==0)
printf("EVEN\n");
else
printf("ODD\n");
}
if(x>y)
big=x;
else
big=y;
printf(“BIG=%d\n”,big);
}
/* absolute value */
#include <stdio.h>
main()
{
int x;
printf("Enter a integer\n");
scanf("%d",&x);
if(x<0)
printf("absolute value is %d\n",-x);
else
printf("absolute value is %d\n",x);
}
/* quadrant position */
#include <stdio.h>
main()
{
Int x,y;
printf("Enter the coordinate\n");
scanf("%d%d",&x,&y);
if(x>0 && y>0)
printf("FIRST QUADRANT\n");
/* alphabet or not */
#include <stdio.h>
main()
{
charch;
printf("Enter a character\n");
scanf("%c",&ch);
if(ch>= 'a' &&ch<='z')
printf("alphabet\n");
else
printf("not a alphabet\n");
}
/* vowel or not */
#include <stdio.h>
main()
{
char ch;
printf("Enter a alphabet\n");
scanf("%c",&ch);
if(ch== 'a' || ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("vowel\n");
else
printf("not a vowel\n");
}
Nested if…else statement is one of the conditional control-flow statements. If the body of if
statement contains at least one if statement, then that if statement is called as ―Nested if…else
statement‖. The nested if…else statement can be used in such a situation where at least two
conditions should be satisfied in order to execute particular set of instructions. It can also be used
to make a decision among multiple choices. The nested if…else statement has the following
form:
Syntax: if(condition1)
{
if(condition 2)
{
stmt1;
}
else
{
stmt2;
}
}
35
else
{
stmt 3;
}
stmt-x;
In this syntax,
Whenever nested if…else statement is encountered, first <condition1> is tested. It returns either true
or false.
If condition1 (or outer condition) is false, then the control transfers to else-body (if exists) by
skipping if-body.
If condition1 (or outer condition) is true, then condition2 (or inner condition) is tested. If the
condition2 is true, if-body gets executed. Otherwise, the else-body that is inside of if statement
gets executed.
36
#include<stdio.h>
#include<conio.h>
void main()
{
int a ,b,c;
else
{
if(c>b)
printf("%d\n",c);
else
printf("%d\n",b);
}
if (condition 1)
simple or compound statement // s1
else if (condition 2)
simple or compound statement // s2
else if ( condition 3)
simple or compound statement // s3
.....
else if ( conditon n )
simple or compound statement // sn
If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are tested.
If all are false, the default stmt at the end gets executed. After then the control transfers to stmt-x.
If any one of all conditions is true, then the body associated with it gets executed. After that the
control transfers to stmt-x.
Points to Remember
1. We can use if-else if when you want to check several conditions but still execute one
statement.
2. When writing an if-else if statement, be careful to associate else statement to the appropriate
if
statement.
3. We must have parentheses around the condition.
Example program:
/* to find grade when percentage of marks are given */
#include<stdio.h>
void main()
{
int m1,m2,m3,avg,tot;
printf("enter three subject marks");
scanf("%d%d%d",&m1,&m2,&m);
tot=m1+m2+m3;
38
avg=tot/3;
if(avg>=75)
{
printf("distinction");
Explanation
1. The switch expression should be an integer expression and, when evaluated, it must have an
integer value.
2. The case constant expression must represent a particular integer value and no two case
expressions should have the same value.
3. The value of the switch expression is compared with the case constant expression in the order
specified, that is, from the top down.
4. The execution begins from the case where the switch expression is matched and it flows
downward.
5. In the absence of a break statement, all statements that are followed by matched cases are
executed.
6. If there is no matched case then the default is executed. You can have either zero or one default
statement.
7. In the case of a nested switch statement, the break statements break the inner switch statement.
Flow chart:
Whenever, switch statement is encountered, first the value of <exp> gets matched with case values.
If suitable match is found, the statements block related to that matched case gets executed. The
break statement at the end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed and then the control gets
transferred to Next-statement.
40
Point to Remember
1. case constructs need not be serial.
2. characters can be used.
3. combination of integers and characters is possible.
4. default is optional.
5. Brace in case block is optional
//switch 1
// to display name of the day
#include <stdio.h>
void main()
{
int day;
printf("Enter day number\n");
scanf("%d",&day);
switch(day)
{
case 1:
printf("monday\n");
break;
case 2:
printf("tuesday\n");
break;
case 3:
printf("wednesday\n");
break;
case 4:
printf("thursday\n");
break;
case 5:
printf("friday\n");
break;
case 6:
printf("saturday\n");
break;
case 7:
printf("sunday\n");
break;
default:
printf("Wrong entry\n");
}
}
//switch 2
// to display the gender
#include <stdio.h>
void main()
41
{
charch;
printf("Enter your gender\n");
scanf("%c",&ch);
switch(ch)
{
case 'm':
case 'M':
printf("so you are a male\n");
break;
case 'f':
case 'F':
printf("so you are a female\n ")
break;
default:
printf("Wrong entry\n");
}
}
while LOOP
Introduction
The while loop is used when we want to repeat the execution of a certain statement or a set of
statements (compound statement).
Syntax
The general format for a while loop is
while (condition)
simple or compound statement (body of the loop)
For example,
i = 0;
while (i<5)
{
printf(" the value of i is %d\n", i);
i = i + 1;
}
Explanation
1. Before entering into the loop, the while condition is evaluated. If it is true then only the loop
body is executed.
2. Before making an iteration, the while condition is checked. If it is true then the loop body is
executed.
3. It is the responsibility of the programmer to ensure that the condition is false after certain
iterations; otherwise, the loop will make infinite iterations and it will not terminate.
4. The programmer should be aware of the final value of the looping variable. For example, in
this case, the final value of the looping variable is 5.
5. While writing the loop body, you have to be careful to decide whether the loop variable is
updated at the start of the body or at the end of the body.
42
#include<stdio.h>
#include<conio.h> int main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d ",i); i=i+1;
}
}
do-while LOOP
Introduction
The do-while loop is used when we want to execute the loop body at least once. The do-while loop
executes the loop body and then traces the condition.
Syntax
The general format for a do-while loop is
do
simple or compound statement
while (condition);
For example,
43
i = 0;
do
{
printf(" the value of i is %d\n", i);
i = i + 1;
}
while (i<5);
Explanation
1. The loop body is executed at least once.
2. The condition is checked after executing the loop body once.
3. If the condition is false then the loop is terminated.
4. In this example, the last value of i is printed as 5.
#include<stdio.h>
for LOOP
Introduction
The for loop is used only when the number of iterations is predetermined, for example, 10 iterations
or 100 iterations.
Syntax
The general format for the for loop is
for (initializing; continuation condition; update)
simple or compound statement
For example,
for (i = 1; i<=5; i++)
{
printf("%d”, i");
}
Explanation
1. The for loop has four components; three are given in parentheses and one in the loop body.
2. All three components between the parentheses are optional.
3. The initialization part is executed first and only once.
4. The condition is evaluated before the loop body is executed. If the condition is false then the
loop body is not executed.
5. The update part is executed only after the loop body is executed and is generally used for
updating the loop variables.
6. The absence of a condition is taken as true.
7. It is the responsibility of the programmer to make sure the condition is false after certain
iterations.
#include<conio.h>
void main()
{
int i,n;
printf("enter the value"); scanf("%d ",&n);
45
for(i=1;i<=n;i++)
{
printf("%d\n",i);
}
}
// cosine series
main()
{
int i, n;
float x,denom, term, sum,deg;
printf("Enter value of x in deg and number of terms: \n");
scanf("%f%d", °, &n);
x=deg*3.14/180;
sum = term = 1;
for ( i = 1; i<= n; i++)
{
denom = (2 * i )*( 2 * i - 1);
term *= -(x*x)/ denom;
sum += term;
}
printf("\ndeg = %.1f, Sum = %.2f", deg, sum);
} /* end of main */
47
// to find the sum of digits of a number
#include <stdio.h>
main()
{
intn,sum=0,digit;;
printf("Enter a number\n");
scanf("%d",&n);
while(n!=0)
{
digit=n%10;
sum=sum+digit;
n=n/10;
}
printf("%d",sum)
}
48
break statement
The break statement is used within the looping control statements, switch statement and nested
loops. When it is used with the for, while or do-while statements, the control comes out of the
corresponding loop and continues with the next statement.
When it is used in the nested loop or switch statement, the control comes out of that loop / switch
statement within which it is used. But, it does not come out of the complete nesting.
break;
The following representation shows the transfer of control when break statement is used:
Any loop
{
statement_1;
statement_2;
:
break;
next_statement;
#include<conio.h>
int main()
{
int i;
49
for(i=1; i<=10; i++)
{
if(i==6)
break;
printf("%d",i);
}
}
Output: 12345
2. continue statement
A continue statement is used within loops to end the execution of the current iteration and proceed
to the next iteration. It provides a way of skipping the remaining statements in that iteration after the
continue statement. It is important to note that a continue statement should be used only in loop
constructs and not in selective control statements.
Syntax for continue statement is:
continue;
The following representation shows the transfer of control when continue statement is used:
Any loop
statement_1; statement_2;
:
continue;
next_statement;
int i, sum=0, n;
for(i=1; i<=10; i++)
{
3. goto statement
The goto statement transfers the control to the specified location unconditionally. There are certain
situations where goto statement makes the program simpler. For example, if a deeply nested loop is
to be exited earlier, goto may be used for breaking more than one loop at a time. In this case, a break
statement will not serve the purpose because it only exits a single loop.
label:
statement_1; statement_2;
:
goto label;
In this syntax, goto is the keyword and label is any valid identifier and should be ended with a colon
(:).
The identifier following goto is a statement label and need not be declared. The name of the
statement or label can also be used as a variable name in the same program if it is declared
appropriately. The compiler identifies the name as a label if it appears in a goto statement and as a
variable if it appears in an expression.
If the block of statements that has label appears before the goto statement, then the control has to
move to backward and that goto is called as backward goto. If the block of
statements that has label appears after the goto statement, then the control has to move to forward
and that goto is called as forward goto.
51
Program for goto statement:
#include<stdio.h>
printf("www."); goto x;
y:
printf("expert"); goto z;
x:
printf(".com");
PROGRAM 1
1
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n;
for(line=1;line<=3;line++)
{
for(n=1;n<=line; n++)
printf("%3d",n);
printf("\n");
}
}
PROGRAM2
1
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n,gap;
for(line=1;line<=3;line++)
{
for(gap=1;gap<=20-line;gap++)
printf(" ");
52
for (n=1;n<=line;n++)
printf("%4d",n);
printf("\n");
}
}
PROGRAM 3
/* 1
12
123
1234
12345
*/
#include <stdio.h>
void main()
{
int line ,n,gap;
for(line=1;line<=5;line++)
{
for(gap=1;gap<=5-line;gap++)
printf(" ");
for(n=1;n<=line;n++)
printf("%2d",n);
printf("\n");
}
}
PROGRAM 4
1
121
12312
1234123
123451234
#include <stdio.h>
void main()
{
int line ,n,gap;
for(line=1;line<=5;line++)
{
for(gap=1;gap<=20-line;gap++)
printf(" ");
for(n=1;n<=line;n++)
printf("%2d",n);
for(n=1;n<line;n++)
printf("%2d",n);
printf("\n");
53
}
}
//program 5 :Pascal triangle
#include <stdio.h>
void main()
{
int binom,n,q,g,x;
binom=1;
q=0;
printf("enter no of rows\n");
scanf("%d",&n);
while(q<n)
{
for(g=40-3*q;g>0;g--)
printf(" ");
for(x=0;x<=q;x++)
{
if((x==0)||(q==0))
binom=1;
else
binom = (binom*(q-x+1))/x;
printf("%6d",binom);
}
printf("\n");
q++;
}
}
Programming exercises:
*****
* *
* *
* *
*****
*****
*****
*****
*****
*****
54
*
**
**
* *
*****
10101
01010
10101
01010
10101
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
Lecture-13
55
digit=rev%10;
switch(digit)
{
case 1:
printf("ONE ");
break;
case 2:
printf("TWO ");
break;
case 3:
printf("THREE ");
break;
case 4:
printf("FOUR ");
break;
case 5:
printf("FIVE ");
break;
case 6:
printf("SIX ");
break;
case 7:
printf("SEVEN ");
break;
case 8:
printf("EIGHT ");
break;
case 9:
printf("NINE ");
break;
case 0:
printf("ZERO ");
}
rev=rev/10;
}
while(temp%10==0)
{
printf("ZERO ");
temp=temp/10;
}
}
FUNCTIONS
56
Definition:
A function is a set of instructions under a name that carries out a specific task, assigned to it.
CLASSIFICATION of functions:
1. User defined functions (UDF)
2. Library functions
USER DEFINED FUNCTIONS
Example:
void sum( ) function without arguments and without return value
int sum( ) function without arguments but with return value
void sum(int ,int) function with arguments but without return value
int sum(int,int) function with arguments and with return value
Function prototype:
If we use any variable in the program, we declare that variable in the declaration section of the
program. Similarly, any function that is to be called should be declared before its call in the
Function declaration should be done either in the declaration section of calling function
or before it. The function prototype should agree with definition of that function.
Prototype contains the data type returned by the function followed by the name of that
function and a pair of parentheses enclosing the data type of each parameter separately.
57
Function definition
FUNCTION CALL
Function call means, accessing a function. A function can be called by specifying its
name, followed by a list of arguments enclosed in the parentheses, and separated by comma
Example: f=fact(n);
If a function call does not require any arguments, an empty pair of parentheses must
follow the function name.
A function call may appear itself or it may be one of the operand within a expression.
Example: printf(“%d”,fact(n));
Arguments in function call, and formal parameters in function declaration must be same
in number, type and order.
OUTPUT
x=50 y=0
Example programs on functions
Factorial of number by using function
#include <stdio.h>
main()
{
long int fact(int);
int n;
long int f;
printf("Enter a number\n");
scanf("%d",&n);
f = fact(n);
printf("The factorial of %d is %ld",n,f);
} /*end of main */
/* function fact*/
long int fact(int x)
{
int i;
long int f1=1;
for(i=1;i<=x;i++)
f1 = f1*i;
return(f1);
59
}
Fibonacci series by function
main()
{
int n;
void fib(int);
printf( "\nHow many Fibonacci numbers
required ? ");
scanf("%d", &n);
printf("\nThe first %3d fibonaccinumbers are\n", n);
fib(n);
}
void fib(int n)
{
int i, f1, f2, f3;
f1 = f2 = 1;
printf("%5d\n", f1);
printf("%5d\n", f2);
for( i = 3; i<= n; i++)
{
f3 = f1 + f2;
printf("%5d\n", f3);
f1 = f2;
f2 = f3;
}
}
GCD of two numbers by function
void main()
{
int m,n,g;
int gcd(int,int);
} /* End of main() */
int gcd(int m,int n)
{
int r,g1;
do
60
{
r=m%n;
if(r!=0)
{
m=n;
n=r;
}
}while(r!=0);
g1=n;
return(g1);
} /* End of function gcd */
LCM of two numbers by function
main()
{
int m,n;
int lcm(int,int);
} /* End of main() */
#include <stdio.h>
void main()
{
int palin(int);
int num,ans;
printf("Enter a number\n");
scanf("%d",&num);
ans=palin(num);
if(ans==1)
printf("%d is palindrome\n",num);
else
printf("%d is not palindrome\n",num);
}
/* function palin */
int palin(int num)
{
int rev=0,temp,digit;
temp=num;
while(num!=0)
{
digit= num%10;
rev = rev*10 + digit;
num = num/10;
}
if(rev==temp)
return 1;
else
return 0;
}
RECURSIVE FUNCTIONS
A function which calls itself until a certain condition is reached is called recursive function
/* to find factorial of a number recursively */
#include <stdio.h>
main()
{
62
int rfactorial(int);
int n,f;
printf("Enter a number\n");
scanf("%d",&n);
f=rfactorial(n);
printf("Factorial of %d is %d",n,f);
/* factorial */
int rfactorial(int n)
{
if(n==0)
return 1;
else return(n*rfactorial(n-1));
}
/* to find nth fib number recursively */
#include <stdio.h>
main()
{
int rfib(int);
int n,f;
printf("Enter a number\n");
scanf("%d",&n);
f=rfib(n);
printf("n thfibonacci number is %d",f);
}
/* rfib */
int rfib(int n)
{
if(n==1||n==2)
return 1;
else return(rfib(n-1)+rfib(n-2));
}
/* to find GCD of two numbers recursively */
#include <stdio.h>
main()
{
int rgcd(int,int);
int m,n,g;
}
/* function rgcd */
int rgcd(int m,int n)
63
{
if(m%n==0)
return n;
else
return(rgcd(n,m%n));
}
int rsum(int n)
{
if(n==0)
return n;
else return(n%10+rsum(n/10));
}
#include <stdio.h>
void main()
64
{
int rpower(int,int);
int m,n;
printf("Enter two number\n");
scanf("%d%d",&m,&n);
printf("%d power %d is %d\n",m,n,rpower(m,n));
}
int rpower(int m,int n)
{
if(n==0)
return 1;
else
return(m*rpower(m,n-1));
}
STORAGE CLASSES
Normally the life of a variable is limited to a function as long as the function is alive. How to
make it alive in a file or throughout the program or limiting only to a block inside a function or
to make common to a desired couple of functions etc., The answer lies in “STORAGE
CLASSES” or “VARIABLE TYPES”.
65
There are four types of storage classes.
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
AUTOMATIC VARIABLES:
Automatic variables are declared inside a function, in which they are to be utilized. They
are created when the function is called and destroyed automatically when the function is exited.
By default all variables are automatic variables. These are also called local or internal variables.
EXTERNAL VARIABLES
Variables that are both alive and active throughout the entire program are called external
variables. These variables are available to all functions in that program. Whatever changes that
occur in a function, will effect the value of that variable.
STATIC VARIABLES
When a variable is declared as a static variable it is assigned the value zero. Static
variables are initialized only once. They will not be initialized for second time during the
program. When static is applied to a global variable, the global variable becomes inaccessible
outside the file.
REGISTER VARIABLES
This is local to a function or a block. If a compiler finds a physical register in the CPU free for
the time being, and also big enough to hold the value, then it may stick that variable in that
register. Otherwise, the compiler treats that variable as ordinary. It is machine dependent. But
compiler will not give error messages even if no register available in reserve. If we know that a
particular variable will be used often inside function-say the variable inside a loop-then we can
declare that variable with class register. So that the interaction will be very fast.
66
auto int x=1;
{
auto int x=2;
{
auto int x=3;
printf(“%d\n”, x);
}
printf(“%d\n”,x);
}
printf(“%d\n”,x);
}
Output
3
2
1
// program to illustrate automatic and external variables
#include <stdio.h>
int x=1;
int fun1()
{
x=x+10;
return x;
}
int fun2()
{
int x;
x=20;
return x;
}
int fun3()
{
x=1000;
return x;
}
void main()
{
int x=100;
printf("% d\n",fun1());
printf("%d\n",fun2());
printf("% d\n",fun3());
x=0;
printf("%d\n",x);
printf("% d\n",fun1());
printf("%d\n",fun2());
printf("% d\n",fun3());
}
OUTPUT
11
20
67
1000
0
1010
20
1000
int fun()
{
static int x=0;
x+=1;
return(x);
}
OUTPUT
1
2
3
4
// program to illustrate register variable
#include <stdio.h>
void main()
{
register inti;
int i;
for(i=1;i<1000;i++)
printf("% d",i);
}
automatic variable static variable
2. It must be declared inside the function 2. It can be declared inside or outside the
function
3. If it is not initialized, garbage value is 3. If it is not initialized, zero is stored
stored 4. It is initialized once and only one but not
4. It is initialized every time function is every
called that is repeated initialization time when function is called
5. It is lost when function terminates 5. It is lost when program terminates but not
when function terminates
68
Local variable Global variable
1. It is declaration inside the function 1.It is declaration outside the function
2.It is declared by 2. It is declared by int a=10
auto int a=10 or
int a = 10 (auto is default scope)
3. If it is not initialized. garbage value is 3. If it is not initialized zero is stored
stored Eg: int a; Eg: int a;
a is garbage value a=0
4. It is created when the function starts 4. It is created before program execution
execution and lost when the function starts and lost when program terminates
terminates
5. It is visible in only one function. 5. It is visible through out the program.
6. It can be accessed in only one function that 6. It can be accessed in more than one
is the function.
Iterative Recursive
69
1. Function calls some other functions 1. Function calls some itself
2. while loop, do while loop or for loop is 2. if statement is necessary in recursive function
necessary in iterative function
3. Fast in execution since one function 3. Slow in execution since several function calls
call is enough to get the result are involved to get the result, as number of
function increases execution will slow down.
4. Function call leads to value 4. Function call leads to another function call
Eg: fact(4) = 24 Eg: fact(4) = 4 x fact(3)
UNIT III
ARRAYS
Introduction to Arrays
Till now you might have declared variables to hold data and to perform operations on it. Just like
given below-
int a=10;
char ch=’a’;
These variables can hold only one data item at a time. Let us take some example where collection of
data items need to be stored….
• 60 students marks secured in a subject
• Salaries of 100 employees
we are supposed to declare multiple variables to hold the above data for each example.
language provides a derived data types called arrays.
efinition
An array is collection of homogeneous elements stored in continuous memory locations and shares a
common name.
here are several forms of an array used in C: one-dimensional or single-dimensional and
multidimensional array.
eclaration of one-dimensional or single-dimensional
Like any other variables, arrays must be declared before they are used. The general form of array
declaration is
Syntax: datatype array_name[sizeofarray];
The data type specifies the type of data/element that will be stored in the array, such as int,
float, or char.
The size indicates the maximum number of data/elements that can be stored in the array.
The size of array should be a int constant or constant expression.
Let us take the same example to declare suitable one dimensional array variable to hold the data.
70
• 60 students marks secured in a subject
unsigned short int PPS[60];
• Salaries of 100 employees
float salaries_of_employees[100];
Elements are stored in consecutive memory allocations. Each block is of size two because
variable ‘ a’ is of data type ‘int’. If array variable is of ‘float ‘ data type then each block
occupies four bytes.
So total memory occupied by an array whose size is given as ‘n’ is-
sizeof(datatype of the variable)*n
First element in the array is stored at a[0], second at a[1] and so on fifth element is stored at
a[4]. If size of an array is ‘n’ then elements in the array stored from 0 to n-1 index/subscript.
Storing/ retrieving data into/from the array is done by using index/subscript.
• Array is initialized with elements can be done at static time (while writing the code) or
dynamic time( at the time of executing the program).
Static Initialization
Example 1:
int a[5]; //array declaration
//array initialization
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
Example 2:
int a[5]={10,20,30,40,50}; // array declaration and initialization
71
Dynamic Initialization
Example 3:
int a[5],i;
printf(“Enter 5 integer elements:”);
for(i=0;i<=4;i++)
scanf(“%d”,&a[i]);
At the time of execution user can give 5 data items which will be stored in the array.
int a[5]={10,20,30,40,50};
printf(“%d\t%d\t%d\t%d\t%d”,a[0], a[1], a[2], a[3], a[4]);
int a[5]={10,20,30,40,50},i;
for(i=0;i<=4;i++)
printf(“%d”,a[i]);
In both the cases elements stored in the indexes from ‘0’ to ‘4’ will be displayed.
As loop variable value changes the subscript of an array changes and corresponding
element will be displayed.
}
Output:
73
• a[i]=a[i]+1 // add ‘1’ to value at ‘a[i]’
• a[i]++ // add ‘1’ to value at ‘a[i]’
• a[i]+=1 // add ‘1’ to value at ‘a[i]’
• a[k]=a[i]; // ‘i’th indexed element stored at index ‘k’
# include<stdio.h>
int main( )
{
inti , a[5];
printf(“Enter 5 integer elements: ”); /* reading values into Array */
for (i=0; i<5; i++)
scanf(“ %d ”, &a[i]);
/* printing of a[i] values */
printf(“The array elements in reverse order are:”);
for(i=4; i>=0 ; i--)
printf(“%d ”, a[i]);
}
Output:
Find whether a given element/key exists or not in the array of elements is called search.
This operation can be done by using two methods- simplest method is a sequential search or linear
search and binary search.
The basic idea of linear search is start comparing the key with each element in the array from index
‘0’ to index ‘n’-1 if ‘n’ is the size of the array.
if key is found display the position/index at which element exist and exit the search
otherwise search will be continued till the end of the array and display the key is not found.
In binary search method , halves the size of the list and searches only in half of the array by
finding the mid element index using first(low) and last(high) index of the array.
The procedure is as follows-
• Find mid element by using low and high
75
• If key is less than mid element then search will be done in left of the array by updating high
• Else If key is greater than mid element then search will be done in right of the array by
updating low
• Otherwise mid element itself is the search element.
his will be continued until low is less than high. Unsuccessful search make low greater than high. To
perform binary search the elements should be increasing order in the array.
/* Program to implement linear search */
#include<stdio.h>
int main()
{
int n;
printf("\n Enter the size of the array:");
scanf("%d",&n);
int a[n],i,key,FOUND=0;
int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(key>a[mid])
low=mid+1;
else if(key<a[mid])
high=mid-1;
else
{
printf("\n Found at %d",i);
FOUND=1; break;
}
}
if(FOUND == 0)
printf("\n NOT FOUND...");
return 0;
}
Output Binary search logic Interpretation for
successful search
76
Bubble Sorting
Sorting operation will keep the element in an order.
Basic principle of bubble sort is consecutive/adjacent elements are compared and exchanges their
values if they are not in the order. This process bubbles the smallest element in the array to ‘0’ index
and largest to ‘n-1’ index where ‘n’ is the size of the array.
The following depicts the different stages of the bubble sort.
pass1 Comparison on
44 22 -1 3 10 44 , 22 (swap)
22 44 -1 3 10 44, -1 (swap)
22 -1 44 3 10 44 , 3 (swap)
22 -1 3 44 10 44, 10 (swap)
22 -1 3 10 44 Pass1 completed and largest element (44) placed in the correct
position. It is not going to be considered in the next iteration.
Pass2 Comparison on
-1 22 3 10 44 22, -1 (swap)
-1 3 22 10 44 22, 3 (swap)
-1 3 10 22 44 22, 10 (swap)
-1 3 10 22 44 Pass 2 completed . 22 is placed in the correct position. It is not
going to be considered in the next iteration.
Pass3 Comparison on
-1 3 10 22 44 -1, 3 (no swap)
-1 3 10 22 44 3,10 (no swap)
-1 3 10 22 44 Pass 3 completed . 10 is placed in the correct position .It is not
going to be considered in the next iteration.
Pass4 Comparison on
-1 3 10 22 44 -1, 3 (no swap)
-1 3 10 22 44 Pass 4 completed . 3 is placed in the correct position .It is not
going to be considered in the next iteration.
Always single element in the array will be in sorted order itself. So algorithm stops its passes.
77
int a[n],i,j,temp;
printf("\n Enter %d numbers for sorting",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Before Sorting ....\n");
for(i=0;i<n;i++)
printf("%5d",x[i]);
//sorting logic
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1]; /* swap */
a[j+1]=temp;
}
}
printf("\n After Sorting ....\n");
for(i=0;i<n;i++)
printf("%5d",x[i]);
return 0;
}
Selection Sorting
Selection sort finds the minimum element from the array and place it in the beginning.
#include <stdio.h>
main()
{
int a[20],n,i, j, po,se,temp;
printf("How many elements\n");
scanf("%d",&n);
• Arrays with more than one dimension are called multidimensional arrays.
• Array of one dimensional array is called two dimensional array.
Example:
int a[10][10];
float b[20][20];
• Two dimensions are useful to store data in a table form. Ie take the previous example 60
student marks in a subject.
• In order to store 60 students’ marks obtained in 6 subjects then six one dimensional arrays
need to be declared for each subjects.
• It will be difficult to remember the variable name of each subject if multiple subjects exist.
Static initialization
initialization of an array: this can be done in two ways
1. int a[2][2] = { {3,6} , {2,9} }; // each 1D array enclosed in {} and separated with ,
2. int a[2][2] = { 3,6,2,9}; // based on 2nd dimension it will identify the number of
// elements in each row.
dynamic initialization
• To represent 2 dimensions we need two variable one for each dimension.
int a[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf(“%d”,&a[i][j]);
}
a[3][3]={1,2,3,4,5,6,7,8,9};
hen the array will be …
80
row1 row 2 row 3
To accesses the 2nd element at 3rd row we need to use the indexes as a[1][2]. So element in ith
row jth column will be accesses as a[i-1][j-1].
All the elements are stored in continuous locations. Two dimensional array is also called as
array of arrays.
First dimension in the 2D array tells about how many one dimensional arrays are required,
second dimension tells about how many elements in each one dimensional array .
82
/* loop to display resultant matrix */
printf("The multiplication of A and B is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%3d",c[i][j]);
printf("\n");
}
}
83
for(j=0;j<r;j++)
printf("%3d",b[i][j]);
printf("\n");
}
}
Enter the size of matrix
23
Enter the matrix values
123
456
Transpose of a :
1 4
2 5
3 6
84
printf("location = %d\n",i+1);
found =1;
}
}
if(found==0)
printf(" element not found\n");
}
OUTPUT:
Enter how many numbers
8↵
Enter the number
34 5 89 54 7 15 77 23 ↵
Enter the key
77↵
Search is successful
Location =7
} /* end of main */
/*Function input */
void input( int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */
/* Function Bsearch */
void bsearch (int a[],intn,int key)
{
intlow,high,mid,flag=0;
low=0;
high=n-1;
while(low<=high)
85
{
mid=(low+high)/2;
if(key < a[mid])
high=mid-1;
else if(key > a[mid])
low = mid+1;
else if(key == a[mid])
{
printf("search is successful\n");
printf("location = %d\n",mid+1);
flag=1;
break;
}
}
if(flag==0)
printf("search is unsuccessful\n");
} /* end of function bubblesort */
OUTPUT:
Enter how many numbers
10 ↵
Enter the number
3 5 8 54 7 15 76 23 79 11 ↵
Enter the key
79↵
Search is successful
Location =9
int a[25],n;
printf("How many numbers to sort ? ");
scanf("%d",&n);
printf("\nEnter %d numbers below:\n", n);
input(a,n);
bubblesort(a,n);
printf("\nThe sorted Array is: \n");
output(a,n);
} /* end of main */
/*Function input */
void input( int a[],int n)
86
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */
/* Function Bubblesort */
void bubblesort (int a[],int n)
{
int pass, j, temp;
for ( pass = 1; pass < n; pass++ )
{
for ( j =0 ; j < n-1; j++ )
{
if( a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
} /* end of function bubblesort */
/* Function output */
void output (int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
printf("%5d\n", a[i]);
} /* end of function output */
#include <stdio.h>
main()
{
void ssort(int [],int);
void display(int [] ,int);
void readarray(int [],int);
int a[20],n;
printf("How many elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
readarray(a,n);
ssort(a,n);
display(a,n);
}
87
void readarray(int a[],int n)
{
inti;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
1. We can pass entire two dimensional array to function like one dimensional array.
2. When we pass two dimensional array to a function, in the function definition formal
argument, the size of the column is must and size of the row is optional.
88
/*Program to add two matrices by using functions*/
#include <stdio.h>
main()
{
void readmat(int [ ][10],int,int);
void matadd(int [ ][10],int [ ][10],int [ ][10],int,int);
void display(int [ ][10],int,int);
matadd(A, B, C,m,n);
printf("Matrix A is :\n");
display(A, m,n);
printf("Matrix B is :\n");
display(B, m,n);
printf("\nMATRIX C (= A + B) is:\n");
display(C, m,n);
} /* end of main */
#include <stdio.h>
main()
{
void readmat(int [][10],int,int);
void matmul(int [][10],int [][10],int [][10],int,int,int);
void display(int [][10],int,int);
if(n!=p)
printf("multiplication not possible\n");
else
{
printf("\nEnter elements of matrix A \n");
readmat (A, m,n);
matmul(A, B, C,m,q,n);
printf("Matrix A is :\n");
display(A, m,n);
90
printf("Matrix B is :\n");
display(B, p,q);
printf("\nMATRIX C (= A X B) is:\n");
display(C, m,q);
}
} /* end of main */
91
STRINGS: ONE-DIMENSIONAL CHARACTER ARRAYS
Definition:
Strings are defined as an array of characters. The difference between a character array and a string
is the string is terminated with a special character ‘\0’ the null character, which is a character all
of whose bits are zero, i.e., a NUL (not a NULL). (The null character has no relation except in
name to the null pointer. In the ASCII character set, the null character is named NUL.)
Although C does not have a string data type, it allows string constants. For example: ”hello
students” is a string constant.
Declaration of a String:
Strings can be declared like one-dimensional arrays. For example,
char str[30];
char text[80];
String Initialization:
Character arrays or strings allow a shorthand initialization,
for example,
char str[9] = “I like C”;
which is the same as
char str[9] = {‘I’,‘ ’,‘l’,‘i’,‘k’,‘e’,‘ ’,‘C’,‘\0’};
Whenever a string, enclosed in double quotes, is written,C automatically creates an array of
characters containing that string, terminated by the \0 character. C language allows the
alternative notation
char msg[] = “Hello”;
that is always used in practice. It should be noted that the size of the aggregate ‘msg’ is six bytes,
five for the letters and one for the terminating NUL. There is one special case where the null
character is
not automatically appended to the array. This is when the array size is explicitly specified and
the number of initializers completely fills the array size. For example, char c[4] = “abcd”; Here,
the array c holds only the four specified characters, a, b, c, and d. No null character terminates
the array.
String Representation:
Printing Strings:
The conversion type ‘s’ may be used for output of strings using printf(). Width and precision
specifications may be used with the %s conversion specifier. The width specifies the minimum
92
output field width; if the string is shorter, then space padding is generated. The precision
specifies the maximum number of characters to display. If the string is too long, it is truncated. A
negative width implies left
justification of short strings rather than the default right justification. For example,
printf(“%7.3s”,name);
This specifies that only the first three characters have to be printed in a total field width of seven
characters and right justified in the allocated width by default. We can include a minus sign to
make it left justified (%-7.3). The following points should be noted:
• When the fi eld width is less than the length of the string, the entire string is printed.
• The integer value on the right side of the decimal point specifies the number of characters
to be printed.
• When the number of characters to be printed is specified as zero, nothing is printed.
• The minus sign in the specification causes the string to be printed as left justified.
Example program:
#include <stdio.h>
int main()
{
char s[]=“Hello, World”;
printf(“>>%s<<\n”,s);
printf(“>>%20s<<\n”,s);
printf(“>>%-20s<<\n”,s);
printf(“>>%.4s<<\n”,s);
printf(“>>%-20.4s<<\n”,s);
printf(“>>%20.4s<<\n”,s);
return 0;
}
Output:
The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in
the input/output operations of the strings.
C gets() function
The gets() function enables the user to enter some characters followed by the enter key. All the
characters entered by the user get stored in a character array. The null character is added to the
array to make it a string. The gets() allows the user to enter the space-separated strings. It returns
the string entered by the user.
char[] gets(char[]);
The gets() function is risky to use since it doesn't perform any array bound checking and keep
reading the characters until the new line (enter) is encountered. It suffers from buffer overflow
Example:
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
C puts() function
The puts() function is very much similar to printf() function. The puts() function is used to print
the string on the console which is previously read by using gets() or scanf() function. The puts()
function returns an integer value representing the number of characters being printed on the
console. Since, it prints an additional newline character with the string, which moves the cursor
to the new line on the console, the integer value returned by puts() will always be equal to the
number of characters present in the string plus 1
int puts(char[]);
94
Example:
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
Example:
This program checks whether character is alphanumeric or not.
95
#include<ctype.h>
int main()
{
char ch;
if(isalnum(ch))
printf("%c is an alphanumeric character.\n",ch);
else
printf("%c is not an alphanumericcharacter.\n",ch);
return 0;
}
String Manipulation:
The string header, string.h, provides many functions useful for manipulating strings or character
arrays. Some of these are mentioned below:
Example programs:
The given code shows the use of the strcpy()function.
#include <string.h>
96
int main()
{
char s1[] =“Hello, world!”;
char s2[20];
strcpy(s2, s1);
puts (s2);
return 0;
}
The following program illustrates the comparison of two strings.
#include <stdio.h>
#include <string.h>
int main()
{
char x[50],y[]=“a programming example”;
strcpy(x,“A Programming Example”);
if(strcmp(x,“A Programming Example”) == 0)
printf(“Equal \n”);
else
printf(“Unequal \n”);
if( strcmp(y,x) == 0)
printf(“Equal \n”);
else
printf(“Unequal \n”);
return 0;
}
int main()
{
char s[30] =“Hello,”;
charstr[] =“world!”;
printf(“%s\n”, s);
strcat(s, str);
printf(“%s\n”, s);
return 0;
}
Declaration:
A two-dimensional array of strings can be declared as follows:
<data_type><string_array_name>[<row_size>][<columns_size>];
Consider the following example on declaration of a two-dimensional array of strings.
char s[5][30];
Initialization:
Two-dimensional string arrays can be initialized as shown
97
char s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};
which is equivalent to
Examples:
The following program demonstrates how an individual string of an array of strings can be used
to take input from the user. As mentioned before, each row (i.e., s[i], if ‘s’ is the array of strings)
of an array of strings is a string.
#include <stdio.h>
int main()
{
inti;
char s[10][30], t[30];
for(i=0;i<10;i++)
scanf(“%s”,s[i]);
for(i=0;i<10;i++)
printf(“\n%s”,s[i]);
return 0;
}
The following program sorts an array of strings using bubble sort. Note here that strcmp() is used
to compare the string. strcpy() is used for interchanging the strings.
#include <stdio.h>
#include <string.h>
int main()
{
char s[10][30], t[30];
inti,j,n;
printf(“\n how many strings:”);
scanf(“%d”,&n);
printf(“\n enter the strings:\n”);
for(i=0;i<n;i++)
scanf(“%s”,s[i]);
printf(“\n **starting comparing and sorting**”);
for(i=0;i<n-1;i++)
for(j=i+1; j<n; ++j)
if(strcmp(s[i],s[j])>0)
98
{
strcpy(t,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],t);
}
printf(“\n **sorted array**\n”);
for(i=0;i<n;i++)
printf(“\n%s”,s[i]);
return 0;
}
UNIT IV
Pointer :
A pointer is a variable that stores the address of another variable. Unlike other variables that hold
values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you
can say stores) an integer value, however an integer pointer holds the address of a integer variable.
Definitions:
Call by address: facilitating the changes made to a variable in the called function to become permanently
available in the function from where the function is called.
Call-by-value :A particular way of implementing a function call, in which the arguments are passed by their
value (i.e., their copies).
Dangling pointer: A pointer pointing to a previously meaningful location that is no longer meaningful;
usually a result of a pointer pointing to an object that is de allocated without resetting the value of the pointer.
Dynamic memory allocation :The process of requesting and obtaining additional memory segments
during the execution of a program.
Function pointer: A function has a physical location in memory that can be assigned to a pointer. Then it
is called function pointer. This address is the entry point of the function and it is the address used when the
function is called.
Garbage collection: If only implicit dynamic allocation is allowed then deallocation must also be done
by implicit means, which is often called garbage collection.
NULL : A special C constant, defined as macro in stdio.h as or 0, or (void*)), that can be used as the null
value for pointers.
Null pointer: A null pointer is a special pointer value that points nowhere. I is initialized with value 0 or
NULL.
Static memory allocation: Memory layout for static data prepared by the compiler.
Void pointer :A void pointer is a special type of pointer that can point to any data type.
Memory Layout:
• Attributes of variables
• Name
• Location (address)
• Type and value
• Scope, lifetime
• Operations
• The location of a variable is decided by the compiler and the operating system at run-time.
• The initial value of a variable without assigning a value, the result is a garbage value.
• The primary use of a pointer is to access and, if appropriate, change the value of the variable that the
pointer is pointing to.
• The other pointer operator available in C is ‘*’, called the ‘value at address’ operator. It returns the
value stored at a particular address. It is also called indirection operator/ dereference operator.
Pointer Variable :
Definition :
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
101
address.
The general form of a pointer variable declaration is
Syntax : type *var-name;
102
long *p p is pointer to a long integer
unsigned char p P is an unsigned character
unsigned char *p P is pointer to an unsigned character
Some Pointer Variable Declarations
Example:
Initializing Pointers :
A Pointer is similar to any other variable excepts that it holds only memory address and therefore it needs
to be initialized with a valid address before it can be used.
• Unlike a simple variable that stores a value, a pointer must be initialized with a specified address prior
to its use.
103
•A pointer should be initialized with another variable’s memory address, with 0, or with the keyword
NULL prior to its use; otherwise the result may be a compiler error or a run-time error.
Example :
#include <stdio.h>
int main()
{
int *p; /* a pointer to an integer */
printf(“%d\n”,*p);
return 0;
}
Assigning Pointers :
• A pointer is bound to a specific data type (except pointer to void) . A pointer to an int cannot hold the
address of a character variable in which case a compiler error would result.
• The following pointer initializations are invalid.
int a=6, *ip;
float *p;
char ch=’A’;
p=&a;
ip=&ch:
om the Below Figure :
• r points to the same address that p points to, which is the address of i.
• We can assign pointers to one another, and the address is copied from the right-hand side to the
left- hand side during the assignment.
• To print the memory address stored in pointers and non-pointer variables using the %p conversion specifier
and to learn the use of the %p conversion specifier.
104
• Addresses must always be printed using %u or %p or %x. If %p is used, the address is printed in
hexadecimal form. If %u is used, address is printed in decimal form.
Example 1 :
/* Program to illustrate Pointer Initialization*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
*p=&a;
printf(“\n*p = %p”, *p);
return 0;
}
Example 2 :
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
p=&a;
printf(“\n*p = %p”, *p);
return 0;
}
Output:
p = 0022FF2C
• No
• In C, pointers are not allowed to store any arbitrary memory address, but they can only store addresses
of variables of a given type.
• Consider the following code:
int *pi;
pi= (int*)1000;
*pi = 5;
• Location 1000 might contain the program. Since it is a read only, the OS will throw up a segmentation
fault.
Example:
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main()
105
{
int num = 15;
int *iPtr = #
printf(“ The value of a num is %d”, num);
num = 100;
printf(“ The value of a num after num=10 is %d”, num);
*iPtr = 25;
printf(“ The value of a num after *iPtr = 15 is %d”, num);
}
Output:
The value of num is 15
The value of num after num = 100 is 100
The value of num after *iPtr = 25 is 25
Void Pointer :
•A void pointer is a special type of pointer.
•It can point to any data type, from an integer value or a float to a string of characters.
•Its sole limitation is that the pointed data cannot be referenced directly (the asterisk * operator cannot
be used on them) since its length is always undetermined. Use type casting or assignment
Example:
/* Program to illustrate Void Pointer */
int main()
{
int a=10,
double b=3.1415;
void *vp;
vp=&a;
printf(“\n a=%d”, *((int*)vp));
vp=&b;
printf(“\n a= %d”, *((double *)vp));
return 0;
}
Output :
a= 10
b= 3.141500
Null Pointer :
• Null pointer is a special pointer that points nowhere. That is, no other valid pointer to any other variable
106
or array cell or anything else will ever be equal to a null pointer.
#include <stdio.h>
int *ip = NULL;
• It is also possible to refer to the null pointer using a constant 0,
int *ip = 0;
• NULL is a constant that is defined in the standard library and is the equivalent of zero for a pointer.
• NULL is a value that is guaranteed not to point toany location in memory.
Use of Pointers :
Call by reference : One of the typical applications of pointers is to support call by reference. However, C does
not support call by reference as do other programming languages such as PASCAL and FORTRAN.
• Typically a function call is made to communicate some arguments to the function.
• C makes use of only one mechanism to communicate arguments to a function: call by
value.
• This means that when a function is called, a copy of the values of the arguments is created
and given to the function.
• Call by reference: Simulated by the use of pointers called “call by address”.
Example:
/* Program to illustrate call by Value*/
void swap(int a, int b)
{
int temp; temp=a; a=b; b=temp;
}
int main()
{
int x=5,y=10;
void swap(int,int); printf(“%d %d\n”,x,y);
swap(x,y);
printf(“%d %d\n”,x,y);
return 0;
}
Output:
5 10
5 10 No swapping
Output:
5 10
10 5
Returning more than one value from a function:
Example :
Program to print area by illustrating returning more than one value from a function*/
#include <stdio.h>
int main()
• An array is a non-empty set of sequentially indexed elements having the same type of data.
• Each element of an array has a unique identifying index number. Changes made to one element of
an array does not affect the other elements.
• An array occupies a contiguous block of memory. The array a is laid out in memory as a contiguous
block, as shown.
Example :
/* Program to illustrate arrays*/
#include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array[0]);
return 0;
}
Output:
2147478270
2147478270
A pointer variable (of the appropriate type) can also be used to initialize or point to the
first element of the array.
109
Below figure depicts the equivalence among array notation and pointer notation.
• For any one-dimensional array a and integer i, the following relationships are always true.
a[i] ≡ *(a+i) ≡ *(i+a) ≡ i[a]
• An array may be passed to a function, and the elements of that array may be modified without
110
having to worry about referencing and dereferencing.
• All array names that are function parameters are always converted into pointers by the compiler.
• Because when passing an array to a function, the address of the zero-th element of the array is copied to
the pointer variable which is the formal parameter of the function.
• However, arrays and pointers are processed differently by the compiler, represented differently at runtime.
Differences between Array Name & Pointer :
• When memory is allocated for the array, the starting address is fixed, i.e., it cannot be changed during
program execution. Therefore, array name is an address constant.
• The & (address of) operator normally returns the address of the operand. However, arrays are the
exception.
• When applied to an array (which is an address), it has the same value as the array reference without the
operator.
• This is not true of the equivalent pointers, which have an independent address.
• The sizeof operator returns the
• Size of the allocated space for arrays in case of arrays.
• 4 or 8 bytes depending on the machine architecture.
Arrays Pointers
Array allocate space automatically It is explicitly assigned to point to an allocated
111
space
It cannot be resized It can be resized using realloc( )
It cannot be reassigned It can be reassigned
sizeof(arrayname) gives the number of bytes sizeof(p) gives the number of bytes used to
occupied by the array store the pointer variable p
Pointer Arithmetic :
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a
pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers:
++, --, +, and –
112
Important Points - Pointer Arithmetic:
Array of Pointers :
• An array of pointers can be declared very easily.
Example: int *p[20];
• Declares an array of 20 pointer, each of which points to an integer.
• 1st pointer is p[0], 2nd is p[1], and so on up to p[19].
• These start off as uninitialized—they point to some unknown point in memory. We could make
them point to integer variables in memory thus.
Example :
113
Pointers to Array : We can declare a pointer to a simple integer value and make it point to the array as is
done normally.
Example :
int v[5] = {1004, 2201, 3000, 432, 500};
int *p = v;
printf(“%d \n”, *p);
This piece of code displays the number, which the pointer p points to, that is the first number in the array,
namely 1004. We can use instructions such as += and -= to refer to different elements in the array.
114
Difference between an array of pointers and a pointer to an array
A two-dimensional array in C is treated as a one dimensional array whose elements are one-dimensional arrays
(the rows).
• C does not do run-time range checking of array subscripts.
• In C the rightmost subscript of a two-dimensional array varies faster than the leftmost.
• Multi-dimensional array is stored in a ‘row major addressing’ format.
• The following expressions are equivalent for a two dimensional array
a[i][j]= *(a[i]+ j) = (*(a + i))[j] = *(*(a + i)+ j)
• Arrays of dimension higher than two work in a similar fashion.
• Let us describe how three-dimensional arrays work.
• If the following is declared
int a[7][9][2];
• In case of multi-dimensional arrays all sizes except the first must be specified.
116
Physical representation of a two-dimensional array
Example 1 :
117
scanf("%d %d",&m,&n);
printf("\nEnter the elements of A: ");
getdata(A,m,n);
printf("\nEnter the elements of B: ");
getdata(B,p,q);
printf("\nGiven matrix A is:\n");
display(A,m,n);
printf("\nGiven matrix B is:\n");
display(B,p,q);
add(A,B,C,m,n);
printf("\nGiven Resultant matrix C is:\n");
display(C,m,n);
return 0;
}
Example 2 :
int *A[10],*B[10],*C[10],m, n, i;
printf("\nEnter the values of m and n: ");
scanf("%d %d",&m,&n); //read the values of m and n
for(i=0;i<m;++i) //allocate memory dynamically
{
A[i]=(int*)malloc(n*sizeof(int));
B[i]=(int *)malloc(n*sizeof(int));
C[i]=(int *)malloc(n*sizeof(int));
}
getdata(A,m,n);
getdata(B,m,n);
add(A,B,C,m,n);
display(C,m,n);
Example 3 :
printf("\n");
}
return;
}
Example 4 :
int **A,**B,**C, i, m, n;
printf("\nEnter the values of m and n: "); scanf("%d %d",&m,&n);
//read the values of m and n
for(i=0;i<m;++i)
A[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;++i)
B[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;++i)
C[i]=(int *)malloc(n*sizeof(int));
Example 5 :
119
printf("\n");
}
return;
}
Pointers to Functions :
C also allows pointers to point to functions and it is one of the powerful feature
Declaration of a Pointer to a Function
return_type (*fptr) (argument_type1, argument_type2, ..);
xample:
int(*fp)(int, char, float); //fp is a pointer to a function that take one int, one char, one float
and returns an int
• Parenthesis are important and int *fp(); declares a function that returns an integer pointer
• A dynamic memory allocation uses functions such as malloc() or calloc() realloc() to get memory
dynamically.
• If these functions are used to get memory dynamically and the values returned by these functions are
121
assigned to pointer variables, such assignments are known as dynamic memory allocation.
• Memory is assigned during run-time.
• In dynamic memory allocation, memory is allocated at runtime from heap.According to
• ANSI compiler, the malloc() and calloc() returns a void pointer on successful allocation of memory. If
sufficient memory is not available, the malloc() and calloc() returns a NULL.
• calloc() initializes all the bits in the allocated space set to zero where as malloc() does not do this.
• When dynamically allocated, arrays are no longer needed, it is recommended to free them immediately.
#includestdio.h>
#include<stdlib.h>
int main()
{
int N,*a,i,s=0;
printf(“\n enter no. of elements of the array:”);
scanf(“%d”,&N);
a=(int *)malloc(N*sizeof(int));
if(a==NULL)
{
printf(“\n memory allocation unsuccessful...”);
exit(0);
}
printf(“\n enter the array elements one by one”);
for(i=0; i<N;++i)
{
scanf(“%d”,&a[i])); /* equivalent statement
scanf(“%d”,(a+i));*/
s+=a[i];
}
printf(“\n sum is %d ”,s); return 0;
}
Freeing Memory :
• Dynamically allocated memory is de-allocated with the free function. If p contains a pointer previously
returned by malloc(), a call such as free(p);
• calloc() requires two parameters, the first for the number of elements to be allocated and the second for the
size of each element, whereas malloc() requires one parameters.
122
• calloc() initializes all the bits in the allocated space set to zero whereas malloc() does not do this.
• P=calloc(m, n) is essentially equivalent to p = malloc(m * n);
• malloc(0) results are unpredictable. It may return some other pointer or it may return some other
implementation-dependent value.
Advantages of Pointers :
• Pointers save memory space
• Execution time with pointer is fast because data is manipulated with address i.e directly with
memory location.
• Memory is accessed efficiently with pointers
• Dynamic memory is allocated
123
• Pointers are used with data structures.
• Pointers are useful for representing two dimensional and multi dimensional Arrays.
Drawbacks of Pointers :
• A programmer is likely to commit mistakes such as typographical mistakes and providing wrong offsets.
• Porting the code to other implementations would require changes, if data type sizes differ. This would lead
to portability issues.
• Pointers have data types but the size of a pointer variable is always 4-bytes (in a 32-bit machine) 8-bytes (in
a 64-bt machine) whatever the data type is used in declaring it.
Structures
Definition
Arrays allow defining type of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C that allows combining data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library.
You might want to track the following attributes about each book−
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data type,
with more than one member. The format of the struct statement is as follows –
data_typestruct_member n;
} [one or more structure variables separated by comma];
The structure_nameis optional and each struct_memberis a normal variable definition, such as int i; or
float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon,
you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure –
struct Books
{
char title[50]; char author[50]; char subject[100]; intbook_id;
}book;
124
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we wish to
access. You would use the keyword structto define variables of structure type.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
Struct Books Book1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare Book2 of type
Book*/
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n",Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n",Book2.subject);
125
printf( "Book 2 book_id : %d\n", Book2.book_id); return 0;
}
When the above code is compiled and executed, it produces the following result
Book 1 title : C Programming
Book 1 author :Nuha Ali
Nested structures
Structure written inside another structure is called as nesting of two structures. Nested Structures are
allowed in C Programming Language. We can write one Structure inside another structure as member of
another structure.
Example:
structdate
{
int date; int month; int year;
};
struct Employee
{
charename[20];
intssn;
float salary;
struct date doj;
}emp1;
Structure members are accessed using dot operator. ‘date‘ structure is nested within Employee
Structure. Members of the ‘date‘ can be accessed using ’employee’ emp1 &doj are two structure
names (Variables)
Accessing Month Field : emp1.doj.month Accessing day Field : emp1.doj.day Accessing year Field
:emp1.doj.year
126
The following example shows how to use nested structure in a program
#include <stdio.h>
struct Employee
{
charename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
When the above code is compiled and executed, it produces the following result
Employee Name :Pritesh Employee SSN : 1000 Employee Salary : 1000.500000 EmployeeDOJ
: 22/6/1990
Arrays of Structures
We may declare the structure variable as an array by using index. Arrays of structures are passed using
the following syntax,
structstructure_name{ data_type struct_member1; data_typestruct_member2;
data_typestruct_membern;
};
structstructure_namestruct_variable[index_value];
You can pass a structure as a function argument in the same way as you pass any other variable or
pointer. Like all other types, we can pass structures as arguments to a function. In fact, we can pass individual
members, structure variables, a pointer to structures etc to the function. Similarly, functions can return either
an individual member or structures variable or pointer to the structure.
We can pass individual members to a function just like ordinary variables.The following program demonstrates
how to pass structure members as arguments to the function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 structstudent
8{
9 charname[20];
10introll_no;
11intmarks;
12};
13
14voidprint_struct(charname[],introll_no,intmarks);
15
16intmain()
17{
18structstudentstu={"Tim",1,78};
19print_struct(stu.name,stu.roll_no,stu.marks);
20return0;
21}
128
22
23voidprint_struct(charname[],introll_no,intmarks)
24{
25printf("Name: %s\n",name);
26printf("Roll no: %d\n",roll_no);
27printf("Marks: %d\n",marks);
28printf("\n");
29}
When the above code is compiled and executed, it produces the following result
Name: Tim
Roll no: 1
Marks: 78
• In lines 7-12, a structure student is declared with three members namely name, roll_no and marks.
• In line 14, a prototype of function print_struct() is declared which accepts three arguments namely
name of type pointer to char, roll_no of type int and marks is of type int.
• In line 18, a structure variable stu of type struct student is declared and initialized.
• In line 19, all the three members of structure variable stu are passed to the print_struct() function. The
formal arguments of print_struct() function are initialized with the values of the actual arguments.
• From lines 25-27, three printf() statement prints name, roll_no and marks of the student.
• The most important thing to note about this program is that stu.name is passed as a reference because
name of the array is a constant pointer. So the formal argument of print_struct() function i.e name
and stu.name both are pointing to the same array. As a result, any changes made by the
function print_struct() will affect the original array. We can verify this fact by making the following
amendments to our program.
• In lines 7-12, a structure student is declared with three members namely: name, roll_no and marks.
• In line 14, the prototype of function print_struct() is declared which accepts an argument of type struct
student.
• In line 18, a structure variable stu of type struct student is declared and initialized.
• In line 19, print_struct() function is called along with argument stu. Unlike arrays, the name of structure
variable is not a pointer, so when we pass a structure variable to a function, the formal argument
of print_struct() is assigned a copy of the original structure. Both structures reside in different memory
locations and hence they are completely independent of each other. Any changes made by
function print_struct() doesn't affect the original structure variable in the main() function.
• The printf() statements from lines 25-27 prints the details of the student.
Just as we can return fundamental types and arrays, we can also return a structure from a function. To return a
130
structure from a function we must specify the appropriate return type in the function definition and declaration.
Consider the following example:
struct player check_health(struct player p);
{
...
}
This function accepts an argument of type struct player and returns an argument of type struct player.
The following program demonstrates how we can return a structure from a function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 structplayer
8{
9 charname[20];
10floatheight;
11floatweight;
12floatfees;
13};
14
15voidprint_struct(structplayerp);
16structplayerdeduct_fees(structplayerp);
17
18intmain()
19{
20structplayerp={"Joe",5.9,59,5000};
21print_struct(p);
22p=deduct_fees(p);
23print_struct(p);
24
25return0;
26}
27
28structplayerdeduct_fees(structplayerp)
29{
30p.fees-=1000;
31returnp;
32}
33
34voidprint_struct(conststructplayerp)
131
35{
36printf("Name: %s\n",p.name);
37printf("Height: %.2f\n",p.height);
38printf("Weight: %.2f\n",p.weight);
39printf("Fees: %.2f\n",p.fees);
40
41printf("\n");
42}
When the above code is compiled and executed, it produces the following result
Name: Joe
Height: 5.90
Weight: 59.00
Fees: 5000.00
Name: Joe
Height: 5.90
Weight: 59.00
Fees: 4000.00
You can define pointers to structures in the same way as you define pointer to any other variable –
132
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To find the
address of a structure variable, place the '&'; operator before the structure's name as follows –
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the
→ operator as follows –
struct_pointer->title;
The following program demonstrates how to access structure members using pointers.
#include <stdio.h>
#include <string.h>
struct Books{
chartitle[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */ voidprintBook(struct Books *book ); int main( ) {
structBooksBook1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare Book2 of type
Book*/
/* book 1 specification */
strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
133
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces the following result – Book title : C Programming
Book author :Nuha Ali
Book subject : C Programming Tutorial Book book_id : 6495407
Book title : Telecom Billing Book author : Zara Ali
Book subject : Telecom Billing Tutorial Book book_id : 6495700
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
structnode {
intdata1;
chardata2;
structnode* link;
};
intmain()
{
structnode ob;
return0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a self-
referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing, as by default it
contains garbage value.
134
The following Program to demonstrate Self referential structure.
#include <stdio.h>
structnode {
intdata1;
chardata2;
structnode* link;
};
Int main()
{
structnode ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
Unions
A union is a special data type available in C that allows storing different data types in the same
memory location. You can define a union with many members, but only one member can contain a value at
any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.
135
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your program. The
format of the union statement is as follows–
The union tag is optional and each member definition is a normal variable definition, such as int i; or
float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon,
you can specify one or more union variables but it is optional. Here is the way you would define a union type
named Data having three members i, f, and str–
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It
means a single variable, i.e., same memory location, can be used to store multiple types of data. You can use
any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum
space which can be occupied by a character string.
The following example displays the total memory size occupied by the above union –
#include <stdio.h>
#include <string.h>
union Data {
inti; float f;
char str[20];
};
Int main( )
{
union Data data;
printf("Memorysizeoccupiedbydata:%d\n",sizeof(data));
return0;
}
136
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult– Memorysizeoccupiedbydata:20
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish to access.
You would use the keyword union to define variables of union type.
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy(data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result – data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final value
assigned to the variable has occupied the memory location and this is the reason that the value of str member
is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the main
purpose of having unions –
#include <stdio.h>
#include <string.h>
union Data
{
137
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy(data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result – data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
The enum keyword is also used to define the variables of enum type. There are two ways to define the
variables of enum type as follows.
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main()
{
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri, Sat, Sun);
138
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid, Satu,
Sund);
return 0;
}
When the above code is compiled and executed, it produces the following result –
UNIT V
INTRODUCTION TO FILES:
In real world application when data is large then it is necessary to stored on the disk in
files. A file represents a sequence of bytes. file is created in secondary storage. Files are of two
types text file and binary file.
C language provides access on files with high/low level functions .FILE is a structure
defined in standard input/output library.
The file pointer is created and used as FILE *fp; where fp is a file pointer
Types of files
1. Text File :
A text stream consist of a sequence of characters. they are grouped in line. stores the
data in the text form
2. Binary File :
It stores the data in the binary form (1's and 0's). A binary stream consists of a
sequence of data. They are stored in their memory representation.
Operations on Files
C language support a number of functions to perform basic operation on file
• creating a file
• opening a file
• writing into the file
• reading from the file
• close the file
files I/O functions to manipulate data in file :
fopen() : create a file or open an existing file
fclose() : close a file
getc() : read a character
putc() : write a character
fprintf() : write a formatted values
fscanf() : read set of values
getw() : read an integer
putw() :write an integer
139
How to open a file?
fopen() function is used to open a file . This function creates a new file if the file does
not exist. .
Syntax: fopen(filename,mode)
Here, the first argument is file name and second argument is access mode.
The following are the different access modes in C,
r : read mode
w : writing mode
a : append mode
r+ : First reading then writing
w+: reading and writing and content is truncated
a+ : reading and writing and content is not truncated
Example:
#include<stdio.h>
int main()
{
FILE *fp; //creating a file pointer
fp=fopen("abc.txt","r"); // open a file
fclose(fp); // at the end close the file
return 0;
}
Summary exercise:
1. File pointer is created using FILE structure which is defined in stdio.h header file.
2. There 2 types of files: Text file, binary file
3. files can be opened in different modes to manipulate data using fopen() function.
Example: Write a program to read data from file using fgetc() method
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("myfile.txt","r");
do {
c = fgetc(fp);
if( c==EOF ) {
break ;
}
printf("%c", c);
} while(1);
fclose(fp);
return(0);
}
2. fgets():
It reads a string from a stream.
3. fscanf()
This function is to read strings from a file, but it stops reading after encountering the
first space character.
141
Syntax: int fscanf(FILE *fp, const char *format, [ argument, ...])
Example: Write a program to read data from file using fscanf() method
#include <stdio.h>
void main() {
FILE *fp;
char name[255];
int rollnum;
fp = fopen(“myfile.txt”, “r”);
fscanf(fp, "%s", name);
fscanf(fp, "%d", rollnum);
}
Reading data from binary file:
The following function is used for reading data from a Binary File.
1. fread()
Reads data from the given stream into the array .
Syntax: size_t fread(void *ptr, size_t sizeOfElements, size_t numberOfElements,
FILE *fp);
Here,
ptr − the pointer to a block of memory with a minimum size of sizeOfElements *
numberOfElements bytes.
sizeOfElements − the size in bytes of each element to be read.
numberOfElements − the number of elements, each one with a size of size bytes.
fp − the pointer to a FILE object that specifies an input stream.
Example: Write a program to read data from file using fread() method
#include <stdio.h>
int main () {
FILE *fp;
char output[100];
/* Open file for reading */
fp = fopen("myfile.txt", "r");
Key topics / themes of the lecture : Writing data to files, error handing during file
operations
142
WRITING DATA TO FILES
We can write data to both text files as well as binary files.
Writing data to a text file:
The following 3 functions are used for writing data to a Text File.
1. fputc():
The fputc() function writes the character value of the argument c to the output stream
referenced by file pointer. It returns the written character written on success otherwise
EOF if there is an error.
Syntax: int fputc(int c, FILE * fp );
Example: Write a program to write data to a file using fputc() method
#include <stdio.h>
int main () {
FILE *fp;
int ch;
fp = fopen("myfile.txt", "w");
for( ch = 65 ; ch <= 92; ch++ ) {
fputc(ch, fp);
}
fclose(fp);
return 0 ;
}
2. fputs():
It writes the string to the output stream referenced by file pointer.
Syntax: char *fgets( char *str, FILE *fp );
#include <stdio.h>
main() {
FILE *fp;
fp = fopen(“myfilet.txt", "w");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
3. fprintf()
It sends formatted output to a stream..
Syntax: int fprintf(FILE *fp, const char *format, [ argument, ...])
143
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * fp;
fp = fopen ("file.txt", "w");
fprintf(fp, "%s %d", "CSE dept code is", 733);
fclose(fp);
return 0;
}
writing data to binary file:
The following function is used for writing data to a Binary File.
1. fwrite()
It writes data from the array pointed to by ptr to the given stream.
Syntax: size_t fread(void *ptr, size_t sizeOfElements, size_t numberOfElements,
FILE *fp);
Here,
ptr − the pointer to a block of memory with a minimum size of sizeOfElements *
numberOfElements bytes.
sizeOfElements − the size in bytes of each element to be read.
numberOfElements − the number of elements, each one with a size of size bytes.
fp − the pointer to a FILE object that specifies an input stream.
#include<stdio.h>
int main () {
FILE *fp;
char str[] = "CSE department code is 733";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
return 0;
}
Example: Demonstrate a program to access data from a file using random access file operations.
#include <stdio.h>
int main () {
FILE *fp;
int len;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("Total size of file.txt = %d bytes\n", len);
return 0;
}
# include <filename>
or
145
#include “file name”,
If included inside <> then the compiler looks for the file in an implementation defined
manner (or system directory paths). If included inside a quote “ ” statement then it searches for
the file in the same directory as the program being written.
So if we include a file named file1 while writing a program name code.c which is being
stored in a folder called test. Then inclusion like so -- #include “file1” will tell the compiler to
look for the file inside the test folder, It looks at neighboring folders or subfolders too but it starts
its search in the test folder.(This sub search option is compiler dependent).
A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros: Object-like Macros, Function-like Macros
When this line appears in a file, all subsequent occurrences of identifier that do not
appear in string literals will be replaced by the replacement text automatically before program
compilation takes place.
Replaces all subsequent occurrences of the symbolic constant PI with numeric constant
3.14159. Symbolic constants enable the programmer to create a name for a constant and use that
name throughout program execution. If this needs to be modified ,it has to be done in the #define
directive statement. After recompilation all definitions get modified accordingly.
Function-like Macros
146
Output:
Minimum between 10 and 20 is: 10
Macro Function
Macro is Preprocessed Function is Compiled
No Type Checking Type Checking is Done
Code Length Increases Code Length remains Same
Speed of Execution is Speed of Execution is Slower
Faster
Before Compilation macro name is replaced by During function call , Transfer of
macro value Control takes place
Useful where small code appears many time Useful where large code appears many time
Generally Macros do not extend beyond one line Function can be of any number of lines
Macro does not Check Compile Errors Function Checks Compile Errors
Preprocessor Formatting
A preprocessing directive cannot be more than one line in normal circumstances. It may be split
cosmetically with Backslash-Newline. Comments containing Newlines can also divide the
directive into multiple lines.
for example, you can split a line cosmetically with Backslash-Newline anywhere:
/*
*/ # /*
*/
defi\
ne
FO\ O
10\ 20
is equivalent into #define FOO 1020.
#undef
To undefine a macro means to cancel its definition. This is done with the #undef directive.
Syntax:
#undef token
define and undefine example
#include
<stdio.h>
#define PI
3.1415 #undef PI
147
main() {
printf("%f",PI);
}
Output:
Compile Time Error: 'PI' undeclared
#ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the
code.
Syntax:
#ifdef MACRO
//code
#endif
#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the
code.
Syntax:
#ifndef MACRO
//code
#endif
#if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code.
Syntax:
#if expression
//code
#endif
#else
The #else preprocessor directive evaluates the expression or condition if condition of #if is false.
It can be used with #if, #elif, #ifdef and #ifndef directives.
Syntax:
148
Syntax with #elif
#if expression
//if code
#else
//else code
#endif
#if expression
//if code
#elif expression
//elif
code
#else
//else code
#endif
Example Code
#include <stdio.h> #include
<conio.h> #define
NUMBER 1 void main() {
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}
O/P:
Value of Number is non-zero
Example Code:
char array[BUFFER_SIZE] =
[0]; int I = 9;
printf(“%d”,i);
149
printf(“%s”,array
); return 0;
Conditional Compilation:
Example
– #if
!defined(MY_CONSTANT)
#define MY_CONSTANT 0
#endif
150
These directives determine if MY_CONSTANT is defined or not. The expression defined
(MY_CONSTANT) evaluates to 1 if MY_CONSTANT is not defined and is defined else it
evaluates to 0.
#include <stdio.h>
#define MEMBER
int main()
float amount,total;
printf("enter amount\n");
scanf("%f",&amount);
#ifdef MEMBER
total= amount*0.8;
printf("Amount to be paid=%f",total);
#else
printf("Amount to be paid=%f",amount);
#endif
151
Summary exercise:
Following table will show you various directives that we have studied in this chapter:
Directives Description
152