BB PPS Course Notes
BB PPS Course Notes
Objective:
Basic representation of data and how to process data using binary representation
Inside a computer.
Techniques for specifying data, operations on data, and problem solving using a
Programming language.
Identification of computer components, Operating environments, IDEs.
Categorization of high-level languages.
To write an Algorithm and flowchart for knowing steps to solve a problem.
Usage of keywords, identifiers, operators to solve mathematical questions.
Outcome:
On Successful completion of the course, students will be able to Identify and understand the
computing environments for scientific and mathematical problems.
Scope:
The Module/Unit covers the following topics: Components of a computer, Operating system,
compilers, Program Development Environments, steps to solve problems, Algorithm, Flowchart /
Pseudocode with examples. Programming languages and generations, categorization of high-level
languages. Structure of C program, keywords, identifiers, Variables, constants, I/O statements,
operators, precedence, and associativity.
1
.
While the topics are taught by introducing programming development environments and also how to
write algorithm and flowchart for to solve problems using C language
Text andReference:
(a) Text Book:
TB2. M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India
Learning Private Limited 2018
IV Operators and usage of keywords Can know the working of different operators
and its associativity and precedence.
2
( Note: Take Lecture No, Theme from lesion plan )
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
3
then sends back the processed data to storage.
4) Outputting: It is the process of presenting the processed data through output devices like
monitor, printer and speakers.
5) Controlling: This operation is performed by the control unit that is part of CPU. The control
unit ensures that all basic operations are executed in a right manner and sequence.
Operatingsystem:
In the Computer System (comprises of Hardware and software), Hardware can only understand
machine code (in the form of 0 and 1) which doesn't make any sense to a naive user.
We need a system which can act as an intermediary and manage all the processes and resources
present in the system.
The purpose of an operating system is to provide an environment in which a user can execute
programs in convenient and efficient manner.
Compilers:
o A compiler is a translator that converts the high-level language into the machine
language.
o High-level language is written by a developer and machine language can be understood
by the processor.
o Compiler is used to show errors to the programmer.
o The main purpose of compiler is to change the code written in one language without
4
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.
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
5
o Assembler
o Linker
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
6
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 can be named as 'a.out'. For example, if we are using printf() function in a
program, then the linker adds its associated code in an output file.
ProgramDevelopmentEnvironments:
The development environment helps the developers to develop the application or product using
a set of processes and programming tools.
An development environment provides developers an interface and convenient view of the
development process which includes writing code, testing the same and packaging the build so
that it can be deployed.
Ex:
Microsoft Visual Studio
Turbo C/C++
Dev C/C++
Flowchart:
Flowchart is a diagrammatic representation of sequence of logical steps of a program.
Flowcharts use simple geometric shapes to depict processes and arrows to show relationships
and process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
7
Input/ Output Used for denoting program inputs and outputs.
Examples:
Here is a flowchart to calculate the average of two numbers.
8
Here is a flowchart to calculate the even or odd number.
9
Programming 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.
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.
i. Machine Language
The advantage of machine language is that it helps the programmer to execute the programs
faster than the high-level programming language.
Assembly language (ASM) is also a type of low-level programming language that is designed for
10
specific processors. It represents the set of instructions in a symbolic and human-
understandable form. It uses an assembler to convert the assembly language to machine
language.
The advantage of assembly language is that it requires less memory and less execution time to
execute a program.
The main advantage of a high-level language is that it is easy to read, write, and maintain.
High-level programming language includes Python, Java, JavaScript, PHP, C#, C++,
Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.
Procedural Oriented Programming (POP) language is derived from structured programming and
based upon the procedure call concept. It divides a program into small procedures
called routines or functions.
The advantage of POP language is that it helps programmers to easily track the program flow
and code can be reused in different parts of the program.
The advantage of POP language is that it helps programmers to easily track the program flow
and code can be reused in different parts of the program.
The main advantage of object-oriented programming is that OOP is faster and easier to execute,
maintain, modify, as well as debug.
11
Note: Object-Oriented Programming language follows a bottom-up approach.
Natural language is a part of human languages such as English, Russian, German, and
Japanese. It is used by machines to understand, manipulate, and interpret human's language. It is
used by developers to perform tasks such as translation, automatic summarization, Named
Entity Recognition (NER), relationship extraction, and topic segmentation.
The main advantage of natural language is that it helps users to ask questions in any subject and
directly respond within seconds.
Middle-level programming language lies between the low-level programming language and
high-level programming language. It is also known as the intermediate programming language
and pseudo-language.
A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human
language.
Introduction to C:
The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is
known as mother language.
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:
12
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
14
IDENTIFIERS:
Identifiers refer to the names of program elements such as variables, functions and arrays.
Identifiers are sequence of characters chosen from the set A–Z, a–z, 0–9, and _
(underscore).
C is a case sensitive language so that ALFA and Alfa are different.
The underscore symbol _ is generally in the middle of an identifier (embedded).
Identifiers may be of reasonable length of 8–10 characters though certain computers
allow up to 32 characters.
Identifier names must start with an alphabet or underscore followed by letters, digit or a
combination of both.
C has a list of keywords that cannot be used anywhere other than that predefined in the
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
15
These constants can further be divided as follows :
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
16
‘B’ = 66
‘a’ = 97
‘0’ = 48
‘1’ = 49
String Constants:
A string constant consists of zero or more number of characters enclosed within double quotes.
The characters within quotes could be digits, characters, special characters and blank spaces.
Ex: "Red", "Rs.20.25", " "
Note that ‘A’ is not equal to “A” since a string constant containing a single character does not
have a corresponding integer value. In fact it contains two characters, the specified character
followed by a null character represents by \0.
Coding constants:
There are 3 types of code constants used in programs:
Literal constants
Defined constants
Memory constants
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:
17
printf(“format string”, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted. They are the
general characters which will be displayed as they are .
arg1, arg2 are the output data items.
Syntax:
scanf (“format string”, &arg1, &arg2, …..);
Format string consists of the conversion specifier. Arguments can be variables or array name and
represent the address of the variable. Each variable must be preceded by an ampersand (&).
Array names should never begin with an ampersand.
scanf works totally opposite to printf. The input is read, interpret using the conversion specifier
and stores it in the given variable.
The conversion specifier for scanf is the same as printf.
scanf reads the characters from the input as long as the characters match or it will terminate.
The order of the characters that are entered are not important.
It requires an enter key in order to accept an input.
OPERATORS IN C :
C provides several operators for elementary arithmetic operations like addition, subtraction,
18
multiplication, division, residue-modulo (the operation that gives the remainder after division of
one integer by another) and logical manipulations.
An operator is a symbol used for certain type of manipulations, logical or mathematical. The
data on which the operators act are called operands. An expression is a valid combination of
operators and operands that results in a value.
For example in the expression : 12*5
* is the multiplication operator,
12 and 5 are the operands.
Binary Operators:
Binary operators operate on two operands. They are classified into five categories as follows:
(i) Arithmetic
(ii) Relational
(iii) Logical
(iv) Assignment
(v) Bitwise
Ternary Operators:
Ternary operators act on three data elements. The conditional operator (?:) is a ternary operator
19
Special Operators:
Special operators include operators such as comma (,) and sizeof.
ARITHMETIC OPERATORS:
C supports five arithmetic operators.
Operator Purpose
+ Addition
– Subtraction or (unary)
* Multiplication
/ Division
% Remainder after integer division
Dividing one integer by another integer is called as integer division, which truncates, the
fractional part. The % operator gives the remainder of such a division.
For example, consider a = 10, b = 3.
a % b gives 10% 3 giving the result 1
and a/b gives 10/3 giving the result 3
Mixed-mode Arithmetic operations consists of a real and an integer operand. If one of the
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
20
!= Not equal to
In the 4th and 5th example given above the expressions contain arithmetic expression. Thus in
the relational expression (i+j)>=k, the arithmetic expression i+j will be evaluated and then the
result is compared with k. These arithmetic operators have higher priority over relational
operators. The relational operators are used to compare two quantities in decision statements.
LOGICAL OPERATORS:
Logical operators are used to combine two or more logical expressions. There are 3 logical
operators in C. They are logical AND, logical OR and logical NOT
Operator Meaning
! logical NOT
&& logical AND
|| logical OR
The result of a logical AND is true only if both operands are true. The result is false if
either operand is false.
The result of a logical OR is false only if both operands are false. The result is true if
either operand is true.
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 :
21
variable=variable/constant/expression;
For example :
x=10; /*x is assigned a value 10 */
sum=a+b; /*Thesumofa&bwhichis20isassignedtosum*/
Where += is the abbreviated or compound operator. In the above case + = means add
5ton.Thedifferentshorthandassignmentoperatorsare:
The priority of the above operators + =, –=, *=, /= and % = is the same as theassignment
operator.
Difference between = = and = operator
1. == is an equality or relational operator, used for comparison = is an
assignmentoperator which assigns the resultant value on its right hand side to the
variableon its left hand side.
2. == operator does not change the value of the variable on the left hand side.However
= operator does change the value of the variable on the left hand side of the
assignmentstatement.
22
INCREMENT/DECREMENTOPERATOR
Theincrement and decrement operators are specifically used in C or C++.
They are not generally available in other languages.
Increment operator ++ is used to increment the value of the variable by 1.Decrement
operator – – is used to decrement the value of the variable by 1.
They are also called as unary operators Fig. 2.14. Since they operate on only one
dataelement.
int a, b;
:
a = 5;
b = --a;
will result in the value of a and b to be 4.
Post-increment operator ++ is written to the right of its operand as in n ++; which is the
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.
23
Difference between postfix & prefixoperators
(i) The pre-increment or decrement operator first increments or decrements the value
of its operand by 1 and then assigns the resulting value to the variable onthe left
hand side. For example,consider
int a, b; a =
15;
b = ++a;
In this example, the value of a is incremented by 1 and then this value 16 is assigned
tob.
(ii) The post increment or decrement operator first assigns the value to the variable on
the left hand side and then increments or decrements the operand by 1. Consider the
following program segment:
intm,n; n =
2;
m = n– –;
The value of n is first assigned to m and then it is decremented i.e., n becomes 1, but
value of m is 2.
In subscripted variables.
a[j++]=5;
is equivalent to a[j]=5;
j++;
Similarly, a[++i]=5;
is equivalent to i = i+1;
a[i] = 5;
Consider the statement
x = n++/2;
where n = 5. After execution, n is 6 but x gets the value 5/2 which is 2.
24
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.
SPECIALOPERATORS
C consists of some special operators. The operators , , &,*,.and , are called special
operators in C.
Operator Description
, Comma operator
sizeof size in bytes
& address of operand
* accessing value at that address
. dot operator
arrow operator
The CommaOperator
(i) The comma operator is used to separate a list of expressions given as a single
25
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
(i) Thesizeofoperatorreturnsthesizeinbytesoftheoperandontheright.
(ii) The syntaxis
sizeof(n)
Example 2.30
26
/* Program to show usage of sizeof operator
*/ #define STRING “Usage of sizeof
Operator” #include <stdio.h>
main()
{
char a = ‘p’;
clrscr();
printf(“\n The size ofcharis : %d \n”,sizeof(char));
printf(“\n Therefore the size of char ais : %d \n”,sizeof(a));
printf(“\n However the size of‘p’is : %d \n”,sizeof(‘p’));
printf(“\nSTRING : \”%s\”
\n”,STRING); printf(“\n The number of bytes in STRINGis : %d
\n”,sizeof STRING); printf(“\n The size ofshortis : %d\n”,sizeof(short));
printf(“\n The size ofintis : %d\n”,sizeof(int));
printf(“\n The size oflongis : %d\n”,sizeof(long));
printf(“\n The size offloatis : %d\n”,sizeof(float));
printf(“\n The size ofdoubleis : %d
\n”,sizeof(double)); getch();
}
Output
The size ofcharis 1
Therefore the size of charais 1
However the size of‘p’is 2
STRING : “Usage of sizeof
Operator” The number of bytes inSTRINGis 25
The size ofshortis 2
The size ofintis 2
The size oflongis 4
The size offloatis 4
The size ofdoubleis 8
27
BITWISEOPERATORS:
C supports a powerful set of operators known as bitwise operators. The bitwise
operatorsare used for controlling and interacting with hardware and also for
manipulating data at the bit level.
The Bitwise operators are as shown below table.
Operator Description
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ one’s complement
(i) Bitwise operators cannot be applied to float or double. They can be applied to
integersonly.
(ii) All except ~ operator are used in binary operations. Tilde (~) is a unaryoperator.
(iii) Bitwise operators perform bitwise logical AND, bitwise logical OR,
bitwiseexclusiveOR,bitwiseshiftleftandshiftright.
(iv) Bitwise operators work on their operands bit by bit starting from the least
significant bit. The truth table for logical bitwise operations is as shown in below
table.Trueistakentobe1andfalseaszero.
Bitwise ANDOperator:
TheBitwise AND operator is represented by the symbol & (ampersand). The
result of AND operation is 1 if both operand bits are 1, otherwise, the result is zero.
Further,theANDoperationisdoneonthebinaryrepresentationoftheoperands.
4 & 5 results in 4
i.e., binary value of4is 0100
binary value of5is 0101
AfterANDoperation 0100 i.e.,4
28
Bitwise & operator is used to check whether a particular bit is 0 or 1. Consider the
number 21. Its bit pattern is represented by
0001 0101
To check whether the fourth bit is 0 or 1, AND operation must be done withanother
operand whose value must be 24 i.e., 16, which can be represented as00010000.
Therefore, 00010101
0001 0000 & mask
0001 0000
Consider x = 4, y = 9
xis 00000100 4
yis 00001001 9
x|yis 00001101 i.e.,13
The bitwise OR is used to set a particular bit on (set to 1).
Consider x = 4
x is 00000100
~x is 11111011
Bitwise ShiftOperator
29
The shift operators are used to push the bit patterns to the right or left by thenumber of bits given
by theirright operand
The Right shift operator is of the form :
expression>>n
where n is the number of bit positions to be shifted. However the rightmost n bitsare
lost. Further the left most n bits which are vacant will be filled with zero. For
examplex>>4shiftsallbitsby4placestotheright.
The Left shift operator is of the form
expression<<n
where n is the number of bit positions to be shifted. The left most n bits are lost andthe
rightmost n bits are vacated and filled with zeros.
Shift operators are used for multiplication and division by 2. For example, the statement
x = y << 2;
shifts two bit to the left in y. Further the value of x is equal to y multiplied by 2 2.
Similarly, the statement
x = y >> 2;
shifts the bits in y to the right by 2. Also the value of x is equal to y divided by 2 2.
PRECEDENCE OF ARITHMETICOPERATORS:
30
In the case of nested parentheses, the inner most parentheses is evaluated first and
the evaluation continuesoutwards.
When two operators with the same precedence are encountered, the evaluation is
done from left to right as inthe above example. This is known an associativity.
Parenthesescanbeusedtochangetheorderofevaluation
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.
Summary exercise:
32
3. Different types of datatypes
33
Course Code: 20CS C01
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:
E.Balaguruswamy,ProgramminginANSIC,TataMcGraw-Hill.
34
Module/ Theme Learning Objectives
Lecture
L.9 Introduction to decision control statements To learn what are various control structures,
like If, If-else. classification, if, if else, nested if else
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.
35
Lecture : 9
Objectives: 1.What are various control structures
2. Classification
3. if, if else, nested if else
Control structures
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.
36
2. flow chart for simple if.
Whenever simple if statement is encountered, first the condition is tested. It returns either
true or false. If the condition is false, the control transfers directly to stmt-x without considering
the stmt block. If the condition is true, the control enters into the stmt block. Once, the end of
stmt block is reached, the control transfers to stmt-x
Output:
enter a number
12
Even number
if - else statement
if…else statement is used to make a decision based on two choices. It has the following
form:
1. Syntax:
if(condition)
{
true stmt block;
}
else
{
false stmt block;
}
Stmt-x;
In this syntax,
if and else are the keywords.
37
<condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses .
The true stmt block and falsestmtblock are simple statements or compound statements or
null statements.
stmt-x is any valid C statement.
2. Flow chart:
If the condition is false, the control enters into the false stmt block by skipping true stmt
block.
Once, the end of false stmt block is reached, the control transfers to stmt-x.
#include <stdio.h>
main()
{
int x;
printf("Enter a number\n");
scanf("%d",&x);
if(x%2==0)
printf("EVEN\n");
else
printf("ODD\n");
}
38
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");
39
}
/* 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
{
40
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>
41
#include<conio.h>
void main()
{
int a ,b,c;
else
{
if(c>b)
printf("%d\n",c);
else
printf("%d\n",b);
}
Programming Problems:
1. Develop a C program to check whether a number is negative, positive or zero. (L3) (CO3)
2. Develop a C program to check whether a number is divisible by 5 and 11 or not. (L3) (CO3)
3. Develop a C program to check whether a year is leap year or not. (L3) (CO3)
4. Develop a C program to input any alphabet and check whether it is vowel or consonant. (L3)
(CO3)
5. Develop a C program to input any character and check whether it is alphabet, digit or
special character.(L3) (CO3)
6. Develop a C program to check whether a character is uppercase or lowercase
alphabet.(L3) (CO3)
7. Develop a C program to input angles of a triangle and check whether triangle is valid or
not.(L3) (CO3)
8. Develop a C program to input all sides of a triangle and check whether triangle is valid or
not.(L3) (CO3)
9. Develop a C program to check whether the triangle is equilateral, isosceles or scalene
triangle.(L3) (CO3)
10. Develop a C program to find all roots of a quadratic equation. (L3) (CO3)
42
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.
43
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");
44
THE switch STATEMENT
Introduction
We can use a switch statement when we want to check multiple conditions. It can also be done using an if
statement but it will be too lengthy and difficult to debug.
Syntax
The general format for a switch statement is
switch(integer expression)
{
case 1:
statement;
break;
case 2:
statement;
break;
---------
default:
statement;
}
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.
45
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;
46
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
47
Percentage >= 40% : Grade E
Percentage < 40% : Grade F
4. 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%
5. 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)
6. Develop a C program print total number of days in a month using switch case.(L3)(CO3)
7. Develop a C program to check whether an alphabet is vowel or consonant using switch
case.(L3)(CO3)
8. Develop a C program to find maximum between two numbers using switch case.(L3)(CO3)
9. Develop a C program to find roots of a quadratic equation using switch case.(L3)(CO3)
10. 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.
48
#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
{
printf(" the value of i is %d\n", i);
49
i = i + 1;
}
while (i<5);
Explanation
1. The loop body is executed at least once.
2. The condition is checked after executing the loop body once.
3. If the condition is false then the loop is terminated.
4. In this example, the last value of i is printed as 5.
#include<stdio.h>
for LOOP
Introduction
The for loop is used only when the number of iterations is predetermined, for example, 10 iterations or 100
iterations.
Syntax
The general format for the for loop is
for (initializing; continuation condition; update)
50
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);
}
}
51
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()
{
longint fact=1;
inti,n;
printf(“Enter a positive number to find factorial\n”);
scanf(“%d”,&n);
for(i=1; i<n; i++)
fact *=i;
printf(“The factorial of %d is %ld”,n,fact);
}
2. Fibonacci series
main()
{
int i, f1, f2, f3, n;
f1 = f2 = 1;
52
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.
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.
The following representation shows the transfer of control when break statement is used:
Any loop
{
statement_1;
statement_2;
:
break;
next_statement;
#include<conio.h>
int main()
{
int i;
Output: 12345
2. continue statement
A continue statement is used within loops to end the execution of the current iteration and proceed to the
next iteration. It provides a way of skipping the remaining statements in that iteration after the continue
statement. It is important to note that a continue statement should be used only in loop constructs and not in
selective control statements.
Syntax for continue statement is:
continue;
55
The following representation shows the transfer of control when continue statement is used:
Any loop
statement_1; statement_2;
:
continue;
next_statement;
int i, sum=0, n;
for(i=1; i<=10; i++)
{
3. goto statement
The goto statement transfers the control to the specified location unconditionally. There are certain situations
where goto statement makes the program simpler. For example, if a deeply nested loop is to be exited
earlier, goto may be used for breaking more than one loop at a time. In this case, a break statement will not
serve the purpose because it only exits a single loop.
label:
56
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
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n;
for(line=1;line<=3;line++)
57
{
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
123451234
#include <stdio.h>
void main()
{
int line ,n,gap;
58
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:
*****
* *
* *
* *
*****
59
*****
*****
*****
*****
*****
*
**
**
* *
*****
10101
01010
10101
01010
10101
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
60
Lecture-13
Case Study on control structures:
while(temp%10==0)
{
printf("ZERO ");
temp=temp/10;
}
}
62
26. Rewrite the following without using compound relations(L2)(CO3)
if(EM>90&&EG>95||Total>190)
printf(“SUCCESS”);
else
printf(“Failure”);
26. what is the output of the following program(L2)(CO3)
main()
{
int i;
for(;i;)
i--;
printf(“%d”,i);
}
27. Distinguish between source code, object code and executable code.(L4)(CO3)
28. Draw flow chart for various loops.(L3)(CO3)
29. Draw flow chart for various control constructs.(L3)(CO3)
Programs:
1
1 2
1 2 3
1 2 3 4
1
1 2
1 2 3
1 2
1
1
63
1 2
1 2 3
1
1 2 1
1 2 3 2 1
1
2 1 2
3 2 1 2 3
15. Write a program to print the sum of first n terms of sine series.(L3)(CO3)
16. Write a program to print the sum of first n terms of cosine series.(L3)(CO3)
17. Write a program to print the Pascal triangle.(L6)(CO3)
18. Write a program to find nth Fibonacci number.(L3)(CO3)
19. Write a program to generate first n terms of Fibonacci series.(L3)(CO3)
20. Write a program to find factorial of a number.(L3)(CO3)
21. Write a program to check whether the given number is prime or not.(L3)(CO3)
22. Write a program to print first n prime numbers.(L3)(CO3)
23. Write a program to print prime numbers upto n.(L3)(CO3)
24. Write a program to print prime numbers between n1 and n2.(L3)(CO3)
25. WAP to display menu for selecting addition, subtraction, multiplication and division and
compute according to menu chosen. (Use do-while).(L3)(CO3)
26. WAP to addition, subtraction, and multiplication of two complex numbers (a+ib) and
(x+iy).(L3)(CO3)
27. Using while loop, write a program to print all Armstrong numbers between 1 and 500. If
sum of cubes of each digit of the numbers is equal to the number itself, then number is called
Armstrong number.(L3)(CO3)
For example: 153 = (1*1*1) + (5*5*5) + (3*3*3)
28. WAP to find whether the given number is strong or not using functions.(L3)(CO3)
(Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145 )
29. Input a year from keyboard and determine whether it is leap year or not using the
conditional operator.(L3)(CO3)
30. 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)
31. WAP to calculate nPr= n!/(n-r)!(L3)(CO3)
32. WAP to calculate nCr =n! / n!*(n-r)!(L3)(CO3)
33. WAP to find whether the given number is perfect or not
Example ( 6 is perfect number since 6 = 1 + 2 + 3)(L3)(CO3)
34. WAP to convert given decimal number to binary number by using a function.(L3)(CO3)
64
Course Code: 20CS C01
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.
Text andReference:
(a) Text Book:
65
Pradeep DeyandManasGhosh,“ProgramminginC”,OxfordPress,2 nd 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.
66
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
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.
67
return value, return value type should be indicated as void.
Function definition
FUNCTION CALL
Function call means, accessing a function. A function can be called by specifying its
name, followed by a list of arguments enclosed in the parentheses, and separated by comma
Example: f=fact(n);
If a function call does not require any arguments, an empty pair of parentheses must
follow the function name.
A function call may appear itself or it may be one of the operand within a expression.
Example: printf(“%d”,fact(n));
Arguments in function call, and formal parameters in function declaration must be same
in number, type and order.
OUTPUT
x=50 y=0
Example programs on functions
Factorial of number by using function
#include <stdio.h>
main()
{
long int fact(int);
int n;
long int f;
printf("Enter a number\n");
scanf("%d",&n);
f = fact(n);
printf("The factorial of %d is %ld",n,f);
} /*end of main */
/* function fact*/
long int fact(int x)
{
int i;
long int f1=1;
for(i=1;i<=x;i++)
f1 = f1*i;
return(f1);
69
}
Fibonacci series by function
main()
{
int n;
void fib(int);
printf( "\nHow many Fibonacci numbers
required ? ");
scanf("%d", &n);
printf("\nThe first %3d fibonaccinumbers are\n", n);
fib(n);
}
void fib(int n)
{
int i, f1, f2, f3;
f1 = f2 = 1;
printf("%5d\n", f1);
printf("%5d\n", f2);
for( i = 3; i<= n; i++)
{
f3 = f1 + f2;
printf("%5d\n", f3);
f1 = f2;
f2 = f3;
}
}
GCD of two numbers by function
void main()
{
int m,n,g;
int gcd(int,int);
} /* End of main() */
int gcd(int m,int n)
{
int r,g1;
70
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() */
71
/* function digitsum() */
int digitsum(int num)
{
int digit,sum=0;
while(num !=0)
{
digit = num%10;
sum = sum+ digit;
num = num/10;
}
return sum;
}
To check whether the number is palindrome or not by using function
#include <stdio.h>
void main()
{
int palin(int);
int num,ans;
printf("Enter a number\n");
scanf("%d",&num);
ans=palin(num);
if(ans==1)
printf("%d is palindrome\n",num);
else
printf("%d is not palindrome\n",num);
}
/* function palin */
int palin(int num)
{
int rev=0,temp,digit;
temp=num;
while(num!=0)
{
digit= num%10;
rev = rev*10 + digit;
num = num/10;
}
if(rev==temp)
return 1;
else
return 0;
}
RECURSIVE FUNCTIONS
A function which calls itself until a certain condition is reached is called recursive function
/* to find factorial of a number recursively */
#include <stdio.h>
72
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;
73
}
/* function rgcd */
int rgcd(int m,int n)
{
if(m%n==0)
return n;
else
return(rgcd(n,m%n));
}
int rsum(int n)
{
if(n==0)
return n;
else return(n%10+rsum(n/10));
}
74
/* to find m power n recursively */
#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));
}
75
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 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
76
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;
}
int fun3()
{
x=1000;
return x;
}
77
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
int fun()
{
static int x=0;
x+=1;
return(x);
}
OUTPUT
1
2
3
4
// program to illustrate register variable
#include <stdio.h>
void main()
{
register inti;
int i;
for(i=1;i<1000;i++)
78
printf("% d",i);
}
automatic variable static variable
2. It must be declared inside the function 2. It can be declared inside or outside the
function
3. If it is not initialized, garbage value is stored 3. If it is not initialized, zero is stored
4. It is initialized every time function is called 4. It is initialized once and only one but not
that is repeated initialization every
5. It is lost when function terminates time when function is called
5. It is lost when program terminates but not
when function terminates
6. It can be accessed in only one function that is 6. It can be accessed in more than one function.
the
79
Iterative Recursive
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
80
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
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
84
Review and revision exercise (2) :
Case Study:
1. To display the given decimal number in words using user defined function
2. To display the given decimal number in roman numbers using user defined function
3. To find the day name when date is entered using user defined function
Expected Questions:
Short answer type:
85
Course Code: 20CS C01
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.
Text andReference:
(a) Text Book:
1. M.T. Somashekar “Problem Solving with C”, 2 nd Edition, Prentice Hall India Learning Private
Limited 2018
86
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
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]);
At the time of execution user can give 5 data items which will be stored in the array.
89
Retrieving elements from an array using subscript
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
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( )
{
inti , a[5];
printf(“Enter 5 integer elements: ”); /* reading values into Array */
for (i=0; i<5; i++)
scanf(“ %d ”, &a[i]);
/* printing of a[i] values */
printf(“The array elements in reverse order are:”);
91
for(i=4; i>=0 ; i--)
printf(“%d ”, a[i]);
}
Output:
Find whether a given element/key exists or not in the array of elements is called search.
This operation can be done by using two methods- simplest method is a sequential search or linear search
and binary search.
The basic idea of linear search is start comparing the key with each element in the array from index ‘0’ to
index ‘n’-1 if ‘n’ is the size of the array.
if key is found display the position/index at which element exist and exit the search
otherwise search will be continued till the end of the array and display the key is not found.
In binary search method , halves the size of the list and searches only in half of the array by finding the mid
element index using first(low) and last(high) index of the array.
The procedure is as follows-
Find mid element by using low and high
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 */
#include<stdio.h>
int main()
{
int n;
printf("\n Enter the size of the array:");
scanf("%d",&n);
93
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
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
94
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]);
//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 */
95
a[j+1]=temp;
}
}
printf("\n After Sorting ....\n");
for(i=0;i<n;i++)
printf("%5d",x[i]);
return 0;
}
Selection Sorting
Selection sort finds the minimum element from the array and place it in the beginning.
#include <stdio.h>
main()
{
int a[20],n,i, j, po,se,temp;
printf("How many elements\n");
scanf("%d",&n);
96
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
Arrays with more than one dimension are called multidimensional arrays.
Array of one dimensional array is called two dimensional array.
Example:
int a[10][10];
float b[20][20];
Two dimensions are useful to store data in a table form. Ie take the previous example 60 student
marks in a subject.
In order to store 60 students’ marks obtained in 6 subjects then six one dimensional arrays need to
97
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 …
To accesses the 2nd element at 3rd row we need to use the indexes as a[1][2]. So element in i th 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.
98
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
32
Enter the elements for matrix A
222
222
Enter the elements for matrix B
33
33
33
The multiplication of A and B is
18 18
18 18
101
2 5
3 6
} /* end of main */
/*Function input */
void input( int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */
/* Function Bsearch */
void bsearch (int a[],intn,int key)
{
intlow,high,mid,flag=0;
low=0;
high=n-1;
while(low<=high)
{
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;
103
break;
}
}
if(flag==0)
printf("search is unsuccessful\n");
} /* end of function bubblesort */
OUTPUT:
Enter how many numbers
10
Enter the number
3 5 8 54 7 15 76 23 79 11
Enter the key
79
Search is successful
Location =9
int a[25],n;
printf("How many numbers to sort ? ");
scanf("%d",&n);
printf("\nEnter %d numbers below:\n", n);
input(a,n);
bubblesort(a,n);
printf("\nThe sorted Array is: \n");
output(a,n);
} /* end of main */
/*Function input */
void input( int a[],int n)
{
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;
104
for ( pass = 1; pass < n; pass++ )
{
for ( j =0 ; j < n-1; j++ )
{
if( a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
} /* end of function bubblesort */
/* Function output */
void output (int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
printf("%5d\n", a[i]);
} /* end of function output */
#include <stdio.h>
main()
{
void ssort(int [],int);
void display(int [] ,int);
void readarray(int [],int);
int a[20],n;
printf("How many elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
readarray(a,n);
ssort(a,n);
display(a,n);
}
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);
106
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
/*Function to print the elements of a matrix */
void display(int X[10][10],int rows ,int cols)
{
inti, j;
for(i = 0; i< rows; i++)
{
for( j = 0; j < cols; j++)
printf("%5d", X[i][j]);
printf("\n");
}
} /* end of function display */
#include <stdio.h>
main()
{
void readmat(int [][10],int,int);
void matmul(int [][10],int [][10],int [][10],int,int,int);
void display(int [][10],int,int);
if(n!=p)
printf("multiplication not possible\n");
else
{
printf("\nEnter elements of matrix A \n");
readmat (A, m,n);
matmul(A, B, C,m,q,n);
printf("Matrix A is :\n");
display(A, m,n);
printf("Matrix B is :\n");
display(B, p,q);
printf("\nMATRIX C (= A X B) is:\n");
display(C, m,q);
}
108
} /* 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
109
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);
}
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
110
};
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?
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
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)
112
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
Questions under Blooms Level-6
7. Develop a program for sorting n integers using selection sort/bubble sort. (CO3,4,5)
8. Distinguish Lvalue and Rvalue of an array element. Explain the difference with example. (CO5)
9. Develop a program to store ‘n’ terms of a Fibonacci series in a variable length array. (CO3,4,5)
10. Discuss binary search/linear search with appropriate example in detail. (CO5)
11. Discuss bubble sort/selection sort with appropriate example in detail. (CO5)
Questions under Blooms Level-2,3
12. Explain in detail about the initialization, access and memory allocation of one dimensional arrays
with the help of a diagram. (CO5)
13. Explain in detail about the initialization, access and memory allocation of two dimensional arrays
with the help of a diagram. (CO5)
14. Compare a scalar variable and arrays. (CO5)
15. Demonstrate with an example about passing an array to a function.(CO3,4,5)
16. Illustrate with an example about variable length array.(CO5)
17. An integer array is declared of size 10. If the first element of the array is stored at 0x12345 memory
location. Find the memory location where 6th element of the array will be. (CO5)
114
Course Code: 20CS C01
Instructors Name:
Objective:
Outcome:
learn about one-dimensional and two-dimensional strings and the way they are declared,
initialized, manipulated, inputted, and displayed.
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:
115
(a) Text Book:
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 fi eld width is less than the length of the string, the entire string is printed.
The integer value on the right side of the decimal point specifies the number of characters
to be printed.
When the number of characters to be printed is specified as zero, nothing is printed.
The minus sign in the specification causes the string to be printed as left justified.
Example program:
#include <stdio.h>
int main()
{
char s[]=“Hello, World”;
printf(“>>%s<<\n”,s);
printf(“>>%20s<<\n”,s);
printf(“>>%-20s<<\n”,s);
printf(“>>%.4s<<\n”,s);
printf(“>>%-20.4s<<\n”,s);
printf(“>>%20.4s<<\n”,s);
return 0;
}
Output:
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.
int main()
{
char ch;
if(isalnum(ch))
printf("%c is an alphanumeric character.\n",ch);
else
printf("%c is not an alphanumericcharacter.\n",ch);
121
return 0;
}
String Manipulation:
The string header, string.h, provides many functions useful for manipulating strings or character
arrays. Some of these are mentioned below:
Example programs:
The given code shows the use of the strcpy()function.
#include <string.h>
int main()
{
char s1[] =“Hello, world!”;
char s2[20];
strcpy(s2, s1);
puts (s2);
return 0;
}
The following program illustrates the comparison of two strings.
#include <stdio.h>
#include <string.h>
int main()
122
{
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
127
word from a sentence. Note that the word may appear any number of times.(L4,L3)(CO4)
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
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
Learning Private Limited 2018.
TB2: AKSharma“ComputerFundamentalsand Programming”, 2nd Edition, University
Press,2018.
129
TB3: Pradeep DeyandManasGhosh,“ProgramminginC”,OxfordPress,2nd Edition,2017.
L.28 Arrays and Pointers, Pointer Arithmetic To know various Arithmetic operations that
and Arrays. can be performed on Pointers and to
understand how to use pointers with arrays to
solve complex problems.
Pointers
Arrays and Pointers
Dynamic Memory Allocation
Pointer :
A pointer is a variable that stores the address of another variable. Unlike other variables that
130
hold values of a certain type, pointer holds the address of a variable. For example, an integer variable
holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer
variable.
Definitions:
Call by address: facilitating the changes made to a variable in the called function to become
permanently available in the function from where the function is called.
Call-by-value :A particular way of implementing a function call, in which the arguments are passed
by their value (i.e., their copies).
Dynamic memory allocation :The process of requesting and obtaining additional memory
segments during the execution of a program.
Function pointer: A function has a physical location in memory that can be assigned to a pointer.
Then it is called function pointer. This address is the entry point of the function and it is the
address used when the function is called.
Garbage collection: If only implicit dynamic allocation is allowed then deallocation must also be
done by implicit means, which is often called garbage collection.
NULL : A special C constant, defined as macro in stdio.h as or 0, or (void*)), that can be used as the
null value for pointers.
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 ofpointer 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
133
2. Indirection Operator and Dereferencing :
The primary use of a pointer is to access and, if appropriate, change the value of the
variable that the pointer is pointing to.
The other pointer operator available in C is ‘*’, called the ‘value at address’ operator. It
returns the value stored at a particular address. It is also called indirection operator/
dereference operator.
Pointer Variable :
Definition :
A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, you must declare a pointer before using
it to store any variable address.
The general form of a pointer variable declaration is
Syntax : type *var-name;
134
Declaring a Pointer – Pointer Declaration :
Like other variables, in a program, a pointer has to be declared.
A pointer will have a
value, scope, lifetime, and name.
Pointers will occupy a certain number of memory locations.
The pointer operator available in C is ‘*’ , called ‘value at address’ operator.
The syntax for declaring a pointer variable is
datatype * pointer_variable
The data type of pointer and the variable must match, an int pointer can hold the
address of int variable, similarly a pointer declared with float data type can hold the
address of a float variable.
Declaration What it means
int p p is an integer
int *p p is a pointer to an integer
char p p is a character
char *p p is a pointer to a character
long p p is a long integer
long *p p is pointer to a long integer
unsigned char p P is an unsigned character
unsigned char *p P is pointer to an unsigned character
Some Pointer Variable Declarations
Example:
135
Output :
In Turbo C:
the size of integer pointer is 2
the size of fl oat pointer is 2
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
136
result.
The following pointer initializations are invalid.
int a=6, *ip;
float *p;
char ch=’A’;
p=&a;
ip=&ch:
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);
137
return 0;
}
Example 2 :
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
p=&a;
printf(“\n*p = %p”, *p);
return 0;
}
Output:
p = 0022FF2C
No
In C, pointers are not allowed to store any arbitrary memory address, but they can only
store addresses of variables of a given type.
Consider the following code:
int *pi;
pi= (int*)1000;
*pi = 5;
Location 1000 might contain the program. Since it is a read only, the OS will throw up a
segmentation fault.
Example:
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main()
{
int num = 15;
int *iPtr = #
printf(“ The value of a num is %d”, num);
num = 100;
138
printf(“ The value of a num after num=10 is %d”, num);
*iPtr = 25;
printf(“ The value of a num after *iPtr = 15 is %d”, num);
Output:
The value of num is 15
The value of num after num = 100 is 100
The value of num after *iPtr = 25 is 25
Void Pointer :
A void pointer is a special type of pointer.
It can point to any data type, from an integer value or a float to a string of characters.
Its sole limitation is that the pointed data cannot be referenced directly (the asterisk *
operator cannot be used on them) since its length is always undetermined. Use type
casting or assignment
Example:
/* Program to illustrate Void Pointer */
int main()
{
int a=10,
double b=3.1415;
void *vp;
vp=&a;
printf(“\n a=%d”, *((int*)vp));
vp=&b;
printf(“\n a= %d”, *((double *)vp));
return 0;
}
Output :
a= 10
b= 3.141500
Null Pointer :
Null pointer is a special pointer that points nowhere. That is, no other valid pointer to any
139
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 toany location in memory.
Use of Pointers :
Call by reference : One of the typical applications of pointers is to support call by reference.
However, C does not support call by reference as do other programming languages such as
PASCAL and FORTRAN.
Typically a function call is made to communicate some arguments to the
function.
C makes use of only one mechanism to communicate arguments to a
function: call by value.
This means that when a function is called, a copy of the values of the
arguments is created and given to the function.
Call by reference: Simulated by the use of pointers called “call by address”.
Example:
/* Program to illustrate call by Value*/
void swap(int a, int b)
{
int temp; temp=a; a=b; b=temp;
}
int main()
{
int x=5,y=10;
void swap(int,int); printf(“%d %d\n”,x,y);
swap(x,y);
printf(“%d %d\n”,x,y);
return 0;
}
Output:
140
5 10
5 10 No swapping
Output:
5 10
10 5
Returning more than one value from a function:
Example :
/* Program to print area by illustrating returning more than one value from a function*/
#include <stdio.h>
int main()
{
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);
141
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;
}
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 :
142
/* 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.
Below figure depicts the equivalence among array notation and pointer notation.
143
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.
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
146
UNIT IV
Objective:
Outcome:
1. On Successful completion of the course, students will be able to Apply structures, and unions
to solve mathematical and scientific problems.
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.
Hall.
L.32 Structures: Definition and Initialization To understand how to define, represent, and
of Structures. how to use Structure.
Definition
Arrays allow defining type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows combining data items of
different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book−
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member. The format of the struct statement is as follows –
data_typestruct_member n;
} [one or more structure variables separated by comma];
The structure_nameis optional and each struct_memberis a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the
final semicolon, you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure –
struct Books
{
char title[50]; char author[50]; char subject[100]; intbook_id;
}book;
To access any member of a structure, we use the member access operator (.). The member
149
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( )
{
When the above code is compiled and executed, it produces the following result
Book 1 title : C Programming
Book 1 author :Nuha Ali
150
Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Nested structures
Structure written inside another structure is called as nesting of two structures. Nested Structures
are allowed in C Programming Language. We can write one Structure inside another structure as member
of another structure.
Example:
structdate
{
int date; int month; int year;
};
struct Employee
{
charename[20];
intssn;
float salary;
struct date doj;
}emp1;
Structure members are accessed using dot operator. ‘date‘ structure is nested within Employee
Structure. Members of the ‘date‘ can be accessed using ’employee’ emp1 &doj are two
structure names (Variables)
Accessing Month Field : emp1.doj.month Accessing day Field : emp1.doj.day Accessing year
Field :emp1.doj.year
#include <stdio.h>
struct Employee
{
charename[20];
int ssn;
float salary;
151
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
When the above code is compiled and executed, it produces the following result
Employee Name :Pritesh Employee SSN : 1000 Employee Salary : 1000.500000 EmployeeDOJ
: 22/6/1990
Arrays of Structures
We may declare the structure variable as an array by using index. Arrays of structures are passed
using the following syntax,
structstructure_name{ data_type struct_member1; data_typestruct_member2;
data_typestruct_membern;
};
structstructure_namestruct_variable[index_value];
152
Structures as Function Arguments
You can pass a structure as a function argument in the same way as you pass any other variable or
pointer. Like all other types, we can pass structures as arguments to a function. In fact, we can pass
individual members, structure variables, a pointer to structures etc to the function. Similarly, functions
can return either an individual member or structures variable or pointer to the structure.
We can pass individual members to a function just like ordinary variables.The following
program demonstrates how to pass structure members as arguments to the function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is global.
5 */
6
7 structstudent
8{
9 charname[20];
10introll_no;
11intmarks;
12};
13
14voidprint_struct(charname[],introll_no,intmarks);
15
16intmain()
17{
18structstudentstu={"Tim",1,78};
19print_struct(stu.name,stu.roll_no,stu.marks);
20return0;
21}
22
23voidprint_struct(charname[],introll_no,intmarks)
24{
25printf("Name: %s\n",name);
26printf("Roll no: %d\n",roll_no);
27printf("Marks: %d\n",marks);
28printf("\n");
29}
153
When the above code is compiled and executed, it produces the following result
Name: Tim
Roll no: 1
Marks: 78
154
11intmarks;
12};
13
14voidprint_struct(structstudentstu);
15
16intmain()
17{
18structstudentstu={"George",10,69};
19print_struct(stu);
20return0;
21}
22
23voidprint_struct(structstudentstu)
24{
25printf("Name: %s\n",stu.name);
26printf("Roll no: %d\n",stu.roll_no);
27printf("Marks: %d\n",stu.marks);
28printf("\n");
29}
When the above code is compiled and executed, it produces the following result
Name: George
Roll no: 10
Marks: 69
155
Returning Structure from Function
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 global.
5 */
6
7 structplayer
8{
9 charname[20];
10floatheight;
11floatweight;
12floatfees;
13};
14
15voidprint_struct(structplayerp);
16structplayerdeduct_fees(structplayerp);
17
18intmain()
19{
20structplayerp={"Joe",5.9,59,5000};
21print_struct(p);
22p=deduct_fees(p);
23print_struct(p);
24
25return0;
26}
27
156
28structplayerdeduct_fees(structplayerp)
29{
30p.fees-=1000;
31returnp;
32}
33
34voidprint_struct(conststructplayerp)
35{
36printf("Name: %s\n",p.name);
37printf("Height: %.2f\n",p.height);
38printf("Weight: %.2f\n",p.weight);
39printf("Fees: %.2f\n",p.fees);
40
41printf("\n");
42}
When the above code is compiled and executed, it produces the following result
Name: Joe
Height: 5.90
Weight: 59.00
Fees: 5000.00
Name: Joe
Height: 5.90
Weight: 59.00
Fees: 4000.00
You can define pointers to structures in the same way as you define pointer to any other variable
–
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To
find the address of a structure variable, place the '&'; operator before the structure's name as follows –
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the
→ operator as follows –
struct_pointer->title;
The following program demonstrates how to access structure members using pointers.
#include <stdio.h>
#include <string.h>
struct Books{
chartitle[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */ voidprintBook(struct Books *book ); int main( ) {
structBooksBook1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare
Book2 of type Book*/
/* book 1 specification */
strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
158
/* print Book1 info by passing address of Book1 */ printBook(&Book1);
/* print Book2 info by passing address of Book2 */ printBook(&Book2);
return 0;
}
voidprintBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces the following result – Book title : C
Programming
Book author :Nuha Ali
Book subject : C Programming Tutorial Book book_id : 6495407
Book title : Telecom Billing Book author : Zara Ali
Book subject : Telecom Billing Tutorial Book book_id : 6495700
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
structnode {
intdata1;
chardata2;
structnode* link;
};
159
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()
{
structnode ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
160
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return0;
}
When the above code is compiled and executed, it produces the following result
30
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–
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 –
161
#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.
#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
162
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;
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;
}
When the above code is compiled and executed, it produces the following result –
Summary exercise:
165
L2
11. The operator used to find the size of any variable
A) sizeof() B)sizof() C) sizeof() D) size()
L1
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
166
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
167
Objective:
Outcome:
On Successful completion of the course, students will be able to develop applications with
files.
Scope:
TB1. M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India Learning
Private Limited 2018
TB2. A K Sharma “Computer Fundamentals and Programming”, 2nd Edition, University
Press, 2018
TB3. Pradeep Dey and Manas Ghosh, “Programming in C”, Oxford Press, 2nd Edition,
2017
168
RB3. E. Balaguruswamy, Programming in ANSI C, Tata McGraw-Hill.
RB4. ReemaTharaja “Introduction to C Programming”, Second Edition, OXFORD Press,
2015
RB5: https://www.tutorialspoint.com/cprogramming/index.htm
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
169
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;
170
}
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)
171
a) text file
b) big text file
c) binary file
d) empty text
Answer: c) binary file
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
172
Discussion questions / Expected Questions:
1. Compare and contrast Text file and binary file.(CO6)(BT3)
2. Explain different modes to open a text file. (CO6)(BT2)
3. How does file pointer created in C program? (CO6)(BT1)
4. Why do we need a file? (CO6)(BT1)
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():
173
It reads a string from a stream.
3. fscanf()
This function is to read strings from a file, but it stops reading after encountering the
first space character.
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 .
174
Syntax: size_t fread(void *ptr, size_t sizeOfElements, size_t numberOfElements, FILE
*fp);
Here,
ptr − the pointer to a block of memory with a minimum size of sizeOfElements *
numberOfElements bytes.
sizeOfElements − the size in bytes of each element to be read.
numberOfElements − the number of elements, each one with a size of size bytes.
fp − the pointer to a FILE object that specifies an input stream.
Example: Write a program to read data from file using fread() method
#include <stdio.h>
int main () {
FILE *fp;
char output[100];
/* Open file for reading */
fp = fopen("myfile.txt", "r");
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.
175
b) fscanf() can specifies a stream from which to read whereas scanf() can read only from
standard input
c) fscanf() and scanf() has no difference in their functions
d) fscanf() and scanf() can read from specified stream
Answer:b) fscanf() can specifies a stream from which to read whereas scanf() can read
only from standard input
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
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
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 );
177
Example: Write a program to write data to a file using fputs() method
#include <stdio.h>
main() {
FILE *fp;
fp = fopen(“myfilet.txt", "w");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
3. fprintf()
It sends formatted output to a stream..
Syntax: int fprintf(FILE *fp, const char *format, [ argument, ...])
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * fp;
fp = fopen ("file.txt", "w");
fprintf(fp, "%s %d", "CSE dept code is", 733);
fclose(fp);
return 0;
}
writing data to binary file:
The following function is used for writing data to a Binary File.
1. fwrite()
It writes data from the array pointed to by ptr to the given stream.
Syntax: size_t fread(void *ptr, size_t sizeOfElements, size_t numberOfElements, FILE
*fp);
Here,
ptr − the pointer to a block of memory with a minimum size of sizeOfElements *
numberOfElements bytes.
sizeOfElements − the size in bytes of each element to be read.
numberOfElements − the number of elements, each one with a size of size bytes.
fp − the pointer to a FILE object that specifies an input stream.
#include<stdio.h>
178
int main () {
FILE *fp;
char str[] = "CSE department code is 733";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
return 0;
}
Example: Demonstrate a program to access data from a file using random access file
operations.
#include <stdio.h>
int main () {
FILE *fp;
int len;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("Total size of file.txt = %d bytes\n", len);
return 0;
}
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.
180
c) fprint(), scanf()
d) read(), write()
Answer:b) fread(), fwrite()
5. Which C function is used to move current pointer to the beginning of file.?(CO6)(BT1)
a) revise(fp)
b) rewind(fp)
c) ftell(fp)
d) frewind(fp)
Answer:b) rewind(fp)
Objective:
Outcome:
181
Scope:
1. M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India Learning Private Limited 2018
2. AKSharma“ComputerFundamentalsandProgramming”,2ndEdition, University Press,2018
3. PradeepDeyandManasGhosh,“ProgramminginC”,OxfordPress,2nd 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
182
# 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
184
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
185
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
//cod
e
#endif
#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code.
Syntax:
#ifndef MACRO
//cod
e
#endif
#if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes
the code.
Syntax:
#if expression
//cod
e
#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:
186
Example Code:
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
Example –
#if !defined(MY_CONSTANT)
#define MY_CONSTANT 0
#endif
187
These directives determine if MY_CONSTANT is defined or not. The expression defined
(MY_CONSTANT) evaluates to 1 if MY_CONSTANT is not defined and is defined else it evaluates to 0.
#include <stdio.h>
#define MEMBER
int main()
float amount,total;
printf("enter amount\n");
scanf("%f",&amount);
#ifdef MEMBER
total= amount*0.8;
printf("Amount to be paid=%f",total);
#else
printf("Amount to be paid=%f",amount);
#endif
188
Summary exercise:
Following table will show you various directives that we have studied in this chapter:
Directives Description
Questions:
189
MCQ
void main()
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
190
D. Garbage value
Answer: A
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
191