Programming With Problem Solving
Programming With Problem Solving
[R22A0501]
LECTURE NOTES
It is said that 'C' is a god's programming language. One can say, C is a base for the
programming. If you know 'C,' you can easily grasp the knowledge of the other
programming languages that uses the concept of 'C'
Unit I – Introduction to Computer System, Problem Solving with algorithms and flowcharts
Basics of C Language – Structure, Tokens, Data types, Operators, Expressions
Unit II –Control structures and Arrays
Unit III – Modular Programming using functions
Unit IV – Strings, Pointers and Dynamic Memory Management
Unit V – Structures, Unions and Files
We would like to extend our sincere gratitude to Dr. VSK Reddy, Director, Malla Reddy
College of Engineering and Technology (autonomous) and Dr. S. Srinivasa Rao, Principal,
Malla Reddy College of Engineering and Technology, under whose patronage we were able
to write this content. We are also indebted to Dr.S. Shanthi, Head of the Department,
Computer Science and Engineering for her constant support and motivation for our
academic growth. We would also like to acknowledge our colleagues who have provided
their valuable suggestions in preparing this content.
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
PROGRAMMING FOR PROBLEM SOLVING
L T P C
3 1 - 3
COURSE OBJECTIVES:
1. Understand the use of computer system in problem solving and to build program logic
with algorithms and flowcharts.
2. To learn the syntax and semantics of C Programming Language
3. To learn the usage of structured programming approach in solving problems
4. To learn the usage of strings and pointers
5. To understand the usage of structures and files.
UNIT - I:
Introduction to Programming:
Compilers, Compiling and executing a program, Representation of Algorithms and Flowcharts
with examples.
Introduction to C Programming Language: Structure of a C Program, I/O: Simple input and
output with scanf() and printf(), Keywords, Identifiers, Constants, Variables, Data types,
Operators, Expressions and precedence, Expression evaluation, Type conversion.
TEXT BOOKS:
1. Jeri R. Hanly and Elliot B.Koffman, Problem solving and Program Design in C 7th Edition,
Pearson.
2. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage Learning, (3rd
Edition).
3. E. Balagurusamy, Computer fundamentals and C, 2nd Edition, McGraw-Hill.
REFERENCE BOOKS:
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of
India.
2. Yashavant Kanetkar, Let Us C, 18th Edition, BPB.
3. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
4. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
5. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition.
6. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill.
COURSE OUTCOMES:
PAGE
S.NO UNIT NAME
NUMBER
UNIT –I Introduction to Problem Solving, Basics of C 6-47
The computer allows us to do tasks more efficiently, quickly, and accurately than we could by hand. In
order for this powerful machine to be a useful tool, it must be programmed. That is, we must specify what
we want done and how. We do this through programming.
A computer is not intelligent. It cannot analyze a problem and come up with a solution. A human (the
programmer) must analyze the problem, develop the instructions for solving the problem, and then
have the computer carry out the instructions.
Once we have written a solution for the computer, the computer can repeat the solution very quickly
and consistently, again and again. The computer frees people from repetitive and boring tasks.
Problem solving requires thinking about the problem at a high level of abstraction while writing
programming language code requires a very low level of abstraction
To write a program for a computer to follow, we must go through a two-phase process: problem solving
and implementation
Problem-Solving Phase
1. Analysis and Specification: Understand (define) the problem and what the solution mustdo.
2. General Solution (Algorithm): Specify the required data and the logical sequences of steps that
solve theproblem.
3. Verify: Follow the steps exactly to see if the solution really does solve theproblem.
Implementation Phase
1. Concrete Solution (Program): Translate the algorithm (the general solution) into a
programminglanguage.
2. Test: Have the computer follow the instructions. Then manually check the results. If you find
errors, analyze the program and the algorithm to determine the source of the errors, and then
makecorrections.
The programmer begins the programming process by analyzing the problem, breaking it into
manageable pieces, and developing a general solution for each piece called an algorithm. The
solutions to the pieces are collected together to form a program that solves the original
problem.
INTRODUCTION TO COMPUTING
Computer systems
Computer is a digital electronic device which understands only 0’s and 1’s. It performs
all arithmetic calculations (Addition, multiplication...) and non arithmetic calculations (copy,
choose, move, compare….).
A computer is a system made of two components: Hardware and Software
The computer hardware is the physical equipment. The software is the collection of
programs (instructions) that allow the hardware to do its job. The computer manipulates these
symbols in the desired way by following an intellectual map called program. A program is a
detail set of humanly prepared instructions that directs the computer to
functioninaspecificwaytoproducethedesiredresults.Computerintelligencequotientor
I.Q is zero. It does not have any thinking, arguing or decision-taking power of its own. This
power is intelligently conferred to it by proper programming methods by persons handling it.
Computer Hardware:
1. Inputdevices
2. Central processing unit(CPU)
3. Primary (Main) storage or Immediate Access memory Storage(I.A.S)
4. Outputdevices
5. Auxiliary storage devices or secondary memory or backing storage devices (floppy disk, tape...)
The input device is usually a keyboard where programs and data are entered into the
computer. Examples of the other input devices include a mouse, a pen, or stylus, a touch
screen, or an audio input unit.
The central processing unit (CPU) is responsible for executing instruction such as
arithmetic calculations, comparisons among data, and movement of data inside the system.
Primary storage is a place where the programs and data are stored are erased when we
turn off a personal computer or when we log off from a time-sharing computer.
The output device is usually a monitor or a printer to show output. If the output is
shown on the monitor, we say we have a soft copy. If a printed on the printer, we say we have
a hard copy.
Auxiliary storage is used for both input and output. It is a place where the programs and
data are stored permanently. When we turn off the computer, our programs and data remain
in the secondary storage, ready for the next time we need them.
Computer Software:
Computer software is divided into two categories: system software and application
software. System software manages the computer resources. It provides the interface between
the hardware and the users but does nothing to directly serve the users need. Application
software is a directly responsible for helping users solves their problem.
System Software:
System software consists of programs that manages the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interface to communication systems such as internet protocols.
System support software provides system utilities and other operating services.
System development software includes the language translators that convert programs into
machine language for execution, debugging tools to ensure that the programs are errorfree.
Application software:
These are divided into two classes: General-purpose software and Application-specific
software
General-purpose software is purchased from a software developer and can be used for more
than one application. Examples like word processor, database managementsystems.
Application-specific software can be used only for its intended purpose. A general ledger
system used by accountants and a material requirements planning system used by a
manufacturing organization are examples.
USER
UNIT-I
Topics Covered
Computer languages
Low Level Language: The only programming language available was machine languages. Each
computer has its own machine language which is made of streams of 0’s and 1’s. The only
language understood by computer hardware is machinelanguage.
1. Middle Level Language: The programs are written using the instructions of CPU is called
Assembly level language. It uses symbols, or mnemonics, to represent the various
machine language instructions. Examples are TASM,MASM
2. High Level Language: In the Assembly level language programmers need to concentrate
on the hardware so it is tedious because each machine instruction had to be individually
coded. So the High level language was developed it is English like language where
instruction typically translates into machine languageinstructions.
The procedure for turning a program written in C into machine language. These steps
are repeated many times during development to correct errors and make improvements to
thecode.
The software used to write programs is known as text editor. A text editor helps us
enter, change, and store character data. Depending on the editor on our system, we could use
it to write letters write programs.
The main difference between the text processing and program writing is that program are
written using lines of code, while most text processing is done with characters and lines. After
complete a program, we save our file to disk. This file will be input to the compiler; it is known
as a sourcefile.
Compiling Programs:
The code in a source file stored on the disk must be translated into machine language. This is
the job of the compiler. The C compiler is actually two separate programs: The Preprocessor
and thetranslator
The preprocessor reads the source code and prepares it for translator. While preparing the
code, it scans for special instruction known as preprocessor commands. These commands tell
the preprocessor to look for the special code libraries, make substitutions in the code, and in
other ways prepare the code for translation with machine language. The result of
preprocessing is called the translation unit. After the preprocessor has prepared the code for
compilation the translator does the actual work of converting the program into machine
language. An object module is the coding machinelanguage.
As we will see late, a C Program is made up of many functions. We write some of these
functions, and they are a part of our source program. However, there are other functions, such
as input/output process and mathematical library functions that exists else where and must be
attached to our program. The linker all of these functions, ours and system’s, into pour final
executable programs.
Executing Programs:
Once our program has been linked, it is ready for execution. To execute a program, we use an
operating system command, such as run, to load the program into primary memory and
execute it. Getting the program into memory is the function of an operating system program
known as the loader. It locates the executable program and reads it into memory. When
everything is loaded, the program takes control and it begins execution. In today’s integrated
development environment, these steps are combined under one mouse click or pull-down
windows.
In typical program execution, the program reads data from processing, either from the user or
from a file. After the program process the data, it prepares the output. Data output can be to
the user monitor or to file. When the program has finished its job, it tells the operating system,
which then removes the program from the memory.
Algorithms
Features of an algorithm:
Effectiveness :All the operations used in the algorithm can be performed exactly in a fixed duration
time.
Input : An algorithm has certain precise inputs before the execution of the algorithm begins.
Output : An algorithm has one or moreoutputs
Pseudo code
Pseudo code is similar to everyday English; Pseudo code is an artificial and informal language
that helps programmers develops algorithms. It is convenient and user-friendly although it is
not an actual computer programming language. Pseudo code programs are not actually
executed on computers. Rather, they merely help the programmers “think out” a program
before attempting to write it in a programming language such asC.
Mimic good code and good English. Variable names should be mnemonic, include
comments where it is useful.
Ignore unnecessary details. Use some convention to group statements.(begin/end,
brackets).
Take advantage of programming short hands. Using if-else or looping structures is more
concise.
Consider thecontext.
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 10
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving
Step4: write/print c
Step5: stop
Example 2: An algorithm /Pseudo code to find whether a given number is odd number or a even
number.
Step1: Start
Step2: Read the numbern
Step3: If (n % 2) = 0 then
write n is even number Go to step 5
Step4: write n is odd number
Step5: Stop
Flow Chart
Read a, b
c= a + b
Write c
c cc
Stop
INTRODUCTION TO C LANGUAGE
History of C
C is a structured programming language. It is considered a high-level language because it allows the
programmers to concentrate on the problem at hand and not worry about the machine that the
program will be using. C, like modern languages, is derived from ALGOL. The first language to use a
block structure. ALGOL is used in Europe but not in America this leads to the development of
Structured programming languages. In 1967, Martin Richards developed a language called Basic
Combined Programming Language, or BCPL. Ken Thompson followed in 1970 with similar language he
simply called B. B was used to developed the first version of the UNIX, one of the popular network
operating system in use today. Finally, Dennis M. Ritchie developed C, which took many concepts from
ALGOL, BCPL, and B and added the concept of data types.
The history of ‘C’ started in 1972 by the BELL Laboratories, USA., where Dennis
M.Ritchie proposed this language. The growing popularity of ‘C’, the changes in the language
over the years and the creation of compilers by groups not involved in its design, combined to
demonstrate a need for a more precise and more contemporary definition of the language. In
1983, the American National Standards Institute (ANSI) established a committee whose goal
was to produce “An unambiguous and machine- independent definition of the language C”. The
result is the ANSI standard for C.
Structure of a C Program: Every C program contains a number of several building blocks known
as functions. Each function of it performs task independently. A function is subroutine that may
consists one or more statements.
Documentation section:
To enhance the readability of the program, programmers can provide comments about the
program in this section. Comments can be used any where in the program but too many
comments are avoided. It is useful for documentation. This gives the clarity of the program can
be followed if it is properly documented. The comments can be inserted with a single
statement or in nested statements.
Examples
// This is a single comment
/*This is a example of
nested comments */
Link Section or Header file section: C program depends upon some header files for function
definition that are used in program. A header file contains the information required by the
compiler when calls to the library functions used in the program occur during compilation. Each
header file by default is extended with .h. The file should be included using #include directive.
Example: line 2
In this example <stdio.h> file is included i.e. all the definitions and prototypes of functions
defined in this file are available in the current program. This file is compiled with original
program.
Global declaration section: This section declares some variables that are used in more than one
function. These variables are known as global variables. These must be declared outside of all
the functions.
Main program section: Every program written in C language must contain main() function.
Empty parenthesis after main is necessary. The function main() is starting point of every ‘C’
program. The execution of the program always begins with the function main(). Except the
main () function, other sections may not be necessary. The program execution starts with the
opening brace ‘ { ‘ and ends with the closing brace ‘ } ‘. Between these two braces the
programmer should declare the declaration part and the executable part.
Declaration Part: the declaration part declares the entire variables that are used in executable
part. The initialization of variables also done here. The initialization means providing the initial
value to thevariables
Executable Part: This part contains the statements following the declaration of the variables.
This part contains a set of statements. These statements are enclosed between thebraces.
1. Modularity
2. Extendability
3. Portability
4. Efficiency and Speed
5. Flexibility
Modularity: Ability to break down large modules into a manageable sub modules. It is one of
the important features of the structured programming languages. C is a structured
programming language.
Portability: Ability to port (install) existing software in different platforms (Unix, Windos etc.) is
called portability. It means that the programs written on one machine can be executed on
different machine with or without minor changes in the program. C programs can be executed
on many machines with little or no change.
Efficiency and speed: C language has rich set of data types and operators making the language
more efficient and fast. The language provides some operators example: increment and
decrement operators) which speed up the execution to large extent. Further, it also provides
user defined data types (example: structures) through which miscellaneous data can be easily
manipulated.
Middle Level Languague: Though C is a high level language often it is called as middle level
language because programs written in c language run at the speeds matching to that of the
programs written in assembly level language. Due to this reason C language is widely used in
developing system software.
Flexibility: ASCII C complier has only 32 keywords. These are the basic building blocks of the
programming language. C is also called as programmers’ language. With 32 keywords a
programmer is able to solve any type of task due to this reason programmers have the
complete control over the language their by gaining the flexibility.
C Tokens:
In a Passage of text, individual words and punctuation marks are called as tokens. In a C
program, the smallest individual units are known as C tokens. The following are different
categories of C tokens.
1) Keywords 2) Identifiers 3) Constants 4) Operators
Keywords:
Keywords are also known as reserve words. These keywords are only to be used for their
intended purpose and as identifiers. All the Keywords are lowercase.
Example: auto, char, int, long, goto, return, register…etc
Note: The keywords with at least one uppercase letter can be used as an identifier.
Identifiers:
Identifier allows us to name data and other objects in the program. Different programming
languages use different syntactical rules to form identifiers. In C, the rules for identifiers are
very simple. The only valid names symbols are the capital letter A through Z, the lowercase
letters a through z, the digits 0 and 9, and the underscore. The first character of the identifiers
cannot be a digit. The last rule is that the name we create cannot be keywords. C allows names
to be up to 63 characters long.
Rules of identifiers
1. An identifier must start with a letter or underscore: it may not have a space or a hypen,
or any other special symbol.
Variables
A variable is a place holder that occupies some part of the memory which can initialize or
assigned or changed during the execution of the program.
Declaration of variables
Initialization of variable
Conventions
1. Declare variable names in lowercaseletters
2. Variables names should provide a hint on what it is going to hold.
Constants A constant is a value that doesn’t change during the execution of a program. These
are generally declared before main function.
Constants
Integer constant: Numeric value without decimal part is called integer constant.
Example: 5, -66
Real constant: Numeric value with decimal part is called as real constant. The precision of a real
value indicates number of digits after decimal point. Example: 5.0, - 98.76…
Character constant: A single character enclosed in single quotes is called as character constant.
Character Set
Alphabet:a-z A-Z
Digits: 0-9
Special characters: $, ?, ; , , …..
Declaration of a constant
Note: In an 8 bit character set, a character occupies 1 byte, whereas in 16 bit character set, a
character occupies 2 bytes. Character constants have integer values known as ASCII values
(ASCII-American Standard code for Information Interchange).Since each character represents
an integer value, it is also possible to perform arithmetic operations on character constants.
Spacebar is also a character constant.
String constant: A single character or a group of characters enclosed in double quotes is called
string constant.
Example: “5” , “temperature”
Note: Character constant occupies 1 byte where as string constant occupies 2 bytes.
Backslash Character constants: C supports some special backslash character constants that are used in
output functions. These are also known as escape sequences.
Data Types
A data type consists of the values it represents and the operations defined upon it. The C
language has defined a set of data types that can be divided into four general categories: void,
integral, floating-point, and derived as shown below
Void type:
The void type, designated by the keyword void, has no values and no operations, although
having no values and operations might seem unusual. It can also be used to define that a
function has no return value.
Integral type
The C language has three integral types: Boolean, character, and integer. Integral types cannot
contain a fraction part; they are whole numbers.
Boolean: Boolean type can represent only two values: true or false. C used integers to
represent the Boolean values: a nonzero number (Positive or negative) was used to
represent true, and zero was used to represent false. The Boolean type, which is
referred to the keyword bool, is stored in memory as 0(false) or1(true).
Character: A character is any value that can be represented in the computer’s alphabet,
or as it is better known, its character set. An 8-bit character set represent up to
256characters.
Integer: An integer type is a number without a fraction part. C supports four different
sizes of the integer datatypes:
Floating-Point Types The C standard recognizes three floating –point types: real,
imaginary, andcomplex.
Real: The real type holds values that consist of an integral and a fractional part. The C
language supports three different sizes of real types: float, double, and long double.
Operators:
Operators are C tokens which can join together individual constants, variables, array elements
and functions references. Operators act upon data items called operators.
C operators are classified into following categories:
1. Arithmeticoperators
2. Relationaloperators
3. Logicaloperators
4. Assignmentoperators
5. Increment and decrementoperators
6. Conditionaloperators
7. Bitwiseoperators
8. Specialoperators
Arithmetic operators:
Multiplication
*
/ Division
% Modulo division
Integer arithmetic: Both the operands are integer in an integer arithmetic. It always yields an
integer value.
Example: a+b, a-b
Real arithmetic: Both the operands are real in real arithmetic. It yields real value as result. It cannot
be applied to % operator.
Example:
float a=20.0, b= 3.0
a+b= 20.0+3.0=23.000000
a/b=20.0/3.0=6.6666667
a%b=20.0%3.0(invalid expression)
Mixed mode arithmetic: when one is integer and other is real it is known as mixed mode arithmetic.
Here, result will always be real.
Example:
int a=20.0, b=3;
a+b= 20.0+3=23.0
a/b=20.0/3=6.666667
a%b=20.0%3 (invalid expression)
Relational operators: These operators compare two quantities and depending on their
relation the result will be either true or false
Example
Logical operators:
|| Logical OR
! Logical NOT
Logical NOT: the result of the expression will be true, if the expression is false and vice versa.
Syntax: !Exp2
Example: x=20
Assignment operators:
Example:
Examples:
1. int a=9;
y=++a; The value of y will be 10;
2. int a=9;
y=a++; The value of y will be 9;
Operator Action
a++ Post-increment
++a Pre-increment
a-- Post-decrement
--a Pre-decrement
In the above statement, the expression a>b is evaluated since; it is false value of c will be
assigned to y. so value of y will be 15.
Bitwise operators:
Bitwise operators are similar to that of logical operators except that they work on binary bits.
When bitwise operators are used with variables, they are internally converted to binary
numbers and then bitwise operators are applied on individual bits. Bitwise operators do
manipulation on bits stored in memory. These operators work with char and int data types.
They cannot be used with floating point numbers.
| Bitwise OR
^ Bitwise exclusive OR
Special operators:
Comma operator
Sizeof operator
Comma operator: The comma operator ‘, ’ has the lowest priority among all the operators
available in C. This operator is used to separate the related expressions. The expressions
separated by comma operator need not be included within the parenthesis.
Sizeof operator: It returns number of bytes the operand occupies. Operand may be a variable,
a constant, or a data type qualifier.
Member operators: These are used to access members of structures and unions.
Example:
Var.member1; // when var is a structure variable.
Var->members2; // when var is a pointer to structure variable.
Input/output Functions
Input and output operations on data can be done by using input and output functions. An
input function reads data from keyboard and stores in the variable whereas output function
prints value in the variable on the screen
Formatted input function accepts an input data that has been arranged in a particular format
through keyboard.
arg1,arg2…..argn are the list of variables whose values are to be printed onto the screen
Note: The arguments should match in number, order and type with the format specifications.
The format specifier can also contain sub-specifiers: flags, width, .precision and code
flags Description
Left-justify within the given field width; Right justification is the default (see width sub-
-
specifier).
Forces to preceed the result with a plus or minus sign (+ or -) even for positive
+
numbers. By default, only negative numbers are preceded with a - sign.
width Description
.precision Description
int main ( )
return 0;
The integer w indicates the minimum number of positions that are to be used for display of the
value.The integer p indicates the number of digits to be displayed after decimal point
(precision). The value when displayed is rounded to p decimal places & printed right-justified in
#include<stdio.h>
int main()
{
float y= 98.7654;
printf("\n %f", y);
printf("\n%7.4f",y);
printf("\n%7.2f",y);
printf("\n%-7.2f",y);
return 0;
}
int main()
{
printf(“%c”,’S’);
printf(“\n%3c”,’S’);
printf(“\n%6c”,’S’);
return 0;
}
S
S
S
UNFORMATTED IO FUNCTIONS
INPUT FUNCTIONS
1. getch()
2. getche()
3. getchar()
4. gets()
1. getch():- reads a character from keyboard and it does not require pressing of enterkey after
entering a key, entered character is not displayed onconsole.
charch;
ch=getch();
2. getche():- reads a character from keyboard and it does not require pressing of enterkey after
entering a key, entered character is echoed back on to theconsole.
char ch;
ch=getche();
getch() and getche() are available in the header file conio.h (console input output
header file)
gets(ch);
OUTPUT FUNCTIONS:
1. putchar()
2. puts()
3. putch()
char ch;
ch=getchar();
putchar(ch);
char ch[10];
gets(ch);
puts(ch);
3. putch():-prints a character on to thescreen
char ch;
ch=getchar();
putch(ch);
Expressions
Here a priority comes into picture with precedence. The order in which the operators in a
complex expression are evaluated is determined by a set of priorities known as precedence.
Higher the precedence that expression will be calculated first. If two operators with the same
precedence occur in a complex expression, another attribute of an operator, its associativity,
takes control. Associativity is parsing direction used to evaluate an expression. It can be either
left-to-right or right-to-left.
Note: when two operators having same precedence occur in an expression, their associativity
is left-to-right. We can divide the simple expression into six categories.
Expression
Categories
1. c=a+b*d;
2. x==y;
3. x+=y;
Note: An expression always reduces to single value.
Primary Expressions: A primary expression consists of only one operand with no operator. In c,
the operand in the primary expression can be name, a constant, or a parenthesized expression.
Names: A name is any identifier for a variable, a function or any other object in the language.
The following are examples of some names used as primaryexpressions:
Examples: a, b12, price, calc, INT_MAX, size etc.
Literal constants: A constant is a piece of data whose value can’t change during the execution
of the program.
Examples: 5, 123.98, ‘A’
Postfix Expressions: The postfix expression consists of one operand following by one operator.
Postfix increments/decrements: The postfix increments and postfix decrements are also
postfix operators. The value of the postfix increment expression is determined before the
variable is increased. For instance, if the variable a contains 4 before the expression is
evaluated, the value of the expression a++ is 4. As a result of evaluating the expression and its
side effect, a contains 5.
x = a (value of expression is a)
Example: x=a++
a = a+1(value of a is incremented by 1)
Prefix increment/decrement: In C, we have only two prefix operators that form prefix
expressions: prefix increment and prefix decrement. With the prefix operators, the effect takes
place before the expression that contains the operator is evaluated.
a = a +1 (value of a is incremented by 1)
Example: x=++a
the variable a contains 4 before the expression is evaluated, after evaluation the
value of both a and x will be 5.
Unary Expressions: A unary expression, like a prefix expression, consists of one operand and
one operator. The major difference is a prefix expression needs a variable while unary
expression can have an expression or a variable as the operand.
Sizeof: The sizeof operator tells us the size, in bytes, of a type or a primary expression. On some
PC the size of int is 2 bytes, some mainframes it is 4 bytes, and on super computers it is 16
bytes. It is important to know the exact size of an integer; we can use the sizeof operator with
the integertype.
Unary plus/minus: The unary plus and unary minus are what we think of as simply the plus and
minus signs. In C, however, they are actually operators. Because they are operators, they can
be used to compute the arithmetic value of an operand.
Expression Contents of a Before expression Expression value
+a 3 +3
-a 3 -3
+a -5 -5
-a -5 +5
Binary Expressions: These binary expressions are formed by an operand – operator-
operandcombination.
Examples: Any two numbers added, subtracted, multiplied or divided are usually formed in algebraic
notation, which is a binary expression.
Assignment expression: The assignment expression evaluates the operand on the right side of
the operator (=) and places its value in the variable on the left. The assignment expression has
a value and a side effect.
The value of the total expression is the value of the expression on the right of the
assignment operator(=).
The side effect places the expression value in the variable on the left of the
assignmentoperator.
Note: The left operand in an assignment expression must be a single variable.
Simple assignment: a = 5, b =x+1, i = i+1
The left variable must be able to receive it; that is, it must be a variable, not a constant. If the
left operand cannot receive a value and we assign one to it,we get a compile error.
Compound assignment: A compound assignment is a shorthand notation for a simple
assignment. It requires that the left operand be repeated as a part of the right expression. Five
compound assignment operators are *=, +=, /=, %=, -=.
Precedence:
Example: 2+3*7
This expression is actually two binary expressions, with one addition and on multiplication
operators. So the multiplication has the higher priority then 3*7=21 and adds the remaining
21+2=23.
Note: Associativity is applied when we have more than one operator of the same precedence
level in an expression.
Left-to-right associativity:
Example: 3 * 8 / 4 % 4 * 5
Here all these operators have the same precedence so associativity from left to right.
((((3 * 8) / 4) % 4) * 5) -> (((24/4) %4) *5) -> ((6%4) * 5) -> (2 *5) -> 10
Side Effects: In assignment C first evaluates the expression on the right of the assignment
operator and then places the value in the left variable. Changing the value of the left variable is
a side effect.
Example: x =4;
This simple expression has three parts. First, on the right of the assignment operator is
a primary expression that has the value 4. Second, the whole expression (x=4) also has a value
of 4. And third, as a side effect, x receives the value 4.
Evaluating Expressions
a * 4 + b /2 – c * b
Following are the rules:
1. Replace the variable by their values. This gives us the following expression:
3 * 4 +4/2 – 5 * 4
2. Evaluate the highest precedence operators, and replace them with the resulting value.
In the above expression, the operators with the highest precedence are the multiply
and divide. We therefore evaluates them first from the left and replace them with the
resulting values. The expression is now (3 * 4) + (4/2)- (5*4) -> 12 +2– 20
3. Repeat step 2 until the result is obtained.Result=-6
- -a * 7 /2 –c ++ *b.
2. Evaluate the postfix expression(c++). Remember that as a postfix expression, the value
of c++ is same as the value of c; the increment takes place after the evaluation. The
expression isnow
- -a * 7 /2 – 5 *b.
3. Evaluates the prefix expression (--a) Remember that as a prefix expression, the value of
- -a is the value after the side effect, which means that we first decrement a and then
use its decrementedvalue.
2* 7 /2 – 5 *b
4. The multiply and division are now evaluated using their associativity rule, left to right.
The expression isnow
14 /3 -5 * b-> 7-5 *4 -> 7-20= -13
Note: In C, if a single variable is modified more than once in an expression, the result is
undefined.
An expression that contains variables and constants of different data types is called as mixed –
modeexpression.
There are 2 types of data conversions that take place in mixed-mode expression.
1. Implicit dataconversion(Coercion)
2. Explicit data conversion(TypeCasting)
1. Implicit data conversion: In this type the control will automatically convert data values
of lower type are converted to the data types of highertypes.
Example program:
#include<stdio.h>
main()
{
int r1=6,r2=4,r3;
float r4=2.3,r5=3.2,r6;
double r7;
float(36.600)
double(r7) (36.00000000)
printf(“\n r7=%lf”,r7);
}
Output: r7=36.00000000
Rule1: when a real value is assigned to an integer variable, the fractional part of the real value
is truncated and only integer part is assigned to a variable.
Rule2: when an integer value say 10 is assigned to float variable, it is stored as 10.0000.
int(97) char(a)
op = x;
char(a) int(65)
printf(“\n x=%d, op=%c”, x, op);// Output: x=65,op=A
}
Rule 3: when a character is assigned to an integer variable, the ASCII value of the char is
assigned to variable.
Rule 4: when a valid integer value (0 to 255) is assigned to char variable. Character equivalent
of the integer value is assigned to a variable.
Note: Assigning an integer value into a character variable beyond its range. i.e. less than zero
or greater than 255 leads to logical errors.
2. Explicit data conversion: In this type of data conversion between the output of an
rvalue is forced to act as user specified data type. It refers to the process of changing an
entity of one data type intoanother.
Typecasting
float(2.0000) int(2)
Output: 2.0000
z=(float)x/y;
UNIT-II
Topics Covered
Conditional Branching and Loops: if and switch statements,nested if-else. Iteration and
Loops – Use of while, do-while and for loops, nested loops, use of goto, break and
continue statements.
Arrays – One and two dimensional arrays, creating, accessing and manipulating elements of
arrays.
Control Structures
A program is nothing but the execution of sequence of one or more instructions. Some times it
is desirable to alter the execution of sequence of statements in the program depending upon
certain circumstances. This involves decision making through branching and looping. Control
statements specify the order in which the various instructions in a program are to be executed
by the computer. i.e. they determine the ‘flow of control’ in a program. Various control
statements in C are:
Selection or decision control statements
Case control statements
Repetition or Loop control statements
Selection control statements:- Selection control statements allow the computer to take a
decision as to which statement is to be executed next. Different selection control statements
are:
If statement
Conditional operator
if statement: The if statement is a powerful decision making statement and is used to control
the flow of execution of statements. It can be achieved through different forms of if statement.
a) simple if b) if – else c)nested if-else d) else-if ladder
a) simple if statement: C uses the keyword “if” to execute a set of statements or one
statements when the logical condition istrue.
Syntax: if(condition or expression)
{
Statements-block;
}
next statement
It allows the computer to evaluate the expression first and then depending on the value of
expression, the control is transfers to the particular statement. If the expression is true(non-
zero value) then the statement-block is executed and next statement is executed. If the
expression is false(zero), directly next statement is executed without executing the statement-
block. Statement-block may be one or more statements. If more than one statement, then keep
all those statements in compound block({ })
Example:
b) if –else statement: It is an extension of simple if. It takes care of both the true as well as
false conditions. It has two blocks. One is for if and it is executed when the condition is true,
the other block is for else and it is executed when the condition is false. No multiple else
statements are allowed with oneif.
Syntax: if(testcondition)
{
True block statements
}
else
{
Next statement
If the condition is true then true block statement(s) is executed, otherwise if the condition is
false, then false-block statement(s) is executed. The else cannot be used without if.
c) Nested if-else statement: When a series of decisions are involved, we have to use more than
one if-else in nested form.
Syntax: if( condition-1)
{
if(condition -2)
{
………
if(condition-3)
{
Statement -1
}
else
{
Statement -2
}
}
else
{
Statement-3
}
}
else
{
Statement-4
}
Next statement
In this kind of statements, number of logical conditions is checked for executing various
statements. If any condition is true then associated block will be executed, otherwise it skips
and executes else block statements. We can add repetitively if statements in else block also.
Example: if(a>b)
{
if(a>c)
{
printf(“ ais big”);
else
{
printf(“c is big”);
}
}
else
{
if(c>b)
{
printf(“c is big”);
}
else
{
printf(“ b is big’);
}
}
d) else-if ladder: The else-if ladder is used when multipath decisions areinvolved.
Syntax: if(condition-1)
Statement-1
else if(condition2)
Statement-2
elseif(condition-3)
Statement-3
..
..
..
else
Statement-x
Next statement
Example: if(avg>=70)
printf(“distinction”);
elseif(avg>=60)
printf(“ first class”);
else if(avg>=50)
printf(“secondclass”);
else if(avg>=40)
printf(“third class”);
else
printf(“fail”);
Case control statement: At times, the if condition may increase the complexity of the program
when one of many alternatives is to be selected. C has built-in multiway decision statement
known as switch-case. The switch statement requires only one argument variable or
expression. It tests the value of a given variable against a list of case values and when a match is
found, a block of statements associated with that case is executed, if not such match, then
default statement is executed.
The expression is an integer expression or character. Value-1, value-2 are either integer
constants or character constants. These values should be unique with in a switch statement.
Case labels end with colon ( : ).
The break statement signals the end of a particular case and causes an exit from the switch
statement, transferring the control to the next statement following the switch.
The default is an optional case when present. It will be executed if the value of the expression
doesn’t match with any of the case values. If not present, no action takes place if all matches
fail and control goes to the next statement.
Example: switch(op)
{
case ‘+’: c=a+b; break;
case ‘-’: c=a-b; break;
case ‘*’: c=a*b; break;
case ‘/’: c=a/b;break;
default: printf(“wrong option”);
}
Many tasks are needed to be done with the help of a computer and they are repetitive in
nature. Such type of actions can be easily done by using loop control statements.
A loop is defined as a block of statements which are repeatedly executed for certain number of
times to do a specific task.
Steps in loops:-
while
do-while
for
while: This is the simplest looping structure in C. the while is an entry-controlled loop
statement.
Syntax: initial statement
while(test condition)
{
Statement(s)
Update statement
}
Flow chart:
Start
Initialization
Condition
An action or
series of actions
End
The test condition may be any expression, is evaluated and if it is true then the body of the loop
is executed. The test condition is once again executed for updated values, and if it is true the
body of the loop is executed once again. This process is repeated until the test condition is
finally becomes false and control is transferred out of the loop to the next statement. The body
of the loop may contain one or more statements. The braces are needed if the body of the loop
contains more than one statement.
Example:
#include<stdio.h>
main()
{
int i,sum;
i = 1;
sum=0;
while(i<=10)
{
sum = sum + i ;
i + +;
}
printf(“sum=%d”,sum);
}
Here the value, sum of first ten numbers is stored into the variable sum; i is called as loop
variable.
The loop is repeated for ten times to do that process, each time by incrementing the value of i
by one. Once the value of i becomes 11 then the test condition becomes false and the control is
out of theloop.
do-while: On some occasions it might be necessary to execute the body of the loop before the
test condition is performed. Such situations can be handled by the do-while statement. Do-
while id exit controlled loop statement.
Syntax:initial statement
do
{
Statement(s)
Update statement
} while(test – condition);
Next statement
Flow chart:
Start
series of actions
true Condition
false
The body of the loop is executed first, and then at the end of the loop the test condition is
evaluated, if it is true then the statements are executed once again. The process of execution
continues until the test condition finally becomes false and the control is transferred to the
next statement
Example: main()
{
int i, sum;
i =1;
sum=0;
do
{
sum = sum + i;
i + +;
} while( i<=10);
printf(“Sum=%d”, sum);
}
The for statement: The for loop entry controlled loop that provides a more concise loop
controlstructure.
Syntax: for( initialization ; test-condition ;increment/decrement)
{
Statement(s)
}
Next statement
The for loop allows to specify three things about the loop in a single line.
i. Setting a loop counter variable to an initial value using assignment statement. Eg:
i=1count=0;
ii. the test condition is a relational expression that determines the number of
iterations desired or it determines when to exit from the loop. If the test condition is
true, the body of the loop is executed, otherwise the loop is terminated and
execution continues with the next statement after theloop.
Eg: i<=10
iii. After evaluating the last statement of the body the loop, the control is transferred
to the increment/decrement statement of the loop. And the new value is again
tested to see whether it satisfies the loop condition ornot.
Eg: i++, ++I, i+=2
The body of the loop may contain one or more statements. In case there is more than
one statement thenbraces
The three sections of for loop must be separated by semicolons (;). Initialization and
incr/decr parts may contain more than one statement must be separated by commas.
Example: for(i=1, j=10 ; i<=10 ; i++, j--)
The test-condition may have any compound relation and the testing need not be limited
only to the loopvariable.
Example: for(i=1; i<20 && sum <100 ; i++)
It is permissible to use expressions in the assignment statement of initialization and
incr/decrsections.
Example: for( k=(a+b)/2;k>0;k=k/2)
The sections of for loop my absent depends on requirement in the program. But it leads
to take some extra care about thosesections.
Example:
for( ; ; )
This statement leads to infinite loop or never–ending process.
Nesting of loops: The way if statement can be nested, similarly whiles and for can also be
nested.
{
for(j=1;j<=2;j++) // inner for loop
printf(“\n”);
}
Here in this example nested for loop is used, and the total process is executed for 6( 3 * 2)
times. And the output of this example will be: 1 1 1 2
2 1 2 2
3 1 3 2
The way for loops have been nested here, similarly while and do-while can also be nested. Not
only this, a for loop can occur within a while loop, or a while within a for.
Example: Comparison of three loops. Finding the sum of first 10 numbers by using all loop
statements.
#include<stdio.h>
int main()
{
int i,sum;
sum=0;
i=1;
do
{
sum=sum+i;
i++;
}while(i<=10);
printf(“Sum of first 10 numbers = %d”, sum);
return 0;
}
Program to write the sum of first 10 numbers by using for loop.
#include<stdio.h>
int main()
{
int i,sum;
for(i=1,sum=0;i<=10;i++)
{
sum=sum+i;
}
printf(“Sum of first 10 numbers = %d”, sum);
return 0;
}
Jumps in loops: We often come across some situations where we want to make a jumpfrom
one statement to other statement, jump out of a loop or to jump to next iteration of the loop
instantly,. This can be accomplished by the statements like:
break
continue
goto.
When we want to jump out of a loop instantly without waiting to get back to the
condition test, then the keyword break allows us to dothis.
Output: 1 1 1 2
2 1 2 2
3 1 3 2
In this example when j value equals 5, break takes the control outside the inner for loop
only, since it is placed inside the inner loop.
When we want to take the control to the beginning of the loop by passing the
statements inside the loop which are not yet been executed, then the keyword continue
allows us to dothis.
It causes the next iteration of the loop to begin and it applies only toloops.
A continue is usually associated with anif.
Example: for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
if(i = = j)
continue;
else
printf(“ \n%d %d”, i, j);
}
}
Output: 12
21
In this example when i and j values are equal, continue takes the control to the inner for loop
by ignoring rest of the statements in the inner forloop.
The goto statement alerts the normal sequence of program execution and control
transfers to some other part of theprogram.
The goto statement leads the control to go to the particular part of the program by
indicating in its labelname.
Syntax: gotolabel;
Where label is a unique identifier used to label the target statement to which control will be
transferred. The general format of the label statement is:
label : statement;
Example:
void main()
{
int x;
read:
scanf(“%d”,&x);
if(x<0)
goto read;
else
printf(“x=%d”,x);
}
Here read is label, whenever x value entered as negative(x<0) then the control goes to read
label, and once again scanf( ) statement executed to read next value.
Arrays:
C supports a derived data type known as array that can be used to handle large amounts of data
(multiple values) at atime.
An array is collection of elements of the same data type, which share a common name.
The first element in the array is numbered 0, so the last element is one less than the size of the
array.
Before using an array its type and dimension must be declared, so that the compiler will know
what kind of an array and size of an array.
Each array element is referred by specifying the array name followed by one or more subscripts,with
each subscript enclosed in square brackets.The value of each subscript must be expressed as a
non-negative integer, variable or expression. The number of subscript determines the dimensionality of
the array. We can use arrays to represent not only list of values but also tables of data in two or more
dimensions. We have different types of arrays based on itsdimensional.
One-dimensional arrays / Single-dimensional arrays
Two-dimensional arrays / Double-dimensional arrays
Multi-dimensional arrays
A list of items can be given one variable name using only one subscript and such a variable is
called one-dimensional array or single-dimensional variable.
The data-type specifies the type of elements such as int, float or char. And the size indicates the maximum
number of elements that can be stored in that array
Note: C language character strings are as simple as array of characters. And every string should be
terminated by null character (‘\0’).
The computer internally reserves five storage locations for array a in the above example as follows.
Memory address
a[0] 2000
a[1] 2002
a[2] 2004
a[3] 2006
a[4] 2008
These elements may be used in programs just like any other Cvariables.
Y= a [4] * 2;
Note: C performs no bounds (array size) checking and therefore care should be exercised to ensure that
the array indices are within the declared limits.
Initialization of one-dimensional arrays: After an array is declared its elements must be initialized.
Otherwise they will contain garbage values. An array can be initialized at either of the followingstages.
At compile time
At runtime
We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared. The values in the list must and should be separated by comma.
Eg:
int counter[ ] = { 1, 1, 1, 1}; here the size is optional, it may be omitted. In such cases the
compiler allocates enough space for all initialized elements.
char name[ ] = { ‘S’, ‘I’, ‘M’, ‘H’, ‘A’,‘\0’}; here declares the name to be an array of
characters, and is initialized by the string “SIMHA” ending with the null character. And we can do
the same thing in another way also. i.e. we can assign the entire string at a time, not an element
by element asfollows:
char name [ ] = “SIMHA”
int num[3] = { 10,20,30,40,50 }; will not work. It is illegal in C. i.e. if we have more initializes than
the declared size, the compiler will produce an error.
Run time initialization: An array can be explicitly initialized at run time. At the time of execution array
values can begiven.
Examples:
1)
int a[ 10 ] ;
for ( i=0; i<10;i++)
scanf(“%d”,&a [ i ]);
2)
float x [15];
for( i=0; i<15;i++)
scanf(“%f”, &x [ i ] );
3)
char name[10];
for(i=0;i<5;i++)
or
scanf(“ %s”,name);
or
char name[10];
gets(name);
#include<stdio.h>
int main()
{
int i,sum=0;
int a [ 10 ] = { 12, 3, 5, 43, 21, 1, 6, 8, 9, 11};
// Array a is initialized at compile time
/* finding the sum of array a */
#include<stdio.h>
int main()
{
int a[ 10], i, n,sum=0;
printf (“Enter no.of elements :”);
scanf (“%d”, &n);
printf(“Enter %d elements :”,n);
for(i=0; i<n; i++)
scanf(“%d”,&a [i]); // run timeinitialization
/* finding the sum of array a */
for(i=0; i<n; i++)
sum = sum + a[ i ];
printf(“\n Sum of elements of array a is %d”, sum);
return 0;
}
Two - Dimensional Arrays: C allows us to define the data in the form of table of items by using
two-dimensional arrays.
Syntax: data-type array-name[rowsize][columnsize];
Eg: int a[3][4] ; Here a is two dimensional array with row size 3 and column size 4., and the total
elements we can store in this array a is 12 (i.e. 3 * 4).
Each dimension of the array is indexed from zero to its maximum size minus one; the first index
selects the row and the second index selects the column with in that row. Two dimensional arrays are
stored in memory as follows:
Examples: Representation of two dimensional array in memory
Initializing Two Dimensional Arrays: Like on-dimensional arrays, two-dimensional arrays can also be
initialized at compile time and runtime.
Two-dimensional arrays may be initialized by following their declaration with a list of initial
values enclosed in braces. Until and unless we initialize the array explicitly it is having some garbage
values initially.
{ 3, 5, 7 } ,
{12, 22, 32 }
};
We can also initialize a two dimensional array in the form of a matrix as follows:
inta [ ] [ 3] ={
{ 3, 5, 7 },
{12, 22, 32 }
};
If the values are missing in an initialization,they are automatically set to zero.i.e.
So here the first two elements of the first row are initialized by 1 and 5 respectively, the first element of
second row to 12, and all other elements to zero.
Ex: Program to print the multiplication table for first 10 numbers up to the 10 multiples.
#include<stdio.h>
#define ROW 10
#define COLUMN 10
int main()
{ int i,j,r,c,table[ROW][COLUMN];
printf("\n MULTIPLICATION TABLE \n\n");
printf("X|");
for(j=1;j<=COLUMN; j++)
printf("%5d",j);
printf("\n \n\n");
for(i=0;i<ROW;i++)
{
r=i+1;
printf("%d | ",r);
for(j=1;j<=COLUMN;j++)
{
c=j;
table [i][j]= r*c;
printf("%5d",table[i][j]);
}
printf("\n\n");
}
return 0;
}
In the above program the size of the array table is mentioned as ROW and COLUMN (i.e. table[ROW]
[COLUMN]) where these symbolic constants having the values 10 and 10. It is always good practice to
take the size of the array in terms of symbolic constants instead of directly taking the values.
Multi-Dimensional arrays:
C allows arrays of three or more dimensions. The compiler determines the exact limit.
of the ithdimension.
Eg: int table [3][4][2]; Here table is the three dimensional array containing 24 integer elements (i.e. 3 *
4 * 2 = 24).
UNIT-III
Topics Covered
In the preceding chapters, we used only the three non-derived types, void, integral, and floating –
point. These are used to solve only the limited amount of problems. There are six derived data types in
C: Array, Functions, Pointer, Structure, Union, and Enumerated. Breaking a complex problem into
smaller parts (understandable parts). We call each of these parts of a program a module and the
process of subdividing a problem into manageable parts top-down design. In the principle of top-down
design and structured programming, a program is subjected to factoring, that is the program is divided
into main module and its related modules. Each module is in turn divided into sub modules until the
resulting modules cannot be further subdivided. A C program finds itself in a similar fashion as in top-
down structured designing. It cannot handle all the tasks by itself. Instead it requests other program-
like entities – calledfunctions.
Function: Definition
A function is a self-contained block of one or more statements that perform a particular task. Every C
program can be thought of as a collection of these functions, and one of which must be
main( ) function.
The execution of the program always starts and ends with main function and main function can call
other functions. A called function can receive control from a calling function, when the called function
completes its execution it returns the control back to the calling function. The communication between
calling function and called function is by passing parameters at the time of calling.
Advantages of functions in C
It facilitates top-down modular programming; here the problem can be factored into
understandable and manageablesteps.
Reusing of the code: The length of the source program can be reduced by using functions at
appropriate places. i.e writing functions avoids rewriting of same code over andover.
Using functions it becomes easier to write programs and keep track of what they are doing.
The functions are much easier to understand andtest.
C comes with rich and valuable set of library functions that makes programmer’s workeasier.
Libraryfunctions
User-definedfunctions
Library functions: The library functions are predefined set of functions. The user can only use these
functions but can’t change or modify them. These functions are already defined, tested and debugged
in C standard library. When the user needs to use library functions, then a call to these functions is
required.
Eg: The basic input and output functions like printf( ) , scanf( ) are defined in the C library header file
stdio.h.
sqrt( ), sin( ), cos( ), tan( ), pow( ), getchar( ), exit( ), toupper( ), strcmp( ), strlen( ) etc., all these are
some C library functions.
User-defined functions: These are defined by the user according to the requirement in the application.
The user can modify and can create any number of functions based on requirement. The user can
certainly understand the internal working of the function.
The library functions are not required to written by the user, where as user-defined functions
have to develop by the user at the time of writing ofapplication.
The user can’t modify the meaning of the library functions. But user can modify the user-
definedfunctions.
The library functions are already tested and debugged, but the user-defined functions need to
argument declaration
Executable statement
……
……
……
}
In function structure all parts not essential, it is based on the requirement of the program and
some sections or parts may beabsent.
Return-type is any data type
All functions by default return int typedata.
Function-name can be any name like variables which follows naming conventions of identifiers.
The arguments list and its associated declaration are optional. These are any valid variable
name separated by commas. There may be any number of variables, any type of variables with
respect to the function calling statement and these variables receive values from calling
function.
The declaration of local variables is required only when any local variables are used in the
function.
A function can have any number of executable statements.
The return is a keyword which is followed by some expression or value. The return statement
returns a value to the calling function and is optional. When there is no return statement, then
no value is being returned to the calling function. We can return only one value at atime.
Eg: int add( int x, int y) int add(x,y) int add( int x, int y)
{ int x, y; {
int z; ( or ) { (or) return ( x + y );
z = x + y; int z; }
return z; z = x + y;
} return z;
}
Every user-defined function can have its declaration (also called as function prototyping) and
definition. Some other function can call thisfunction.
When function calling statement is invoked, the control is transferred to the function definition.
It is then executed and the control is transferred back to the calling function to execute next
statement.
Any function can call any other function and can call itself(recursion).
A function can call any number oftimes.
C permits nesting of functions. Main can call function-1, which calls function-2, which calls
function-3 and soon.
The arguments (parameters) of function calling statement are actual arguments; the
arguments of called function are formal arguments.
The actual and formal arguments should match in number, type andorder.
The formal arguments receive values from actual arguments when a function is calling, and by
this a communication between calling function and called function is made.
When a function call is made, only a copy of the values of actual arguments is passed into the
called function’s formal arguments.
The values of the actual arguments must be assigned before the function call is made.
The formal arguments must be valid variable names, but the actual arguments may be variable
names, expressions, or constants.
#include <stdio.h>
int main()
{
int a, b, c;
int add(int,int); // function declaration orprototyping
printf(“Enter two values“);
scanf(“%d%d”, &a, &b);
c=add(a,b); //function call statement
printf(“ addition of a, b is %d”,c);
return 0;
}
int add( int x,inty) // add function definition
{
int z;
z = x + y;
return z;
}
return statement:-
Functions uses return statement to return a value to the calling function. And exit from the
called function is done by the return statement.
The return statement returns only one value at a time. There may be more than one return
statement in a function, but it returns only one value.
The value returned by the called function is collected by the calling function.
Return statement with out any value will return value one.
Absence of return statement indicates that no value is returned, such functions return type is
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 76
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving
Function prototype:
Function prototyping is nothing but function declaration; it consists of function’s return type,
name, and arguments list withtype.
When a function is defined, the function header in the definition must be same like its
prototypedeclaration.
The function prototype statement is terminated bysemicolon.
A prototype statement helps the compiler to check the return type and arguments type of
thefunction.
The prototype of library functions is given in the respective header files, those we include by
using #include pre-processor directive.
Eg: int add( int,int); voiddisplay(charc); float average(float, float,float);
Category of functions: A function depending on whether the arguments are present or not, and a
value is returned or not may belong to one of the following categories.
Eg:
#include<stdio.h>
void displayline();
void message ();
int main()
{
displayline( );
message( );
displayline( );
return 0;
}
void displayline ( ) // no arguments and no return type for display line
{
int i;
for(i=1; i<=80; i++)
printf(“-“);
printf(“\n”);
}
void message( )
{
printf(“ ** TRY TO UNDERSTAND THE LANGUAGE **** \n ”);
printf(“ ***NOT TO BYHARD THE LANGUAGE ***** \n ”);
}
OUTPUT: -
** TRY TO UNDERSTAND THE LANGUAGE ****
***NOT TO BYHARD THE LANGUAGE *****
-
The nature of data communication between the calling function and the called function is
with arguments but no return values.
One-way data communication between calling function and called function through
arguments.
The control is transferred to the called function by passing some arguments, after
performing the task; the control is back to the calling function without returning any value.
Eg: #include<stdio.h>
void displayline(char);
void message(char);
int main( )
{
char name[30] = “DENNIS RITCHIE”;
char ch = ‘-’;
displayline( ch);
message( name);
displayline( ch);
return 0;
}
void displayline (char x ) // with arguments and no return type for displayline
{
int i;
for(i=1; i<=80; i++)
printf(“%c”, x);
printf(“\n”);
}
OUTPUT: -
DENNIS RITCHIE
-
Eg:
#include<stdio.h>
int factorial();
int main( )
{
int f;
f = factorial( );
printf(“ \n Factorial f = %d”, f);
return 0;
}
1. Call by value:
In call by value mechanism a copy of the data is sent to the function. That is the values of actual
arguments are being copied into formal arguments. And ensures that the original data in the
calling function cannot bechanged.
Memory is allocated temporarily for formal parameters and localvariables.
Whatever the modifications are done for formal parameters will not affect the
actualparameters.
2. Call by Reference:
In call by reference mechanism the address of the data rather than a copy is sent to the
function. That is the address of actual arguments is being passed into formal arguments.
The called function can change the original data in the callingfunction.
When we pass the addresses, the receiving parameters should be pointers to hold these
addresses.
What ever the modifications are done for formal parameters will directly affect the actual
parameters.
C language does not have a true call by reference and it is stimulated by call by address.
Here the copy of the actual data a, b is sent to formal parameters of swap function, in swap function
these are swapped but the changes made to x, y are not affect the values of a, b in main function.
Because the copy the data is sent but not original location.
Here the address of the actual data (&a, &b) is sent to formal parameters ( *x, *y) of swap function, in
swap function instead of creating temporary memory locations for x and y, the same memory locations
of a, b referenced by x, y. So changes made to x, y are directly affects a, b in main function. So finally
swapped values are stored in a, b.
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed.
There are three places where variables can be declared in C programming language −
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to
functions outside their own.
The following example shows how local variables are used. Here all the variables a, b, and c are local
to main() function.
#include stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization*/
a =10;
b =20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b,c);
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold
their values throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration.
The following program show how global variables are used in a program.
#include <stdio.h>
/* global variable declaration */
int g;
int main ( )
{
int a, b; /* local variable declaration */
a =10;
b =20;
g = a +b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return0;
}
A program can have same name for local and global variables but the value of local variable inside a
function will take preference
#include <stdio.h>
int g = 20; /* global variable declaration */
int main ( )
{
int g = 10; /* local variable declaration */
printf ("value of g = %d\n", g);
return 0;
}
When the above code is compiled and executed, it produces the following result − value of g = 10
Formal Parameters:
Formal parameters are treated as local variables with-in a function and they take precedence over
global variables.
Storage classes:
All the variables in C, not only to have a data type, they also have a “Storage classes”. The storage
class of variable tells the compiler that:
(a) The storage area of the variable: there are basically two kinds of locations in a computer where
such variables or values to be kept, “Memory and CPU Registers. The storage class of a
variable determines in which of these two locations the value is stored.
(b) The initial value of the variable if not initialized.
(c) The scope of the variable(active) that in which functions the value of the variable would be
available.
(d) Life of the variable (alive) that is how long the variable would be active or exist in the
program, i.ethe longevity of the variable.
1. Automatic variables.
2. Register variables.
3. Static variables.
4. External variables.
1. Automatic storage classes variables: The features of automatic storage classes variablesare:
Storage :Memory
Initial value : Garbage value or unpredictable value.
Scope : Local to the block in which it isdefined.
Life time : Until end of function or end of block where it isdefined.
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.
Because of the scope of the automatic variables,they are also referred to local or
internal variables.
Ex: 1.
#include<stdio.h>
main ( )
{
auto int i; int j;
printf (“\n %d \t %d”, i, j);
}
Output: some garbage values, because they are not initialized to any value. A variable j without having
any storage class is by default automatic. So both i, j are automatic variable.
Ex: 2.
#include<stdio.h>
main ( )
{
auto int a = 1;
{
auto int a =2;
{
auto int a = 3;
printf(“a =%d”,a);
}
printf(“ \n a = %d”, a);
}
printf(“ \n a = %d”, a );
}
Output: 3
2
1
2. Register variables:
The features of a variable defined to be of Register storage class are:
Storage : Registers
Initial value : Garbage value or unpredictablevalue.
Scope : Local to the block in which it isdefined.
Lifetime : Until end of function orblock.
1. A variable stored in CPU Register can always be accessed faster than the one whichis stored
inmemory.
2. If a variable is used at many placed in a program, then it is better to declare it as register variable.
Ex:- loop countervariables.
3. We can use the keyword “register” to declare registervariables.
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 87
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving
We cannot use register class for all types of variables, because CPU registers in a micro computer are
usually 16- bit registers and therefore cannot hold a float value or a double value which require 4
and 8 bytes respectively. However C will automatically convert register variables into non register
variables once the limit is reached.
Ex:-
#include<stdio.h>
main ( )
{
register int i;
for(i = 1; i < = 10; i++)
printf(“\n %d”, i);
}
Storage : Memory
Initial value : Zero
Scope : Global (may be internal static or external static)
Lifetime : Value of the variable persists between different function call.
void Display ( )
{
static int x = 0; x = x +1;
printf(“x = %d \n”, x);
}
Output:- x =1
x =2
x =3
4. External variables:- The features of a variable whose storage class has been defined as external
are as follows:
Storage : Memory
Initial value : Zero
Scope : Global
Life time : As long as the program’s execution doesn’t come to an end.
Output: 20
10
Recursion:
When a function calls itself, then that process is called as recursion and that function is called
as recursive function.
Recursive functions can be used to solve problems where the solution is expressed in terms of
successively applying the same solution to subsets of theproblems.
Every recursive functions must has to have two basicproperties:
( i ) A termination condition called anchor step to avoid infinite process.
(ii) A repetition statement called recurrence step to repeat the function calling process.
Recursion is of two types. Direct recursion and indirect recursion.
When a function calls itself, then it is direct recursion. But when function-1 calls function-2 and
in turn function-2 calls function-1 then it is indirect recursion.
Eg: To calculate the factorial value of number 4,the recursion processis as follows.
#include<stdio.h>
int main()
{
int n, f;
intfactorial(int); // function declaration or prototyping
n = 4;
f =factorial(n); // function calling statement
printf(“ \n Factorial f = %d”,f);
return 0;
}
UNIT – IV
Topics Covered
Strings – Introduction to strings, declaration and Initialization, String Input / Output functions,
String manipulation functions, Array of strings
Pointers – Defining Pointer, declaration and Initialization, accessing variables through
pointers, pointers to arrays, pointers to functions, pointers to structures, command line
arguments, enumeration data type
Dynamic Memory allocation: Allocating and freeing memory(malloc(), calloc(), realloc()
and free()
Strings
H Y D E R A B A D \0
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
Reading Strings:-
The input function scanf ( ) can be used with %s format specification to read astring.
Eg: charname[30];
scanf(“%s”, name);
The scanf() function to read multi word strings is doesn’t consider white spaces. It
terminatestheinputstringatfirstoccurrenceofwhitespace.Somultiwordstringscan’t read by using
scanf()function.
Eg: char city[30];
scanf(“%s”,city);
If the input string is “NEW DELHI”, then the variable city can store only “NEW”, it ignores the rest
because white space is occurred after NEW.
To read multi word strings, we can use gets( ) function orgetchar( ) function repeatedly.
Eg: char city[20];
gets(city);
if the input string is “NEW DELHI”, then name contains total string “NEW DELHI”.
(Or)
inti=0;
char city[20], ch;
do
{
ch=getchar();
name[ i ]=ch;
i++;
} while(ch != ‘ \n’);
C language doesn’t allow operators that work on stings directly. I.e. assignment, arithmetic,
equality operator etc doesn’t work withstrings.
Eg:char s1[10],s2[10];
s1 =“WELCOME” Invalid
s1==s2 Invalid
s1+s2 Invalid
We can also print strings by using puts () function and putchar () functionrepeatedly
Eg: puts(name)
OR
for(i=0;name[i]!=’\0’;i++)
{
putchar(name[i]);
}
PROGRAM TO READ A STRING AND PRINT IT
#include<stdio.h>
int main()
{
char ch, city[20]; int i;
printf("Enter a city name ");
i=0;
do
{
ch=getchar();
city[i]=ch;
i++;
}while(ch!='\n');
i=i-1;
city[i]='\0';
printf("The city is :");
puts(city);
return 0;
}
strcpy( ): It is to copy one string into another, and it returns the resultant string.
strcmp( ): It is to compare two strings to check their equality. If they are equal it returns zero,
otherwise it returns the numeric difference between the first non matching characters in the strings.
(i.e. +ve if first one is greater, -ve if first one is lesser).
Syntax: strcmp (string1,string2);
strcat( ):This function is used to join two strings together, and it returns the resultant string.
String1 is appended with string2 by removing the null character of string1 and string2 remains
unchanged. The resultant string is stored in string1.
strcat (city1,city2);
Here city2 is appended to city1. So city1= “HELLOWORLD” and city2=”WORLD”.
strlen(): It is to find out the length of the given string and it returns an integer value, that is the number
of characters in the given string. It takes only oneparameter
Syntax: strlen(string1);
It gives the length of string1.
Array of Strings
We have array of integers, array of floating point numbers, etc. Similarly we have array of strings also.
Collection of strings is represented using array of strings.
Declaration:
char arr[row][col]; where,
arr - name of thearray
row - represents number of strings
Initialization:-
char arr[row][col] = { list of strings };
Example:-
char city[5][10]={“DELHI”, “CHENNAI”, “BANGALORE”,“HYDERABAD”,“MUMBAI” };
D E L H I \0
C H E N N A I \0
B A N G A L O R E \0
H Y D E R A B A D \0
M U M B A I \0
In the above storage representation memory is wasted due to the fixed length for all strings
#include<stdio.h>
int main()
{
int i;
char ch_arr[3][10] = {"spike",
"tom",
"jerry"
};
for(i = 0; i < 3; i++)
{
printf("string = %s \n", ch_arr[i]);
}
return 0;
}
POINTERS:
Pointer: A Pointer is a variable which can store the address of another variable
dataype*var_name
datatype is the pointer's base type; it must be a valid C data type and var-name isthe name of the
pointervariable
Example: If p1, p2 are two pointer variables then operations such as p1+4, p2 - 2, p1 - p2
can be performed
Example: If the address of p1 is 1002. After using p1=p1+1, the value becomes 1004 but
not 1003.
Pointer to array:
Elements of an array can be accessed through a pointer also. We can declare a pointer variable and
store the address of the first element of the array in the pointer variable. All the elements of the
array can be accessed through the pointer.
Example: int arr[10] = {1,2,3,4,5};
int *ptr =arr;
In the above example, arr is an integer array, ptr is an integer pointer in which address of the first
element of the array is stored
Pointers to Functions
A function, like a variable has a type and address location in the memory. It is therefore possible to
declare a pointer to a function, which can then be used as an argument in another function .
A pointer to a function can be declared as follows.
Syntax: datatype (*fptr)();
fptr is a pointer to a function which returns type value
A function pointer can be made to point to a specific function by assigning the name of the function to
the pointer
Example:
int multiply(int a,intb); function declaration
int(*fptr)(int,int); pointer to afunction
fptr=multiply; assigning address of multiply tofptr
n=(*fptr)(a,b); function call using pointerfptr
Pointers to Structures:
Pointer is a variable that holds address of another data variable. We can also define pointer to
structure. That is we can declare a pointer as a structure variable and store the address of a structure
variable in the pointer of the same structure. Now, Structure members can be accessed using the
pointer variable.
Eg:
struct book
{
char name[20];
char author[20];
int pages;
};
struct book *ptr;
Here ptr is a pointer variable to the structure book. We can access the members of the structure by
using ptr variable and is accomplished by indirect member selector operator (->) or structure pointer
operator.
i,e ptr->name, ptr->author, ptr->pages.
car name[20];
char author[20];
int pages;
};
int main()
{
struct book b1 = {“let us c”,”kanetkar”,100};
struct book *ptr;
ptr=&b1;
printf(“\n%s by %s of %d pages”,b1.name,b1.author,b1.pages);
printf(“”\n %s by %s of %d pages”, ptr->name, ptr->author, ptr->pages);
return 0;
}
In the above example ptr is a variable, which is used to hold the address of structure variable. The
structure members can be accessed using the indirect selector operator.
*ptr->rno is same as (*ptr).rno.
The parenthesis around *ptr are necessary, because the member operator, has a higher precedence
than the operator “*”.
Dynamic MemoryManagement
Dynamic allocation: Dynamic memory allocation is the process ofallocating memory during execution
time.
Dynamic Memory Allocation Functions in C:
This allocation technique uses predefined functions to allocate and release memory for data during
execution time.
Function Syntax
1. malloc( ):
2. calloc( ) : calloc( ) function is also like malloc( ), but calloc( ) initializes the allocated memory
tozero.
3. realloc( ):
realloc ( ) function modifies the allocated memory size by malloc( )and calloc( )
functions to newsize.
If enough space doesn’t exist in memory of current block to extend, new block is
allocated for the fullsize of reallocation,then copies the existing data to new block and
then frees the oldblock.
4. free ( ):
free ( ) function frees the allocated memory by malloc ( ) and calloc ( ) functions and returns
the memory to the system
Example:
Program to allocate memory for an array dynamically, store and access its values
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int *a, i, n;
printf(“Enter the size of the array”);
scanf(“%d”,&n);
a = (int *) calloc(n , sizeof(int));
printf(“Enter %d elements into the array”);
for(i=0; i<n;i++)
scanf(“%d”,&a[i]);
printf(“\nElements of the array”); for(i=0;i<n;i++)
printf(“%d ”,a[i]);
free(a);
return 0;
}
UNIT-V
Topics Covered
Structures
Structure is a collection of logically related elements of different data types.
Structure is a mechanism for packing data of different types. It is a convenient tool for handling a group of
logically related data items.
Eg: It can be used to represent a set of attributes, such as student-name, roll-number, and marks. We use a
structure to represent all these different data elements.
Syntax:
struct tag-name
{
Datatype member-1;
Dattype member-2;
:
:
Datatype member-n;
};
Eg: struct student
{
int rno;
char name[20];
int tm;
float avg;
};
different datatype.
Structure declaration should be terminated bysemicolon.
Structure declaration doesn’t get any space for its members, it simply describes a format called template
to represent theinformation.
Memory allocated only after declaring structurevariables.
Structure variables can be declared using tag-name asfollows:
Here student is a structure and it is having 4 different members which are logically related.
And s1, s2 and s3 are three structure variables.
It is also allowed to combine both the template declaration and structure variables declaration in
one statement. The declaration is asfollows:
struct student
{
int rno;
char name[20];
int tm;
float avg;
}s1,s2;
Tag-name is optional in structure declaration. When tag-name is absent then structure variables
should be created in structure declaration itself, beforesemicolon.
Members of the structure can be accessed by writing structure variable name with member selection
operator (dot operator . ) and member name.
Syntax
structure variable . member;
Eg: s1. rno=28;
s1 . tm = 500;
Structure Initialization:
Like any other data type, a structure variable can be initialized. We can initialize a structure at
compile time and also we can initialize the structure members at run time.
Compiletime initialization: One way to initialize structure members is direct initialization. struct
student s1 = { 28, “ SUN”, 500, 90};
Here, when initializing the structure directly like above, and then the order should be
maintained. That is the order of assigning values is same as the order of members declared in the
structure.
We can initialize structu remember satrun time by conside ring thes can statement as follows:
scanf (“%d%s%d%f”, &s1.rno, s1.name, &s1.tm,&s1,avg);
#include<stdio.h>
struct student
{
int rno;
char name[20];
int tm;
float avg;
};
int main()
{
struct student s1 = { 28,"SUN",450,89};
printf("\n Roll Number : %d",s1.rno);
printf("\n Name : %s",s1.name);
printf("\n Total : %d",s1.tm);
printf("\n Average: %f", s1.avg);
return 0;
}
Output:-
Roll Number: 28 Name:
SUN Total: 450
Average: 89.000000
We can copy one structure variable into another; it can be achieved by copying individual
members or entire structure at a time by using assignment statement.
Eg: struct student s1, s2;
s2 =s1;
Comparison of structure variables for their equality and inequality purpose by using equality
operator
(==), and inequality operator (!=) is not allowed in all compilers. If it is necessary to compare two
structure variables then it is to follow individual structure member’scomparison
Array of structures
We can declare an array of structures, where each element of the array represents a structure
variable.
Eg: The total marks and average marks analysis of the marks report obtained by a class of 60
students is asfollow:
struct students[60];
Array of structures allowed us to create an array of similar type of elements which themselves
are a collection of dissimilar datatype.
In an array of structures all elements of the array are stored in adjacent memory locations
#include<stdio.h>
struct marks
{
int m1;
int m2;
int m3;
int m4;
};
int main( )
{
int sum=0, i;
struct marks s[3] = { {56,67,78,59}, {60,50,70,80}, {52,62,72,82} };
for(i=0;i<3;i++)
{
sum=0;
sum = sum + s[i].m1 + s[i].m2 + s[i].m3 + s[i].m4;
printf(“\n Total marks of %d = %d”, s[i], sum);
}
return 0;
}
Union:
Union is a concept borrowed from structures and therefore follows the same syntax as structures.
Union is a group of logically related data values of different type with the common name. And we
can use . (dot) operator to access individual members of a union as in structures.
Ex:
union
{
int m;
float x;
char c;
}code;
code.m=10;
code.x=12.05;
code.c=’A’;
However, there is major distinction between the union and structure is in terms of storage. In
structures each member has its own storage location, whereas all the members of a union use the
same location. Union can handle only one member at a time.
Structure Union
Collection of values of different Collection of values of different data types
datatypes
Declaration: Declaration:
struct <tag name> union <tag name>
{ {
Datatype1 member1; Datatype1 member1;
Datatype2 member2; Datatype2 member2;
. .
. .
. .
Datatype-nmembers- n; Datatype-n members-n;
}; };
The memory allocated for structure is The memory allocated for union is equal to
equal to its member’s total size. its member size, which allocation (Memory
(Memory is allocated only when a is allocated only when a union
structure variable is defined). variable is defined).
struct item1 union item2
{ {
Int m; float x; Int m; float x; char c;
char c; }u;
}s;
Memory allocated for s is 2+4+1=7 bytes. Memory allocated for u is 4 bytes
All the members can be accessed at a Only member can be accessed at a time.
time.
Values assigned to one member will not Values assigned to one member May cause
cause the change in other members. the change in value of other members.
The usage of structure is efficient when The usage of union is efficient when
all Members are actively used in the members of it are not required to be
program accessed at the same time.
FILES
A File is a collection of records that can be accessed through the set of library functions. Record is
nothing but collection of fields of related data items. These files are stored on the disk and can be
accessed through file-handling functions provided by the C-standard library.
Eg: Here a file called “STUDENT.DAT” which is having 5 students’ records. And every record is
collection of 4 fields.
Types of I/O:There are numerous library functions available for I/O. these can be classified into two
broad categories:
Console I/O: Functions to receive input from keyboard and write output to VDU (monitor). The
screen and keyboard are called a console. Console I/O functions can be further classified into two
categories – formatted console I/O and unformatted console I/O. The basic difference between them
is that the formatted functions allow the input and output to be formatted as per requirements. The
different console I/O functions are as follows:
Formatted functions: The input function scanf( ) and the output function printf( ) are called
formatted console I/O functions. By using the format specifiers and escape sequence characters we
can use these functions to read/print required format ofinformation.
Unformatted functions:- The input functions like getch( ), getche( ), getchar( ) and gets( ) are called
unformatted input functions and putch( ),putchar( ), and puts( ) are unformatted output functions.
Each and every function is having its own syntax andmeaning.
File I/O: Sometimes it is necessary to store the data in a manner that can be later retrieved and
displayed either in a part or in whole. This medium is usually a “file” on the disk. File I/O can be
handled by using different functions.
Formatted functions: The file input function fscanf( ) and the file output function fprintf( ) are called
formatted file I/O functions.
Unformatted functions: The input functions like getc( ), getw( ), and fread( ) are called unformatted
file input functions and putc( ), putw( ), and fwrite( ) functions are unformatted file output functions.
Each and every function is having its own syntax andmeaning.
File streams:- Stream is either reading or writing of data. The streams are designed to allow the user
to access the files efficiently. A stream is a file or physical device like key board, printer, monitor,
etc., The FILE object uses these devices. When a C program is started, the operating system is
responsible for opening three streams:standard input stream(stdin),standard output
stream (stdout), standard error(stderr).Normally the stdin is connected to the keyboard, the stdout
and stderr are connected to the monitor.
Text files and Binary files: C uses two types of files, text files and binary files.
Text files:- Text file is a file consists of a sequence of characters divided into lines with each line
terminated by a new line(‘\n’). A text file is writing using text stream. We can read and write text files
using different input/output functions. Formatted input/output (scanf/printf), character input/output
(getchar/putchar), and string input/output (gets/puts) functions. And these functions can work with
only text files. A text file contains only textual information like alphabets, digits, and special symbols.
In actuality the ASCII codes of these characters are stored in text files.
Basic operations on files: The file consists of large, amount of data, which can be read or modified
depending on the requirement. The basic operations that can be performed on files are:
a) Opening a file: A file has to be opened before to read and write operations. This can be achieved
through fopen() function.
Syntax: FILE*fp;
fp=fopen(filename,mode);
Here is a pointer pointing to the file“filename”,which can be opened in specified mode. The fopen()
performs three tasks:
i) It searches the disk for opening the file.
ii) If file exists, it opens that file, if the file is not existing this function returns NULL in case of read
mode. In case of write mode, it creates a new file and in case of append mode it opens that
file for updating.
iii) It locates a file pointer pointing to the first character of thefile.
Ex: FILE *fp;
fp = fopen(“sample.txt”, ”r”);
if (fp==NULL)
printf(“file does not exist”);
else
{
.................
}
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 113
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving
b)Reading/writing a file: Once the file is opened, the associated file pointer points to the starting of
the file. If the file is opened in writing mode, then we can write information by using different
functionslike:
putc ( ): Putting a character in to the file. It works with only character data type. One character
at a time can write into a file.
Ex: char ch =’a’;
putc (ch,fp);
putw ( ): putting or writing of an integer value to a file.
Ex: int x = 5;
putw(x,fp);
fprintf(): writing a group of values into a file.
Syntax:
fprintf (file pointer, ”control string”, list of arguments);
Ex: fprintf (fp, ”%s %d %d ”, name, rno,marks);
If the file is opened in reading mode, then we can read information from the file, i.e. using some
functions like:
getc ( ): getting a character from the file, or reading the file information character by character at a
time, upto the end of the file by using this function.
Ex: char ch;
ch = getc (fp);
getw( ): getting or reading integer value from a file. Ex: intx;
x = getw (fp);
fscanf ( ): This function is used to read the information from a file record-wise. It is used to read
more values at atime.
Ex: fscanf(fp,”%s%d%d”, name, &no,&marks);
Among all the above different file i/o functions, fscanf() and fprintf() are called as formatted i/o
functions. Printf and scanf are also called as formatted i/o functions.
c) closing a file: After reading/writing a file ,it is needed to close that file .fclose() is used to close a
file. It closes only one file at atime.
fclose (fp):-close a file which is pointed by fp.
fcloseall ( ):-close all opened files at a time.
Different modes to open a file: The tasks performed by fopen() function when a file is opened in each of
these modes are as follows:
1. ”r” (Read) mode: opens the file that already exists for reading only. If the file doesn’t exist it
returnsNULL.
2. ”w”(write) mode: File is opened for writing, if the file exists its contents are over written
and if the file doesn’t exists , then a new file is created.It returns NULL if it is unable to open the
file.
f1=fopen(“sample.txt”, ”w”);
3. ”a”(append) mode: searches for the file, if it exists then appending new contents at the end
of the file.If a file doesn’t exist then a file with a specified name is created and ready to get
append oradd.
f1 = fopen (“sample.txt”, ”a”);
4. ”r+” (Read & write mode): This is for both reading and writing the data. If the file doesn’t
exist then it returnsNULL.
5. ”a+” (Append & Read) mode: The file can be read as well as data can beappended.
The two modes of binary files are:
1. “rb” (read binary) mode: Binary file is opened for readingonly.
2. “wb” (write binary) mode: Binary file opened for writingonly.
NOTE: While opening the file in text mode we can use either “r” or “rt”/ “w” or “wt”, but since text mode
is the default mode we usually drop the “t”.
/* PROGRAM TO COPY ONE FILE INTO ANOTHER FILE */
#include <stdio.h>
int main()
{
FILE *fs,*ft; char ch;
fs=fopen("sample.txt","r");
if (fs==NULL)
{
puts("cannot open source file\n");
exit(1);
}
ft=fopen("sample1.txt","w");
if (ft==NULL)
{
puts("cannot open target file");
exit(1);
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 115
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving
}
while((ch=fgetc(fs))!=EOF)
fputc(ch,ft);
fclose(fs);
fclose(ft);
return 0;
}
/* EXAMPLE PROGRAM FOR ACCESSING BINARY FILES USING fwrite( ) , fread( ) FUNCTIONS */
#include<stdio.h>
int main()
{
int i,n;
FILE *fp1,*fp2,*fp3;
struct employ
{
char name[20];
int eno;
int bsal;
};
struct employ e[3];
fp1=fopen("EMP.DAT","wb");
for(i=0;i<3;i++)
{
printf("\n Enter name, num, and basic pay \n");
scanf("%s%d%d",e[i].name,&e[i].eno,e[i].bsal);
}
fwrite(&e,sizeof(e),3,fp1);
fclose(fp1);
fp1=fopen("EMP.DAT","rb");
fread(&e,sizeof(e),3,fp1);
for(i=0;i<3;i++)
{
printf("\n Name:%s",e[i].name);
printf("\n Number :%s",e[i].eno);
printf("\n basic pay :%s",e[i].bsal);
}
fclose(fp1);
return 0;
}