Programming for Problem Solving Theory 2020-21
Programming for Problem Solving Theory 2020-21
TECHNOLOGY (Autonomous)
Material
1
PROGRAMMING FOR PROBLEM SOLVING
DEPARTMENT OF CPDS/CSE
Name: ……………………………………….
Section………………Year…………………..
GOKARAJU RANGARAJU
2
Preface
The main objective of the course entitled “Programming for Problem Solving” is to make first year
B.Tech students familiar with the Computer Programming concepts and language fundamentals in a
more systematic manner. This material is written according to GRIET GR-20(Autonomous)
syllabus. This book has been prepared to meet the requirements of Programming for Problem
Solving
2. S T G Y .Sandhya
3. K. Ch. Suneetha
4. A. Sravanthi
5. D. Suguna Kumari
6. P. Rajesh
7. A.Sowmya
8. R.S.Shalini
9. M.Suresh Babu
3
COURSE: PROGRAMMING FOR PROBLEM SOLVING (T) CODE : GR20A1007
COURSE SYLLABUS
I/O: Simple input and output with formatted I/O and unformatted I/O.
Conditional Branching and Loops: Conditional branching with if, if-else, nested if else, else if ladder, switch-case,
loops : for, while, do-while, jumping statements: goto, break, continue.
Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of arrays.
4
Structures and unions: Defining structures, initializing structures, Array of structures, arrays within structures,
nested structures, unions, typedef.
Files: Text and Binary files, Creating and Reading and writing text and binary files, Random access to files, Error
Handling in files Command line arguments, Enumeration data type.
Preprocessor: Commonly used Preprocessor commands like include, define, undef, if, ifdef, ifndef,elif.
5
UNIT-I
I/O: Simple input and output with formatted I/O and unformatted I/O.
Algorithm:
Algorithm is a finite set of instructions that , if followed accomplishes a particular task. The
same problem can be solved with different methods. So, to solve a problem different
algorithms, may be accomplished. Algorithm may vary in time, space utilized.
User writes algorithm in his / her own language. So, it cannot be executed on
computer. Algorithm should be in sufficient detail that it can be easily translated into any
language.
Advantages of Algorithms:
• It provides the core solution to a given problem. the solution can be implemented on a
computer system using any programming language of user‘s choice.
• It facilitates program development by acting as a design document or a blue print of a
given problem solution.
• It ensures easy comprehension of a problem solution as compared to an equivalent
computer program.
• It eases identification and removal of logical errors in a program.
• It facilitates algorithm analysis to find out the most efficient solution to a given
problem.
Disadvantages of Algorithms:
In large algorithms the flow of program control becomes difficult to track.
Algorithms lack visual representation of programming constructs like flowcharts.
Understanding the logic becomes relatively difficult.
Examples:
Flowchart:
• It is a symbolic diagram of operations sequence, dataflow, control flow and processing logic
in information processing.
Purpose of a Flowchart :
•Provides communication.
•Provides an overview.
•Shows all elements and their relationships.
•Quick method of showing program flow.
•Checks program logic.
•Facilitates coding.
•Provides program revision.
•Provides program documentation.
Advantages of a Flowchart :
•Flowchart is an important aid in the development of an algorithm itself.
•Easier to understand than a program itself.
• Independent of any particular programming language.
•Proper documentation.
•Proper debugging.
•Easy and clear presentation.
7
Limitations of a Flowchart :
•Complex logic.
•Drawing is time consuming.
•Difficult to draw and remember.
•Technical detail.
Step 1 : Start
Step 2 : Input num1 , num2
Step 3 : Temp = num1
Step 4 : num1 = num2
Step 5 : num2 = Temp
Step 6 : Output num1 , num2
Step 7 : Stop
8
Flowcharts
Develop an algorithm and flowchart to find the largest among two numbers.
Ans: Algorithm:
Step 1 : Start
Step 2 : Input A , B
Step 3 : if A > B then output A
else output B
Step 4 : Stop
Flowchart :
9
Develop an algorithm and flowchart to find the largest among three numbers. Algorithm:
Step 1 : Start
Step 2 :Input A, B, C
Step 3 :If A > B goto step 4 ,otherwise goto step 5.
Step 4 :if A > C goto step 6,otherwise goto step 8
Step 5 :if B > C go to step 7,otherwise goto step 8
Step 6 : print A is largest and goto step9
Step 7 : print B is largest and goto step9
Step 8 : print C is largest and goto step9
Step 9 :Stop
Flowchart:
Flowchart:
10
Algorithm:
Step 1:Start
Step 2:Input n
Step 3:Initialize counter variable, i , to 1 and factors = 1 Step
4:if i<= n go to step 5 otherwise goto step 7
Step 5:Calculate factors = factors * i
Step 6:Increment counter variable, i, and goto step 4
Step 7:output factors.
Step 8:stop
Pseudocode:
Pseudocode is an informal way of programming description that does not require any strict
programming language syntax or underlying technology considerations. It is used for creating
an outline or a rough draft of a program. Pseudocode summarizes a program’s flow, but
excludes underlying details. System designers write pseudocode to ensure that programmers
understand a software project's requirements and align code accordingly.
Advantages of pseudocode –
• Pseudocode is understood by the programmers of all types.
• it enables the programmer to concentrate only on the algorithm part of the code
development.
• It cannot be compiled into an executable program.
Example of Pseudocode:
Bigger of 2 numbers:
Read A,B.
A=1;
11
While(A!=6)
Do sum=sum+A;
Endwhile.
Print sum;
End
It is the job of programmer to write and test the program. The following are four steps for creating
and running programs:
Example : word processor. The text editor could be generalized word processor, but every
compiler comes with associated text editor.
After the program is completed the program is saved in a file to disk. This file will be input to the
compiler, it is known as source file. The following figure shows the various steps in building a C –
program
12
Fig: Steps followed to Build a C – program
A. Compiling Programs: The code in a source file on the disk must be translated into machine
language. This is the job of compiler which translates code in source file stored on disk into machine
language. The C compiler is actually two separate programs: the preprocessor and the translator. The
preprocessor reads the source code and prepares it for the compiler. It scans special instructions
known as preprocessor commands. These commands tell the preprocessor to take for special code
libraries, make substitutions in the code. The result of preprocessing is called translation unit. The
translator reads the translation unit and writes resulting object module to a file that can be combined
with other precompiled units to form the final program. An object module is the code in machine
language. This module is not ready for execution because it does not have the required C and other
functions included.
Example: printf( ) , cos( )… etc Their codes exists elsewhere , they must be attached to our program.
The linker assembles all these functions, ours and the system‘s, into a final executable program.
C.Executing Programs : Once our program has been linked, it is ready for execution. To execute a
program, we use operating system command, such as run to load the program in to main memory
and execute it. Getting program into memory is the function of an Operating System programs
called loader. Loader locates the executable program and reads it into memory. In a typical program
execution, the program reads data for processing, either from user or from file. After the program
processes the data, it prepares output. Data output can be to user‘s monitor or to a file. When
program has executed, Operating System removes the program from memory.
13
14
15
16
17
18
19
20
.
In computer programming, a logic error is a bug in a program that causes it to operate incorrectly, but
not to terminate abnormally (or crash). A logic error produces unintended or undesired output or other
behavior, although it may not immediately be recognized as such.
Logic errors occur in both compiled and interpreted languages. Unlike a program with a syntax error, a
program with a logic error is a valid program in the language, though it does not behave as intended. Often the
only clue to the existence of logic errors is the production of wrong solutions, though static analysis may
sometimes spot them.
Object Code :
Object code is produced when an interpreter or a compiler translates source code into recognizable and
executable machine code. Object code is a set of instruction codes that is understood by a computer at the
lowest hardware level. Object code is usually produced by a compiler that reads some higher level computer
language source instructions and translates them into equivalent machine language instructions.
Executable Code :
It is Software in a form that can be run in the computer. It typically refers to machine language, which is the set
of native instructions the computer carries out in hardware. Executable files in the DOS/Windows world use
.exe and .com file extensions, while executable files in Unix and Mac do not require specific extensions. They
are identified by their file structure.
Structure of C Program:
21
Documentation section :
This section consists of a set of comment lines giving the name of the program, and other details. which the programmer
would like to user later.
Ex:- /*Addition of two numbers */
Link section:Link section provides instructions to the compiler to link functions from thesystem library.
Ex:- # include<stdio.h>
# include<conio.h>
Definition section:Definition section defines all symbolic constants.
Ex:- # define A 10.
Global declaration section:Some of the variables that are used in more than one functionthroughout the program are
called global variables and declared outside of all the functions. This section declares all the user-defined functions.
VARIABLES
It is a data name that may be used to store a data value. It cannot be changed during the
execution of a program. A variable may take different values at different times during
execution. A variable name can be chosen by the programmer in a meaningful way so as to
reflect its function or nature in the program.
Rules:
Variable names may consist of letters, digits and under score( _ ) character.
22
First char must be an alphabet or an ‗-‘
Length of the variable cannot exceed upto 8 characters, some C compilers can
recognized upto 31 characters.
White space is not allowed.
Variables name should not be a keyword.
Uppercase and lower case are significant.
Ex:- mark,sum1,tot_value,delhi (valid)
Prics$, group one, char (invalid)
Declaration and initialization of variables with examples:
Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.
The syntax for declaring a variable is as follows:
data-type v1,v2,…….,vn;
v1,v2,…,vn are the names of variables. Variables are separated by commas. A declaration statement must end
with a semicolon. For example , valid declarations are:
int count;
int number, total;
double ratio;
The simplest declaration of a variable is shown in the following code fragment:
Example:
/*…………….ProgramName……….*/
int main()
{
//Declarations
float x,y;
int code;
short int count;
long int amount;
double deviation;
unsigned n;
char c;
/*…………………………Computation…………………………*/
}
/*…………………………Program ends…………………..*/
Initialization of variable :
Initialize a variable in c is to assign it a starting value. Without this we can't get
whatever happened to memory at that moment.
C does not initialize variables automatically. So if you do not initialize them properly,
you can get unexpected results. Fortunately, C makes it easy to initialize variables
when you declare them.
For Example :
int x=45;
intmonth_lengths[] ={23,34,43,56,32,12,24};
struct role = { "Hamlet", 7, FALSE, "Prince of Denmark ", "Kenneth Branagh"};
*Note : The initialization of variable is a good process in programming.
Data types :
A data type is a classification of the type of data that a variable can hold in computer programming.
Data type is the type of the data that are going to access within the program. C supports different data
23
types. Each data type may have pre-defined memory requirement and storage representation.
i) Integer (int)
ii) Character(char)
iii) Floating (float)
24
i)Integer types:
Integers are whole numbers with a range of values supported by a particular machine. Integers
occupy one word of storage and since the word size of the machine vary. If we use 16 bit word
length the size of an integer value is -32768 to +32767. In order to control over the range of
numbers and storage space, C has 3 classes of integer storage, namely short, long, and unsigned.
FORMAT
DATA TYPE RANGE SIZE
SPECIFIER
4 bytes
Unsigned short int 0 to 255 %d or %i
0 to 65,535 4 bytes
Unsigned int %u
4 bytes
Unsigned long int 0 to 4,294,967,295 %lu
Character type:-
Single character can be defined as a character (char) type data. Characters are usually stored in 8bits
of internal storage. Two classes of char types are there.
25
iii) Floating point types:
Floating point (real) numbers are stored in 32 bits, with 6 digits of precision when
accuracy provided by a float number is not sufficient.
Syntax: typedef data-type identifier; where data-type indicates the existing datatype identifier
indicates the new name that is given to the data type.
Where identifier is user-defined datatype which is used to declare variables that can have one of the
values enclosed within the braces. value1 ,value2,……valuen all these are known as enumeration
constants.
v1=value3;
v2=value1;…
……
Ex:-enum day {Monday,Tuesday………….
sunday}; enum day week-f,week-end
Week-f = Monday
CONSTANTS IN C
Constants is the most fundamental and essential part of the C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the
same during the entire execution of the program.
Constants are also called literals.
Constants can be any of the data types.
26
It is considered best practice to define constants using only upper-case names.
Types of C constants:
1.Integerconstants
2.Real constants
3.Character constants
4. String constants
1. Integer constants: An integer constant refers to a sequence of digits. There are three
types ofintegers, namely, decimal integer, octal integer and hexadecimal integer.
Examples of Integer Constants:
426 ,+786 , -34(decimal integers)
037, 0345, 0661(octal integers)
0X2, 0X9F, 0X (hexadecimal integers)
CONSTANT MEANING
‘\0’ NULL
‘\t’ Horizontal tab
‘\b’ Backspace
‘\a’ Audible bell
‘\n’ New line
‘\v’ Vertical tab
‘\?’ Question mark
‘\’’ Single Quote
‘\”’ Double Quote
‘\\’ Backslash
These character combinations are called escape sequences.
Operators :
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.
1. Arithmetic Operators: C provides all the basic arithmetic operators. These can operate onany
built –in data type allowed in C.
28
Operator Meaning Examples
+ Addition c=a+5;a=b+c;h=9+6;
- Subtraction d=e-f;
* Multiplication k=3*g;
NOTE:
Integer Arithmetic:
If both the operands in an arithmetic expression are integers then it is known as integer
arithmetic and the result is an integer.
Real Arithmetic:
If both the operands in an arithmetic expression are real operands then it is known as real
arithmetic and the result is real.
If the operands in an arithmetic expression are of different types then it is known as mixed mode
arithmetic and the result is a bigger type.
2. Relational Operators:
Relational operators are used for comparing two quantities, and used for decision making.
For example we may compare the age of two persons or the price of two items which can be
done with the help of relational operators.
An expression containing a relational operator is termed as a relational expression. The
value of a relational expression is either one or zero. It is one if the specified relation is true and
zero if the relation is false. Ex:- 13<34 (true) 23>35(false)
29
Operator Meaning Example Result
== is equal to 8==8 1
When arithmetic expression are used on either side of a relational operator, the arithmetic
expression will be evaluated first and then the results compared, that means arithmetic
operators have a higher priority over relational operators.
3. Logical Operator:
C has 3 logical operators. The logical operators are used when we want to test more than one
condition and make decisions. The operators are as follows:
The logical operators && and || are used when we test more than one condition and make decisions.
Logical expressions combines two or more relational expressions, is also known as compound
relational expression. The truth table for Logical AND and Logical OR is as below
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
30
4. Assignment operator:
These operators are used to assign the result of an expression to a variable. The usual assignment
operator is “=‟. In addition ,C has a set of shorthand assignment operators of the form:
v op = exp;
The use of short hand assignment operators has the following advantages:
i. What appears on the left- hand side need not be repeated and therefore it becomes easier to
write
ii. The statement is more concise and easier to read
iii. The statement is more efficient
++ and - - are increment and decrement operators in C. The operator ++ adds 1 to the operand,
while - - subtracts 1.Both are unary operators. They exist in postfix and prefix forms.
31
++m; or m++; is equal to m=m+1(m+=1;)
We use the increment and decrement statements in for and while loops extensively
y=++m; the value of y=6 and m =6. Suppose if we write the above statement as m=5;
A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. On
the other hand, a postfix operator first assigns the value to the variable on left and then increments the
operand. Likewise for decrement operator.
6. Conditional operator:
The operator?: works as follows: exp1 is evaluated first. If it is non-zero (true), then
theexpression exp 2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is
evaluated and it becomes the value of the expression.
o/p:- Big will be assigned the value of b (45) since a>b is false.
7. Bitwise Operators:
C supports a special operator knows as bitwise operators for manipulation of data at bit
level.These operators are used for testing the bits, or shifting them right to left.
Note: Bitwise operators may not be applied to float or double.
| Bitwise OR x|y
32
8. Special operators:
C supports some special operators such as comma operator, size of operator, pointer operators(&
and *) and member selection operators (. and -> ).
comma operator: The comma operator is used to link the related expressions together. Acomma-
linked list of expressions is evaluated left to right and the value of right- most expression is the value
of the combined expression. For example, the statement
This statement first assigns the value 10 to x, then assigns 5 to y and finally assigns 15. In for loops: for
sizeof operator: The sizeof is a compile time operator and when used with an operand, itreturns the
number of bytes the operand occupies. The operand may be variable, a constant or a data type qualifier.
m = sizeof (sum);
The sizeof operator is normally used to determine the lengths of arrays and structures when their sizes are not known to
the programmer. It is also used to allocate memory space dynamically to variables during execution of a program
Expressions:
An expression in C is some combination of constants, variables, operators and function calls.
Examples:C= a + b;
tan (angle)
•Most expressions have a value based on their contents.
•A statement in C is just an expression terminated with a semicolon. For
Example:
sum = x + y + z;
The rules given below are used to evaluate an expression,
1. If an expression has parenthesis, sub expression within the parenthesis is evaluated first and
arithmetic expression without parenthesis is evaluated first.
2. The operators of high level precedence are evaluated first.
3. The operators at the same precedence are evaluated from left to right or right to left depending on
the associativity of operators.
Expressions are evaluated using an assignment statement of the form:
variable = expression;
33
Expression evaluation:
variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and the result then replaces the previous value of the variable on the left-hand side.
All variables used in the expression must be assigned values before evaluation is attempted
Ex:- x = a*b-c;
y = b/c*a;
z = a-b / c+d;
Ex:- x= a-b/3+c*2-1 when a=9, b=12, and c=3 the expression becomes. x = 9-
12/3 +3*2-1
Step1: x = 9-4+3*2-1
Step2: x = 9-4+6-1
Step3: x = 5+6-1
Step4: x = 11-1
Step5: x = 10
Note:
1. Precedence rules decide the order in which different operators are applied
2. Associativity rule decides the order in which multiple occurrences of the same level
operators are applied.
34
Hierarchy of operators in C :
The higher the position of an operator is, higher is its priority.When an expression
contains two operators of equal priority the tie between them is settled using the
associativity of the operators.
Left to Right means, as you go from left to right in an expression which operator among the two is
found, execute it first.Right to left means, as you go from right to left in an expression which operator
among the two is found, execute it first.
Consider expression a=3/2*5 Here there is a tie between operators of same priority, that is between /
and *. This tie is settled using the associativity of / and *. But both enjoy Left to Right associativity,
which means as you go from left to right / is found so execute it first.
The table clearly shows the associativity and precedence of operators in c.
35
!= IS NOT EQUAL TO RIGHT
8 & BITWISE AND LEFT TO
RIGHT
9 ^ BITWISE XOR LEFT TO
RIGHT
10 | BITWISE OR LEFT TO
RIGHT
11 && LOGICAL AND LEFT TO
RIGHT
12 || LOGICAL OR LEFT TO
RIGHT
13 ?: TERANARY LEFT TO
RIGHT
14 = ASSIGNMENT OPERATOR SIMPLE
+= ASSIGNMENT BY SUM
-= ASSIGNMENT BY DIFFERENCE
*= ASSIGNMENT BY PRODUCT RIGHT TO
/= ASSIGNMENT BY QUOTIENT LEFT
%= ASSIGNMENT BY REMAINDER
<< = ASSIGNMENT BY BITWISE LEFT SHIFT
>>= ASSIGNMENT BY BITWISE RIGHT SHIFT
&= ASSIGNMENT BY BITWISE AND
^= ASSIGNMENT BY BITWISE XOR
|= ASSIGNMENT BY BITWISE OR
15 , COMMA LEFT TO
RIGHT
For Example:
i= 2*3/4+4/4+8-2+5/8
i=6/4+4+8-2+5/8
i=1+4/4+8-2+5/8
i=1+1+8-2+5/8
i=1+1+8-2+0
i=2+8-2+0
i=10-2+0
i=8+0
i=8
Type conversion:
It is a process of converting a variable value or a constant value temporarily from one data type to
other data type for the purpose of calculation is known as type conversion.
Implicit: In this lower data type can be converted into higher data type automatically. The figure
36
below shows the C conversion hierarchy for implicit –type conversion in an expression:
The sequence of rules that are applied while implicit type conversion is as follows: All
1. if one of the operands is long double the other will be converted to long double and the result
will be long double.
2. else, if one of the operand is double, the other will be converted to double and the result will be
double.
3. else, if one of the operand is float ,the other will be converted to float and the result will be float.
4. else, if one of the operand is unsigned long int, the other will be converted to unsigned long int and
the result will be unsigned long int.
5. else, if one of the operand is long int, the other is unsigned int then
a) if unsigned int can be converted into long int, the unsigned int operand will be converted as such
and the result will be long int.
b) else both operands will be converted to unsigned long int and the result will be unsigned long
int.
6. else if one of the operand is long int ,the other will be converted into long int and the result will be
long int.
7. else if one of the operand unsigned int ,the other will be converted into unsigned int and the result
will be unsigned int.
The final result of an expression is converted to the type of the variable on the left of the assignment
sign before assigning the value to it. The following changes are introduced during the final
assignment.
37
ii. double to float causes rounding of digits
iii. long int to int causes dropping of the excess higher order bits
Example : Consider the following variables along with their datatypes: int
Explicit:
In this type of conversion, the programmer can convert one data type to other
datatype explicitly .Such conversions are also known as forced conversions
or manual conversions or type casting.
Syntax: (datatype) (expression) Expression can be a constant or a variable
int a=10;
float(a)> 10.00000
Example:
float c,f;
clrscr();
scanf("%f",&f);
c=(float)5/9*(f-32);
38
printf("\n c=%f",c);
getch();
Reading, processing and writing of data are the three essential functions of a computer program. Most
programs take some data as input and display the processed data. We have two methods of providing
data to the program variables. One method is to assign values to variables through the assignment
statements like x=5, a=0 and so on. Another method is to use the input function scanf, which can read
data from a keyboard. We have used both the methods in programs. For outputting results, we have
used extensively the function printf, which sends results out to a terminal.
The program takes some I/P- data, process it and gives the O/P.We have two methods for providing
data to the program
C language has 2 types of I/O statements. All these operations are carried out through function calls.
getchar ( ):- It reads single character from standard input device. This function don‘t require
anyarguments.
Ex:- char x;
x = getchar( );
putchar ( ):- This function is used to display one character at a time on the standard
outputdevice.
39
Syntax:-putchar(variable_name);
Ex:- char x;
putchar(x);
program:
void main( )
char ch;
printf("enter a character:");
ch=getchar( );
printf("\ncharacter is:");
putchar(ch);
Output:
enter a char a
char is a
gets( ):- This function is used to read group of characters(string) from the standard I/P device.
Syntax:-gets(string name);
Ex:- gets(s);
puts( ):- This function is used to display string to the standard O/P device.
Syntax:-puts(string name);
Ex:- puts(s);
program:
void main()
{
char s[10];
puts(“enter name”);
gets(s);
puts(“print name:”);
puts(s);
40
}
Output:
getch():- This function reads a single character directly from the keyboard without displaying
onthe screen. This function is used at the end of the program for displaying the output (without
pressing (Alt-F5).
Ex:- char c;
c = getch();
getche():- This function reads a single character from the keyboard and echoes(displays) it tothe
current text window.
Ex:- char c;
c = getche();
Program:
void main()
{
char ch, c;
printf("enter char");
ch = getch();
41
printf("%c", ch);
printf("enter char");
c = getche();
printf("%c",c);
}
Output :-
enter character a
enter character b
b
ctype.h
Function Test
isdigit(c) Is c a digit?
isprint(c) Is c a character?
program:
void main()
{
char a;
printf(“enter char”);
a = getchar();
if (isupper(a))
{
x= tolower(a);
putchar(x);
}
else
42
putchar(toupper(a));
}
Output:-
enter char A
a
Formatted I/O refers to input and output that has been arranged ina particular format.
scanf( ) :-scanf() function is used to read information from the standard I/P device.
Syntax:-scanf(“controlstring”, &variable_names);
Control string (also known as format string) represents the type of data that the user is going
to accept and gives the address of variable.
Control string and variables are separated by commas. Control string and the variables going
to I/P should match with each other.
Ex:-int n;
scanf(“%d”,&n);
The percentage sign(%) indicates that a conversion specification follows. w is an integer number
that specifies the field width of the number to be read and d known as data type character
indicates that the number to be read is in integer mode.
Ex:-scanf(“%2d,%5d”,&a,&b);
31426
43
Inputting Real Numbers:
The field width of real numbers is not to be specified unlike integers. Therefore scanf reads
real numbers using the simple specification %f.
Suppose the following data are entered as input: 23.45 34.5 The
Ex:scanf(“%s”,name1);
Formatted Output:
printf( ): This function is used to output any combination of data. The outputs are produced insuch a
way that they are understandable and are in an easy to use form. It is necessary for the programmer to
give clarity of the output produced by his program.
2. Format specifications that define the O/P format for display of each item.
The control string indicates how many arguments follow and what their types are.
The var1, var2 etc..are variables whose values are formatted and printed according to the
specifications of the control string.
The arguments should match in number, order and type with the format specifications
44
45
UNIT-II
Conditional Branching and Loops: Conditional branching with if, if-else, nested if else, else if ladder, switch-
case, loops : for, while, do-while, jumping statements: goto, break, continue.
Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of arrays.
Searching: Basic searching in an array of elements, linear and binary search.
0 X (0) 0
0 X (1) 0
1 0 0
1 1 1
Expr2is not evaluated in the first two cases since its value is not relevant to the result.
Examples:
1.if (5 || ++x)
{
printf("%d\n",x);
}
2.int x =0;
if(5||2&&++x)
printf("%d", x);
46
3.(a >= 0) && (b < 10)
5. (13 * a) * (b/13 – 1)
Conditional Branching:
Conditional statements help you to make decision based on certain conditions. These conditions are
specified by a set of conditional statements having boolean expressions which are evaluated to a
boolean value true or false.
When we need to execute a block of statements only when a given condition is true then we use
variants of if statements .
1. Simple if statement.
2. if…else statement.
3. Nested if…else statement.
4. else if ladder
Syntax: if ( condition )
stmt block;
stmt-x;
In this syntax,
if is the keyword. <condition>is a relational expression or logical expression or any expression that
returns either true or false. It is important to note that the condition should be enclosed within
parentheses ‘(‘ and ’ )’.
The stmt block can be a simple statement or a compound statement or a null statement.
stmt-xis any valid C statement.
The flow of control using simple if statement is determined as follows:
Whenever simple if statement is encountered, first the condition is tested. It returns either true or false.
47
If the condition is false, the control transfers directly to stmt-x without considering the stmt block. If
the condition is true, the control enters into the stmt block. Once, the end of stmt block is reached, the
control transfers to stmt-x.
#include<stdio.h>
void main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
}
Output: enter age 57
person is retired
2. if—else statement:
if…else statement is used to make a decision based on two choices. It has the following form:
Whenever if...else statement is encountered, first the condition is tested. It returns either true or false.
If the condition is true, the control enters into the true stmt block. Once, the end of true stmt block is
reached, the control transfers to stmt-x without considering else-body.
If the condition is false, the control enters into the false stmt block by skipping true stmt block.
Once, the end of false stmt block is reached, the control transfers to stmt-x.
Syntax: if(condition)
{
truestmt block;
}
else
{
falsestmt block;
}
stmt-x;
In this syntax,
48
The flow of control using if...else statement is determined as follows:
#include<stdio.h>
void main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
else
printf("person is not retired\n");
}
Nested if Statements:
• The statement executed as a result of an if statement or else clause could be another if statement
• An else clause is matched to the last unmatched if (no matter what the indentation implies)
• Braces can be used to specify the if statement to which an else clause belongs
Flow chart:
49
Example program:
void main ( )
int a, b;
if(a>b)
if(a>c)
printf("%d\n", a);
else
printf("%d\n", b);
else
if(c>b)
printf("%d\n“ , c);
else
printf("%d\n“ , b); }
Else-if ladder:
Else if ladder is one of the conditional control-flow statements.
It is used to make a decision among multiple choices.
Flow chart:
50
Example Program:
void main()
int m1,m2,m3,avg,tot;
scanf("%d%d%d", &m1,&m2,&m3);
tot=m1+m2+m3;
avg=tot/3;
if(avg>=75) {
printf("distinction"); }
printf("first class"); }
printf("second class"); }
else if (avg<50) {
printf("fail");
Switch Statement:
51
switch statement is one of decision-making control-flow statements. Just like else if ladder, it is also
used to make a decision among multiple choices. switch statement has the following form:
Syntax:
switch(<exp>)
{
case<exp-val-1>: statements block-1;
break;
case<exp-val-2>: statements block-2;
break;
case<exp-val-3>: statements block-3;
break;
case<exp-val-N>: statements block-N;
break; default:
default statements block;
}
Next-statement;
In this syntax,
The statement block and break statement can be enclosed with in a pair of curly braces { and
}.
The default along with its statements block is an optional one. The break statement can be placed at
the end of default statements block. The default statements block can be placed at anywhere in the
switch statement. If they are placed at any other place other than at end, it is compulsory to include a
break statement at the end of default statements block.
Next-statement is a valid C statement.
52
Whenever, switch statement is encountered, first the value of <exp> gets matched with case
values. If suitable match is found, the statements block related to that matched case gets executed. The
break statement at the end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed and then the control gets
transferred to Next-statement.
Example Program:
It is the process where a set of instructions or statements is executed repeatedly for a specified
number of time or until a condition is satisfied.These statements also alter the control flow of
the program. It can also be classified as control statements in C Programming Language.
1. while Loop
2. do while loop
3. for loop
54
1. while Loop:
The simplest of all the looping structures in c is the
while statement. A WHILE loop has one control
expression, andexecutes as long as that expression
is true.
The basic format of the while statement is:
Syntax:
while(condition)
statements;
The while is an entry –controlled loop statement. The condition is evaluated and if the condition is true
then the statements will be executed. After execution of the statements the condition will be evaluated
and if it is true the statements will be executed once again. This process is repeated until the condition
becomes false and the control is transferred out of the loop .On exit the program continues with the
statement immediately after the body of the loop.
#include<stdio.h>
void main()
{
inti,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d ",i);
i=i+1;
}
}
2 3 4 5 6 7 8 9 10
2. dowhile statement:
It is one of the looping control statements. It is also called as exit-controlled looping control
statement. i.e., it tests the condition after executing the do-while loop body.
55
The main difference between “while” and “do-while” is that in “do-while” statement, the loop body
gets executed at least once, though the condition returns the value false for the first time, which is not
possible with while statement. In “while” statement, the control enters into the loop body only when
the condition returns true.
Flow chart for do while
Syntax:
Initialization statement;
do
statement(s);
} while(<condition>);
next statement;
In this syntax:
while and do are the keywords. <condition> is a relational expression or a compound relational
expression or any expression that returns either true or false. initialization statement, statement(s) and
next_statement are valid ‘c’ statements.
The statements within the curly braces are called as do-while loop body. The updating statement
should be included with in the do-while loop body. There should be a semi-colon (;) at the end of
while(<condition>).
If the condition returns the value false, the control transfers to next statement without
executing do-while loop body. Hence, it states that, the do-while loop body gets executed for the first
time, though the condition returns the value false.
#include<stdio.h>
voidmain()
{
inti,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
do
55
printf("%d ",i);
i=i+1;
}
while(i<=n);
}
Output: enter the range 8
1 2345678
3. for statement:
It is one of the looping control statements. It is also called as entry-controlled looping control
statement. i.e., it tests the condition before entering into the loop body. The syntax for “for” statement
is as follows:
Syntax:
for(exp1;exp2;exp3)
for-body;
next_statement;
In this syntax,
for is a keyword. exp1 is the initialization statement. If there is more than one statement, then
the statements must be separated with commas. exp2 is the condition. It is a relational expression or a
compound relational expression or any expression that returns either true or false. The exp3 is the
updating statement. If there is more than one statement then, they must be separated with commas.
exp1, exp2 and exp3 should be separated with two semi-colons. exp1, exp2, exp3, for-body and
next_statement are valid ‘c’ statements. for-body is a simple statement or compound statement or a
null statement.
Whenever “for” statement is encountered, first exp1 gets executed. After then, exp2 is tested.If exp2 is
true then the body of the loop will be executed otherwise loop will be terminated.
When the body of the loop is executed the control is transferred back to the for statement after
evaluating the last statement in the loop. Now exp3 will be evaluated and the new value is again tested
.if it satisfies body of the loop is executed .This process continues till condition is false.
#include<stdio.h>
void main()
56
inti,n;
printf("enter the value");
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d\n",i);
}
Output: enter the value 5 12345
Nested for loop refers to the process of having one loop inside another loop. We can have
multiple loops inside one another. The body of one ‘for’ loop contains the other and so on. The
syntax of a nested for loop is as follows(using two for loops):
Syntax:
Example Program :
#include <stdio.h>
void main()
{
inti,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
}
Output:
1
12
123
1234
12345
57
Jumping control-flow statements:
Jumping control-flow statements are the control-flow statements that transfer the control to the
specified location or out of the loop or to the beginning of the loop. There are 3 jumping
control statements:
break statement:
The ―break statement is used within the looping control statements, switch statement and nested
loops. When it is used with the for, while or do-while statements, the control comes out of the
corresponding loop and continues with the next statement.
When it is used in the nested loop or switch statement, the control comes out of that loop / switch
statement within which it is used. But, it does not come out of the complete nesting.
break;
Any loop
{
statement_1;
statement_2;
break;
:
}
next_statement;
In this syntax, break is the keyword.
The following representation shows the transfer of control when break statement is used:
Program for break statement:
#include<stdio.h>
#include<conio.h>
int main( )
{
int i;
for(i=1; i<=10; i++)
{
if(i==6) break;
printf("%d",i);
58
}
}
Output:1 2 3 4 5
continue statement:
A continue statement is used within loops to end the execution of the current iteration and
proceed to the next iteration. It provides a way of skipping the remaining statements in that
iteration after the continue statement. It is important to note that a continue statement should be
used only in loop constructs and not in selective control statements.
continue;
where continue is the keyword.The following representation shows the transfer of control when
continue statement is used:
Any loop
{
statement_1;
statement_2;
.....
continue;
......
}
next_statement;
#include<stdio.h>
#include<coni o.h>
int main()
{
int i, sum=0;
for(i=1; i<=n; i++)
{
if(n==6)
continue;
printf("%d\n"i);
}
}
Output: 1 2 3 4 5 7 8 9 10
Exit :
The C library function void exit(int status) terminates the calling process immediately.This function does not
return any value.
void exit(int status)
//Example
#include <stdio.h>
#include <stdlib.h>
int main ()
{
59
printf("Start of the program. \n");
printf("Exiting the program. \n");
exit(0);
printf("End of the program. \n");
return(0);
}
Output:
Start of the program....
Exiting the program....
Arrays
Introduction :
The fundamental data types, namely char, int, float, double and variations of int and
double can store only one value at any given time. Therefore they can be used only to handle
limited amounts of data.In many applications , we need to handle a large volume of data in
terms of reading, processing and printing. To process such large volume of data C supports a
derived data type known as ARRAY that facilitate efficient storing, accessing and
manipulation of data items.
Definition :
Since an array provides a convienent structure for representing data, it is classified as one of
the data structures in C.
Types of Arrays :
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multi-dimensional arrays.
60
ONE-DIMENSIONAL ARRAYS:
A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or a one-dimensional array.
Like anyother variable, arrays must be declared before they are used so that the compiler
can allocate space for them in memory.
Syntax:
type variable-name[size];
The type specifies the type of element that will be contained in the array, such as int, float
or char.
The size indicates the maximum number of elements that can be stored inside the array
For e.g.-
int number[5];
Declares the number to be an array containing 5 elements. Any subscripts 0 to 4 are valid
and the computer reserves five storage locations as shown below
number[0]
number[1]
number[2]
number[3]
number[4]
Note :
1. any reference to the arrays outside the declared limits would not necessarily cause
an error. Rather, it might result in unpredictable program results.
2. The size should be either a numeric constant or a symbolic constant.
After an array is declared, its elements must be initialized. Otherwise, they will
contain “garbage” . an array can be initialized at either of the following stages:
At Compile time
At run time
61
COMPILE TIME INITIALIZATION :
We can initialize the elements of arrays in the same way as the ordinary variables when
they are declared .
Syntax:
the values in the list are separated by commas. For example, the
statement int number[5]={35,40,50,20,25};
will declare the variable number as an array of size 5 and will assign the value to each element
as follows
number[0] 35
number[1] 40
number[2] 50
number[3] 20
number[4] 25
If the number of values in the list is less than the number of elements, then only that
many elements will be initialized. The remaining elements will be set to zero automatically if the
array type is numeric and NULL if the type is char.
Will initialize the first three elements to 0.0, 5.2 and -10.0 and the remaining two
elements to zero.
If we have more initializers than the declared size, the compiler will produce an
error. int number[3]={10,20,30,40}; is illegal in C.
The size may be omitted in the declaration statement. In such cases, the
compiler allocates enough space for all initialized elements.
Will declare the count array to contain four elements with initial values 1. This
approach works fine as long as we initialize every element in the array.
62
Character arrays may be initialized in a similar manner. Thus the
statement
char name[]={‘h’,’e’,’l’,’l’,’o’,’\0’};
Declares the name to be array of five characters, initialized with the string “hello” ending
with the null character. Alternatively we can assign the string literal directly as
char name[]=”hello”;
An array can be explicitly initialized at run time. This approach is usually applied for
initializing large arrays. For example, consider the following segment of C program
for(i=0;i<100;i=i+1)
{
if(i<50)
sum[i]=0.0;
else
sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to 0 while the remaining 50 are
initialized
to 1.0 at run time.
We can also use a read function such as scanf to initialize an array. For example, the
statements
int x[3];
scanf(“%d%d%d”,&x[0],&x[1],&x[2]);
will initialize array elements with the values entered through the key board.
EXAMPLE PROGRAMS : 10
program :
void main()
{
int i;
float x[10],total;
printf(“enter the 10 real numbers”);
for(i=0;i<10;i++)
scanf(“%f”, &x[i]);
63
total=0.0;
for(i=0;i<10;i++)
total=total+x[i]*x[i];
for(i=0;i<10;i++)
printf(“x[%d]=%f\n”,i,x[i]);
printf(“\n sum of the squares =%f”,total);
}
1D array variables stores a list of values only but there could be a situations where a table
of values have to be stored which need 2D arrays. For examples
Periodic table
Sales information of a company
Data in spread sheets etc.
Syntax:
type array-name[row_size][column_size];
→
Row 0 ---- 310 275 365
→ 10 190 325
Row 1 ----
64
INITIALIZING 2D ARRAYS:
Like the 1D arrays, 2D arrays can be initialized by following their declaration with a list
of initial values enclosed in braces. For example
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of the first row to zero and the second row to one. The initialization is done
row by row. The above statement is equivalently written as int table[2][3]={{0,0,0},{1,1,1}};
We can also initialize a two-dimensional array in the form of a matrix as shown below: int
table[2][3]={
{0,0,0},
{1,1,1}
};
When the array is completely initialized with all values, explicitly, we need not specify the
size of the first dimension. That is, the below statement is permitted.
Will initialize the first two elements of the first row to one, the first element of the
second row to two, and all other elements to zero.When all the elements are to be
initialized to zero, the following short-cut method may be used.
int m[3][5]={{0},{0},{0}};
the first element of each row is explicitly initialized to zero while other
elements are automatically initialized to zero.
Example program:
#include<stdio.>
void main()
{
int
disp[2][3];
int i, j;
for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf("Enter value fordisp[%d][%d]:",i,j);
scanf("%d", &disp[i][j]);
}
65
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf("%d ",
disp[i][j]);
if(j==2)
{
printf("\n");
}
}
}
Multidimensional arrays :
C allows arrays of three or more dimensions. The exact limit is determined by the compiler.
Syntax:
type array-name[s1][s2][s3] ------- [sm];
Initializing 3d array:
int arr[3][3][3]= { {
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
66
}
};
67
Example Programs:
1.Develop a program to Find the Largest Two Numbers in a given Array and also
calculate their average
#include <stdio.h>
#define MAX 4
void main()
printf("%5d", array[i]);
printf("\n");
{
temp = largest1;
largest1 = largest2;
largest2 = temp;
}
for (i = 2; i < 4; i++)
68
{
if (array[i] >= largest1)
{
largest2 = largest1;
largest1 = array[i];
}
Output:
Enter 4 integer numbers 80
23
79
58
Input integer are
80 23 79 58
80 is the first largest 79
is the second largest
Average of 80 and 79 = 79
#include <stdio.h>
int main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
69
scanf("%d", &array[c]);
printf("Enter the location where you wish to
insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--)
array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");
for (c = 0; c <= n; c++)
printf("%3d", array[c]);
return 0;
}
Output:
Enter the value of the n = 4
Enter the numbers 3
40
100
68
Enter the location where you wish to insert an element 2
Enter the value to insert 35
3 35 40 100 80
70
a[c] = b[c];
printf("Reverse array is\n");
for (c = 0; c < n; c++)
printf("%d\n", a[c]);
}
71
}
}
}
else
{
printf("\n matrix multiplication is not possible");
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],r1,r2,c1,c2,i,j,k;
clrscr();
printf("\n enter r1,c1,r2,c2");
scanf("%d %d %d %d",&r1,&c1,&r2,&c2);
if(r1==r2&&c1==c2)
{
printf("\n matrix mutliplication possible");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("\n enter a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("\n enter b[%d][%d]:",i,j);
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
72
}
printf("\n product of matrix c:");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("\t%d",c[i][j]);
}
}
}
else
{
printf("\n matrix multiplication is not possible");
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int row,col,a[5][5],i,j,b[5][5];
clrscr();
printf("\n enter order of matrix r,c:"); scanf("%d
%d",&row,&col); for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("\n enter a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
b[j][i]=a[i][j];
}
}
printf("\n transpose matrix b");
for(i=0;i<col;i++)
{
printf("\n");
for(j=0;j<row;j++)
{
printf("\t %d",b[i][j]);
73
}
}
getch();
}
SEARCHING:
Searching is a technique of finding an element from the given data list or set of the
elements like an array, list, or trees. It is a technique to find out an element in a sorted or
unsorted list. For example, consider an array of 10 elements. These data elements are stored in
successive memory locations. We need to search an element from the array. In the searching
operation, assume a particular element n is to be searched. The element n is compared with all
the elements in a list starting from the first element of an array till the last element. In other
words, the process of searching is continued till the element is found or list is completely
exhausted. When the exact match is found then the search process is terminated. In case, no
such element exists in the array, the process of searching should be abandoned.
LINEAR SEARCH:
Linear search technique is also known as sequential search technique. The linear search
is a method of searching an element in a list in sequence. In this method, the array is searched
for the required element from the beginning of the list/array or from the last element to first
element of array and continues until the item is found or the entire list/array has been searched.
Algorithm:
Step 1: set-up a flag to indicate “element not found”
Step 2: Take the first element in the list
Step 3: If the element in the list is equal to the desired element
Set flag to “element found”
Display the message “element found in the list”
Go to step 6
Step 4: If it is not the end of list,
Take the next element in the list
Go to step 3
Step 5: If the flag is “element not found”
Display the message “element not found”
Step 6: End of the Algorithm
Advantages:
1. It is simple and conventional method of searching data. The linear or sequential name
implies that the items are stored in a systematic manner.
2. The elements in the list can be in any order. i.e. The linear search can be applied on
sorted or unsorted linear data structure.
Disadvantage:
1. This method is insufficient when large number of elements is present in list.
2. It consumes more time and reduces the retrieval rate of the system.
74
Time complexity:
O(n)
BINARY SEARCH:
Binary search is quicker than the linear search. However, it cannot be applied on
unsorted data structure. The binary search is based on the approach divide-and-conquer.The
binary search starts by testing the data in the middle element of the array. This determines
target is whether in the first half or second half. If target is in first half, we do not need to check
the second half and if it is in second half no need to check in first half. Similarly we repeat this
process until we find target in the list or not found from the list. Here we need 3 variables to
identify first, last and middle elements.
To implement binary search method, the elements must be in sorted order. Search is
performed as follows:
The key is compared with item in the middle position of an array
If the key matches with item, return it and stop
If the key is less than mid positioned item, then the item to be found must be in first
half of array, otherwise it must be in second half of array.
Repeat the procedure for lower (or upper half) of array until the element is found.
Recursive Algorithm:
Binary_Search(a,key,lb,ub) begin
Step 1: [initialization]
lb=0
ub=n-1;
Step 2: [search for the item]
Repeat through step 4 while lower bound(lb) is less than upper bound.
Step 3: [obtain the index of middle value]
mid = (lb+ub)/2
Step 4: [compare to search for item]
if(key < a[mid]) then
ub=mid-1
otherwise if( key > a[mid]) then
lb=mid+1;
otherwise if(key==a[mid]) Write “match found”
return (mid)
returnBinary_Search(a,key,lb,ub)
Step 5: [unsuccessful search]
Write “match not found”
Step 6: [end of algorithm]
/* C program for recursive binary search to find the given element within array. */
#include<stdio.h>
intbsearch(int [ ],int, int, int);
void main( )
{
76
int a[20],pos,n,k,i,lb,ub;
clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the key value:");
scanf("%d",&k);
lb=0;
ub=n-1;
pos=bsearch(a,k,lb,ub);
if(pos!=-1)
printf("Search successful, element found at position %d",pos);
else
printf("Search unsuccessful, element not found");
getch( );
}
77
int linear(int [ ],int,int ,int);
void main( )
{
int a[20],pos=-1,n,k,i;
clrscr();
printf("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Enter the element to be searched:");
scanf("%d",&k);
pos=linear(a,n,k);
if(pos!=-1)
printf("\n Search successful, Element found at Position %d",pos);
else
printf("Search unsuccessful, element not found ");
}
78
int linear(int a[ ],int n,int low, int k)
{
if(low>= n)
return -1;
else if(k==a[low]
return low;
else
return linear(a,n,low+1,k);
}
}
return -1;
}
Output:-
Enter ‘n’ value : 6
Enter elements for an array : 10 32 22 84 55 78
Enter the element to be searched : 55
Search successful, Element found at Position : 4
/*C program that searches a value in a stored array using non recursive binary search.*/
#include<stdio.h>
void main( )
{
int a[20],pos,n,k,i;
clrscr();
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the key value:");
scanf("%d",&k);
pos=bsearch(a,n,k);
if(pos!= -1)
printf("Search successful, element found at position %d",pos);
else
printf("Search unsuccessful, element not found");
getch( );
}
int bsearch(int a[ ],int n, int k)
{
79
intlb=0,ub,mid;
lb=0;
ub=n-1;
while(ub>=lb)
{
mid=(lb+ub)/2;
if(k<a[mid])
ub=mid-1;
else if(k>a[mid])
lb=mid+1;
else if(k==a[mid])
return(mid);
}
return -1;
}
OUTPUT
Enter ‘n’ value : 67
Enter elements for an array : 35 10 32 25 84 55 78
Enter the element to be searched : 25
Search successful, Element found at Position : 3
80
UNIT-III
Strings: Introduction to strings, operations on characters, basic string functions available in C (strlen, strcat,
strcpy, strrev, strcmp), string operations without string handling functions, arrays of strings.
Functions: Designing structured programs, declaring a function, Signature of a function, Parameters and
return type of a function, call by value, call by reference, passing arrays to functions, recursion, merits and
demerits of recursive functions.
STRINGS
INTRODUCTION:
We can also declare the size much larger than the string in the initialize. That
is, the statement.
char str[10]=”GOOD”;
is permitted. In this case,the computer creates a character array of size 10, places the
value “GOOD” in it, terminates with the null character, and initializes all other elements
to NULL.
81
The storage will look like:
G O O D \0 \0 \0 \0 \0 \0
is not allowed.
scanf(%s”,name);
Note: in the case of character arrays, the ampersand(&) is not required before the variable name.
Disadvantage : scanf terminates its input on the first white space it finds. e.g.-
if enters new york then only new will be read in array name.
We can also specify the field width using the form %ws in scanf for reading a specified
number of characters from the input string.
E.g.- scanf(“%ws”,name);
▪ If w is equal or greater than the number of charcters typed, then entire string
will be stored in the variable
▪ If w is less , then excess characters will be truncated and left unread. E.g.-
scanf(“%6s”,name)
char line[80];
82
scanf(“%[^\n]”,line);
printf(“%s”,line);
will read a line of input from the keyboard and display the same on the screen.
Function getchar is used to read single character from the terminal. This function
repeatedly can be used to read successive single characters from the input and place them
into a character array. Thus, an entire line of text can be read , the reading is terminated
when the newline character (‘\n’) is entered and the null character is then inserted at the end
of the string.
Syntax:char ch;
ch=getchar();
Example program:
#include<stdio.h>
void main()
{
char line[50],ch;
int i=0;
printf(“\n press enter at the end of input”); do
{
ch=getchar();
line[i]=ch; i++;
}while(ch!=’\n’);
i=i-1; line[i]=’\0’;
printf(“%s”,line);
}
another more convienent method of reading a string of text containing whitespaces is to use
the library function gets available in the <stdio.h> header file. syntax:gets(str);
str is a string variable, gets function reads a characters into str from the keyboard until a new- line
83
character is encountered and then appends a null character to the string. unlike scanf, it does not
skip whitespaces.
for example:char line[80];
gets(line);
printf(“%s”,line);
the last two statements can be combined as
follows printf(“%s”,gets(line));
The format %s can be used to display an array of characters that is terminated ny the
null character using printf function.
printf(%s”,line);
We can also specify the precision with which the array is displayed. for
instance, the specification
%10.4
indicates that the first four characters are to be printed in a field width of 10 columns. left-
justified.
Features of %s specifications:
1. when the field width is less than the length of the string, the entire string is printed.
2. the integer value on the right side of the decimal point specifies the number of
characters to be printed.
3. when the number of characters to be printed is specified as zero, nothing is printed.
4. the minus sign in the specification causes the string to be printed left-justified.
5. the specification %.ns prints the first n characters of the string.
Example program:
write a program to store the string and display the string under various format specifications. void
main()
{
char str[14]=”good morning”;
printf(“%14s”,str);
printf(“%4s”,str);
printf(“%14.4s”,str);
printf(“%-14.4s”,str);
printf(“%14.0s”,str);
printf(“%.3s”,str);
printf(“%s”,str);
}
Output:
good morning
84
good
good
goo
good morning
variables.
syntax:
char
ch='a';
putchar(
ch);
Example:
for(i=0;i<12;i++)
putchar(name[i]);
Another and more convenient way of printing string values is to use the
function puts declared in the header file <stdio.h>.
syntax:
puts(str);
where str is a string variable containing a string value, this prints the value of the
string variable str and then moves the cursor to the beginning of the next line on the
screen.
85
ARITHMETIC OPERATIONS ON CHARACTERS:
printf(“%d”,x);
will display the number 97 on the screen.
x=‘a’-1;
printf(“%d”,x)---will print 96, a=97
character constants can also be used in relational expressions. E.g.- ch>=‘A’ &&
ch<=‘Z’ test whether the character in the variable ch is an upper-cas letter.
x= ‘7’-’0’;
printf(“%d”,x)
The C library supports a function atoi (string) that converts a string of digits into their integer
values.
year=atoi(number)
The function converts the string constant “1988”, to its numeric equivalent 1988.
Present in header file <stdlib.h>.C does not provide operators that work on strings
directly like :
str1=“ABC”;
str2=str1; is invalid
86
Strlen() Finds the length of a string
strcat() Function:
the strcat function joins two strings together. it takes the following form:
strcat(string1, string2);
string1 and string2 are character arrays. when the function strcat is executed, string2 is
appended to string1. it does by removing the null character at the end of string1 and
placing string2 from there. the string at the string2 remains unchanged. For example
consider the following three strings:
str1 V E R Y \0
str2 G O \0
V E R Y G O \0
We must make sure that the size of str1 to which str2 is appended is large
enough to accommodate the final string.
strcat function may also append a string constant to a string variable. the following is valid:
strcat(str1,”good”);
C permits nesting of strcat functions. for
example, the statement
strcat(strcat(str1,str2),str3);
is allowed and concatenates all the three strings together. the resultant string is stored in str1.
strcmp() Function:
the strcmp function compares two strings identified by the arguments and has a value
0 if they are equal. if they are not, it has the numeric difference between the first
nonmatching characters in the strings. it takes the form:
strcmp(str1,str2);
str1 and str2 may be string variables or string constants. examples are:
strcmp(str1,str2);
strcmp(str1, “john”);
87
strcmp(“rom”, “ram”);
strcpy() Function:
The strcpy() function works almost like a string-assignment operator. it takes a form:
strcpy(str1,str2);
and assigns the contents of str2 to str1. str2 may be a character array variable or a
string constant.
for example:
strcpy(city, “DELHI”);
will assign the string “DELHI” to the string variable city. similarly,the statement
strcpy(city1,city2) will assign the contents of the string variable city2 to the string variable
city1. the size of the array city1 should be large enough to store the contents of city2.
strlen() Function:
This function counts and returns the number of characters in a string. it takes the
form n=strlen(string)
where n is an integer variable, which receives the value of the length of the string.
Example :
write a program that reads 2 strings s1,s2, and check whether they are equal or not, if they
are not , join them together. then copy the contents of s1 to the variable s3. at the end , the
program should print the contents of all the 3 variables and their lengths.
#include<stdio.h>
void main()
{
char s1[20],s2[20],s3[20];
int x,l1,l2,l3;
printf("\n enter two strings constants");
scanf("%s%s",s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{
printf("\n strings are not equal");
strcat(s1,s2);
}
else
printf("\n strings are equal"); strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf("\n s1=%s length=%d characters",s1,l1);
printf("\n s2=%s length=%d characters",s2,l2);
printf("\n s3=%s length=%d characters",s3,l3);
}
88
output:
enter two strings constants
welcome students
strings are not equal
s1=welcome length=15 characters
s2=students length=8 characters
s3=welcomestudents length=15 characters
strrev() function:
strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given below.
char *strrev(char *string);
example: string “Hello” is reversed using strrev( ) function and output is displayed as “olleH”.
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char s[100];
printf("Enter a string to reverse:\n");
gets(s);
strrev(s);
printf("Reverse of the string: %s\n", s);
}
output:
Enter a string to reverse: rajesh
Reverse of the string: hsejar
string length:
#include<stdio.h>
void main()
{
char str[30];
int i,len=0;
clrscr();
printf("\n enter the string");
gets(str);
for(i=0;str[i]!='\0';i++)
len++;
printf("\n the total no.of characters in the given string is:%d",len-1);
getch();
}
//String concatenation with out string handling function
#include <stdio.h>
void main()
{
char str1[50], str2[50], i, j;
printf("\nEnter first string: ");
scanf("%s",str1);
89
printf("\nEnter second string: ");
scanf("%s",str2);
/* This loop is to store the length of str1 in i
* It just counts the number of characters in str1
* You can also use strlen instead of this.
*/
for(i=0; str1[i]!='\0'; ++i);
90
String comparison with out string handling function
#include<stdio.h>
void main()
{
char str1[30],str2[30];
int i,j,flag=0;
printf("enter the strings to be compared:");
scanf("%s %s",str1,str2);
for (i=0,j=0;str1[i]!='\0'||str2[i]!='\0';i++,j++)
{
if(str1[i]!=str2[j])
{
flag=1; break;
}
}
if(flag==0)
printf("the two strings are equal");
else
printf("the two strings are not equal");
getch();
}
Array of Strings:
We often use list of character strings, such as a list of the names of students in a class,
list of the names of employees in an organization etc. A list of names can be treated as a table
of strings and a two-dimensional character array can be used to store the entire list.
for example, a character array city[5][15] may be used to store a list of 30 city names, each of
length not more than 15 characters. e.g.-
C H A N D I G A R h \0
M A D R A S \0
A H M E D A B A D \0
H Y D E R A B A D \0
B O M B A Y \0
This table can be conveniently stored in a character array city by using the following
declaration:
char city[ ][ ]=
Example Programs:
C Program to Display the Characters in Prime Position a given String
#include <stdio.h>
#include <string.h>
void main()
{
91
int i, j, k, count = 0;
char str[50];
printf("enter string\n");
scanf("%[^\n]s", str);
k = strlen(str);
printf("prime characters in a string are\n");
for (i = 2;i <= k;i++)
{
count = 0;
for (j = 2;j <= k;j++)
{
if (i % j == 0)
{
count++;
}
}
if (count == 1)
{
printf("%c\n", str[i - 1]);
}
}
}
Functions:
The ability to divide a program into abstract, reusable pieces is what makes it possible to write
large programs that actually work right.
The following reasons make functions extremely useful and practically essential:
Enhances redability
Easy to understand.
Allows Code reusability
Structured organization.
Achieves Modular programming
Easy identification of bugs
Data abstraction
Reduction of code repetition so reduces lines of code.
Best suited for large programs or complex programs.
It is used to check logical conditions involving multiple objects and just returns the result.
Code reusability is a method of writing code once and using it many times. Structured
programming also makes the program easy to understand, improves the quality of the program, easy
to implement and reduces time.
93
Definition:
Main Function in C:
In C, the "main" function is treated the same as every function, it has a return type (and in some
cases accepts inputs via parameters called command line arguments).
In C, program execution starts from the main () function. The only difference is that the main
function is "called" by the operating system when the user runs the program.
The main function can in-turn may call other functions. When main calls a function, it passes the
execution control to that function. The function returns control to main when a return statement is
executed or when end of function is reached.
Types of Functions:
94
User Defined Functions in C:
A user can create their own functions for performing any specific task of program are called
user defined functions. To create and use these function we have to know these 3 elements.
A. Function Declaration
B. Function Definition
C. Function Call
1. Function declaration
The program or a function that calls a function is referred to as the calling program or calling
function. The calling program should declare any function that is to be used later in the program
this is known as the function declaration or function prototype.
2. Function Definition
The function definition consists of the whole description and code of a function. It tells that
what the function is doing and what are the input outputs for that. A function is called by simply
writing the name of the function followed by the argument list inside the
95
parenthesis. Function definitions have two parts:
Function Header
Function Body
3. Function Call
In order to use the function we need to invoke it at a required place in the program.
This is known as the function call.
Signature of a function:
A function’s signature includes the function's name and the number, order and type of its formal
parameters.
{
declarations
Statements
return value
}
function-name
parameters
96
Parameter field is optional.
If no parameter is passed then no need to write this field value
Example:
Parameter:The term parameter refers to any declaration within the parentheses following the
function name in a function declaration or definition.
Argument:The term argument refers to any expression within the parentheses of a function call.
Calling function: The function which is making a call to any function is called calling function
97
Parameter Passing Techniques in C:
In C functions exchange information by means of parameters and arguments (which are inputs
given to a function).
There are two ways to pass arguments/parameters to function calls -- call by value and call by
reference.
Call by value:
In call by value a copy of actual arguments is passed to respective formal arguments.
#include <stdio.h>
void swap(int, int);
int main ()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(x, y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("Values of a and b is %d %d\n",a,b);
}
Output:
Call by reference:
In call by reference the location (address) of actual arguments is passed to formal arguments, hence
any change made to formal arguments will also reflect in actual arguments.
#include <stdio.h> void
swap(int*, int*); int
main()
{
int x, y;
printf("Enter the value of x and y\n");
98
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y); return 0;
}
1 The actual arguments are variables, The actual arguments are addresses of
constants or expressions. variables.
4 The formal arguments are also variables. The formal arguments are pointers.
5 Changes made in the called function are Changes made in the called function are
not reflected back in the calling reflected back in the calling function.
function.
6 The calling and the called function The calling and the called function
maintains separate copies of data. maintains or shares a common location.
99
8 Example of function proto type: Example of function proto type:
Swap(a,b); Swap(&a,&b);
Parameters vs Arguments in C:
The term parameter (sometimes called formal parameter) is often used to refer to the
variable as found in the function definition, while argument (sometimes called
actual parameter) refers to the actual input supplied at function call.
1 These are the variable found in the These are the variable found in the
function call. function definition or declaration.
3 Example: Example:
4 They are the original source of information They get the values after function call occurs.
5 They are supplied by the caller or They are initialized with the values of actual
programmer. arguments.
Note:
1. Order, number, and type of the actual arguments in the function call must match with formal
arguments of the function (except for functions with variable list of arguments).
2. If there is type mismatch between actual and formal arguments then the compiler will try to convert
the type of actual arguments to formal arguments if it is legal, otherwise a garbage value will be
passed to the formal argument.
100
3. When actual arguments are less than formal arguments, the garbage value is supplied to the formal
arguments.
4. Changes made in the formal argument do not affect the actual arguments.
One-dimensional Arrays:
We can pass individual elements by either passing their data values or by passing their
addresses. We pass data values i.e; individual array elements just like we pass any data value
.As long as the array element type matches the function parameter type, it can be passed. The called
function cannot tell whether the value it receives comes from an array, a variable or an expression.
void fun1(int );
void main()
{
int a[2][2]={1,2,3,4};
fun1(a[0][1]);
}
void fun1(int x)
{
printf(“%d”,x+10);
}
101
2. Passing whole array (idea of call by reference)
As array name is a constant pointer pointing to first element of array(storing the base
address),Passing array name to a function itself indicates, that we are passing address of first
element of array .
To pass the whole array we simply use the array name as the actual parameter. In the called
function, we declare that the corresponding formal parameter is an array. We do not need to specify the
number of elements.
Program:
Two-dimensional array:
When we pass a 2-D array to a function, we use the array name as the actual parameter.
The formal parameter in the called function header, however must indicate that the array has two
dimensions.
Rules:
1. The function must be called by passing only the array name.
2. In the function definition, the formal parameter is a 2-D array with the size of the second
dimension specified.
Program:
void fun1(int a[][2]);
void main()
{
int a[2][2]={1,2,3,4};
102
fun1(a);
}
void fun1(int x[][2])
{
int i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“%3d”,x[i][j]);
printf(“\n”);
}
}
Recursion :
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch
makes the recursive call and other doesn't.
When a function calls itself, a new set of local variables and parameters are allocated storage
103
on the stack, and the function code is executed from the top with these new variables. A recursive
call does not make a new copy of the function. Only the values being operated upon are new. As each
recursive call returns, the old local variables and parameters are removed from the stack, and
execution resumes immediately after the recursive call inside the function.
The main advantage of recursive functions is that we can use them to create clearer and simpler
versions of several programs.
Output
Enter a positive integer: 6
Factorial of 6 = 720
#include<stdio.h>
void fibo_rec(int n, int f1, int f2); void
main()
{
int f1=0, f2=1,n;
printf("Enter any number to print the fibonacci series: ");
scanf("%d",&n);
if(n<=0)
printf("Enter a valid number\n");
else if(n==1)
printf("fibonacci series is: %d",f1);
else if(n==2)
104
printf("fibonacci series is: %d %d",f1,f2);
else {
printf("fibonacci series is: %d %d ",f1,f2);
fibo_rec(n-2,f1,f2);
printf("\n\n");
}
}
void fibo_rec(int n, int f1, int f2)
{
int f3;
if(n==0)
return;
f3=f1+f2;
printf("%3d ",f3);
fibo_rec(n-1,f2,f3);
}
Both recursion and iteration are used for executing some instructions repeatedly until some
condition is true. A same problem can be solved with recursion as well as iteration but still there are
several differences in their working and performance that I have mentioned below.
Recursion Iteration
definition Recursion refers to a situation where Iteration refers to a situation where
a function calls itself again and again some statements are executed again
until some base and again using loops until some
condition is reached condition is true
Performance It is comparatively slower because Its execution is faster because it doesn’t
before each function call the current use stack.
state of function is stored in stack.
After the return statement the
previous function state is again
restored from stack.
memory Memory usage is more as stack is Memory usage is less as it doesn’t use
used to store the current function stack.
state.
Size of code is comparatively Iteration makes the code size bigger.
Code Size smaller in
recursion.
Limitations of recursion:
Slower than its iterative solution.
For each step we make a recursive call to a function. ...
105
May cause stack-overflow if the recursion goes too deep to solve the problem.
Difficult to debug and trace the values with each step of recursion.
106
UNIT-IV
Pointers: Idea of pointers, Defining pointers, pointer to pointer, void pointer, Null pointer ,Pointers to Arrays and
Structures, function pointer.
Structures and unions: Defining structures, initializing structures, Array of structures, arrays within structures,
nested structures, unions, typedef.
POINTERS:
A Pointer is a constant or variable that contains an address that can be used to access data.
Examples:
int *ptr;
In c programming every variable keeps two types of value Value of variable. Address of variable where it has
stored in the memory. Meaning of following simple pointer declaration and definition:
int a=5;
int* ptr; ptr=&a;
Explanation:
About variable ―a
Name of variable: a
Value of variable which it keeps: 5
Address where it has stored in memory: 1025 (assume)
About variable ―ptr :
Name of variable: ptr
Value of variable which it keeps: 1025 6.Address where it has stored in memory: 5000
As you know, every variable is a memory location and every memory location has its address defined which can
be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following
example, which prints the address of the variables defined –
#include <stdio.h>
int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
When the above code is compiled and executed, it produces the following result –
Address of var1 variable: bff5a400 Address of var2 variable: bff5a3f6
107
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable address.
The general form of a pointer variable declaration is –
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer
variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer
declarations –
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long
hexadecimal number that represents a memory address. The only difference between pointers of different data
types is the data type of the variable or constant that the pointer points to.
Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked lists,
queues, stacks and trees.
Pointers reduce length and complexity of programs.
They increase the execution speed and thus reduce the program execution time.
How to Use Pointers?
There are a few important operations, which we will do with the help of pointers very frequently. (a) We define
a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address
available in the pointer variable. This is done by using unary operator * that returns the value of the variable
located at the address specified by its operand. The following example makes use of these operations –
include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var ); /* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip ); /* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
When the above code is compiled and executed, it produces the following result – Address of var variable:
bffd8b3c
Address stored in ip variable: bffd8b3c Value of *ip variable: 20
Declaration and Initializing a Pointer:
In C, every variable must be declared for its type. Since pointer variable contain addresses that belong to a
separate data type, they must be declared as pointers before we use them.
Declaration of a pointer variable: The declaration of a pointer variable takes the following form:
data type *pt_name;
This tells the compiler three things about the variable pt_name:
108
The * tells that the variable pt_name is a pointer variable. 2)pt_name needs a memory location
3)pt_name points to a variable of type
data_type Ex: int *p;
Declares the variable p as a pointer variable that points to an integer data type.
void main( )
{
int a = 5 ;
printf ( "\nAddress of a = %u", &a );
printf ( "\nValue of a =%d", a );
}
Output: The output of the above program would be:
Once a pointer has been assigned the address of a variable, to access the value of the variable using pointer we
use the operator ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The
„value at address‟ operator is also called ‘indirection’ operator (or dereferencing operator).
Ex:
Int main()
{
int a = 5 ;
printf ( "\nAddress of a = %u", &a );
printf ( "\nValue of a = %d", a ) ;
printf ( "\nValue of a = %d", *( &a));
return 0;
}
Output: The output of the above program would be:
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its
data type as shown below –
#include <stdio.h> const int MAX = 3; int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1]; for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %x\n", i-1, ptr ); printf("Value of var[%d] = %d\n", i-1, *ptr );
/* move to the previous location */ ptr--;
110
}
return 0;
}
When the above code is compiled and executed, it produces the following result –
Address of var[2] = bfedbcd8 Value of var[2] = 200 Address of var[1] = bfedbcd4 Value of var[1] = 100
Address of var[0] = bfedbcd0 Value of var[0] = 10
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that
are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared.
The following program modifies the previous example − one by incrementing the variable pointer so long as the
address to which it points is either less than or equal to the address of the last element of the array, which is
&var[MAX - 1] –
#include <stdio.h> const int MAX = 3; int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have address of the first element in pointer */ ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] )
{
printf("Address of var[%d] = %x\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr );
/* point to the previous location */ ptr++;
i++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result – Address of var[0] = bfdbcb20
Value of var[0] = 10
Address of var[1] = bfdbcb24 Value of var[1] = 100 Address of var[2] = bfdbcb28 Value of var[2] = 200 Pointer
Operations:
C language allows us to add integers to pointers and to subtract integers from pointers
Ex: If p1, p2 are two pointer variables then operations such as p1+4, p2 - 2, p1 - p2 can be performed.
Pointers can also be compared using relational operators. Ex: p1>p2, p1==p2, p1! =p2 are valid operations.
We should not use pointer constants in division or multiplication. Also, two pointers cannot be added. p1/p2,
p1*p2, p1/3, p1+p2 are invalid operations.
Pointer increments and scale factor:-
Let us assume the address of p1 is 1002. After using p1=p1+1, the value becomes 1004 but not 1003.
Thus when we increment a pointer, its values is increased by length of data type that points to. This length is
called scale factor.
Pointer Expressions:
Like other variables pointer variables can be used in expressions.
If p1 and p2 are properly declared and initialized pointers, then the following statements are valid:
Y=*p1**p2;
Sum=sum+*p1;
Z=5*-*p2/*p1;
*p2=*p2+10;
*p1=*p1+*p2;
*p1=*p2-*p1;
111
NOTE: in the third statement there is a blank space between ‘/’ and * because the symbol /*is considered as
beginning of the comment and therefore the statement fails. if p1 and p2 are properly declared and initialized
pointers then, ‘C’ allows adding integers to a pointer variable.
EX:
Int a=5,b=10;
Int *p1,*p2;
p1=&a;
p2=&b;
Now, P1=p1+1=1000+2=1002;
P1=p1+2=1000+(2*2)=1004; P1=p1+4=1000+(2*4)=1008; P2=p2+2=3000+(2*2)=3004;
P2=p2+6=3000+(2*6)=3012;
Here addition means bytes that pointer data type hold are subtracted number of times that is subtracted to the
pointer variable.
void pointer:
Pointers can also be declared as void type. Void pointers cannot be dereferenced without explicit type
conversion. This is because, being void the compiler cannot determine the size of the object that the pointer points
too. Though void pointer declaration is possible, void variables declaration is not allowed. Thus, the declaration
void P displays an error message. "size of ‘p’ is unknown or zero" after compilation. C program to declare a void
pointer. Assign address of int, float and char variables to the void pointer using type casting method. Display the
contents of various variables.
#include<stdio.h>
#include<conio.h> Void main()
{
int p;
float d;
char c;
void *pt;
clrscr();
pt=&p;
*(int*)pt=10;
printf("\n p=%d",p);
pt=&d;
*(float *)pt=3.4;
112
printf("\n d=%f",d);
pt=&c;
*(char *)pt= ‘s’;
printf("\n c=%c",c); getch();
}
O/P:
p=10 d=3.4
c=s
In the above example, the statement *(int *)pt=10 assigns the integer value 10 to pointer pt i.e., to variable ‘p’. the
declaration *(int *) tells the compiler that the value assigned is of integer type. Thus, assignments of float and
char type are carried out. The statements *(int *)pt=10,
*(float *)pt=3.4, *(char *)pt=’s’ helps the compiler to exactly determine the size of data type.
Null pointer:
A null pointer is a pointer which points nothing.
Some uses of the null pointer are:
To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.
To pass a null pointer to a function argument when we don’t want to pass any valid memory address.
To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer
related code e.g. dereference pointer variable only if it’s not NULL.
Example program:
#include <stdio.h>
int main() {
int *p= NULL;//initialize the pointer as null.
printf("The value of pointer is %u",p);
return 0;
}
Pointers to pointers:
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the
address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second
pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in
front of its name. For example, the following declaration declares a pointer to a pointer of type int –
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the
asterisk operator be applied twice, as is shown below in the example −
#include <stdio.h> int main ()
{
int var; int *ptr;
int **pptr; var = 3000;
/* take the address of var */
113
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output:
Value of var = 3000
Value available at *ptr = 3000 Value available at **pptr = 3000
Example 2: program to print value of a variable through pointer and pointer to pointer.
#include<stdio.h>
#include<conio.h> Void main ()
{
int x=10,*p, **q;
P=&x;
Q=&p;
clrscr ();
printf("value of x=%d address of x=%u", x, &x);
printf("through *p value of x=%d address of x=%u",*p, p);
printf("through **q value of x=%d address of x=%u", **q,*q);
getch ();
}
Output:
Value of x=10 address of x=2000
Through*p value of x=10 address of x=2000
Through **q value of x=10 address of x=2000
Example :-
void main()
int *ap[3];
int al[3]={10,20,30};
int k;
for(k=0;k<3;k++)
ap[k]=al+k;
114
for(k=0;k<3;k++)
printf(“\t %u”,ap[k]);
printf(“\t %7d\n”,*(ap[k]));
Output:
Address Element
4060 10
4062 20
4064 30
In the above program , the addresses of elements are stored in an array and thus it represents array of pointers.
A two-dimensional array can be represented using pointer to an array. But, a two-dimensional array can be
expressed in terms of array of pointers also. The conventional array definition is,
Where,
Note that exp2 is not used while defining array of pointers. Consider a two-dimensional vector initialized with 3
rows and 4 columns as shown below,
int p[3][4]={{10,20,30,40},{50,60,70,80},{25,35,45,55}};
The elements of the matrix p are stored in memory row-wise (can be stored column-wise also) as shown in Fig.
int *p[3];
115
Here, p is an array of pointers. p[0] gives the address of the first row, p[1] gives the address of the second row
and p[2] gives the address of the third row. Now, p[0]+0 gives the address of the
element in 0th row and 0th column, p[0]+1 gives the address of the elements in 0 th row and 1st column and so
on. In general,
Pointers to structures:
We have pointers pointing to int, float, arrays etc., We also have pointers pointing to structures. They are called
as structure pointers.
To access the members of a structure using pointers we need to perform The following
operations:
4 Access members of structure using (. ) operator or using (->)member selection operator or arrow
operator.
Syntax:
struct tagname
datatype member1;
datatype member2;
};
ptr=*var;
(*ptr).member1; or ptr->member1;
The parentheses around *ptr are necessary because the member operator ‟.‟ has a higher precedence than the
116
operator „*‟
Example:
struct student
int rno;
char name[20]; };
Ex: Program to read and display student details using pointers to structures
struct student
{
int HTNO;
char NAME[20];
float AVG;
};
void main()
printf(“AVERAGE MARKS=%f”,ptr->AVG);
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.
type (*fptr)();
This tells the complier that fptr is a pointer to a function which returns type value the parentheses around *fptr
is necessary.
117
Because type *gptr(); would declare gptr as a function returning a pointer to type.
We can make a function pointer to point to a specific function by simply assigning the name of the function
to the pointer.
double (*p1)();
p1=mul();
It declares p1 as a pointer to a function and mul as a function and then make p1 to point to the
function mul.
To call the function mul we now use the pointer p1 with the list of parameters.
i,e (*p1)(x,y); //function call equivalent to mul(x,y);
Program:
void main()
int x,y;
double (*p1)();
double res;
p1=mul;
return(val);
Output:
118
Structures
Definition: A structure is a collection of one or more variables of similar or different data types, grouped together
under a single name. By using structures variables, arrays, pointers etc can be grouped together.
The structure definition associated with the structure name is referred as tagged structure. It doesn‟t create an instance
of a structure and does not allocate any memory.
{ {
…… float marks[6];
…… };
Type variable-n;
};
Where,
1. struct is the keyword which tells the compiler that a structure is being defined.
119
The syntax of typedefined structure is
{ {
…… float marks[6];
…… }student;
Type variable-n;
}Type;
where
B. struct is the keyword which tells the compiler that a structure is being defined.
D. The closing brace must end with type definition name which in turn ends with semicolon.
Variable declaration:
Memory is not reserved for the structure definition since no variables are associated with the structure definition. The
members of the structure do not occupy any memory until they are associated with the structure variables.
Type v1,v2,v3,….vn;
Alternate way:
struct TAG
{
Type varaible1;
Type variable2;
……
……
120
Type variable-n; } v1, v2, v3;
Ex:
struct book
char name[30];
int pages;
College contains the following fields: College code (2characters), College Name, year of
establishment, number of courses. Each course is associated with course name (String),
duration, number of students. (A College can offer 1 to 50 such courses)
struct college
char code[2];
char college_name[20];
int year;
int no_of_courses;
};
void main( )
….
struct course
char course_name[20];
float duration;
121
int no_of_students;
};
void main( )
….
Initialization structures :
The rules for structure initialization are similar to the rules for array initialization. The initializers are enclosed in
braces and separated by commas. They must match their corresponding types in the structure definition.
Consider the structure definition for student with three fields name, roll number and average marks. The initialization of
variable can be done as shown below,
struct student
int roll_number;
float avg;
122
(ii) Initialization during Structure declaration:-
Consider the structure definition for student with three fields name, roll number and average marks. The initialization of
variable can be done as shown below:
typedef struct
int x;
int y;
float t;
char u;
} SAMPLE;
The figure shows two examples of structure in sequence. The first example demonstrates what happens when not all
fields are initialized. As we saw with arrays, when one or more initializers are missing, the structure elements will be
assigned null values, zero for integers and floating-point numbers, and null (‘\0’) for characters and strings.
Example: Construct a structure type personal, that would contain person name, date of joining and salary.
Develop a program to initialize one person data and display the same.
struct personal
float salary;
};
void main( )
123
printf(“%s%d%s%d%f”,person.name,person.day,person.month,person.year,person.salary );
Structures use a dot (.) operator(also called period operator or member operator) to refer its elements. Before dot,
there must always be a structure variable. After the dot, there must always be a structure element.
structure_variable_name . structure_member_name
struct student
int roll_number;
float avg;
};
s1.name --> refers the string “ravi” s1.roll_number --> refers the
roll_number 10 s1.avg --> refers avg 67.8
Example : Create a structure type book, that would contain book name, author, pages and price. Simulate a
program to read this data using member operator (.) and display the same.
struct book
float salary;
};
void main( )
124
{
Output:-
609
350.00
This method is to pass each member of the structure as an actual argument of the function call. The actual arguments are
treated independently like ordinary variables. This is the most elementary method and becomes unmanageable and
inefficient when the structure size is large.
Program:
#include<stdio.h>
void main ( )
{
char name[15]; int emp_no;
float salary; }record;
record e1 = {"smith",2,20000.25};
e1.salary = arriers(e1.name,e1.emp_no,e1.salary);
{
125
m = m + 2000;
}
}
Output
smith 2 22000.250000
This method involves passing a copy of the entire structure to the called function. Any changes to structure members
within the function are not reflected in the original structure. It is therefore, necessary for the function to return the
entire structure back to the calling function.
The general format of sending a copy of a structure to the called function is:
data_type function_name(struct_typetag_name)
………
………
return(expression);
The called function must be declared for its type, appropriate to the data type it is expected to return.
The structure variable used as the actual argument and the corresponding formal argument in the called function must be
of the same struct type.
The return statement is necessary only when the function is returning some data back to the calling function. The
expression may be any simple variable or structure variable or an expression using simple variables.
When a function returns a structure, it must be assigned to a structure of identical type in the calling function. The called
functions must be declared in the calling function appropriately.
Program:
126
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[20];
float percentage;
};
int main()
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
return 0;
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
Output:
Id is: 1
typedef struct
127
{
return e2;
Output:
Smith 2 20000.25
Jones 16 9999.99
Array of structures:
An array is a collection of elements of same data type that are stored in contiguous memory locations. A structure is a
collection of members of different data types stored in contiguous memory locations. An array of structures is an array
in which each element is a structure. This concept is very helpful in representing multiple records of a file, where each
record is a collection of dissimilar data items.
As we have an array of integers, we can have an array of structures also. For example, suppose we want to store the
information of class of students, consisting of name, roll_number and marks, A better approach would be to use an array
of structures.
Let‟s take an example, to store the information of 3 students, we can have the following structure definition and
declaration,
128
struct student
float avg; };
Defines an array called s, which contains three elements. Each element is defined to be of type struct student.
Let‟s take an example, to store the information of 5 employees, we can have the following structure definition and
declaration,
struct employee
int empid;
char name[10]; float salary;
};
Defines array called emp, which contains five elements. Each element is defined to be of type struct employee.
{2,”ravi”,65000}, {3,”tarun”,82000},
{4,”rupa”,5000}, {5,”deepa”,27000}};
Ex: C program to calculate student-wise total marks for three students using
array of structures.
char rollno[10];
char name[20]; float sub[3]; float total;
};
129
void main( )
scanf("%d",&s[i].sub[j]);
total = total + s[i].sub[j];
Ex: Develop a C program using array of structures to create employee records with the following fields: emp-id, name,
designation, address, salary and display it.
#include<stdio.h>
struct employee
{
int emp_id;
char name[20];
130
{
int i;
printf("\t\t\t\t Enter 3 employees details");
for(i=0; i<3; i++)
scanf(“%d”,&emp[i].emp_id); gets(emp[i].name);
gets(emp[i].designation); gets(emp[i].address);
scanf(“%f”,&emp[i].salary);
printf(“%d”,emp[i].emp_id); puts(emp[i].name);
puts(emp[i].designation); puts(emp[i].address);
printf(“%f”,emp[i].salary);
struct tag_name1
type1 member1;
…….
…….
};
struct tag_name2
type1 member1;
……
131
……
……
};
(ii) The syntax of another method for the nesting of the structure is as follows
struct structure_nm
- ----------
- ----------
<data-type> element n;
struct structure_nm
- ----------
- ----------
}outer_struct_var;
int rno;
132
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a structure with two members. Structure
stud_Res is called as 'outer structure' while stud_subj is called as 'inner structure.'
The members which are inside the inner structure can be accessed as follow: result.subj.subjnm
result.subj.marks
int rno;
char std[10];
struct stud_Marks
char subj_nm[30];
int subj_mark;
}marks;
}result;
void main()
Output:
133
Roll number :1 Standard :Btech Subject
code : GR11002 Marks : 63
Ex: Design a C program using nested structures to read 3 employees details with the following fields; emp-id, name,
designation, address, da ,hra and calculate gross salary of each employee.
#include<stdio.h>
struct employee
{
int emp_id; char name[20];
char designation[10];
char address[20];
struct salary
int i;
scanf(“%d”,&emp[i].emp_id); gets(emp[i].name);
gets(emp[i].designation); gets(emp[i].address);
scanf(“%f”,&emp[i].sal.da); scanf(“%f”,&emp[i].sal.hra);
printf("\n******************************************");
printf(“%d”,emp[i].emp_id); puts(emp[i].name);
puts(emp[i].designation); puts(emp[i].address);
printf(“%f”,emp[i].sal.da); printf(“%f”,emp[i].sal.hra);
printf(“%f”,grosssalary);
}}
134
Difference between Arrays within Structures and Array of Structures :
Arrays within structure:
It is also possible to declare an array as a member of structure, like declaring ordinary variables. For example to
store marks of a student in three subjects then we can have the following definition of a structure.
struct student
int roll_number;
float avg;
};
Array of structures:
An array is a collection of elements of same data type that are stored in contiguous memory locations. A structure is a
collection of members of different data types stored in contiguous memory locations. An array of structures is an array
in which each element is a structure. This concept is very helpful in representing multiple records of a file, where each
record is a collection of dissimilar data items.
Ex:
Let‟s take an example, to store the information of 5 employees, we can have the following structure definition and
declaration,
struct employee
};
Defines array called emp, which contains five elements. Each element is defined to be of type struct student.
135
For the student details, array of structures can be initialized as follows, struct employee emp[5]
= {{1,”ramu”25,20000},
{2,”ravi”,65000},
{3,”tarun”,82000},
{4,”rupa”,5000}, {5,”deepa”,27000}};
Ex: Construct a C program using structure to create a library catalogue with the following fields: Access number,
author‟s name, Title of the book, year of publication, publisher‟s name, and price.
struct library
{
int acc_no;
char author[20];
char title[10];
int year_pub;
char name_pub[20];
float price;
};
void main( )
It can be linked together to form useful data structures such as lists, queues, stacks and trees.
136
The syntax for using the self referential structure is as follows:
struct tag_name
{
Type1 member1;
Type2 member2;
……….
Ex:-
struct node
int data;
Unions:
A union is one of the derived data types. Union is a collection of variables referred under a single name. The
syntax, declaration and use of union is similar to the structure but its functionality is different.
Syntax:
union union_name
<data-type> element 1;
<data-type> element 2;
………………
}union_variable;
Example:
union techno
{
int comp_id; char nm; float sal;
}tch;
A union variable can be declared in the same way as structure variable. union tag_name var1,
var2...;
137
A union definition and variable declaration can be done by using any one of the following
We can access various members of the union as mentioned: a.c a.i a.f and memory organization
is shown below,
In the above declaration, the member f requires 4 bytes which is the largest among all the members. Figure 5.8 shows
how all the three variables share the same address. The size of the union here is 4 bytes.
A union creates a storage location that can be used by any one of its members at a time. When a different member is
assigned a new value, the new value supersedes the previous members‟ value.
Structure Union
138
…………… ……………
}; };
struct tag_name var; union tag_name var;
(vii) Size Size of the structure depends Size is given by the size of the
on the type of members, adding largest member
size of all the members. sizeof(un_variable)
sizeof (st_var);
139
UNIT-V
Files: Text and Binary files, Creating and Reading and writing text and binary files, Random access to files,
Error Handling in files Command line arguments, Enumeration data type.
Preprocessor: Commonly used Preprocessor commands like include, define, undef, if, ifdef, ifndef, elif.
File : A file is an external collection of related data treated as a unit. A file is a place on a disk where a group of
related data is stored and retrieved whenever necessary without destroying data
The primary purpose of a file is to keep record of data. Record is a group of related fields. Field is a group of
characters which convey meaning.
Files are stored in auxiliary or secondary storage devices. The two common forms of secondary
storage are disks (hard disk, CD and DVD) and tapes.
Each file ends with an end of file (EOF) at a specified byte number, recorded in file structure.
A file must first be opened properly before it can be accessed for reading or writing. When a file is opened an
object (buffer) is created and a stream is associated with the object.
It is advantageous to use files in the following circumstances.
There are two kinds of files depending upon the format in which data is stored:
1)Text files
2) Binary files
Text files:
A text file stores textual information like alphabets, numbers, special symbols, etc.
actually the ASCII code of textual characters its stored in text files. Examples of some text files include c, java,
c++ source code files and files with .txt extensions. The text file contains
the characters in sequence. The computer process the text files sequentially and in forward direction. One can
perform file reading, writing and appending operations. These operations are performed with the help of inbuilt
functions of c.
Binary files:
Text mode is inefficient for storing large amount of numerical data because it occupies large space. Only solution
to this is to open a file in binary mode, which takes lesser space than the text mode. These files contain the set of
bytes which stores the information in binary form. One main drawback of binary files is data is stored in human
unreadable form. Examples of binary files are .exe files, video stream files, image files etc. C language supports
binary file operations with the help of various inbuilt functions
It is a string of characters that make up a valid file name which may contain two parts,a primary name and an
optional period with the extension.
Prog1.c
Myfirst.java Data.t
xt store
140
DATA STRUCTURE:
It is defined as FILE in the library of standard I/O function definitions. Therefore all files are declared as type
FILE.FILE is a define data type.
FILE *fp;
PURPOSE:
It defines the reason for which a file is opened and the mode does this job. fp=fopen(“filename”,”mode”);
NOTE: To perform operations on binary files the following modes are applicable with an extension b like
rb,wb,ab,r+b,w+b,a+b,which has the same menaing but allows to perform operations on binary files.
141
Basic operations on file:
Naming a file
Opening a file
Reading data from file
Writing data into file
Closing a File
In order to perform the basic file operations C supports a number of functions .Some of the Important file
handling functions available in the C library are as follows:
FUNCTION OPERATION
NAME
fopen() Creates a new file for use or Opens an existing file for use
Examples: Student.dat, file1.txt, marks.doc, palin.c The general format of declaring and opening a file is
FILE *fp; //declaration
fp=fopen (“filename”,mode”); //statement to open file.
Here FILE is a data structure defined for files. fp is a pointer to data type FILE. filename is the name of the file.
mode tells the purpose of opening this file.
142
Reading data from file:
Input functions used are ( Input operations on files)
getc(): It is used to read characters from file that has been opened for read operation.
This statement reads a character from file pointed to by file pointer and assign to
c. It returns an end-of-file marker EOF, when end of file has been reached
fscanf();
This function is similar to that of scanf function except that it works on files.
Example fscanf(f1,”%s%d”,str,&num);
The above statement reads string type data and integer type data from file.
fgets(): This function reads a string from a file pointed by a file pointer. It also copies the string to a memory
location referred by an array.
Syntax: fgets(string,no of bytes,filepointer);
fread(): This function is used for reading an entire structure block from a given file.
Syntax: fread(&struct_name,sizeof(struct_name),1,filepointer);
putc():This function writes a character to a file that has been opened in write mode.
Syntax: putc(c,fp);
This statement writes the character contained in character variable c into a file whose pointer is fp.
fprintf():This function performs function, similar to that of printf.
d. fputs(): This function writes a string into a file pointed by a file pointer.
e. fwrite(): This function is used for writing an entire block structure to a given file.
143
Closing a file:
A file is closed as soon as all operations on it have been completed.Closing a file ensures that all outstanding
information associated with the file is flushed out from the buffers and all links to the file are broken. Another
instance where we have to close a file is to reopen the same file in a different mode.
Library function for closing a file is,
fclose(file pointer);
Example: fclose(fp);
Where fp is the file pointer returned by the call to fopen(). fclose() returns 0 on success (or)
- 1 on error. Once a file is closed, its file pointer can be reused for another file. Note: fcloseall() can be used to
close all the opened files at once.
putc()/fputc() -:
It is used to write a character contained in the character variable to the
file associated with the FILE pointer fp. fputc() also returns an end-of –marker EOF, when an end of file has
been reached.
fp=fopen("input1.txt","w");
printf("\n enter some text hereand press cntrl D or Z to stop:\n"); while((ch=getchar())!=EOF)
fputc(ch,fp); fclose(fp); fp=fopen("input1.txt","r"); printf("\n The entered text is : \n");
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
fwrite(): It is used for writing an entire structure block to a given file in binary mode.
Syntax: fwrite(&structure variable,sizeof(structure variable),1,filepointer);
Example: fwrite(&stud,sizeof(stud),1,fp);
fread(): It is used for reading an entire structure block from a given file in binary mode.
Syntax: fread(&structure variable,sizeof(structure variable),1,filepointer);
Example: fread(&emp,sizeof(emp),1,fp1);
146
Random access to files :
At times we needed to access only a particular part of a file rather than accessing all the data sequentially, which
can be achieved with the help of functions fseek, ftell and rewind available in IO library.
ftell():-
ftell takes a file pointer and returns a number of type long, that corresponds to the current position. This function
is useful in saving the current position of the file, which can later be used in the program.
Syntax: n=ftell(fp);
n would give the Relative offset (In bytes) of the current position. This means that already n
bytes have a been read or written
rewind():-
It takes a file pointer and resets the position to the start of the file.
Syntax: rewind(fp);
n=ftell(fp);
would assign 0 to n because the file position has been set to start of the file by rewind(). The first byte in the file
is numbered 0, second as 1, so on. This function helps in reading the file more than once, without having to close
and open the file.
Whenever a file is opened for reading or writing a rewind is done implicitly.
fseek:- fseek function is used to move the file pointer to a desired location within the file.
Syntax: fseek(file ptr,offset,position);
file pointer is a pointer to the file concerned, offset is a number or variable of type long and position is an integer
number which takes one of the following values. The offset specifies the number of positions(Bytes) to be
moved from the location specified by the position
which can be positive implies moving forward and negative implies moving backwards.
Example: fseek(fp,10,0) ;
STATEME MEANING
NT
147
fseek(fp,0L,0); Go to beginning similar to rewind()
fseek(fp,0L,2); Go to the end of file, past the last character of the file.
fseek(fp,-m,2); Go backwards by m bytes from the end.(positions the file to the mth
character from the end)
#include<stdio.h>
void main()
{
FILE *fp;
char ch; fp=fopen("my1.txt","r"); fseek(fp,21,SEEK_SE
T); ch=fgetc(fp);
while(!feof(fp))
{
printf(“%c\t”,ch); printf(“%d\n”,ftell(fp
)); ch=fgetc(fp);
}
rewind(fp); printf(“%d\n”,ftell(fp
)); fclose(fp);
}
Trying to perform an operation on a file, when the file is opened for another type of operations.
Opening a file with an invalid filename. Attempting to write a write protected file.
If we fail to check such read and write errors, a program may behave abnormally when an error occurs. An
unchecked error may result in a premature termination of the program or incorrect output. In C we have two
status - inquiry library functions feof and ferror that can help us detect I/O errors in the files.
a). feof(): The feof() function can be used to test for an end of file condition. It takes a FILE pointer as its only
argument and returns a non zero integer value if all of the data from the specified file has been read, and returns
zero otherwise. If fp is a pointer to file that has just opened for reading, then the statement
if(feof(fp)) printf(“End of data”);
would display the message “End of data” on reaching the end of file condition.
ferror(): The ferror() function reports the status of the file indicated. It also takes a file pointer as its argument
and returns a nonzero integer if an error has been detected up to that point, during processing. It returns zero
otherwise. The statement
if(ferror(fp)!=0)
148
printf(“an error has occurred\n”);
fp==null: We know that whenever a file is opened using fopen function, a file pointer is returned. If the file
cannot be opened for some reason, then the function returns a null pointer. This facility can be used to test
whether a file has been opened or not.
Example
if(fp==NULL)
perror(): It is a standard library function which prints the error messages specified by the compiler. For
example:
if(ferror(fp)) perror(filename);
149
Standard error stderr Your screen
The file pointers are the means to access the file for reading and writing purpose. This section explains how to
read values from the screen and how to print the result on the screen.
Standard Input
Standard input is where things come from when you use scanf(). In other words, scanf("%d", &val);
is equivalent to the following fscanf():
fscanf(stdin, "%d", &val);
Standard Output
Similarly, standard output is exactly where things go when you use printf(). In other words, printf("Value =
%d\n", val):
is equivalent to the following fprintf():
fprintf(stdout, "Value = %d\n", val):
Remember that standard input is normally associated with the keyboard and standard output with the screen,
unless redirection is used.
Standard Error
Standard error is where you should display error messages. We've already done that above: fprintf(stderr, "Can't
open input file in.list!\n");
Standard error is normally associated with the same place as standard output; however, redirecting standard
output does not redirect standard error.
For example,
% a.out > outfile
only redirects stuff going to standard output to the file outfile... anything written to standard error goes to the
screen.
Develop a c program for the following .there are two input files named “first.dat” and “second.dat” .The
files are to be merged. That is,copy the contents of first.dat and then second.dat to a new file named
result.dat?
Program:
#include<stdio.h> #include<stdlib.h> int main()
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20]; printf("Enter name of first file\n"); gets(file1);
printf("Enter name of second file\n"); gets(file2);
printf("Enter name of file which will store contents of 2 files\n"); gets(file3);
fs1=fopen(file1,"w");
printf("\n enter some text into file1 here and press cntrl D or Z to stop :\n"); while((ch=getchar())!=EOF)
fputc(ch,fs1); fclose(fs1); fs2=fopen(file2,"w");
printf("\n enter some text into file2 here and press cntrl D or Z to stop :\n"); while((ch=getchar())!=EOF)
fputc(ch,fs2); fclose(fs2); fs1 =
fopen(file1,"r"); fs2
= fopen(file2,"r");
if( fs1 == NULL || fs2 == NULL )
{
perror("Error "); exit(1);
}
ft = fopen(file3,"w"); while( ( ch = fgetc(fs1) ) != EOF ) fputc(ch,ft);
while( ( ch = fgetc(fs2) ) != EOF ) fputc(ch,ft);
printf("Two files were merged to %s file successfully.\n",file3); fcloseall();
ft = fopen(file3,"r");
printf(“\n the merged file contents are
:”); while( ( ch = fgetc(fs1) ) != EOF ) putchar(ch);
fclose(f t); return 0;
}
Program is the file name where the executable code of the program is stored. This eliminates the need for the
program to request the user to enter the file names during execution. The „main‟ function can take two
arguments called argc, argv and information contained in the command line is passed on to the program to these
arguments, when „main‟ is called up by the system.
The variable argv is an argument vector and represents an array of characters pointers that point to the command
line arguments.
The argc is an argument counter that counts the number of arguments on the command line. The size of this
array is equal to the value of argc. In order to access the command line arguments, we must declare the „main‟
function and its parameters as follows:
main(argc,argv) int argc;
char *argv[ ];
……….
}
Example:- A program to copy the contents of one file into another using command line
arguments.
152
#include<stdio.h>
#include<stdlib.h>
void main(int argc,char* argv[]) /* command line arguments */
{
FILE *ft,*fs; /* file pointers declaration*/
int c=0; if(argc!=3)
Printf(“\n insufficientarguments”);
fs=fopen(argv[1],”r”);
ft=fopen(argv[2],”w”);
if (fs==NULL)
{
printf(“\nsource file opening error”); exit(1) ;
}
if (ft==NULL)
{
printf(“ target file openingerror”); exit(1) ;
}
while(!feof(fs))
{
fputc(fgetc(fs),ft);
c++;
}
printf(“\n bytes copied from %s file to %s file =%d”, argv[1], argv[2], c); c=fcloseall(); /*closing all files*/
printf(“files closed=%d”,c);
}
Write a C program to write all the members of an array of structures to a file using fwrite(). Read the array from
the file and display on the screen.
#include <stdio.h>
struct s
{
char name[50]; int height;
153
};
int main(){
struct s a[5],b[5];
FILE *fptr;
int i;
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin);
printf("Enter name: ");
gets(a[i].name);
printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
}
Output:
Enter name:ramu
Enter height:156
Enter name:sita
Enter height:140
Enter name:ravi
Enter height:172
Enter name:vijay
Enter height:167
Enter name:raju
Enter height:148
Name:ramu
Height:156
Name:sita
Height:140
Name:ravi
Height:172
Name:vijay
Height:167
Name:raju
Height:148
Preprocessors:
The C Preprocessor is not part of the compiler but is a separate step in the compilation process.In
simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to do required pre-
processing before actual compilation. We'll refer to the C Preprocessor as the CPP.All preprocessor commands
begin with a pound symbol #. It must be the first nonblank character,and for readability, a preprocessor directive
should begin in first column.
154
Invoked automatically by the C compiler o 1st pass: invokes C preprocessor
o 2nd pass: invokes compiler on the resulting C code
Manually invoke C preprocessor gcc –E foo.c
This section lists Three (3) kinds of preprocessor directives:
#ifdef:
Returns true if this macro is defined
Eg:
#ifdef DEBUG
/* Your debugging statement enter here * / #endif
This tells the CPP to do the process the statements enclosed if DEBUG is defined.
This is useful if you pass the -DDEBUG flag to gcc compiler at the time of compilation.
This will define DEBUG, so you can turn debugging on and off on the fly during compilation.
#ifndef: Returns true if this macro is not defined
Eg:
#ifndef MESSAGE
#define MESSAGE "You wish!" #endif
This tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
Few other
#else: The alternative for #if
#elif: #else an #if in one statement
#endif: Ends preprocessor conditional
155
Macros (#define, #undef, #error, #pragma):
#define: Substitutes a preprocessor macro
eg: #define MAX_ARRAY_LENGTH 20. This directive tells the CPP to replace instances of
MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.
#undef: Undefines a preprocessor macro Eg: #undef FILE_SIZE
#define FILE_SIZE 42
This tells the CPP to undefine existing FILE_SIZE and define it as 42.
#error: Prints error message on stderr
#pragma: Issues special commands to the compiler, using a standardized method
Macro Description
STDC Defined as 1 when the compiler complies with the ANSI standard.
Tim e :03:36:24
Line :8
ANSI :1
Preprocessor Operators
The C preprocessor offers following operators to help you in creating macros:
Macro Continuation (\)
A macro usually must be contained on a single line. The macro continuation operator is used to
continue a macro that is too long for a single line. For example:
#define message_for(a, b) \ printf(#a " and " #b ": We love you!\n")
156
Stringize #
The stringize or number-sign operator '#' , when used within a macro definition, converts a macro
parameter into a string constant. This operator may be used only in a macro that has a specified
argument or parameter list. For example:
#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n") int main(void)
{
message_for(Carole, Debra); return 0;
}
When the above code is compiled and executed, it produces the following result: Carole and Debra: We love
you!
Token Pasting ##
The token-pasting operator ## within a macro definition combines two arguments. It permits two
separate tokens in the macro definition to be joined into a single token. For example: #include <stdio.h>
#define tokenpaster(n)
printf ("token" #n " = %d", token##n)
int main(void)
{
int token34 = 40;
tokenpaster(34);
return 0;
}
When the above code is compiled and executed, it produces the following result: token34 = 40
How it happened, because this example results in the following actual output from the preprocessor:
printf ("token34 = %d", token34);
This example shows the concatenation of token##n into token34 and here we have used both
stringize and token-pasting. The defined Operator
The preprocessor defined operator is used in constant expressions to determine if an identifier is
defined using #define. If the specified identifier is defined, the value is true non − zero. If the symbol
is not defined, the value is false zero. The defined operator is specified as follows: #include <stdio.h>
#if !defined (MESSAGE) #define MESSAGE "You wish!" #endif
int m ain(void)
{
printf("Here is the m essage: %s\n", MESSAGE); return 0;
}
When the above code is compiled and executed, it produces the following result: Here is the m essage: You
wish!
Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using parameterized
macros. For example, we might have some code to square a number as follows: int square(int x) {
return x * x;
}
We can rewrite above code using a macro as follows: #define square(x) ((x) * (x))
157
Macros with arguments must be defined using the #define directive before they can be used.
The
argument list is enclosed in parentheses and must immediately follow the macro name.Spaces
are not allowed between and macro name and open parenthesis.
For example:
#include <stdio.h>
#define MAX(x,y)
((x) > (y) ? (x) : (y))
int main(void)
{
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
When the above code is compiled and executed, it produces the following result: Max between 20 and 10 is 20
158
Frequently Asked Questions in Exams:
Unit-1:
1. Explain about operators in C with examples?
2. Define a variable? How to declare and initialize variables in C? What are the rules for naming variables in
C?
3. Define a flow chart and draw a flowchart for finding the factorial of a given umber?
4. Explain Define an algorithm and design an algorithm for finding bigger of three numbers?
5. Explain about loops in C with an example? Give their syntax and flowchart ?
6. Explain about switch statement in C with example? Give its syntax and flow chart?
7. Differentiate between break and continue in C?
8. Differentiate between while and do while loops in C?
9. Write a C program to determine if a number is palindrome or not?
10.Write a C program to display prime numbers till a given number?
UNIT-2:
1. Explain about string handling functions in C ?
2.Write a C program to add two matrices.
3.Implement a C program for Matrix multiplication?
4.Write a C program to find minimum and maximum in a list of elements?
5.Write a C program to sort a given list of elements?
6.Write a C program to determine if a string is palindrome or not?
7.Differentiate between structures and union
8.Explain about array of structures with an example program. Write a C program to find the total marks of n
students. Use a structure of student containing name ,id, and marks of 3 subjects.
9.Define a self-referential structure? Explain the use of pointers in self-referential structures and self-
referential structures in linked lists?
10.Explain about how to access members of a structures using pointers with an example program?
Unit-3:
1. Write a C program to merge two files into a third file?
2. Write a C program to append the contents of a file into another?
3. Define a File? Explain about different modes of opening a file?
4. Write a C program to read and display the contents of a file?
5. Explain about random access to files in detail with an example?
6. Explain about command line argument swith an example in C?
7. Explain about the following pre-processor commands with exam
(i) include (ii) define (iii) undef (iv) if (v) ifdef
Unit-4:
1. Explain about different parameter passing techniques in detail with an example program?
2. Define recursion? What are its merits and demerits? Write a C program to find the factorial
using recursion and non-recursion?
3. Explain about different dynamic memory allocation functions in detail with example?
4. Differentiate between static and dynamic memory allocation?
5. Differentiate between formal and actual argumnets?
6. Explain about various categories of functions with examples.
159
Unit-5:
1. Algorithm/ Program/Example for Linear search.
2. Algorithm/ Program/Example for binary search.
3. Algorithm/ Program/passes for insertion sort.
4. Algorithm/ Program/passes for Selection sort.
5. Algorithm/ Program/passes for Bubble sort.
161