_PPS Notes
_PPS Notes
IV Operators and usage of keywords Can know the working of different operators
and its associativity and precedence.
1
Components of a computer:
o Input Devices
o CPU
o Output Devices
o Primary Memory
o Secondary Memory
1) Inputting: It is the process of entering raw data, instructions and information into the computer.
It is performed with the help of input devices.
2) Storing: The computer has primary memory and secondary storage to store data and
instructions. It stores the data before sending it to CPU for processing and also stores the processed
data before displaying it as output.
3) Processing: It is the process of converting the raw data into useful information. This process is
performed by the CPU of the computer. It takes the raw data from storage, processes it and then
sends back the processed data to storage.
4) Outputting: It is the process of presenting the processed data through output devices like
monitor, printer and speakers.
5) Controlling: This operation is performed by the control unit that is part of CPU. The control
unit ensures that all basic operations are executed in a right manner and sequence.
2
Operatingsystem:
In the Computer System (comprises of Hardware and software), Hardware can only understand
machine code (in the form of 0 and 1) which doesn't make any sense to a naive user.
We need a system which can act as an intermediary and manage all the processes and resources
present in the system.
Compilers:
o A compiler is a translator that converts the high-level language into the machine language.
o High-level language is written by a developer and machine language can be understood by
the processor.
o Compiler is used to show errors to the programmer.
o The main purpose of compiler is to change the code written in one language without
changing the meaning of the program.
o When you execute a program which is written in HLL programming language then it
executes into two parts.
o In the first part, the source program compiled and translated into the object program (low
level language).
o In the second part, object program translated into the target program through the assembler.
3
Compilation Process in C:
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code or machine
code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the directive
and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into an
executable form:
o Preprocessor
o Compiler
o Assembler
o Linker
4
Preprocessor
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler converts
this code into assembly code. Or we can say that the C compiler converts the pre-processed code
into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file in
DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the
name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The main
working of the linker is to combine the object code of library files with the object code of our
program. Sometimes the situation arises when our program refers to the functions defined in other
files; then linker plays a very important role in this. It links the object code of these files to our
program. Therefore, we conclude that the job of the linker is to link the object code of our program
with the object code of the library files and other files. The output of the linker is the executable
file. The name of the executable file is the same as the source file but differs only in their
extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the executable file
5
can be named as 'a.out'. For example, if we are using printf() function in a program, then the linker
adds its associated code in an output file.
ProgramDevelopmentEnvironments:
The development environment helps the developers to develop the application or product using a
set of processes and programming tools.
An development environment provides developers an interface and convenient view of the
development process which includes writing code, testing the same and packaging the build so
that it can be deployed.
Ex:
Microsoft Visual Studio
Turbo C/C++
Dev C/C++
Flowchart:
Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts
use simple geometric shapes to depict processes and arrows to show relationships and
process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
6
Shows relationships between different shapes.
Arrow
Examples:
Here is a flowchart to calculate the average of two numbers.
7
Here is a flowchart to calculate the even or odd number.
8
Programming Language
As we know, to communicate with a person, we need a specific language, similarly to
communicate with computers, programmers also need a language is called Programming language.
Before learning the programming language, let's understand what is language?
What is Language?
Language is a mode of communication that is used to share ideas, opinions with each other. For
example, if we want to teach someone, we need a language that is understandable by both
communicators.
What is a Programming Language?
A programming language is a computer language that is used by programmers (developers) to
communicate with computers. It is a set of instructions written in any specific language ( C, C++,
Java, Python) to perform a specific task.
A programming language is mainly used to develop desktop applications, websites, and mobile
applications.
Types of programming language
1. Low-level programming language
Low-level language is machine-dependent (0s and 1s) programming language. The processor
runs low- level programs directly without the need of a compiler or interpreter, so the programs
written in low-level language can be run very fast.
Low-level language is further divided into two parts -
i. Machine Language
Machine language is a type of low-level programming language. It is also called as machine code
or object code. Machine language is easier to read because it is normally displayed in binary or
hexadecimal form (base 16) form. It does not require a translator to convert the programs because
computers directly understand the machine language programs.
The advantage of machine language is that it helps the programmer to execute the programs faster
than the high-level programming language.
10
A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human
language.
Example: C, C++ language
Introduction to C:
The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is known
as mother language.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
Structure of C program:
11
Documentation Section :
This section consists of a set of comment lines useful for documentation. Though comments are
not necessary in a program, they help users to understand the program better.
Braces :
All C programs incorporate a set of curly braces { }. Execution of the program begins at the
opening brace { of the main( ) function and ends at its closing brace }.
Declaration Part:
This part is used to declare all the variables, arrays functions etc. used in the C program.
Initialization along with declaration can also be done here.
Executable Part :
This part of the program consists of a set of executable statements such as Input/ Output
statements, arithmetic statements, control statements etc. It can also include comment statements
which are ignored by the compiler (non-executable). The declaration part and the executable part
must be within opening and closing braces.
Every statement in the declaration part and executable part ends with a semicolon.
Subroutine Section:
This section is optional and consists of all the user-defined functions called in the main( ) function.
Example:
/*Program to find the area of a square*/
#include <stdio.h>
main()
{
float side, area ;
side=5;
area=side*side;
printf(―\nArea of a square=%f‘,area);
}
Output:
Area of a square = 25.0
C KEYWORDS:
There are some reserved words in C, called keywords. All the keywords have standard pre-defined
meanings and can be used only for the purpose intended. All keywords must be written in
lowercase. They cannot be used as user-defined identifiers. The standard keywords are listed
below
auto break case char const continue default do double else
enum extern float for goto if int longregister return
short signed sizeof static struct switch typedef union unsigned void
volatile while
IDENTIFIERS:
● Identifiers refer to the names of program elements such as variables, functions and arrays.
● Identifiers are sequence of characters chosen from the set A–Z, a–z, 0–9, and _
13
(underscore).
● C is a case sensitive language so that ALFA and Alfa are different.
● The underscore symbol _ is generally in the middle of an identifier (embedded).
● Identifiers may be of reasonable length of 8–10 characters though certain computers allow
up to 32 characters.
● Identifier names must start with an alphabet or underscore followed by letters, digit or a
combination of both.
● C has a list of keywords that cannot be used anywhere other than that predefined in the
language i.e., you can‘t have a variable named int. Also one must follow the practice of
choosing names for variables which indicate the roles of those variables in the program.
VARIABLES:
A variable is an identifier used to store a single data item. This data could be a numerical quantity
or a character constant. During execution of the program, data must be assigned to the variable.
Therefore a variable can take different values at different times during the execution of the
program. The data stored in the variable can be accessed any time, by referring to the variable
name.
The rules for naming a variable are the same as those for an identifier.
They are :
1. Variable names generally begin with a letter followed by letters, digits underscore or a
combination of all.
2. No special character except the underscore symbol ( _ ) is allowed. Underscore is generally
embedded in a variable name to make it more readable.
3. Maximum length of a variable name should not exceed 32 characters. Normally the length must
not exceed 8 characters since many compilers treat the first 8 characters as significant.
4. C variables are case sensitive, so that Counter, counter and COUNTER are 3 different variables.
5. C keywords cannot be used as variable names.
6. White spaces are not allowed in a variable name.
7. Appropriate variable names must be chosen to indicate their role in the program.
CONSTANTS:
Any fixed value that does not change during the execution of a program is known as a constant. C
consists of several types of constants.
Types of C constants:
C constants can be divided into two categories :
● Primary Constants
● Secondary Constants
14
Integer Constants :
Integers and real constants are numbers and are generally referred to as numeric constants.
An integer constant consists of a sequence of digits and is an integer-valued number. There are 3
types of integer constants depending on the number system.
They are:
● Decimal (base 10)
● Octal (base 8)
● Hexadecimal (base 16)
Real Constants:
Quantities which are represented by numbers with fractional part are called real or floating point
constants.
(a) A real constant must have at least 1 digit.
(b) It must have a decimal point.
(c) It can be either positive or negative.
(d) No commas or blanks are allowed within a real constant.
Character Constants:
(a) A character constant is a single character within single quotes.
(b) The maximum length of a character constant is 1.
(c) Arithmetic operations are possible on character constant since they too represent integer values.
(d) C also recognizes all the backlash character constants (Escape sequences) available.
Note that the character constant ‗2‘ is not the same as the number 2. Every character has an
equivalent integer value known as the ASCII code. Some character constant & their equivalent
ASCII values are as below :
‗A‘ = 65
‗B‘ = 66
‗a‘ = 97
‗0‘ = 48
‗1‘ = 49
15
String Constants:
A string constant consists of zero or more number of characters enclosed within double quotes.
The characters within quotes could be digits, characters, special characters and blank spaces.
Ex: "Red", "Rs.20.25", " "
Note that ‗A‘ is not equal to ―A‖ since a string constant containing a single character does not have
a corresponding integer value. In fact it contains two characters, the specified character followed
by a null character represents by \0.
Coding constants:
There are 3 types of code constants used in programs:
● Literal constants
● Defined constants
● Memory constants
Defined Constants: are constants that can be defined using a preprocessor command #define.
This constant is placed at the beginning of a program since it is a preprocessor command.
For example :
# define MAX 30
The defined constants make the program easily modifiable and enhance the understandability of
the program.
Memory Constants: use a c type qualifier called const, to indicate that the data specified is a
constant and that it cannot be changed.
Its general format is :
const Datatype identifier = value ;
For example :
const float pi = 3.14159 ;
defines a memory constant pi of float type with a value of 3.14159.
I/O statements:
In C programming you can use scanf() and printf() predefined function to read and print data.
i) printf
This function is used for displaying the output on the screen i.e the data is moved from the
computer memory to the output device.
Syntax:
printf(―format string‖, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted. They are the
general characters which will be displayed as they are .
arg1, arg2 are the output data items.
16
Example: Demonstrating the printf function
printf(―Enter a value:‖);
● printf will generally examine from left to right of the string.
● The characters are displayed on the screen in the manner they are encountered until it comes
across % or \.
● Once it comes across the conversion specifiers it will take the first argument and print it in the
format given.
ii) scanf
scanf is used when we enter data by using an input device.
Syntax:
scanf (―format string‖, &arg1, &arg2, …..);
Format string consists of the conversion specifier. Arguments can be variables or array name and
represent the address of the variable. Each variable must be preceded by an ampersand (&). Array
names should never begin with an ampersand.
OPERATORS IN C :
C provides several operators for elementary arithmetic operations like addition, subtraction,
multiplication, division, residue-modulo (the operation that gives the remainder after division of
one integer by another) and logical manipulations.
An operator is a symbol used for certain type of manipulations, logical or mathematical. The data
on which the operators act are called operands. An expression is a valid combination of operators
and operands that results in a value.
For example in the expression : 12*5
* is the multiplication operator,
12 and 5 are the operands.
17
Unary Operators:
Operators that operate on a single operand are known as unary operators. The unary operators
always precede the operand. The different unary operators available in C are :
(i) Unary plus (+)
(ii) Unary minus (–)
(iii) Increment (++)
(iv) Decrement (– –)
(v) Logical NOT (!)
(vi) Bitwise complement (~)
(vii)Address (&)
The unary minus operator is used for negation. It change sign of the quantity on its right i.e., it
multiplies its only operand by –1. Similarly unary plus multiplies its operand by +1.
Binary Operators:
Binary operators operate on two operands. They are classified into five categories as follows:
(i) Arithmetic
(ii) Relational
(iii) Logical
(iv) Assignment
(v) Bitwise
Ternary Operators:
Ternary operators act on three data elements. The conditional operator (?:) is a ternary operator
Special Operators:
Special operators include operators such as comma (,) and sizeof.
ARITHMETIC OPERATORS:
C supports five arithmetic operators.
Operator Purpose
+ Addition
– Subtraction or (unary)
* Multiplication
/ Division
% Remainder after integer division
Dividing one integer by another integer is called as integer division, which truncates, the fractional
part. The % operator gives the remainder of such a division.
For example, consider a = 10, b = 3.
a % b gives 10% 3 giving the result 1
and a/b gives 10/3 giving the result 3
18
% operator can have only integer operands.
Mixed-mode Arithmetic operations consists of a real and an integer operand. If one of the operand
is real, the result is also real.
For example :
15/2.0 = 7.5
However 15/2 = 7
RELATIONAL OPERATORS:
The relational operators are used to form relational expressions, representing conditions that are
either true or false. The result of the expression is an integer. Further, false is represented by zero
value and true in represented by non-zero value. For example expressions
50<200
x>y
are called relational expressions whose value can be either true or false i.e., 50<200 is true. when
x = 10 and y = 5, x > y is true. There are 6 relational operators in C.
They are:
Operator Meaning
> greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
In the 4th and 5th example given above the expressions contain arithmetic expression. Thus in the
relational expression (i+j)>=k, the arithmetic expression i+j will be evaluated and then the result is
compared with k. These arithmetic operators have higher priority over relational operators. The
relational operators are used to compare two quantities in decision statements.
LOGICAL OPERATORS:
Logical operators are used to combine two or more logical expressions. There are 3 logical
operators in C. They are logical AND, logical OR and logical NOT
Operator Meaning
! logical NOT
&& logical AND
|| logical OR
19
● The result of a logical AND is true only if both operands are true. The result is false if
either operand is false.
● The result of a logical OR is false only if both operands are false. The result is true if either
operand is true.
● C also consists of the unary operator ! (not) that negates the value of a logical expression
i.e., it causes true expression to become false and vice-versa. This operator is known as
logical NOT operator. Further like relational operators, a logical expression results in zero
or non-zero value depending on whether it is false or true.
Consider i = 8, x = 5.1, c = ‗a‘ where i is an integer variable, x is a floating point variable and c is a
char variable.
Expression Logical value Integer value
(i>6)&&(c==‘a‘) true 1 (or non-zero)
i<=6||(c==‘b‘) false 0
i>=6&&(c==97) true 1
!(i<=4) true 1
ASSIGNMENTOPERATORS
The assignment operator ‗=‘ is used to assign the value of a variable, constant or expression
to a variable. The syntax is :
variable=variable/constant/expression;
For example :
x=10; /*x is assigned a value 10 */
sum=a+b; /*Thesumofa&bwhichis20isassignedtosum*/
Where += is the abbreviated or compound operator. In the above case + = means add
5ton.Thedifferentshorthandassignmentoperatorsare:
20
Normal Shorthand Operator Meaning
assignment assignment
n=n+1 n += 1 += sum & assign
n = n – 50 n –= 50 –= subtract & assign
n = n*10 n *= 10 *= multiply & assign
n=n/6 n /= 6 /= divide & assign
n=n%5 n %= 5 %= find modulo and assign
The priority of the above operators + =, –=, *=, /= and % = is the same as theassignment operator.
Difference between = = and = operator
1. == is an equality or relational operator, used for comparison = is an assignmentoperator
which assigns the resultant value on its right hand side to the variableon its left hand
side.
2. == operator does not change the value of the variable on the left hand side.However =
operator does change the value of the variable on the left hand side of the
assignmentstatement.
INCREMENT/DECREMENTOPERATOR
Theincrement and decrement operators are specifically used in C or C++.
They are not generally available in other languages.
Increment operator ++ is used to increment the value of the variable by 1.Decrement
operator – – is used to decrement the value of the variable by 1.
They are also called as unary operators Fig. 2.14. Since they operate on only one
dataelement.
21
int a, b;
:
a = 5;
b = --a;
will result in the value of a and b to be 4.
Post-increment operator ++ is written to the right of its operand as in n ++; which is the same
as n = n + 1;
Post-decrement operator – – is also written to the right of its operand as in n—
, and is equivalent to n = n – 1;
Pre-increment and pre-decrement operators ++ and – – are always placed to theleft of the
operand as follows :
++n; /* same as n =n+1*/
––n; /* same as n =n–1*/
The behavior of post and pre–increment or decrement operators are the same when used
with a single operand. However, they behave differently when the operand is embedded in an
expression.
Difference between postfix & prefixoperators
(i) The pre-increment or decrement operator first increments or decrements the value of
its operand by 1 and then assigns the resulting value to the variable onthe left hand
side. For example,consider
int a, b; a =
15;
b = ++a;
In this example, the value of a is incremented by 1 and then this value 16 is assigned to
b.
(ii) The post increment or decrement operator first assigns the value to the variable on the
left hand side and then increments or decrements the operand by 1. Consider the
following program segment:
intm,n; n = 2;
m = n– –;
The value of n is first assigned to m and then it is decremented i.e., n becomes 1, but value
of m is 2.
In subscripted variables.
a[j++]=5;
is equivalent to a[j]=5;
j++;
22
Similarly, a[++i]=5;
is equivalent to i = i+1;
a[i] = 5;
Consider the statement
x = n++/2;
where n = 5. After execution, n is 6 but x gets the value 5/2 which is 2.
Since it contains 3 expressions it is called ternary. The above statement is evaluated as follows :
(i) Expression1 is evaluatedfirst.
(ii) If it is true or non-zero, expression2 is evaluated and its value assigned to the
variable.
(iii) If expression1 is false or zero, expression3 is evaluated and its value assigned to
thevariable.
(iv) Eitherexpression2orexpression3willbeevaluated,butneverboth.
The CommaOperator
(i) The comma operator is used to separate a list of expressions given as a single
expression.
(ii) Thelistswithcommasarealwaysevaluatedfromlefttoright.
(iii) The value of the right most expression becomes the final value of the combined
expression.
(iv) The syntax is of the form:
variable =exp1,exp2, expn;
The sizeofoperator
24
(i) Thesizeofoperatorreturnsthesizeinbytesoftheoperandontheright.
(ii) The syntaxis
sizeof(n)
Example 2.30
/* Program to show usage of sizeof operator
*/ #define STRING “Usage of sizeof
Operator” #include <stdio.h>
main()
{
char a = „p‟;
clrscr();
printf(“\n The size ofcharis : %d \n”,sizeof(char));
printf(“\n Therefore the size of char ais : %d \n”,sizeof(a));
printf(“\n However the size of„p‟is : %d \n”,sizeof(„p‟));
printf(“\nSTRING : \”%s\”
\n”,STRING); printf(“\n The number of bytes in STRINGis : %d
\n”,sizeof STRING); printf(“\n The size ofshortis : %d\n”,sizeof(short));
printf(“\n The size ofintis : %d\n”,sizeof(int));
printf(“\n The size oflongis : %d\n”,sizeof(long));
printf(“\n The size offloatis : %d\n”,sizeof(float));
printf(“\n The size ofdoubleis : %d
\n”,sizeof(double)); getch();
}
25
Output
The size ofcharis 1
Therefore the size of charais 1
However the size of„p‟is 2
STRING : “Usage of sizeof
Operator” The number of bytes inSTRINGis 25
The size ofshortis 2
The size ofintis 2
The size oflongis 4
The size offloatis 4
The size ofdoubleis 8
BITWISEOPERATORS:
C supports a powerful set of operators known as bitwise operators. The bitwise
operatorsare used for controlling and interacting with hardware and also for
manipulating data at the bit level.
The Bitwise operators are as shown below table.
Operator Description
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ one‘s complement
(i) Bitwise operators cannot be applied to float or double. They can be applied to
integersonly.
(ii) All except ~ operator are used in binary operations. Tilde (~) is a unaryoperator.
(iii) Bitwise operators perform bitwise logical AND, bitwise logical OR,
bitwiseexclusiveOR,bitwiseshiftleftandshiftright.
(iv) Bitwise operators work on their operands bit by bit starting from the least significant
bit. The truth table for logical bitwise operations is as shown in below
table.Trueistakentobe1andfalseaszero.
26
Operand Operand x & x|y x^y
1 2 y
x y
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
Bitwise ANDOperator:
TheBitwise AND operator is represented by the symbol & (ampersand). The
result of AND operation is 1 if both operand bits are 1, otherwise, the result is zero.
Further,theANDoperationisdoneonthebinaryrepresentationoftheoperands.
4 & 5 results in 4
i.e., binary value of4is 0100
binary value of5is 0101
AfterANDoperation 0100 i.e.,4
Bitwise & operator is used to check whether a particular bit is 0 or 1. Consider the number
21. Its bit pattern is represented by
0001 0101
To check whether the fourth bit is 0 or 1, AND operation must be done withanother
4
operand whose value must be 2 i.e., 16, which can be represented as00010000.
Therefore, 00010101
0001 0000 & mask
0001 0000
th
result shows that 4 bit is 1 since the resultant value is 16.
Bitwise OROperator
The bitwise OR Operator is represented by the symbol | (vertical bar). It is also known as
inclusive OR. The result of a bitwise OR operation is 1 if either or bothcorresponding bits has a
value 1. Otherwise it is zero.
Consider x = 4, y = 9
xis 00000100 4
yis 00001001 9
27
x|yis 00001101 i.e.,13
The bitwise OR is used to set a particular bit on (set to 1).
Consider x = 4
x is 00000100
~x is 11111011
Bitwise ShiftOperator
The shift operators are used to push the bit patterns to the right or left by thenumber of bits given
by theirright operand
The Right shift operator is of the form :
expression>>n
where n is the number of bit positions to be shifted. However the rightmost n bitsare lost.
Further the left most n bits which are vacant will be filled with zero. For
examplex>>4shiftsallbitsby4placestotheright.
The Left shift operator is of the form
expression<<n
where n is the number of bit positions to be shifted. The left most n bits are lost andthe
rightmost n bits are vacated and filled with zeros.
Shift operators are used for multiplication and division by 2. For example, the statement
x = y << 2;
2
shifts two bit to the left in y. Further the value of x is equal to y multiplied by 2 .
Similarly, the statement
x = y >> 2;
28
2
shifts the bits in y to the right by 2. Also the value of x is equal to y divided by 2 .
PRECEDENCE OF ARITHMETICOPERATORS:
Any arithmetic expressionis evaluated according to the rule of precedence of operators. For
example in the expression.
4*5/2
29
(a < 10&& a + b > 15)
where a = 20, b = 1.
The order of evaluation will be as follows.
(i) Since + operator has the highest priority in the expression, addition is computed first:
a < 10 && 21 > 15
(ii) Both the relational operators have higher priority compared to the logical operator &&.
Here the associativity of relational operators has to be considered which is leftto right.
Thus:
20 <10 && 21 > 15
False && True
(iii) Theresultoflogical&&isfalseor0.
A complete operator precedence summary is listed in Fig. 2.20, from highest to lowest.
30
<,<=, >,>= Relational operators L to R 6
==, != Equality operators L to R 7
& Bitwise AND L to R 8
^ Bitwise XOR (Exclusive OR) L to R 9
Bitwise OR (Inclusive OR) L to R 10
&& Logical AND L to R 11
|| Logical OR L to R 12
?: Conditional operator R to L 13
=, Assignment R to L 14
*=, /=, operators
%=, += and
–= Abbreviated
&=, ^=, assignment
!=, <<=, >>= operators
, Comma operator L to R 15
Summary exercise:
Scope:
The Module covers the following topics: Selective, looping and nested statements. While the topics are
taught using a C language, the intent of the course is to teach a programming methodology and
also a laboratory component that involves development and testing of iterative and procedural
programs using functions.
Text andReference:
nd
Pradeep DeyandManasGhosh,―ProgramminginC‖,OxfordPress,2 Edition,2017
E.Balaguruswamy,ProgramminginANSIC,TataMcGraw-Hill.
33
L.10 Switch-Statement, Nested To understand else-if ladder, switch statement, use
Statements and Examples. for different situations
L.11 Loop ControlStatements: For, While, To understand Loop statements: while, do while and
Do-While and Examples. for statements, how to use with the combination of
other statements
L.13 Case Study on control structures. The general purpose of a case study is to:
→ describe an individual situation (case), in
detail;
→ identify the key issues of the case;
→ analyse the case using relevant theoretical
concepts from the module;
→ recommend a course of action for that
particular case.
Lecture : 9
Objectives: 1.What are various control structures
2. Classification
3. if, if else, nested if else
Control structures
34
Selective control statements:
1. if
2. if else
3. nested if else
4. else if ladder
5. switch
Iterative control statements :
1. for loop,
2. while loop,
3. do while loop
Simple if statement
1. Simple if statement is used to make a decision “yes or no”, based on the available choice. It
has the following form:
Syntax:
if ( condition )
{
stmt block;
}
stmt-x;
In this syntax,
● if is the keyword.
● <condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses and no terminator (;) at the end.
● The stmt block can be a simple statement or a compound statement or a null statement.
● stmt-x is any valid C statement.
35
1. flow chart for simple if.
Whenever simple if statement is encountered, first the condition is tested. It returns either
true or false. If the condition is false, the control transfers directly to stmt-x without considering
the stmt block. If the condition is true, the control enters into the stmt block. Once, the end of
stmt block is reached, the control transfers to stmt-x
Output:
enter a number
12
Even number
if - else statement
if…else statement is used to make a decision based on two choices. It has the following
form:
1. Syntax:
if(condition)
{
true stmt block;
}
else
{
false stmt block;
}
Stmt-x;
In this syntax,
● if and else are the keywords.
36
● <condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses .
● The true stmt block and falsestmtblock are simple statements or compound statements or
null statements.
● stmt-x is any valid C statement.
1. Flow chart:
If the condition is false, the control enters into the false stmt block by skipping true stmt
block.
Once, the end of false stmt block is reached, the control transfers to stmt-x.
#include <stdio.h>
main()
{
int x;
printf("Enter a number\n");
scanf("%d",&x);
if(x%2==0)
printf("EVEN\n");
else
printf("ODD\n");
}
37
11
ODD
if(x>y)
big=x;
else
big=y;
printf(“BIG=%d\n”,big);
}
/* absolute value */
#include <stdio.h>
main()
{
int x;
printf("Enter a integer\n");
scanf("%d",&x);
if(x<0)
printf("absolute value is %d\n",-x);
else
printf("absolute value is %d\n",x);
}
/* quadrant position */
#include <stdio.h>
main()
{
Int x,y;
printf("Enter the coordinate\n");
scanf("%d%d",&x,&y);
if(x>0 && y>0)
printf("FIRST QUADRANT\n");
38
}
/* alphabet or not */
#include <stdio.h>
main()
{
charch;
printf("Enter a character\n");
scanf("%c",&ch);
if(ch>= 'a' &&ch<='z')
printf("alphabet\n");
else
printf("not a alphabet\n");
}
/* vowel or not */
#include <stdio.h>
main()
{
char ch;
printf("Enter a alphabet\n");
scanf("%c",&ch);
if(ch== 'a' || ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("vowel\n");
else
printf("not a vowel\n");
}
Nested if…else statement is one of the conditional control-flow statements. If the body of if
statement contains at least one if statement, then that if statement is called as ―Nested if…else
statement‖. The nested if…else statement can be used in such a situation where at least two
conditions should be satisfied in order to execute particular set of instructions. It can also be
used to make a decision among multiple choices. The nested if…else statement has the
following form:
Syntax: if(condition1)
{
if(condition 2)
{
stmt1;
}
else
{
stmt2;
}
}
else
{
39
stmt 3;
}
stmt-x;
In this syntax,
Whenever nested if…else statement is encountered, first <condition1> is tested. It returns either
true or false.
If condition1 (or outer condition) is false, then the control transfers to else-body (if exists) by
skipping if-body.
If condition1 (or outer condition) is true, then condition2 (or inner condition) is tested. If the
condition2 is true, if-body gets executed. Otherwise, the else-body that is inside of if statement
gets executed.
#include<stdio.h>
40
#include<conio.h>
void main()
{
int a ,b,c;
else
{
if(c>b)
printf("%d\n",c);
else
printf("%d\n",b);
}
Programming Problems:
41
Lecture- 10
Objectives:
1. To understand else-if ladder
2. To understand switch statement
3. Learn to use for different situations
if (condition 1)
simple or compound statement // s1
else if (condition 2)
simple or compound statement // s2
else if ( condition 3)
simple or compound statement // s3
.....
else if ( conditon n )
simple or compound statement // sn
Whenever else if ladder is encountered, condition1 is tested first. If it is true, the statement 1 gets executed.
After then the control transfers to stmt-x.
42
If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are tested. If all are
false, the default stmt at the end gets executed. After then the control transfers to stmt-x.
If any one of all conditions is true, then the body associated with it gets executed. After that the control
transfers to stmt-x.
Points to Remember
1. We can use if-else if when you want to check several conditions but still execute one statement.
2. When writing an if-else if statement, be careful to associate else statement to the appropriate if
statement.
3. We must have parentheses around the condition.
Example program:
/* to find grade when percentage of marks are given */
#include<stdio.h>
void main()
{
int m1,m2,m3,avg,tot;
printf("enter three subject marks");
scanf("%d%d%d",&m1,&m2,&m);
tot=m1+m2+m3;
avg=tot/3;
if(avg>=75)
{
printf("distinction");
Explanation
1. The switch expression should be an integer expression and, when evaluated, it must have an integer
value.
2. The case constant expression must represent a particular integer value and no two case expressions
should have the same value.
3. The value of the switch expression is compared with the case constant expression in the order specified,
that is, from the top down.
4. The execution begins from the case where the switch expression is matched and it flows downward.
5. In the absence of a break statement, all statements that are followed by matched cases are executed.
6. If there is no matched case then the default is executed. You can have either zero or one default
statement.
7. In the case of a nested switch statement, the break statements break the inner switch statement.
44
Flow chart:
Whenever, switch statement is encountered, first the value of <exp> gets matched with case values. If
suitable match is found, the statements block related to that matched case gets executed. The break
statement at the end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed and then the control gets
transferred to Next-statement.
Point to Remember
1. case constructs need not be serial.
2. characters can be used.
3. combination of integers and characters is possible.
4. default is optional.
5. Brace in case block is optional
//switch 1
// to display name of the day
#include <stdio.h>
void main()
{
int day;
printf("Enter day number\n");
scanf("%d",&day);
switch(day)
{
case 1:
printf("monday\n");
break;
case 2:
printf("tuesday\n");
break;
45
case 3:
printf("wednesday\n");
break;
case 4:
printf("thursday\n");
break;
case 5:
printf("friday\n");
break;
case 6:
printf("saturday\n");
break;
case 7:
printf("sunday\n");
break;
default:
printf("Wrong entry\n");
}
}
//switch 2
// to display the gender
#include <stdio.h>
void main()
{
charch;
printf("Enter your gender\n");
scanf("%c",&ch);
switch(ch)
{
case 'm':
case 'M':
printf("so you are a male\n");
break;
case 'f':
case 'F':
printf("so you are a female\n ")
break;
default:
printf("Wrong entry\n");
}
}
Program exercises:
1. Developa C program to input week number and print week day.(L3)(CO3)
2. Developa C program to input month number and print number of days in that month.(L3)(CO3)
3. Develop a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and
Computer. Calculate percentage and grade according to following:(L3)(CO3)
Percentage >= 90% : Grade A
Percentage >= 80% : Grade B
Percentage >= 70% : Grade C
Percentage >= 60% : Grade D
46
Percentage >= 40% : Grade E
Percentage < 40% : Grade F
1. Develop a C program to input basic salary of an employee and calculate its Gross salary according
to following:(L3)(CO3)
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary >20000 : HRA = 30%, DA = 95%
1. Develop a C program to input electricity unit charges and calculate total electricity bill according to
the given condition:(L3)(CO3)
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill(L3)(CO3)
1. Develop a C program print total number of days in a month using switch case.(L3)(CO3)
1. Develop a C program to check whether an alphabet is vowel or consonant using switch
case.(L3)(CO3)
1. Develop a C program to find maximum between two numbers using switch case.(L3)(CO3)
1. Develop a C program to find roots of a quadratic equation using switch case.(L3)(CO3)
1. Develop a C program to create Simple Calculator using switch case.
(L3)(CO3)
Lecture-11
Objective:
1. Loop statements: while, do while and for statements
2. How to use with the combination of other statements.
while LOOP
Introduction
The while loop is used when we want to repeat the execution of a certain statement or a set of statements
(compound statement).
Syntax
The general format for a while loop is
while (condition)
simple or compound statement (body of the loop)
For example,
i = 0;
while (i<5)
{
printf(" the value of i is %d\n", i);
i = i + 1;
}
Explanation
1. Before entering into the loop, the while condition is evaluated. If it is true then only the loop body is
executed.
2. Before making an iteration, the while condition is checked. If it is true then the loop body is executed.
3. It is the responsibility of the programmer to ensure that the condition is false after certain iterations;
otherwise, the loop will make infinite iterations and it will not terminate.
4. The programmer should be aware of the final value of the looping variable. For example, in this case,
the final value of the looping variable is 5.
5. While writing the loop body, you have to be careful to decide whether the loop variable is updated at
the start of the body or at the end of the body.
47
#include<stdio.h>
#include<conio.h>
int main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d ",i);
i=i+1;
}
}
do-while LOOP
Introduction
The do-while loop is used when we want to execute the loop body at least once. The do-while loop executes
the loop body and then traces the condition.
Syntax
The general format for a do-while loop is
do
simple or compound statement
while (condition);
For example,
i = 0;
do
48
{
printf(" the value of i is %d\n", i);
i = i + 1;
}
while (i<5);
Explanation
1. The loop body is executed at least once.
2. The condition is checked after executing the loop body once.
3. If the condition is false then the loop is terminated.
4. In this example, the last value of i is printed as 5.
#include<stdio.h>
for LOOP
Introduction
The for loop is used only when the number of iterations is predetermined, for example, 10 iterations or 100
iterations.
Syntax
49
The general format for the for loop is
for (initializing; continuation condition; update)
simple or compound statement
For example,
for (i = 1; i<=5; i++)
{
printf("%d”, i");
}
Explanation
1. The for loop has four components; three are given in parentheses and one in the loop body.
2. All three components between the parentheses are optional.
3. The initialization part is executed first and only once.
4. The condition is evaluated before the loop body is executed. If the condition is false then the loop
body is not executed.
5. The update part is executed only after the loop body is executed and is generally used for updating
the loop variables.
6. The absence of a condition is taken as true.
7. It is the responsibility of the programmer to make sure the condition is false after certain iterations.
#include<conio.h>
void main()
{
int i,n;
printf("enter the value"); scanf("%d ",&n);
for(i=1;i<=n;i++)
{
printf("%d\n",i);
}
}
50
We may want to control the loop variables in the same for loop. We can use one for loop with a comma
operator in such situations.
Syntax
for (i = 0, j = 10; i< 3 && j > 8; i++, j-)
printf (" the value of i and j %d %d\n",i, j);
Explanation
1. First iis initialized to 0, and j is initialized to 10.
2. The conditions i<3 and j>8 are evaluated and the result is printed only if both conditions are true.
3. After executing the loop body, iis incremented by 1 and j is decremented by 1.
4. The comma operator also returns a value. It returns the value of the rightmost operand.
The value of (i = 0, j = 10) is 10.
#include <stdio.h>
main()
{
int i, n;
float x,denom, term, sum,deg;
printf("Enter value of x in deg and number of
terms: \n");
51
scanf("%f%d", °, &n);
x=deg*3.14/180;
sum = term = x;
for ( i = 2; i<= n; i++)
{
denom = (2 * i - 2)*( 2 * i - 1);
term *= -(x*x)/ denom;
sum += term;
}
printf("\ndeg = %.1f, Sum = %.2f", deg, sum);
} /* end of main */
// cosine series
main()
{
int i, n;
float x,denom, term, sum,deg;
printf("Enter value of x in deg and number of terms: \n");
scanf("%f%d", °, &n);
x=deg*3.14/180;
sum = term = 1;
for ( i = 1; i<= n; i++)
{
denom = (2 * i )*( 2 * i - 1);
term *= -(x*x)/ denom;
sum += term;
}
printf("\ndeg = %.1f, Sum = %.2f", deg, sum);
} /* end of main */
Programming exercises:
Lecture- 12
Objectives:
1. Jumping/ unconditional statements- break,continue,goto
2. Use these with combination of other statements.
3. Understand nested loops.
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.
53
When it is used in the nested loop or switch statement, the control comes out of that loop / switch statement
within which it is used. But, it does not come out of the complete nesting.
break;
The following representation shows the transfer of control when break statement is used:
Any loop
{
statement_1;
statement_2;
:
break;
next_statement;
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
Output: 12345
2. continue statement
A continue statement is used within loops to end the execution of the current iteration and proceed to the
next iteration. It provides a way of skipping the remaining statements in that iteration after the continue
statement. It is important to note that a continue statement should be used only in loop constructs and not in
selective control statements.
54
Syntax for continue statement is:
continue;
The following representation shows the transfer of control when continue statement is used:
Any loop
statement_1; statement_2;
:
continue;
next_statement;
#include<stdio.h>
#include<conio.h>
int main()
{
int i, sum=0, n;
for(i=1; i<=10; i++)
{
3. goto statement
The goto statement transfers the control to the specified location unconditionally. There are certain situations
where goto statement makes the program simpler. For example, if a deeply nested loop is to be exited
earlier, goto may be used for breaking more than one loop at a time. In this case, a break statement will not
serve the purpose because it only exits a single loop.
55
Syntax for goto statement is:
label:
statement_1; statement_2;
:
goto label;
In this syntax, goto is the keyword and label is any valid identifier and should be ended with a colon (:).
The identifier following goto is a statement label and need not be declared. The name of the statement or
label can also be used as a variable name in the same program if it is declared appropriately. The compiler
identifies the name as a label if it appears in a goto statement and as a variable if it appears in an expression.
If the block of statements that has label appears before the goto statement, then the control has to move to
backward and that goto is called as backward goto. If the block of
statements that has label appears after the goto statement, then the control has to move to forward and that
goto is called as forward goto.
printf("www."); goto x;
y:
printf("expert"); goto z;
x:
printf(".com");
PROGRAM 1
1
56
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n;
for(line=1;line<=3;line++)
{
for(n=1;n<=line; n++)
printf("%3d",n);
printf("\n");
}
}
PROGRAM2
1
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n,gap;
for(line=1;line<=3;line++)
{
for(gap=1;gap<=20-line;gap++)
printf(" ");
for (n=1;n<=line;n++)
printf("%4d",n);
printf("\n");
}
}
PROGRAM 3
/* 1
12
123
1234
12345
*/
#include <stdio.h>
void main()
{
int line ,n,gap;
for(line=1;line<=5;line++)
{
for(gap=1;gap<=5-line;gap++)
printf(" ");
for(n=1;n<=line;n++)
printf("%2d",n);
printf("\n");
}
}
PROGRAM 4
1
121
12312
1234123
57
123451234
#include <stdio.h>
void main()
{
int line ,n,gap;
for(line=1;line<=5;line++)
{
for(gap=1;gap<=20-line;gap++)
printf(" ");
for(n=1;n<=line;n++)
printf("%2d",n);
for(n=1;n<line;n++)
printf("%2d",n);
printf("\n");
}
}
//program 5 :Pascal triangle
#include <stdio.h>
void main()
{
int binom,n,q,g,x;
binom=1;
q=0;
printf("enter no of rows\n");
scanf("%d",&n);
while(q<n)
{
for(g=40-3*q;g>0;g--)
printf(" ");
for(x=0;x<=q;x++)
{
if((x==0)||(q==0))
binom=1;
else
binom = (binom*(q-x+1))/x;
printf("%6d",binom);
}
printf("\n");
q++;
}
}
Programming exercises:
*****
58
* *
* *
* *
*****
*****
*****
*****
*****
*****
*
**
**
* *
*****
10101
01010
10101
01010
10101
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
59
Lecture-13
Case Study on control structures:
while(temp%10==0)
{
printf("ZERO ");
temp=temp/10;
}
}
Programs:
1
1 2
1 2 3
1 2 3 4
1
1 2
1 2 3
1 2
1
62
1
1
1 2
1 2 3
1
1 2 1
1 2 3 2 1
1
2 1 2
3 2 1 2 3
1. Write a program to print the sum of first n terms of sine series.(L3)(CO3)
1. Write a program to print the sum of first n terms of cosine series.(L3)(CO3)
1. Write a program to print the Pascal triangle.(L6)(CO3)
1. Write a program to find n Fibonacci number.(L3)(CO3)
th
1. WAP to find whether the given number is strong or not using functions.(L3)(CO3)
(Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145 )
1. Input a year from keyboard and determine whether it is leap year or not using the
conditional operator.(L3)(CO3)
1. Accept three numbers from user and determine which of the two numbers or all three
numbers are equal or not using logical operators.(L3)(CO3)
1. WAP to calculate nPr= n!/(n-r)!(L3)(CO3)
1. WAP to calculate nCr =n! / n!*(n-r)!(L3)(CO3)
1. WAP to find whether the given number is perfect or not
Example ( 6 is perfect number since 6 = 1 + 2 + 3)(L3)(CO3)
63
Course Code: 20CS C01
Instructors Name:
Name Email
Smt. Venkata Sushma Chinta venkatasushmachinta_mech@cbit.ac.in
Objective:
Outcome:
● Decompose a problem into modules and use functions to implement the modules.
Scope:
The Module covers the following topics:Basics of Functions, User-defined Functions, Inter
Function Communication, Standard Functions. Storage Classes (Auto, Register, Static, Extern),
Scope Rules. While the topics are taught using a C language, the intent of the course is to teach
a programming methodology and also a laboratory component that involves development and
testing of iterative and procedural programs using functions.
64
Text andReference:
(a) Text Book:
nd
Pradeep DeyandManasGhosh,―ProgramminginC‖,OxfordPress,2 Edition,2017
E.Balaguruswamy,ProgramminginANSIC,TataMcGraw-Hill.
L.15 Inter Function Communication, To learn basic types of standard functions and
Standard Functions. recursive functions
L.17 Storage Classes (Auto, Register, To learn Storage Classes (Auto, Register, Static,
Static, Extern), Scope Rules. Extern), Scope Rules.
L.18 Case Study on Functions The general purpose of a case study is to:
→ describe an individual situation (case), in
detail;
→ identify the key issues of the case;
→ analyse the case using relevant theoretical
concepts from the module;
→ recommend a course of action for that
particular case.
65
Lecture title L.14 to L.18
Date
Key topics:Introduction,usesoffunctions,Functiondefinition,declaration,passing parameters to
functions, recursion, scope of variables and storageclasses.
Case study using functions.
Definition:
A function is a set of instructions under a name that carries out a specific task,
assigned to it.
CLASSIFICATION of functions:
1. User defined functions (UDF)
2. Library functions
USER DEFINED FUNCTIONS
Example:
void sum( ) function without arguments and without return value
int sum( ) function without arguments but with return value
void sum(int ,int) function with arguments but without return value
int sum(int,int) function with arguments and with return value
Function prototype:
If we use any variable in the program, we declare that variable in the declaration section of the
program. Similarly, any function that is to be called should be declared before its call in the calling
Function declaration should be done either in the declaration section of calling function or
before it. The function prototype should agree with definition of that function.
Prototype contains the data type returned by the function followed by the name of that
function and a pair of parentheses enclosing the data type of each parameter separately.
66
Optionally the name of each parameter may be given.
Function definition
FUNCTION CALL
Function call means, accessing a function. A function can be called by specifying its name,
followed by a list of arguments enclosed in the parentheses, and separated by comma
Example: f=fact(n);
If a function call does not require any arguments, an empty pair of parentheses must
follow the function name.
A function call may appear itself or it may be one of the operand within a expression.
Example: printf(“%d”,fact(n));
Arguments in function call, and formal parameters in function declaration must be same in
number, type and order.
OUTPUT
x=50 y=0
Example programs on functions
Factorial of number by using function
#include <stdio.h>
main()
{
long int fact(int);
int n;
long int f;
printf("Enter a number\n");
scanf("%d",&n);
f = fact(n);
printf("The factorial of %d is %ld",n,f);
} /*end of main */
/* function fact*/
long int fact(int x)
{
68
int i;
long int f1=1;
for(i=1;i<=x;i++)
f1 = f1*i;
return(f1);
}
Fibonacci series by function
main()
{
int n;
void fib(int);
printf( "\nHow many Fibonacci numbers
required ? ");
scanf("%d", &n);
printf("\nThe first %3d fibonaccinumbers are\n", n);
fib(n);
}
void fib(int n)
{
int i, f1, f2, f3;
f1 = f2 = 1;
printf("%5d\n", f1);
printf("%5d\n", f2);
for( i = 3; i<= n; i++)
{
f3 = f1 + f2;
printf("%5d\n", f3);
f1 = f2;
f2 = f3;
}
}
GCD of two numbers by function
void main()
{
int m,n,g;
int gcd(int,int);
69
} /* End of main() */
int gcd(int m,int n)
{
int r,g1;
do
{
r=m%n;
if(r!=0)
{
m=n;
n=r;
}
}while(r!=0);
g1=n;
return(g1);
} /* End of function gcd */
LCM of two numbers by function
main()
{
int m,n;
int lcm(int,int);
} /* End of main() */
#include <stdio.h>
void main()
{
int palin(int);
int num,ans;
printf("Enter a number\n");
scanf("%d",&num);
ans=palin(num);
if(ans==1)
printf("%d is palindrome\n",num);
else
printf("%d is not palindrome\n",num);
}
/* function palin */
int palin(int num)
{
int rev=0,temp,digit;
temp=num;
while(num!=0)
{
digit= num%10;
rev = rev*10 + digit;
num = num/10;
}
if(rev==temp)
return 1;
else
return 0;
71
}
RECURSIVE FUNCTIONS
A function which calls itself until a certain condition is reached is called recursive function
/* to find factorial of a number recursively */
#include <stdio.h>
main()
{
int rfactorial(int);
int n,f;
printf("Enter a number\n");
scanf("%d",&n);
f=rfactorial(n);
printf("Factorial of %d is %d",n,f);
/* factorial */
int rfactorial(int n)
{
if(n==0)
return 1;
else return(n*rfactorial(n-1));
}
/* to find nth fib number recursively */
#include <stdio.h>
main()
{
int rfib(int);
int n,f;
printf("Enter a number\n");
scanf("%d",&n);
f=rfib(n);
printf("n thfibonacci number is %d",f);
}
/* rfib */
int rfib(int n)
{
if(n==1||n==2)
return 1;
else return(rfib(n-1)+rfib(n-2));
}
/* to find GCD of two numbers recursively */
#include <stdio.h>
main()
{
int rgcd(int,int);
int m,n,g;
72
printf("Enter two numbers\n");
scanf("%d%d",&m,&n);
g=rgcd(m,n);
printf("gcd is %d",g);
}
/* function rgcd */
int rgcd(int m,int n)
{
if(m%n==0)
return n;
else
return(rgcd(n,m%n));
}
int rsum(int n)
73
{
if(n==0)
return n;
else return(n%10+rsum(n/10));
}
#include <stdio.h>
void main()
{
int rpower(int,int);
int m,n;
printf("Enter two number\n");
scanf("%d%d",&m,&n);
printf("%d power %d is %d\n",m,n,rpower(m,n));
}
int rpower(int m,int n)
{
if(n==0)
return 1;
else
return(m*rpower(m,n-1));
}
74
STORAGE CLASSES
Normally the life of a variable is limited to a function as long as the function is alive. How
to make it alive in a file or throughout the program or limiting only to a block inside a
function or to make common to a desired couple of functions etc., The answer lies in
―STORAGE CLASSES‖ or ―VARIABLE TYPES‖.
There are four types of storage classes.
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
AUTOMATIC VARIABLES:
Automatic variables are declared inside a function, in which they are to be
utilized. They are created when the function is called and destroyed automatically when
the function is exited. By default all variables are automatic variables. These are also
called local or internal variables.
EXTERNAL VARIABLES
Variables that are both alive and active throughout the entire program are called
external variables. These variables are available to all functions in that program.
Whatever changes that occur in a function, will effect the value of that variable.
STATIC VARIABLES
When a variable is declared as a static variable it is assigned the value zero. Static
variables are initialized only once. They will not be initialized for second time during the
program. When static is applied to a global variable, the global variable becomes
75
inaccessible outside the file.
REGISTER VARIABLES
This is local to a function or a block. If a compiler finds a physical register in the CPU free
for the time being, and also big enough to hold the value, then it may stick that variable
in that register. Otherwise, the compiler treats that variable as ordinary. It is machine
dependent. But compiler will not give error messages even if no register available in
reserve. If we know that a particular variable will be used often inside function-say the
variable inside a loop-then we can declare that variable with class register. So that the
interaction will be very fast.
int fun2()
{
int x;
x=20;
return x;
}
76
int fun3()
{
x=1000;
return x;
}
void main()
{
int x=100;
printf("% d\n",fun1());
printf("%d\n",fun2());
printf("% d\n",fun3());
x=0;
printf("%d\n",x);
printf("% d\n",fun1());
printf("%d\n",fun2());
printf("% d\n",fun3());
}
OUTPUT
11
20
1000
0
1010
20
1000
#include <stdio.h>
void main()
{
int fun();
int i;
for(i=1;i<5;i++)
printf("%d\n",fun());
}
int fun()
{
static int x=0;
x+=1;
return(x);
}
OUTPUT
77
1
2
3
4
// program to illustrate register variable
#include <stdio.h>
void main()
{
register inti;
int i;
for(i=1;i<1000;i++)
printf("% d",i);
}
automatic variable static variable
2. It must be declared inside the function 2. It can be declared inside or outside the function
3. If it is not initialized, zero is stored
3. If it is not initialized, garbage value is stored 4. It is initialized once and only one but not every
4. It is initialized every time function is called that time when function is called
is repeated initialization 5. It is lost when program terminates but not when
5. It is lost when function terminates function terminates
78
1. It is declaration inside the function 1.It is declaration outside the function
2.It is declared by 2. It is declared by int a=10
auto int a=10 or
int a = 10 (auto is default scope)
3. If it is not initialized. garbage value is 3. If it is not initialized zero is stored
stored Eg: int a; Eg: int a;
a is garbage value a=0
4. It is created when the function starts 4. It is created before program execution
execution and lost when the function starts and lost when program terminates
terminates
5. It is visible in only one function. 5. It is visible through out the program.
6. It can be accessed in only one function that is 6. It can be accessed in more than one function.
the
Iterative Recursive
79
1. Function calls some other functions 1. Function calls some itself
2. while loop, do while loop or for loop is 2. if statement is necessary in recursive function
necessary in iterative function
3. Fast in execution since one function call is 3. Slow in execution since several function calls are
enough to get the result involved to get the result, as number of function
increases execution will slow down.
4. Function call leads to value 4. Function call leads to another function call
Eg: fact(4) = 24 Eg: fact(4) = 4 x fact(3)
Summary:
● All C programs contain main() function which is mandatory.
● main() function is the function from where every C program is started to execute.
● Name of the function is unique in a C program.
● C Functions can be invoked from anywhere within a C program.
● There can any number of functions be created in a program. There is no limit on this.
● There is no limit in calling C functions in a program.
● One function can be called within another function.
● C functions can be called with or without arguments/parameters. These arguments are
nothing but inputs to the functions.
● C functions may or may not return values to calling functions. These values are
nothing but output of the functions.
● When a function completes its task, program control is returned to the function from
where it is called.
● There can be functions within functions.
● Before calling and defining a function, we have to declare function prototype in order
to inform the compiler about the function name, function parameters and return value
type.
● C function can return only one value to the calling function.
● When return data type of a function is ―void‖, then, it won‘t return any values
● When return data type of a function is other than void such as ―int, float, double‖, it
80
returns value to the calling function.
MCQs:
1. In C, parameters are always(L2)(CO4)
a) Passed by value
b) Passed by reference
c) Non-pointer variables are passed by value and pointers are passed by reference
d) Passed by value result
Answer: a
3. The variables that are declared inside a function are (L1) (CO4)
a) global variable
b) local variables
c)static variables
d)must be same as the variables declared in main().
Answer: b
4.
81
(L3) (CO4)
a) Compiler error as foo() is not declared in main
b) 1 2
c) 2 1
d) Compile time error due to declaration of functions inside main
Answer: b
5. Can we use a function as a parameter of another function? [Eg: void func1(int func2())]? (L1)
(CO4)
a) Yes, and we can use the function value conveniently
b) Yes, but we call the function again to get the value, not as convenient as in using variable
c) No, C does not support it
d) This case is compiler dependent
Answer: c
6. What is the return-type of the function sqrt().(L2) (CO4)
a) int
b) double
c) float
d) depends on compiler
Answer: b
7. What is the default return type if it is not specified in function definition??(L3) (CO4)
a) void
b) integer
c) double
d) float
Answer: b
8.
82
(L3) (CO4)
a) Error: Return statement cannot be used with conditional operators
b) Error: Prototype declaration
c) Error: Two return statements cannot be used in any function
d) No error
Answer: a
#include <stdio.h>
void foo()
{
return 1;
}
void main()
{
int x = 0;
x = foo();
printf("%d", x);
}
a)2
b)0
c)1
d) 3
Answer: c
a)User defined
b)Library
c)both (a) and (b)
d) None
Answer: c
14. C program must contain at least(L2) (CO4)
a) n functions
b)1 function
c) 2 functions
d) None
Answer: b
15. which of the following is not a storage class specifier?(L2) (CO4)
a) auto
b) register
c) extern
d) volatile
Answer: d
16. what is the initial value of register storage class specifier? (L2) (CO4)
a)0
b)garbage
c)1
d)infinite
Answer: b
Expected Questions:
Short answer type:
85
Course Code: 20CS C01
Instructors Name:
Name Email
Smt. A Sangeetha asangeetha_cse@cbit.ac.in
Objective:
Outcome:
● Learn about one-dimensional and two-dimensional arrays and the way they are declared, initialized,
manipulated, inputted, and displayed.
● Differentiate different dimensions of the array and able to choose appropriate array to store data and
perform operations on them in an application.
Scope:
The Module covers the following topics: Introduction to Arrays, Declaration using Arrays in C, Accessing and storage
of array elements, one dimensional arrays, Searching Algorithms (linear and binary search), Sorting Algorithms
(Selection and Bubble),Two dimensional arrays, matrix operations.
While these topics are taught using a C language, the intent of the course is to teach a programming methodology and
also a laboratory component that involves development and testing of iterative and procedural programs using one-
dimensional and two-dimensional arrays.
86
Text andReference:
(a) Text Book:
1. M.T. Somashekar “Problem Solving with C”, 2 nd Edition, Prentice Hall India Learning Private
Limited 2018
2. A K Sharma “Computer Fundamentals and Programming”, 2nd Edition, University Press, 2018
3. Pradeep Dey and Manas Ghosh, “Programming in C”, Oxford Press, 2nd Edition, 2017
(b) Reference Books:
2. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of India.
5. https://www.tutorialspoint.com/cprogramming/index.htm.
6. https://onlinecourses.nptel.ac.in/noc18-cs10/preview.
L.20 Accessing and storage of array To learn the memory allocation for arrays and accessing
elements, one dimensional arrays elements. Perform basic operations on array elements
L.21 Searching Algorithms (linear and binary Using search operation learner will learn accessing
search) element and apply operators on array elements
L.22 Sorting Algorithms (Selection and Bubble) Learn how nested loops can be used to access
elements in the arrays to perform sorting and analysis
each passes.
L.23 Two dimensional arrays, matrix operations Learn how multiple dimensional can be declared,
initialized, accessed and performing operations on
them
87
Lecture Title: L19 to L23
Date
Key topics : Integer one dimensional and multi-dimensional arrays and its storing, retrieving and memory locations
Introduction to Arrays
Till now you might have declared variables to hold data and to perform operations on it. Just like given below-
int a=10;
char ch=’a’;
These variables can hold only one data item at a time. Let us take some example where collection of data
items need to be stored….
● 60 students marks secured in a subject
● Salaries of 100 employees
So we are supposed to declare multiple variables to hold the above data for each example.
C language provides a derived data types called arrays.
Definition
An array is collection of homogeneous elements stored in continuous memory locations and shares a common
name.
There are several forms of an array used in C: one-dimensional or single-dimensional and multidimensional
array.
Declaration of one-dimensional or single-dimensional
Like any other variables, arrays must be declared before they are used. The general form of array declaration
is
Syntax: datatype array_name[sizeofarray];
⬥ The data type specifies the type of data/element that will be stored in the array, such as int, float, or
char.
⬥ The size indicates the maximum number of data/elements that can be stored in the array.
⬥ The size of array should be a int constant or constant expression.
Let us take the same example to declare suitable one dimensional array variable to hold the data.
● 60 students marks secured in a subject
unsigned short int PPS[60];
● Salaries of 100 employees
float salaries_of_employees[100];
88
⬥ Elements are stored in consecutive memory allocations. Each block is of size two because variable ‘ a’
is of data type ‘int’. If array variable is of ‘float ‘ data type then each block occupies four bytes.
⬥ So total memory occupied by an array whose size is given as ‘n’ is- sizeof(datatype of
the variable)*n
⬥ First element in the array is stored at a[0], second at a[1] and so on fifth element is stored at a[4]. If
size of an array is ‘n’ then elements in the array stored from 0 to n-1 index/subscript. Storing/
retrieving data into/from the array is done by using index/subscript.
● Array is initialized with elements can be done at static time (while writing the code) or dynamic time(
at the time of executing the program).
Static Initialization
Example 1:
int a[5]; //array declaration
//array initialization
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
Example 2:
int a[5]={10,20,30,40,50}; // array declaration and initialization
Dynamic Initialization
Example 3:
int a[5],i;
printf(“Enter 5 integer elements:”);
for(i=0;i<=4;i++)
scanf(“%d”,&a*i+);
89
At the time of execution user can give 5 data items which will be stored in the array.
int a[5]={10,20,30,40,50};
printf(“%d\t%d\t%d\t%d\t%d”,a*0+, a*1+, a*2+, a[3], a[4]);
int a[5]={10,20,30,40,50},i;
for(i=0;i<=4;i++)
printf(“%d”,a*i+);
In both the cases elements stored in the indexes from ‘0’ to ‘4’ will be displayed.
As loop variable value changes the subscript of an array changes and corresponding element will
be displayed.
}
Output:
90
Variable length arrays
Previous version of C(C89) compilers, an array’s size must be an constant, so that compiler can calculate the
size/memory allocation at the compilation time itself. But from C99 onwards, C compilers allows the
programmers to declare an array variable with variable length ie size of an array can be given at execution
time/ run time.
# include<stdio.h>
int main( )
{
int i , a[5];
91
printf(“Enter 5 integer elements: ”); /* reading values into Array */
for (i=0; i<5; i++)
scanf(“ %d ”, &a*i+);
/* printing of a[i] values */
printf(“The array elements in reverse order are:”);
for(i=4; i>=0 ; i--)
printf(“%d ”, a*i+);
return 0;
}
Output:
Find whether a given element/key exists or not in the array of elements is called search.
This operation can be done by using two methods- simplest method is a sequential search or linear search
and binary search.
The basic idea of linear search is start comparing the key with each element in the array from index ‘0’ to
index ‘n’-1 if ‘n’ is the size of the array.
if key is found display the position/index at which element exist and exit the search
otherwise search will be continued till the end of the array and display the key is not found.
92
for(i=0 ; i<n; i++)
if(a[i] == key)
{
printf(“\n Found at %d”,i);
FOUND=1; break;
}
if(FOUND = = 0)
printf(“\n NOT FOUND...”);
return 0;
}
Output when more than the size of the array
In binary search method , halves the size of the list and searches only in half of the array by finding the mid
element index using first(low) and last(high) index of the array.
The procedure is as follows-
● Find mid element by using low and high
● If key is less than mid element then search will be done in left of the array by updating high
● Else If key is greater than mid element then search will be done in right of the array by updating low
● Otherwise mid element itself is the search element.
This will be continued until low is less than high. Unsuccessful search make low greater than high. To perform
binary search the elements should be increasing order in the array.
/* Program to implement linear search */
93
#include<stdio.h>
int main()
{
int n;
printf("\n Enter the size of the array:");
scanf("%d",&n);
int a[n],i,key,FOUND=0;
int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(key>a[mid])
low=mid+1;
else if(key<a[mid])
high=mid-1;
else
{
printf("\n Found at %d",i);
FOUND=1; break;
}
}
if(FOUND == 0)
printf("\n NOT FOUND...");
return 0;
}
Output Binary search logic Interpretation for successful
search
Bubble Sorting
Sorting operation will keep the element in an order.
Basic principle of bubble sort is consecutive/adjacent elements are compared and exchanges their values if
94
they are not in the order. This process bubbles the smallest element in the array to ‘0’ index and largest to ‘n-
1’ index where ‘n’ is the size of the array.
The following depicts the different stages of the bubble sort.
pass1 Comparison on
44 22 -1 3 10 44 , 22 (swap)
22 44 -1 3 10 44, -1 (swap)
22 -1 44 3 10 44 , 3 (swap)
22 -1 3 44 10 44, 10 (swap)
22 -1 3 10 44 Pass1 completed and largest element (44) placed in the correct position.
It is not going to be considered in the next iteration.
Pass2 Comparison on
-1 22 3 10 44 22, -1 (swap)
-1 3 22 10 44 22, 3 (swap)
-1 3 10 22 44 22, 10 (swap)
-1 3 10 22 44 Pass 2 completed . 22 is placed in the correct position. It is not going to
be considered in the next iteration.
Pass3 Comparison on
-1 3 10 22 44 -1, 3 (no swap)
-1 3 10 22 44 3,10 (no swap)
-1 3 10 22 44 Pass 3 completed . 10 is placed in the correct position .It is not going to
be considered in the next iteration.
Pass4 Comparison on
-1 3 10 22 44 -1, 3 (no swap)
-1 3 10 22 44 Pass 4 completed . 3 is placed in the correct position .It is not going to be
considered in the next iteration.
Always single element in the array will be in sorted order itself. So algorithm stops its passes.
for(i=0;i<n;i++)
printf("%5d",x[i]);
95
//sorting logic
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1]; /* swap */
a[j+1]=temp;
}
}
printf("\n After Sorting ....\n");
for(i=0;i<n;i++)
printf("%5d",x[i]);
return 0;
}
Selection Sorting
⬥ Selection sort finds the minimum element from the array and place it in the beginning.
#include <stdio.h>
96
main()
{
int a[20],n,i, j, po,se,temp;
printf("How many elements\n");
scanf("%d",&n);
● Arrays with more than one dimension are called multidimensional arrays.
● Array of one dimensional array is called two dimensional array.
97
elements in a one one-dimensional array.
⬥ Number of elements stored in the array will be size1 *size 2 .
Example:
int a[10][10];
float b[20][20];
● Two dimensions are useful to store data in a table form. Ie take the previous example 60 student
marks in a subject.
● In order to store 60 students’ marks obtained in 6 subjects then six one dimensional arrays need to be
declared for each subjects.
● It will be difficult to remember the variable name of each subject if multiple subjects exist.
Static initialization
initialization of an array: this can be done in two ways
1. int a[2][2] = { {3,6} , {2,9} }; // each 1D array enclosed in {} and separated with ,
2. int a[2][2] = { 3,6,2,9}; // based on 2nd dimension it will identify the number of
// elements in each row.
dynamic initialization
● To represent 2 dimensions we need two variable one for each dimension.
int a[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf(“%d”,&a*i+*j+);
}
int a[3][3]={1,2,3,4,5,6,7,8,9};
Then the array will be …
98
row1 row 2 row 3
⬥ To accesses the 2nd element at 3rd row we need to use the indexes as a[1][2]. So element in ith row jth
column will be accesses as a[i-1][j-1].
⬥ All the elements are stored in continuous locations. Two dimensional array is also called as array of
arrays.
⬥ First dimension in the 2D array tells about how many one dimensional arrays are required, second
dimension tells about how many elements in each one dimensional array .
100
}
101
printf("Transpose of a :\n");
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
printf("%3d",b[i][j]);
printf("\n");
}
}
Enter the size of matrix
23
Enter the matrix values
123
456
Transpose of a :
1 4
2 5
3 6
102
{
if(a[i]==key)
{
printf("search is successful\n");
printf("location = %d\n",i+1);
found =1;
}
}
if(found==0)
printf(" element not found\n");
}
OUTPUT:
Enter how many numbers
8↵
Enter the number
34 5 89 54 7 15 77 23 ↵
Enter the key
77↵
Search is successful
Location =7
} /* end of main */
/*Function input */
void input( int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */
/* Function Bsearch */
void bsearch (int a[],intn,int key)
103
{
intlow,high,mid,flag=0;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key < a[mid])
high=mid-1;
else if(key > a[mid])
low = mid+1;
else if(key == a[mid])
{
printf("search is successful\n");
printf("location = %d\n",mid+1);
flag=1;
break;
}
}
if(flag==0)
printf("search is unsuccessful\n");
} /* end of function bubblesort */
OUTPUT:
Enter how many numbers
10 ↵
Enter the number
3 5 8 54 7 15 76 23 79 11 ↵
Enter the key
79↵
Search is successful
Location =9
int a[25],n;
printf("How many numbers to sort ? ");
scanf("%d",&n);
printf("\nEnter %d numbers below:\n", n);
input(a,n);
bubblesort(a,n);
104
printf("\nThe sorted Array is: \n");
output(a,n);
} /* end of main */
/*Function input */
void input( int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */
/* Function Bubblesort */
void bubblesort (int a[],int n)
{
int pass, j, temp;
for ( pass = 1; pass < n; pass++ )
{
for ( j =0 ; j < n-1; j++ )
{
if( a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
} /* end of function bubblesort */
/* Function output */
void output (int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
printf("%5d\n", a[i]);
} /* end of function output */
#include <stdio.h>
main()
{
void ssort(int [],int);
void display(int [] ,int);
void readarray(int [],int);
int a[20],n;
printf("How many elements\n");
105
scanf("%d",&n);
printf("Enter the elements\n");
readarray(a,n);
ssort(a,n);
display(a,n);
}
106
22
55
1. We can pass entire two dimensional array to function like one dimensional array.
2. When we pass two dimensional array to a function, in the function definition formal argument, the
size of the column is must and size of the row is optional.
#include <stdio.h>
main()
{
void readmat(int [ ][10],int,int);
void matadd(int [ ][10],int [ ][10],int [ ][10],int,int);
void display(int [ ][10],int,int);
matadd(A, B, C,m,n);
printf("Matrix A is :\n");
display(A, m,n);
printf("Matrix B is :\n");
display(B, m,n);
printf("\nMATRIX C (= A + B) is:\n");
display(C, m,n);
} /* end of main */
107
for( j = 0; j < cols; j++)
scanf("%d", &X[i][j]);
} /* end of function read_matrix */
#include <stdio.h>
main()
{
void readmat(int [][10],int,int);
void matmul(int [][10],int [][10],int [][10],int,int,int);
void display(int [][10],int,int);
if(n!=p)
printf("multiplication not possible\n");
else
{
108
printf("\nEnter elements of matrix A \n");
readmat (A, m,n);
matmul(A, B, C,m,q,n);
printf("Matrix A is :\n");
display(A, m,n);
printf("Matrix B is :\n");
display(B, p,q);
printf("\nMATRIX C (= A X B) is:\n");
display(C, m,q);
}
} /* end of main */
Summary exercise:
1. Arrays hold homogeneous data and share a common name.
2. An array that contains single index is one dimensional array. An integer index is used to access the
elements from the range ‘0’ to ‘n-1’ where ‘n’ is the array size.
3. Multi-dimensional arrays contain multiple indexes.
4. Array name itself will give the base address of an array. So when a one dimensional array is passed to
function, call by reference mechanism takes place.
5. When two dimensional array is passed to function, in the function definition formal argument, the
size of the column is must and size of the row is optional.
Lecture topic quiz / MCQs: (All these quiz’s belongs to BL3 & BL4)
1. Test for the output of the following program, if the array begins at address 1200?
main()
{
intarr[] = {2,3,4,1,6};
printf("%d %d",arr, sizeof(arr));
}
2. Identify that the array name gives the base address in all the contexts?
3. Test for the output of the following program, if the array begins at address 65486 ?
main()
{
intarr[] = {12,14,15,23,45};
printf("%u %u",arr, &arr);
}
4. Experiment the expressions arr and &arrgives same for an array of 10 integers ? (arr is the array variable
name)
5. Test for the output of the following program, if the array begins at address 65486 ?
main()
{
intarr[] = {12,14,15,23,45};
printf("%u %u",arr + 1, &arr + 1);
110
}
6. Test for the output of the following program ?
main()
{
float a[] = {12.4,2.3,4.5,6.7};
printf("\n %d",sizeof(a) / sizeof(a[0]));
}
7. Test for the output of the following program if the array begins at 65472?
main()
{
int a[3][4] = {
1,2,3,4,
4,3,2,1,
7,8,9,0
};
printf("\n %u %u",a + 1, &a + 1);
}
8. Inspect if we pass the name of a 1-D int array to a function it decays into a pointer to an int. If we pass the
name of a 2-D array of integers to a function what would it decay into?
111
c) 1
d) 2
5. printf(“%d”,a*3+*4+); In this statement which element is accesses?(BL1)
a) 4th element in the 3rd row of the matrix
b) 3rd element in the 4th row of the matrix
c) 5th element in the 4th row of the matrix
d) 4th element in the 5th row of the matrix
8. In the binary search if the key exist in the middle of the array. How many comparison need to be done.
(BL2)
a) 1
b) n/2
c) n
d) 0
9. In the linear search if the key exist in the middle of the array. How many comparison need to be done.
(BL2)
a) 1
b) n/2
c) n
d) 0
10. Consider a two dimensional array int a[5][5]. Assume each element occupies 2 bytes. The base address of
the array is 1000, elements are stores in row major order. What is the address of a[3][2]?
a) 1034(BL3)
b) 1030
c) 1036
d) 1032
11. The maximum dimensional array variable that can be declared in C. (BL2)
a) 1
b) 2
112
c) 3
d) No limit
12. Pick the operations which cannot be done on an array variable ‘a’ (BL2)
a) ++a, a++
b) a+1, 1+a, a=a+1, a+=1
c) a[i]++, i[a]++, *(a+i)++, *(i+a)++
i. both a and b are not allowed
ii. both a and c are not allowed
iii. both c and b are not allowed
iv. none
13. Pick the uses of arrays (BL2)
a) No need to declare many separate variable to handle many data items
b) Using single variable and subscript all the data items can be accessed
c) Maintaining the code is easy and remembering of variables is reduced on programmers side
d) All
14. Pick the uses of multidimensional arrays (BL2)
a) Able to store data in rows and columns
b) It is an array of arrays
c) In all the dimensional the index will start from ‘0’ and ends at ‘sizeofthedimension-1’
d) All
15. In CBIT in the academic year 2020-2021 first year contains 20 sections, in each section 60 students exist,
each student is having 6 courses. The secured by all students in all subjects in 20 sections need to be
stored. Pick the suitable multidimensional variable to be used to store the data. If data to be stored in row
major order of sections, students and subjects (BL3)
a) Marks[20][60[6];
b) Marks[60][20[6];
c) Marks[20][6[60];
d) Marks[6][60[20];
113
● Count how many duplicates exist
● Swap any two elements in the matrix based on user choice
114
Course Code: 20CS C01
Instructors Name:
Name Email
Smt. E Kalpana ekalpana_cse@cbit.ac.in
Objective:
Outcome:
● learn about one-dimensional and two-dimensional strings and the way they are declared,
initialized, manipulated, inputted, and displayed.
115
Scope:
The Module covers the following topics: Introduction to Strings, Strings representation, String
operations with examples, Case Study on arrays
While the topics are taught using a C language, the intent of the course is to teach a programming
methodology and also a laboratory component that involves development and testing of iterative
and procedural programs using one-dimensional and two-dimensional Strings.
Text andReference:
(a) Text Book:
nd
Pradeep DeyandManasGhosh,―ProgramminginC‖,OxfordPress,2 Edition,2017
E.Balaguruswamy,ProgramminginANSIC,TataMcGraw-Hill.
L.25 String operations with To know about array of strings, its declaration,
examples. initialization, other operations, manipulations,
and uses.
L.26 Case Study on arrays and Discussion The general purpose of a case study is to:
of Previous Question Papers. → describe an individual situation (case), in
detail;
→ identify the key issues of the case;
→ analyse the case using relevant theoretical
concepts from the module;
→ recommend a course of action for that
particular case .
116
Lecture title L.24 to L.26
Date
Key topics :StringsIntroduction, strings representation, string operations with examples.
Case study using arrays.
Declaration of a String:
Strings can be declared like one-dimensional arrays. For example,
char str[30];
char text[80];
String Initialization:
Character arrays or strings allow a shorthand initialization,
for example,
char str[9] = ―I like C‖;
which is the same as
char str[9] = {‗I‘,‗ ‘,‗l‘,‗i‘,‗k‘,‗e‘,‗ ‘,‗C‘,‗\0‘};
Whenever a string, enclosed in double quotes, is written,C automatically creates an array of
characters containing that string, terminated by the \0 character. C language allows the alternative
notation
char msg[] = ―Hello‖;
that is always used in practice. It should be noted that the size of the aggregate ‗msg‘ is six bytes,
five for the letters and one for the terminating NUL. There is one special case where the null
character is
not automatically appended to the array. This is when the array size is explicitly specified and the
number of initializers completely fills the array size. For example, char c[4] = ―abcd‖; Here, the
array c holds only the four specified characters, a, b, c, and d. No null character terminates the
array.
String Representation:
117
String Input and Output:
Printing Strings:
The conversion type ‗s‘ may be used for output of strings using printf(). Width and precision
specifications may be used with the %s conversion specifier. The width specifies the minimum
output field width; if the string is shorter, then space padding is generated. The precision specifies
the maximum number of characters to display. If the string is too long, it is truncated. A negative
width implies left
justification of short strings rather than the default right justification. For example,
printf(―%7.3s‖,name);
This specifies that only the first three characters have to be printed in a total field width of seven
characters and right justified in the allocated width by default. We can include a minus sign to
make it left justified (%-7.3). The following points should be noted:
● When the field width is less than the length of the string, the entire string is printed.
● The integer value on the right side of the decimal point specifies the number of characters
to be printed.
● When the number of characters to be printed is specified as zero, nothing is printed.
● The minus sign in the specification causes the string to be printed as left justified.
Example program:
#include <stdio.h>
int main()
{
char s[]=―Hello, World‖;
printf(―>>%s<<\n‖,s);
printf(―>>%20s<<\n‖,s);
printf(―>>%-20s<<\n‖,s);
printf(―>>%.4s<<\n‖,s);
printf(―>>%-20.4s<<\n‖,s);
printf(―>>%20.4s<<\n‖,s);
return 0;
}
Output:
118
The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the
input/output operations of the strings.
C gets() function
The gets() function enables the user to enter some characters followed by the enter key. All the
characters entered by the user get stored in a character array. The null character is added to the
array to make it a string. The gets() allows the user to enter the space-separated strings. It returns
the string entered by the user.
char[] gets(char[]);
119
The gets() function is risky to use since it doesn't perform any array bound checking and keep
reading the characters until the new line (enter) is encountered. It suffers from buffer overflow
Example:
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
C puts() function
The puts() function is very much similar to printf() function. The puts() function is used to print the
string on the console which is previously read by using gets() or scanf() function. The puts()
function returns an integer value representing the number of characters being printed on the
console. Since, it prints an additional newline character with the string, which moves the cursor to
the new line on the console, the integer value returned by puts() will always be equal to the number
of characters present in the string plus 1
int puts(char[]);
Example:
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
120
Example:
This program checks whether character is alphanumeric or not.
/* C example program of isalnum().*/
#include<stdio.h>
#include<ctype.h>
int main()
{
char ch;
if(isalnum(ch))
printf("%c is an alphanumeric character.\n",ch);
else
printf("%c is not an alphanumericcharacter.\n",ch);
return 0;
}
121
String Manipulation:
The string header, string.h, provides many functions useful for manipulating strings or character
arrays. Some of these are mentioned below:
Example programs:
The given code shows the use of the strcpy()function.
#include <string.h>
int main()
{
char s1[] =―Hello, world!‖;
char s2[20];
strcpy(s2, s1);
puts (s2);
return 0;
}
The following program illustrates the comparison of two strings.
122
#include <stdio.h>
#include <string.h>
int main()
{
char x[50],y[]=―a programming example‖;
strcpy(x,―A Programming Example‖);
if(strcmp(x,―A Programming Example‖) == 0)
printf(―Equal \n‖);
else
printf(―Unequal \n‖);
if( strcmp(y,x) == 0)
printf(―Equal \n‖);
else
printf(―Unequal \n‖);
return 0;
}
int main()
{
char s[30] =―Hello,‖;
charstr[] =―world!‖;
printf(―%s\n‖, s);
strcat(s, str);
printf(―%s\n‖, s);
return 0;
}
Declaration:
A two-dimensional array of strings can be declared as follows:
<data_type><string_array_name>[<row_size>][<columns_size>];
Consider the following example on declaration of a two-dimensional array of strings.
char s[5][30];
Initialization:
Two-dimensional string arrays can be initialized as shown
123
Here every row is a string. That is, s[i] is a string.
Examples:
The following program demonstrates how an individual string of an array of strings can be used to
take input from the user. As mentioned before, each row (i.e., s[i], if ‗s‘ is the array of strings) of
an array of strings is a string.
#include <stdio.h>
int main()
{
inti;
char s[10][30], t[30];
for(i=0;i<10;i++)
scanf(―%s‖,s[i]);
for(i=0;i<10;i++)
printf(―\n%s‖,s[i]);
return 0;
}
The following program sorts an array of strings using bubble sort. Note here that strcmp() is used
to compare the string. strcpy() is used for interchanging the strings.
#include <stdio.h>
#include <string.h>
int main()
{
char s[10][30], t[30];
inti,j,n;
printf(―\n how many strings:‖);
scanf(―%d‖,&n);
printf(―\n enter the strings:\n‖);
for(i=0;i<n;i++)
scanf(―%s‖,s[i]);
printf(―\n **starting comparing and sorting**‖);
for(i=0;i<n-1;i++)
for(j=i+1; j<n; ++j)
124
if(strcmp(s[i],s[j])>0)
{
strcpy(t,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],t);
}
printf(―\n **sorted array**\n‖);
for(i=0;i<n;i++)
printf(―\n%s‖,s[i]);
return 0;
}
Summary:
● Strings are an array of characters terminated by ‗\0‘.
● Character arraysor strings allow a shorthand initialization.
● Although C does not have astring data type, it allows string constants.
● There are a set of input andoutput functions in C suitable for handling strings.
● The manipulation ofstrings can be carried out with the help of several functions provided
inthe <string.h>file.
● Arrays can also be formed with strings.These arecategorized as two-dimensional arrays.
MCQs:
1. Which function will you choose to join two words?(L1)(CO4)
a) strcpy()
b) strcat()
c) strncon()
d) memcon()
Answer: b
2. Show the function that appends not more than n characters.(L2)(CO4)
a) strcat()
b) strcon()
c) strncat()
d) memcat()
Answer: c
3. Which of the following is the variable type defined in header <string.h>?(L1)(CO3)
a) sizet
b) size
c) size_t
d) size-t
Answer: c
4. Identify whether NULL is the macro defined in the header <string.h>.(L3)(CO5)
a) true
125
b) false
Answer: a
5. Recall is there any function declared as strstr()?(L1)(CO4)
a) true
b) false
Answer: a
6. Analyze which of the following function returns a pointer to the located string or a null
pointer if string is not found.(L4)(CO4)
a) strtok()
b) strstr()
c) strspn()
d) strrchr()
Answer: b
7. Identify which of the given function is used to return a pointer to the located
character?(L3)(CO4)
a) strrchr()
b) strxfrm()
c) memchar()
d) strchr()
Answer: d
8. Analyze what will be the output of the following C code?(L4)(CO5)
char str1[] = "Helloworld ";
char str2[] = "Hello";
intlen = strspn(str1, str2);
printf("Length of initial segment matching %d\n", len );
a) 6
b) 5
c) 4
d) no match
Answer: b
9. Identify thefunction that returns the number of characters that are present before the
terminating null character.(L3)(CO4)
a) strlength()
b) strlen()
c) strlent()
d) strchr()
Answer: b
10. Examine the output of the following C code?(L4)(CO5)
char str1[15];
char str2[15];
int mat;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
mat= strncmp(str1, str2, 4);
if(mat< 0)
printf("str1 is not greater than str2");
else if(mat> 0)
126
printf("str2 is is not greater than str1");
else
printf("both are equal");
Expected Questions:
Short answer type:
17. Why do we have a null character (‗\0‘ or NUL) at the end of a string? (L1)(CO5)
18. Apply character manipulation functions and develop a C program that will capitalize all the
letters of a string. (L3,L6)(CO4)
19. Analyze appropriate string manipulation functions and develop a C program that deletes a
word from a sentence. Note that the word may appear any number of times.(L4,L3)(CO4)
127
20. Develop a C program that reads a line of text and counts all occurrences of a particular
word.(L6)(CO5)
21. Explain any four string manipulation functions from <string.h> library with examples.
(L2)(CO4)
128
Unit IV
Course Code: 20CSC01
Course Title: Programming for Problem Solving
Name Email
M Venkata Krishna Reddy krishnareddy_cse@cbit.ac.in
Objective:
Outcome:
1. On Successful completion of the course, students will be able to Apply arrays, pointers,
structures, and unions to solve mathematical and scientific problems.
.
Scope:
The Module covers the following topics: Basic pointers, Pointers with Arrays and Dynamic memory
allocation.
While the topics are taught using a C language, the intent of the course is to teach the usage of pointers along
with arrays to solve large complex problems.
Text and Reference:
TB1: M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India
129
Learning Private Limited 2018.
TB2: AKSharma―ComputerFundamentalsand Programming‖, 2nd Edition, University
Press,2018.
TB3: Pradeep DeyandManasGhosh,―ProgramminginC‖,OxfordPress,2nd Edition,2017.
● Pointers
● Arrays and Pointers
● Dynamic Memory Allocation
Definitions:
Call by address: facilitating the changes made to a variable in the called function to become permanently
available in the function from where the function is called.
Call-by-value :A particular way of implementing a function call, in which the arguments are passed by
their value (i.e., their copies).
Dangling pointer: A pointer pointing to a previously meaningful location that is no longer meaningful;
usually a result of a pointer pointing to an object that is de allocated without resetting the value of the
pointer.
Dynamic memory allocation :The process of requesting and obtaining additional memory segments
during the execution of a program.
Function pointer: A function has a physical location in memory that can be assigned to a pointer. Then it
is called function pointer. This address is the entry point of the function and it is the address used when
the function is called.
Garbage collection: If only implicit dynamic allocation is allowed then deallocation must also be done by
implicit means, which is often called garbage collection.
131
Null pointer: A null pointer is a special pointer value that points nowhere. I is initialized with value 0 or
NULL.
Void pointer :A void pointer is a special type of pointer that can point to any data type.
132
Memory Layout:
●
Attributes of variables
● Name
● Location (address)
● Type and value
● Scope, lifetime
● Operations
● The location of a variable is decided by the compiler and the operating system at run-time.
● The initial value of a variable without assigning a value, the result is a garbage value.
Example:
● the declaration int i=3;
tells the C compiler to
● reserve space in memory to hold the integer value
● associate the name i with this memory location
● store the value 3 at this location
● The other pointer operator available in C is ‗*‘, called the ‗value at address‘ operator. It returns
the value stored at a particular address. It is also called indirection operator/ dereference
operator.
Pointer Variable :
Definition :
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to store
any variable address.
The general form of a pointer variable declaration is
Syntax : type *var-name;
● A pointer provides a way of accessing a variable without referring to the variable directly.
● A pointer is a variable that holds the memory address of another variable.
● A pointer has two parts,
● The address that it holds and
● The value pointed by that address
135
the size of double pointer is 2
the size of character pointer is 2
In GCC:
the size of integer pointer is 4
the size of fl oat pointer is 4
the size of double pointer is 4
the size of character pointer is 4
Initializing Pointers :
A Pointer is similar to any other variable excepts that it holds only memory address and therefore
it needs to be initialized with a valid address before it can be used.
● Unlike a simple variable that stores a value, a pointer must be initialized with a specified
address prior to its use.
● A pointer should be initialized with another variable‘s memory address, with 0, or with the
keyword NULL prior to its use; otherwise the result may be a compiler error or a run-time
error.
Example :
#include <stdio.h>
int main()
{
int *p; /* a pointer to an integer */
printf(“%d\n”,*p);
return 0;
}
Assigning Pointers :
● A pointer is bound to a specific data type (except pointer to void) . A pointer to an int cannot
hold the address of a character variable in which case a compiler error would result.
● The following pointer initializations are invalid.
int a=6, *ip;
float *p;
char ch=’A’;
p=&a;
ip=&ch:
136
From the Below Figure :
● r points to the same address that p points to, which is the address of i.
● We can assign pointers to one another, and the address is copied from the right-hand
side to the left- hand side during the assignment.
● To print the memory address stored in pointers and non-pointer variables using the %p conversion
specifier and to learn the use of the %p conversion specifier.
● Addresses must always be printed using %u or %p or %x. If %p is used, the address is printed in
hexadecimal form. If %u is used, address is printed in decimal form.
Example 1 :
/* Program to illustrate Pointer Initialization*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
*p=&a;
printf(“\n*p = %p”, *p);
return 0;
}
Example 2 :
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
p=&a;
137
printf(“\n*p = %p”, *p);
return 0;
}
Output:
p = 0022FF2C
● No
● In C, pointers are not allowed to store any arbitrary memory address, but they can only store
addresses of variables of a given type.
● Consider the following code:
int *pi;
pi= (int*)1000;
*pi = 5;
● Location 1000 might contain the program. Since it is a read only, the OS will throw up a
segmentation fault.
Example:
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main()
{
int num = 15;
int *iPtr = #
printf(“ The value of a num is %d”, num);
num = 100;
printf(“ The value of a num after num=10 is %d”, num);
*iPtr = 25;
printf(“ The value of a num after *iPtr = 15 is %d”, num);
Output:
The value of num is 15
The value of num after num = 100 is 100
The value of num after *iPtr = 25 is 25
138
Void Pointer :
● A void pointer is a special type of pointer.
● It can point to any data type, from an integer value or a float to a string of characters.
● Its sole limitation is that the pointed data cannot be referenced directly (the asterisk * operator
cannot be used on them) since its length is always undetermined. Use type casting or
assignment
Example:
/* Program to illustrate Void Pointer */
int main()
{
int a=10,
double b=3.1415;
void *vp;
vp=&a;
printf(“\n a=%d”, *((int*)vp));
vp=&b;
printf(“\n a= %d”, *((double *)vp));
return 0;
}
Output :
a= 10
b= 3.141500
Null Pointer :
● Null pointer is a special pointer that points nowhere. That is, no other valid pointer to any other
variable or array cell or anything else will ever be equal to a null pointer.
#include <stdio.h>
int *ip = NULL;
● It is also possible to refer to the null pointer using a constant 0,
int *ip = 0;
● NULL is a constant that is defined in the standard library and is the equivalent of zero for a
pointer.
● NULL is a value that is guaranteed not to point to any location in memory.
Use of Pointers :
Call by reference : One of the typical applications of pointers is to support call by reference. However,
139
C does not support call by reference as do other programming languages such as PASCAL and
FORTRAN.
● Typically a function call is made to communicate some arguments to the function.
● C makes use of only one mechanism to communicate arguments to a function: call
by value.
● This means that when a function is called, a copy of the values of the arguments is
created and given to the function.
● Call by reference: Simulated by the use of pointers called ―call by address‖.
Example:
/* Program to illustrate call by Value*/
void swap(int a, int b)
{
int temp; temp=a; a=b; b=temp;
}
int main()
{
int x=5,y=10;
void swap(int,int); printf(“%d %d\n”,x,y);
swap(x,y);
printf(“%d %d\n”,x,y);
return 0;
}
Output:
5 10
5 10 No swapping
140
void swap(int *,int *);
printf(“%d %d\n”,x,y);
swap(&x, &y);
printf(“%d %d\n”,x,y); return 0;
}
Output:
5 10
10 5
Returning more than one value from a function:
Example :
/* Program to print area by illustrating returning more than one value from a function*/
#include <stdio.h>
int main()
{
float r, area, perimeter;
float compute(fl oat, fl oat *); //function prototype
printf(“\n enter the radius of the circle:”);
scanf(“%f”,&r);
area=compute(r, &perimeter); //function call
printf(“\n AREA = %f”, area);
printf(“\n PERIMETER = %f”, perimeter); return 0;
}
float compute(float r, fl oat *p)
{
float a;
a=(fl oat)3.1415 * r * r;
*p=(fl oat)3.1415 * 2 * r;
return a;
}
141
One-dimensional Arrays and Pointers :
● An array is a non-empty set of sequentially indexed elements having the same type of data.
● Each element of an array has a unique identifying index number. Changes made to one
element of an array does not affect the other elements.
● An array occupies a contiguous block of memory. The array a is laid out in memory as a
contiguous block, as shown.
Example :
/* Program to illustrate arrays*/
#include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array*0+);
return 0;
}
Output:
2147478270
2147478270
A pointer variable (of the appropriate type) can also be used to initialize or point to the
first element of the array.
142
Below figure depicts the equivalence among array notation and pointer notation.
● For any one-dimensional array a and integer i, the following relationships are always true.
143
a*i+ ≡ *(a+i) ≡ *(i+a) ≡ i*a+
● An array may be passed to a function, and the elements of that array may be modified without
having to worry about referencing and dereferencing.
● All array names that are function parameters are always converted into pointers by the compiler.
● Because when passing an array to a function, the address of the zero-th element of the array is
copied to the pointer variable which is the formal parameter of the function.
● However, arrays and pointers are processed differently by the compiler, represented differently
at runtime.
Differences between Array Name & Pointer :
● When memory is allocated for the array, the starting address is fixed, i.e., it cannot be changed during
program execution. Therefore, array name is an address constant.
● The & (address of) operator normally returns the address of the operand. However, arrays are the
exception.
● When applied to an array (which is an address), it has the same value as the array reference without
the operator.
● This is not true of the equivalent pointers, which have an independent address.
● The sizeof operator returns the
● Size of the allocated space for arrays in case of arrays.
● 4 or 8 bytes depending on the machine architecture.
Pointer Arithmetic :
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can on a numeric value. There are four arithmetic operators that
can be used on pointers: ++, --, +, and –
145
Pointers and Strings :
● Strings are one-dimensional arrays of type char. By convention, a string in C is terminated by
the end-of-string sentinel \0, or null character.
● A string constant is treated by the compiler as a pointer.
● For a string, the number of elements it has need not be passed to a function because it has the
terminating null character
Array of Pointers :
● An array of pointers can be declared very easily.
Example: int *p[20];
● Declares an array of 20 pointer, each of which points to an integer.
st nd
● 1 pointer is p[0], 2 is p[1], and so on up to p[19] .
● These start off as uninitialized—they point to some unknown point in memory. We
could make them point to integer variables in memory thus.
Example :
146
Pointers to Array :
We can declare a pointer to a simple integer value and make it point to the array as is done
normally.
Example :
int v[5] = {1004, 2201, 3000, 432, 500};
int *p = v;
printf(“%d \n”, *p);
This piece of code displays the number, which the pointer p points to, that is the first number in the
array, namely 1004.
we can use instructions such as += and -= to refer to different elements in the array.
147
Difference between an array of pointers and a pointer to an array
148
Two-dimensional array and Pointers :
A two-dimensional array in C is treated as a one dimensional array whose elements are one-dimensional
arrays (the rows).
● C does not do run-time range checking of array subscripts.
● In C the rightmost subscript of a two-dimensional array varies faster than the leftmost.
● Multi-dimensional array is stored in a ‗row major addressing‘ format.
● The following expressions are equivalent for a two dimensional array
a[i][j]= *(a[i]+ j) = (*(a + i))[j] = *(*(a + i)+ j)
● Arrays of dimension higher than two work in a similar fashion.
● Let us describe how three-dimensional arrays work.
● If the following is declared
int a[7][9][2];
● In case of multi-dimensional arrays all sizes except the first must be specified.
Example 1 :
149
/* Program to illustrate matrix addition – two dimensional array*/
Example 2 :
int *A[10],*B[10],*C[10],m, n, i;
printf("\nEnter the values of m and n: ");
scanf("%d %d",&m,&n); //read the values of m and n
for(i=0;i<m;++i) //allocate memory dynamically
{
A[i]=(int*)malloc(n*sizeof(int));
B[i]=(int *)malloc(n*sizeof(int));
C[i]=(int *)malloc(n*sizeof(int));
}
getdata(A,m,n);
getdata(B,m,n);
add(A,B,C,m,n);
display(C,m,n);
Example 3 :
151
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
scanf("%d",x[i]+j); //or &x[i][j] or *(x+i)+j
return;
}
void display(int *x[10], int m, int n)
{
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
printf("%4d",*(x[i]+j)); //or x[i][j] or *(*(x+i)+j)
printf("\n");
}
return;
}
Example 4 :
int **A,**B,**C, i, m, n;
printf("\nEnter the values of m and n: "); scanf("%d %d",&m,&n);
//read the values of m and n
for(i=0;i<m;++i)
A[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;++i)
B[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;++i)
C[i]=(int *)malloc(n*sizeof(int));
Example 5 :
printf("\n");
}
return;
}
Pointers to Functions :
C also allows pointers to point to functions and it is one of the powerful feature
Declaration of a Pointer to a Function
return_type (*fptr) (argument_type1, argument_type2, ..);
Example:
int(*fp)(int, char, float); //fp is a pointer to a function that take one int, one char, one float
and returns an int
● Parenthesis are important and int *fp(); declares a function that returns an integer pointer
#includestdio.h>
#include<stdlib.h>
int main()
{
155
int N,*a,i,s=0;
printf(“\n enter no. of elements of the array:”);
scanf(“%d”,&N);
a=(int *)malloc(N*sizeof(int));
if(a==NULL)
{
printf(“\n memory allocation unsuccessful...”);
exit(0);
}
printf(“\n enter the array elements one by one”);
for(i=0; i<N;++i)
{
scanf(“%d”,&a*i+)); /* equivalent statement
scanf(“%d”,(a+i));*/
s+=a[i];
}
printf(“\n sum is %d ”,s); return 0;
}
Freeing Memory :
● Dynamically allocated memory is de-allocated with the free function. If p contains a pointer
previously returned by malloc(), a call such as free(p);
● calloc() requires two parameters, the first for the number of elements to be allocated and the
second for the size of each element, whereas malloc() requires one parameters.
● calloc() initializes all the bits in the allocated space set to zero whereas malloc() does not do this.
● P=calloc(m, n) is essentially equivalent to p = malloc(m * n);
● malloc(0) results are unpredictable. It may return some other pointer or it may return some other
implementation-dependent value.
156
Memory Leak and Memory Corruption
Dangling pointer :
A pointer may be used to hold the address of dynamically allocated memory. After this memory is
freed with the free() function (in C), the pointer itself will still contain the address of the released
block. This is referred to as a dangling pointer.
Memory corruption :
Memory when altered without an explicit assignment due to the inadvertent and unexpected altering of
data held in memory or the altering of a pointer to a specific place in memory is known as memory
corruption.
Advantages of Pointers :
● Pointers save memory space
● Execution time with pointer is fast because data is manipulated with address i.e directly
with memory location.
● Memory is accessed efficiently with pointers
● Dynamic memory is allocated
● Pointers are used with data structures.
● Pointers are useful for representing two dimensional and multi dimensional Arrays.
Drawbacks of Pointers :
● A programmer is likely to commit mistakes such as typographical mistakes and providing wrong
offsets.
● Porting the code to other implementations would require changes, if data type sizes differ. This
would lead to portability issues.
157
● Pointers have data types but the size of a pointer variable is always 4-bytes (in a 32-bit machine)
8-bytes (in a 64-bt machine) whatever the data type is used in declaring it.
Summary exercise:
6. [Pointer is a memory variable that holds address of another variable.
7. Certain Arithmetic Operations can be performed on Pointers.
8. An array name itself is a pointer. Whenever address are stored as array elements, such an
array is called as array of pointers. 2D arrays can be represented using pointers.
9. Dynamic Memory Allocation is the process by which the required memory address is obtained
without an explicit declaration.
3.INT *P; L3
INT A=100;
P=&A;
PRINTF("%d %d",*P,P);
A.100,1000
B. 10,1000
C. 10
D. 1000
158
D.Double
7.The operator used to get value at address stored in a pointer variable is...... L1
A.*
B.&
C.&&
D.||
8. What would be the equivalent pointer expression for referring the array element a[i][j][k][l].
L3
A.((((a+i)+j)+k)+l)
B.*(*(*(*(a+i)+j)+k)+l)
C.(((a+i)+j)+k+l)
D.((a+i)+j+k+l)
Long Questions :
1. Write a program to calculate length of the string using pointers. L6
2. Write a C program to illustrate the use of indirection operator to access the value pointed by a
pointer. L6
3. What are the features of pointers? Write a C program to print address of a variable. L3
4. Explain the declaration of pointers and pointer to pointer with examples. L4
5. Explain the concept of array of pointers with examples. L3
6. With proper examples explain different arithmetic operations on pointers. L3
7. Explain the concept of functions returning pointers with example. L3
8. Write a C program to read and print an array of elements using pointers. L6
9. Write a C program to read and display multiple strings using pointers. L6
10.Write a C Program to perform matrix addition using dynamic memory allocation. L6
160
UNIT IV
Name Email
G.Shanmukhi Rama Shanmukhi.rama_cse@cbit.ac.in
Objective:
Outcome:
1. On Successful completion of the course, students will be able to Apply structures, and
unions to solve mathematical and scientific problems.
161
Scope:
The Module/Unit covers the following topics: Structure definition, initialization and accessing the
members of a structure, nested structures, structures and functions, self- referential structures,
unions, and enumerated data types.
While the topics are taught using a C language, the intent of the course is to teach the usage of
Structures along with functions to solve large complex problems.
TB1: M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India
Hall.
162
L.33 Accessing Members of Structures, To know how to access members of
Nested Structures. structures and to understand how to use
nested structures.
L.34 Self Referential Structures. To understand the concept of self
Referential Structures
L.35 Structures and Functions. To know how to pass and return structure
as argument in functions
L.36 Unions and Enumerated Types. To understand how to define, represent,
and how to use Unions and Enumerated
Types.
Definition
Arrays allow defining type of variables that can hold several data items of the same kind. Similarly
structure is another user defined data type available in C that allows combining data items of different
kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book−
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member. The format of the struct statement is as follows –
163
data_typestruct_member n;
} [one or more structure variables separated by comma];
The structure_nameis optional and each struct_memberis a normal variable definition, such as int
i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final
semicolon, you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure –
struct Books
{
char title[50]; char author[50]; char subject[100]; intbook_id;
}book;
To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we
wish to access. You would use the keyword structto define variables of structure type.
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
Struct Books Book1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare Book2
of type Book*/
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
164
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n",Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n",Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id); return 0;
}
When the above code is compiled and executed, it produces the following result
Book 1 title : C Programming
Book 1 author :Nuha Ali
Nested structures
Structure written inside another structure is called as nesting of two structures. Nested Structures
are allowed in C Programming Language. We can write one Structure inside another structure as member
of another structure.
Example:
structdate
{
int date;
int month;
int year;
};
struct Employee
165
{
charename[20];
intssn;
float salary;
struct date doj;
}emp1;
Structure members are accessed using dot operator. ‘date‘ structure is nested within Employee
Structure. Members of the ‘date‘ can be accessed using ’employee’ emp1 &doj are two
structure names (Variables)
Accessing Month Field : emp1.doj.month Accessing day Field : emp1.doj.day Accessing year Field
:emp1.doj.year
#include <stdio.h>
struct Employee
{
charename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
166
When the above code is compiled and executed, it produces the following result
Employee Name :Pritesh Employee SSN : 1000 Employee Salary : 1000.500000 EmployeeDOJ :
22/6/1990
Arrays of Structures
We may declare the structure variable as an array by using index. Arrays of structures are passed
using the following syntax,
structstructure_name{ data_type struct_member1; data_typestruct_member2;
data_typestruct_membern;
};
structstructure_namestruct_variable[index_value];
You can pass a structure as a function argument in the same way as you pass any other variable or
pointer. Like all other types, we can pass structures as arguments to a function. In fact, we can pass
individual members, structure variables, a pointer to structures etc to the function. Similarly, functions can
return either an individual member or structures variable or pointer to the structure.
We can pass individual members to a function just like ordinary variables.The following program
demonstrates how to pass structure members as arguments to the function.
167
1
2
3
4
5
6
7
8 #include<stdio.h>
9
1 /*
0 structure is defined above all functions so it is
1 global.
1 */
1
2 structstudent
1 {
3 charname[20];
1 introll_no;
4 intmarks;
1 };
5
1 voidprint_struct(charname[],introll_no,intmarks);
6
1 intmain()
7 {
1 structstudentstu={"Tim",1,78};
8 print_struct(stu.name,stu.roll_no,stu.marks);
1 return0;
9 }
2
0 voidprint_struct(charname[],introll_no,intmarks)
2 {
1 printf("Name: %s\n",name);
2 printf("Roll no: %d\n",roll_no);
2 printf("Marks: %d\n",marks);
2 printf("\n");
3 }
2
4
2
5
2
6
2
168
7
2
8
2
9
When the above code is compiled and executed, it produces the following result
Name: Tim
Roll no: 1
Marks: 78
170
9
When the above code is compiled and executed, it produces the following result
Name: George
Roll no: 10
Marks: 69
Just as we can return fundamental types and arrays, we can also return a structure from a
function. To return a structure from a function we must specify the appropriate return type in the
function definition and declaration. Consider the following example:
struct player check_health(struct player p);
{
...
}
This function accepts an argument of type struct player and returns an argument of type struct
player.
The following program demonstrates how we can return a structure from a function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is
171
5 global.
6 */
7
8 structplayer
9{
1 charname[20];
0 floatheight;
1 floatweight;
1 floatfees;
1 };
2
1 voidprint_struct(structplayerp);
3 structplayerdeduct_fees(structplayerp);
1
4 intmain()
1 {
5 structplayerp={"Joe",5.9,59,5000};
1 print_struct(p);
6 p=deduct_fees(p);
1 print_struct(p);
7
1 return0;
8 }
1
9 structplayerdeduct_fees(structplayerp)
2 {
0 p.fees-=1000;
2 returnp;
1 }
2
2 voidprint_struct(conststructplayerp)
2 {
3 printf("Name: %s\n",p.name);
2 printf("Height: %.2f\n",p.height);
4 printf("Weight: %.2f\n",p.weight);
2 printf("Fees: %.2f\n",p.fees);
5
2 printf("\n");
6 }
2
7
2
8
2
172
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
When the above code is compiled and executed, it produces the following result
Name: Joe
Height: 5.90
Weight:
59.00
Fees: 5000.00
Name: Joe
Height: 5.90
Weight:
59.00
Fees: 4000.00
You can define pointers to structures in the same way as you define pointer to any other variable
–
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To
find the address of a structure variable, place the '&'; operator before the structure's name as follows –
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the
→ operator as follows –
struct_pointer->title;
The following program demonstrates how to access structure members using pointers.
#include <stdio.h>
#include <string.h>
struct Books{
chartitle[50];
char author[50];
char subject[100];
int book_id;
};
174
/* function declaration */ voidprintBook(struct Books *book ); int main( ) {
structBooksBook1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare Book2
of type Book*/
/* book 1 specification */
strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
175
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
structnode {
intdata1;
chardata2;
structnode* link;
};
intmain()
{
structnode ob;
return0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’
is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing,
as by default it contains garbage value.
structnode {
intdata1;
chardata2;
structnode* link;
};
Int main()
176
{
structnode ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
Unions
A union is a special data type available in C that allows storing different data types in the same
memory location. You can define a union with many members, but only one member can contain a value
at any given time. Unions provide an efficient way of using the same memory location for multiple-
purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your program.
The format of the union statement is as follows–
177
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as int i;
or float f; or any other valid variable definition. At the end of the union's definition, before the final
semicolon, you can specify one or more union variables but it is optional. Here is the way you would
define a union type named Data having three members i, f, and str–
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple types of
data. You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by a character string.
The following example displays the total memory size occupied by the above union –
#include <stdio.h>
#include <string.h>
union Data {
inti; float f;
char str[20];
};
Int main( )
{
union Data data;
printf("Memorysizeoccupiedbydata:%d\n",sizeof(data));
return0;
}
Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult– Memorysizeoccupiedbydata:20
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish to
access. You would use the keyword union to define variables of union type.
178
The following example shows how to use unions in a program −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy(data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result – data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the value of
str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the
main purpose of having unions –
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
179
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy(data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result – data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
The enum keyword is also used to define the variables of enum type. There are two ways to
define the variables of enum type as follows.
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main()
{
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri,
Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn,
Thurs, Frid, Satu, Sund);
return 0;
180
}
When the above code is compiled and executed, it produces the following result –
Summary exercise:
Long Questions :
1. Define Structure and write the general syntax for declaring and accessing members. L1
2. How to copy and compare structure variables? Illustrate with example. L2
3. Write a C program that defines a structure employee containing the details such as empno,emp
name, department name and salary. The structure has to store 20 employees in anorganization.
Use the appropriate method to define the above details and define a function thatwill display
the contents? L3
4. Explain the Nested structures L2
5. Write a C program to read and display student details using structure. L3
6. Define union. Give the general template for union. L1
7. List out the differences between unions, structures and arrays L4
8. How data elements are stored under unions, explain with example? L3
9. Write a C program to illustrate the concept of structure within structure. L3
183
Course Code: 20CS C01
Course Title: PROGRAMMING FOR PROBLEM SOLVING
Instructors Name:
Name Email
Smt.B.PoonguzharSelvi poonguzharselvi_cse@cbit.ac.in
Objective:
Outcome:
On Successful completion of the course, students will be able to develop applications with
files.
Scope:
184
The Module/Unit covers the following topics:
Files: Introduction to files, file operations, reading data from files, writing data to files, error
handing during file operations – Basic files concepts and manipulation of data stored in a file.
While the topics are taught using a C language, the intent of the course is to teach a
programming methodology to handle files and also a laboratory component that involves
development and testing of programs to manipulate data in files.
TB1. M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India Learning
Private Limited 2018
nd
TB2. A K Sharma “Computer Fundamentals and Programming”, 2 Edition, University
Press, 2018
nd
TB3. Pradeep Dey and Manas Ghosh, “Programming in C”, Oxford Press, 2 Edition,
2017
II Reading data from files To under how to read data from a file.
III Writing data to files, error handing To under how to write data to a file with
during file operations. different error handling approaches.
185
Lecture title L.37
Date
Key topics / themes of the lecture : Introduction to files, file operations
INTRODUCTION TO FILES:
In real world application when data is large then it is necessary to stored on the disk in files.
A file represents a sequence of bytes. file is created in secondary storage. Files are of two types
text file and binary file.
C language provides access on files with high/low level functions .FILE is a structure defined
in standard input/output library.
The file pointer is created and used as FILE *fp; where fp is a file pointer
Types of files
1. Text File :
A text stream consist of a sequence of characters. they are grouped in line. stores the
data in the text form
2. Binary File :
It stores the data in the binary form (1's and 0's). A binary stream consists of a
sequence of data. They are stored in their memory representation.
Operations on Files
C language support a number of functions to perform basic operation on file
● creating a file
● opening a file
● writing into the file
● reading from the file
● close the file
files I/O functions to manipulate data in file :
fopen() : create a file or open an existing file
fclose() : close a file
getc() : read a character
putc() : write a character
fprintf() : write a formatted values
fscanf() : read set of values
getw() : read an integer
putw() :write an integer
Example:
#include<stdio.h>
int main()
{
FILE *fp; //creating a file pointer
fp=fopen("abc.txt","r"); // open a file
fclose(fp); // at the end close the file
return 0;
}
Summary exercise:
1. File pointer is created using FILE structure which is defined in stdio.h header file.
2. There 2 types of files: Text file, binary file
3. files can be opened in different modes to manipulate data using fopen() function.
Look over your lecture notes and create a quiz and/or discussion exercise based on the content.
Doing this will help when students are preparing for exams.
5. If the mode includes b after the initial letter in fopen function then what does it
indicates?(CO6)(BT 1)
a) text file
b) big text file
c) binary file
d) empty text
Answer: c) binary file
188
Answer:a) a) name of the file,mode
a) int type
b) char * type
c) struct type
d) float
Answer:c) struct type
9. For binary files, which of the following must be appended to the mode string. (CO6)(BT 1)
a) b
b) B
c) binary
d) 01
Answer: a) b
10. Select the reason for closing a file in C language.(CO6)(BT3)
a) fclose(fp) closes a file to release the memory used in opening a file.
b) Closing a file clears Buffer contents from RAM or memory.
c) Unclosed files occupy memory and PC hangs when on low memory.
d) All of these
Answer: d) All of these
Example: Write a program to read data from file using fgetc() method
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("myfile.txt","r");
do {
c = fgetc(fp);
if( c==EOF ) {
break ;
}
printf("%c", c);
} while(1);
fclose(fp);
return(0);
}
2. fgets():
It reads a string from a stream.
190
printf(" %s\n", output );
fclose(fp);
3. fscanf()
This function is to read strings from a file, but it stops reading after encountering the
first space character.
Syntax: int fscanf(FILE *fp, const char *format, [ argument, ...])
Example: Write a program to read data from file using fscanf() method
#include <stdio.h>
void main() {
FILE *fp;
char name[255];
int rollnum;
fp = fopen(“myfile.txt”, “r”);
fscanf(fp, "%s", name);
fscanf(fp, "%d", rollnum);
}
Reading data from binary file:
The following function is used for reading data from a Binary File.
1. fread()
Reads data from the given stream into the array .
Syntax: size_t fread(void *ptr, size_t sizeOfElements, size_t numberOfElements, FILE *fp);
Here,
ptr − the pointer to a block of memory with a minimum size of sizeOfElements *
numberOfElements bytes.
sizeOfElements − the size in bytes of each element to be read.
numberOfElements − the number of elements, each one with a size of size bytes.
fp − the pointer to a FILE object that specifies an input stream.
Example: Write a program to read data from file using fread() method
#include <stdio.h>
int main () {
FILE *fp;
char output[100];
191
/* Open file for reading */
fp = fopen("myfile.txt", "r");
Summary exercise:
[At the end of the lecture, briefly look back over your notes and give summarizing the top three
‘take-away’ points (these might include key knowledge and/or any suggested further reading the
lecturer recommends etc)]:
Look over your lecture notes and create a quiz and/or discussion exercise based on the content.
Doing this will help when students are preparing for exams.
2. What is the value of EOF which is defined in stdio.h header file?(CO6) (BT 1)
a) 1
b) 0
c) NULL
d) – 1
Answer: d) – 1
192
3. Infer the statement: "fwrite() can be used only with files that are opened in binary
mode".(CO6) (BT 2)
a) true
b) false
Answer: a) true
193
WRITING DATA TO FILES
We can write data to both text files as well as binary files.
Writing data to a text file:
The following 3 functions are used for writing data to a Text File.
1. fputc():
The fputc() function writes the character value of the argument c to the output stream
referenced by file pointer. It returns the written character written on success otherwise
EOF if there is an error.
Syntax: int fputc(int c, FILE * fp );
Example: Write a program to write data to a file using fputc() method
#include <stdio.h>
int main () {
FILE *fp;
int ch;
fp = fopen("myfile.txt", "w");
for( ch = 65 ; ch <= 92; ch++ ) {
fputc(ch, fp);
}
fclose(fp);
return 0 ;
}
2. fputs():
It writes the string to the output stream referenced by file pointer.
Syntax: char *fgets( char *str, FILE *fp );
#include <stdio.h>
main() {
FILE *fp;
194
fp = fopen(“myfilet.txt", "w");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
3. fprintf()
It sends formatted output to a stream..
Syntax: int fprintf(FILE *fp, const char *format, [ argument, ...])
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * fp;
fp = fopen ("file.txt", "w");
fprintf(fp, "%s %d", "CSE dept code is", 733);
fclose(fp);
return 0;
}
writing data to binary file:
#include<stdio.h>
int main () {
FILE *fp;
char str[] = "AI department is No.1";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
195
fclose(fp);
return 0;
}
Example: Demonstrate a program to access data from a file using random access file operations.
#include <stdio.h>
int main () {
FILE *fp;
int len;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("Total size of file.txt = %d bytes\n", len);
return 0;
}
196
3. clearerr(): this function is used to change the status of the file from error state
syntax: void clearerr(FILE *fp);
Summary exercise:
[At the end of the lecture, briefly look back over your notes and give summarizing the top three
‘take-away’ points (these might include key knowledge and/or any suggested further reading the
lecturer recommends etc)]:
1. fputc(), fprintf() and fwrite() methods are used for writing data to a file
2. fseek(),ftell() and rewind() methods used to access data from a file at random locations
3. feof() function is used for checking the end of file status
Review and revision:
Review and revision exercise (1) :
Look over your lecture notes and create a quiz and/or discussion exercise based on the content.
Doing this will help when students are preparing for exams.
Instructors Name:
Name Email
J Shiva Sai Jshivasai_cse@cbit.ac.in
Objective:
Outcome:
1. M.T. Somashekar ―Problem Solving with C‖, 2 nd Edition, Prentice Hall India Learning Private Limited 2018
nd
2. AKSharma―ComputerFundamentalsandProgramming‖,2 Edition, University Press,2018
nd
3. PradeepDeyandManasGhosh,―ProgramminginC‖,OxfordPress,2 Edition,2017
1. ByronGottfried,Schaum‘s‖OutlineofProgrammingwithC‖,McGraw- Hill.
2. BrianW.KernighanandDennisM.Ritchie,TheCProgrammingLanguage, Prentice Hall ofIndia.
3. E.Balaguruswamy,ProgramminginANSIC,TataMcGraw-Hill.
4. ReemaTharaja ―Introduction to C Programming‖, Second Edition, OXFORD Press,2015.
Lecture Notes
199
# include preprocessor directive:
Only defined at the top of the program definition and only white space and comments may appear before
preprocessor directive line. This directive includes a copy of the specified file or library. And is written
like so-
# include <filename>
or
If included inside <> then the compiler looks for the file in an implementation defined manner (or
system directory paths). If included inside a quote ― ‖ statement then it searches for the file in the same
directory as the program being written.
So if we include a file named file1 while writing a program name code.c which is being stored in
a folder called test. Then inclusion like so -- #include ―file1‖ will tell the compiler to look for the file
inside the test folder, It looks at neighboring folders or subfolders too but it starts its search in the test
folder.(This sub search option is compiler dependent).
A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define
directive. There are two types of macros: Object-like Macros, Function-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. Used to create symbolic constants and macros, meaning useful for renaming long
named data types and certain constants or values which is being used throughout the program definition.
When this line appears in a file, all subsequent occurrences of identifier that do not appear in
string literals will be replaced by the replacement text automatically before program compilation takes
place.
Replaces all subsequent occurrences of the symbolic constant PI with numeric constant 3.14159.
Symbolic constants enable the programmer to create a name for a constant and use that name throughout
program execution. If this needs to be modified ,it has to be done in the #define directive statement. After
recompilation all definitions get modified accordingly.
Function-like Macros
200
Here, MIN is the macro name.
201
Example for Function-like Macros :
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
Output:
Minimum between 10 and 20 is: 10
Macro Function
Macro is Preprocessed Function is Compiled
No Type Checking Type Checking is Done
Code Length Increases Code Length remains Same
Speed of Execution is Speed of Execution is Slower
Faster
Before Compilation macro name is replaced by During function call , Transfer of
macro value Control takes place
Useful where small code appears many time Useful where large code appears many
time
Generally Macros do not extend beyond one line Function can be of any number of lines
Macro does not Check Compile Errors Function Checks Compile Errors
Preprocessor Formatting
A preprocessing directive cannot be more than one line in normal circumstances. It may be split
cosmetically with Backslash-Newline. Comments containing Newlines can also divide the directive into
multiple lines.
for example, you can split a line cosmetically with Backslash-Newline anywhere:
/*
*/ # /*
*/ defi\
ne FO\
O 10\
20
is equivalent into #define FOO 1020.
#undef
To undefine a macro means to cancel its definition. This is done with the #undef directive.
Syntax:
#undef token
define and undefine example
#include <stdio.h>
#define PI 3.1415
#undef PI
202
main() {
printf("%f",PI);
}
Output:
Compile Time Error: 'PI' undeclared
#ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code.
Syntax:
#ifdef MACRO
//code
#endif
#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code.
Syntax:
#ifndef MACRO
/
/
c
o
#if d
e
#
e
n
d
i
f
The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the
code.
Syntax:
#if expression
//code
#endif
#else
The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be
used with #if, #elif, #ifdef and #ifndef directives.
Syntax:
Example
Syntax with #elif
203
#if expression l
/ s
/ e
i /
f /
e
c l
o s
d e
e
c
# o
e d
l e
s
e #
/ e
/ n
e d
l i
s f
e
#
c i
o n
d c
e l
u
# d
e e
n
d <
i s
f t
d
#if expression i
//if code o
#elif expression .
/ h
/ >
e
l #
i i
f n
c
c l
o u
d d
e e
# <
e c
204
o
n
i
o
.
h
>
#
d
e
f
i
n
e
N
U
M
B
E
R
v
o
i
d
m
a
i
n
(
)
{
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
205
#else
p
r
i
n
Output t
(
"
V
a
l
u
e
o
f
N
u
m
b
e
r
i
s
n
o
n
-
z
e
r
o
"
)
;
#
e
n
d
i
f
getch();
}
Value of Number is non-zero
Example Code:
206
char array[BUFFER_SIZE] = [0]; int I
= 9;
printf(“%d”,i);
printf(“%s”,array);
return 0;
Conditional Compilation:
Conditional compilation enables the coder to control the execution of preprocessor directives and
the compilation of program code. Conditional preprocessor directives evaluate constant integer
expressions. The ones that cannot be evaluated in preprocessor directives are sizeof expressions and
enumeration constants.
Every #if construct ends with #endif
207
Example
#if !defined(MY_CONSTANT) #define MY_CONSTANT 0 #endif
#include <stdio.h>
#define MEMBER
int main()
float amount,total;
printf("enter amount\n");
scanf("%f",&amount);
#ifdef MEMBER
total= amount*0.8;
printf("Amount to be paid=%f",total);
#else
printf("Amount to be paid=%f",amount);
#endif
208
Summary exercise:
Following table will show you various directives that we have studied in this chapter:
Directives Description
#define It substitutes a preprocessor macro.
#include It inserts a particular header file from another file.
#undef A preprocessor macro is undefined.
#ifdef It returns true if the macro is defined.
#ifndef It returns true if the macro is not defined.
#if It tests if the compile time condition is true.
#else It is an alternative for #if.
#elif It has #else and #if in one statement.
#endif The conditional preprocessor is ended.
#error It prints the error message on stderr.
#pragma It issues special commands to the compiler by using a standardized method.
Questions:
MCQ
void main()
209
{
int i = 65;
printf("sizeof(i)=%d", sizeof(i));
A. Sizeof(i)=2;
B. Sizeof(i)=1;
C. Compilation error
D. None
Answer:B
#include <stdio.h>
#define p 17;
int main()
{
printf("%d",p);
return 0;
}
A. 17
B. Run-time error
C. Compilation error
D. Garbage value
Answer: A
210
A. During editing
B. During linking
C. During Preprocessor
D. During execution
Answer: C
#include<stdio.h>
#define SQR(x)(x*x)
int main()
{
int a, b=3;
a = SQR(b+2);
printf("%d\n", a);
return 0;
}
A. 25
B. 11
C. Error
D. Garbage value
Answer: B
211