0% found this document useful (0 votes)
22 views

_PPS Notes

The document outlines a course on Programming for Problem Solving, detailing modules on data representation, algorithm design, and programming languages, particularly C. It explains computer components, operating systems, compilers, and the compilation process, alongside flowcharting and programming language types. Additionally, it covers the structure of a C program, including keywords, identifiers, and variables, emphasizing the importance of documentation and the execution flow in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

_PPS Notes

The document outlines a course on Programming for Problem Solving, detailing modules on data representation, algorithm design, and programming languages, particularly C. It explains computer components, operating systems, compilers, and the compilation process, alongside flowcharting and programming language types. Additionally, it covers the structure of a C program, including keywords, identifiers, and variables, emphasizing the importance of documentation and the execution flow in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 211

Course Code:20CS C01

Course Title:PROGRAMMING FOR PROBLEM SOLVING

Module Theme Learning Objectives


/Lectur
e
I Basic data, data types, and To understand how to define, represent,
data representation and process basic data.

II Analyzing, designing, and To diagrammatically understand and


managing a process or program visualize an algorithm using boxes of
for any given problem. various kinds. This representation gives a
step by step insight to a solution of a given
problem.
III Writing algorithm and flowchart By writing algorithm and representing in
to solve any given problem. flowchart helps student to solve a given
problem.

IV Operators and usage of keywords Can know the working of different operators
and its associativity and precedence.

V I/O statements in header file. Working of basic input and output


statements using stdio header file.

( Note: Take Lecture No, Theme from lesson plan )

Lecture title ( L1 etc)


Date [ You Can Write During the Course]
Key topics / themes of the lecture :

Notes, comments and your own Examples with answers/ questions

1
Components of a computer:

There are 5 main computer components that are given below:

o Input Devices
o CPU
o Output Devices
o Primary Memory
o Secondary Memory

The operations of computer components are given below:

1) Inputting: It is the process of entering raw data, instructions and information into the computer.
It is performed with the help of input devices.

2) Storing: The computer has primary memory and secondary storage to store data and
instructions. It stores the data before sending it to CPU for processing and also stores the processed
data before displaying it as output.

3) Processing: It is the process of converting the raw data into useful information. This process is
performed by the CPU of the computer. It takes the raw data from storage, processes it and then
sends back the processed data to storage.

4) Outputting: It is the process of presenting the processed data through output devices like
monitor, printer and speakers.

5) Controlling: This operation is performed by the control unit that is part of CPU. The control
unit ensures that all basic operations are executed in a right manner and sequence.

2
Operatingsystem:
In the Computer System (comprises of Hardware and software), Hardware can only understand
machine code (in the form of 0 and 1) which doesn't make any sense to a naive user.
We need a system which can act as an intermediary and manage all the processes and resources
present in the system.

An Operating System can be defined as an interface between user and hardware. It is


responsible for the execution of all the processes, Resource Allocation, CPU management, File
Management and many other tasks.
The purpose of an operating system is to provide an environment in which a user can execute
programs in convenient and efficient manner.

Compilers:

o A compiler is a translator that converts the high-level language into the machine language.
o High-level language is written by a developer and machine language can be understood by
the processor.
o Compiler is used to show errors to the programmer.
o The main purpose of compiler is to change the code written in one language without
changing the meaning of the program.
o When you execute a program which is written in HLL programming language then it
executes into two parts.
o In the first part, the source program compiled and translated into the object program (low
level language).
o In the second part, object program translated into the target program through the assembler.

3
Compilation Process in C:
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the object code or machine
code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the directive
and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into an
executable form:

o Preprocessor
o Compiler
o Assembler
o Linker

4
Preprocessor
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler converts
this code into assembly code. Or we can say that the C compiler converts the pre-processed code
into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file in
DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the
name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The main
working of the linker is to combine the object code of library files with the object code of our
program. Sometimes the situation arises when our program refers to the functions defined in other
files; then linker plays a very important role in this. It links the object code of these files to our
program. Therefore, we conclude that the job of the linker is to link the object code of our program
with the object code of the library files and other files. The output of the linker is the executable
file. The name of the executable file is the same as the source file but differs only in their
extensions. In DOS, the extension of the executable file is '.exe', and in UNIX, the executable file
5
can be named as 'a.out'. For example, if we are using printf() function in a program, then the linker
adds its associated code in an output file.

ProgramDevelopmentEnvironments:
The development environment helps the developers to develop the application or product using a
set of processes and programming tools.
An development environment provides developers an interface and convenient view of the
development process which includes writing code, testing the same and packaging the build so
that it can be deployed.
Ex:
Microsoft Visual Studio
Turbo C/C++
Dev C/C++
Flowchart:
Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts
use simple geometric shapes to depict processes and arrows to show relationships and
process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.

Symbol Symbol Name Purpose

Used at the beginning and end of the algorithm to


Start/Stop
show start and end of the program.

Indicates processes like mathematical operations.


Process

Input/ Output Used for denoting program inputs and outputs.

Stands for decision statements in a program,


where answer is usually Yes or No.
Decision

6
Shows relationships between different shapes.
Arrow

Connects two or more parts of a flowchart, which


are on the same page.
On-page Connector

Connects two parts of a flowchart which are


spread over different pages.
Off-page Connector

Examples:
Here is a flowchart to calculate the average of two numbers.

7
Here is a flowchart to calculate the even or odd number.

8
Programming Language
As we know, to communicate with a person, we need a specific language, similarly to
communicate with computers, programmers also need a language is called Programming language.
Before learning the programming language, let's understand what is language?
What is Language?
Language is a mode of communication that is used to share ideas, opinions with each other. For
example, if we want to teach someone, we need a language that is understandable by both
communicators.
What is a Programming Language?
A programming language is a computer language that is used by programmers (developers) to
communicate with computers. It is a set of instructions written in any specific language ( C, C++,
Java, Python) to perform a specific task.
A programming language is mainly used to develop desktop applications, websites, and mobile
applications.
Types of programming language
1. Low-level programming language
Low-level language is machine-dependent (0s and 1s) programming language. The processor
runs low- level programs directly without the need of a compiler or interpreter, so the programs
written in low-level language can be run very fast.
Low-level language is further divided into two parts -

i. Machine Language
Machine language is a type of low-level programming language. It is also called as machine code
or object code. Machine language is easier to read because it is normally displayed in binary or
hexadecimal form (base 16) form. It does not require a translator to convert the programs because
computers directly understand the machine language programs.
The advantage of machine language is that it helps the programmer to execute the programs faster
than the high-level programming language.

ii. Assembly Language


Assembly language (ASM) is also a type of low-level programming language that is designed for
specific processors. It represents the set of instructions in a symbolic and human-understandable
form. It uses an assembler to convert the assembly language to machine language.
The advantage of assembly language is that it requires less memory and less execution time to
execute a program.
2. High-level programming language
High-level programming language (HLL) is designed for developing user-friendly software
programs and websites. This programming language requires a compiler or interpreter to
translate the program into machine language (execute the program).
9
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.
A high-level language is further divided into three parts -

i. Procedural Oriented 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.
Procedural Oriented programming language is used by a software programmer to create a program
that can be accomplished by using a programming editor like IDE, Adobe Dreamweaver, or
Microsoft Visual Studio.
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.
Example: C, FORTRAN, Basic, Pascal, etc.

ii. Object-Oriented Programming language


Object-Oriented Programming (OOP) language is based upon the objects. In this programming
language, programs are divided into small parts called objects. It is used to implement real-
world entities like inheritance, polymorphism, abstraction, etc in the program to makes the
program resusable, efficient, and easy-to-use.
The main advantage of object-oriented programming is that OOP is faster and easier to execute,
maintain, modify, as well as debug.
Note: Object-Oriented Programming language follows a bottom-up approach.
Example: C++, Java, Python, C#, etc.

iii. Natural language


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.
3. Middle-level programming language
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.

10
A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human
language.
Example: C, C++ language

Introduction to C:

The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why it is known
as mother language.

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

Structure of C program:

11
Documentation Section :
This section consists of a set of comment lines useful for documentation. Though comments are
not necessary in a program, they help users to understand the program better.

Link(Preprocessor) and Definition Section:


This section contains header files which begin with a # symbol and are extended with .h. They are
also known as preprocessor directives used to include header files in a C program. Examples of
preprocessor statements are
#include<stdio.h>
#include<math.h>
Symbolic Constants are included using # define. For example to define the value of PI, the
statement is:
#define PI 3.14159

Global Declaration Section:


Global declaration section is used to define variables that would be used in more than one function.
Such variables are called global variables and they must be declared before the main( ) function.

The main( ) Function:


12
All C programs must contain main( ) function. Further there must be only one main( ) function.
main( ) denotes the starting of a C program.

Braces :
All C programs incorporate a set of curly braces { }. Execution of the program begins at the
opening brace { of the main( ) function and ends at its closing brace }.

Declaration Part:
This part is used to declare all the variables, arrays functions etc. used in the C program.
Initialization along with declaration can also be done here.

Executable Part :
This part of the program consists of a set of executable statements such as Input/ Output
statements, arithmetic statements, control statements etc. It can also include comment statements
which are ignored by the compiler (non-executable). The declaration part and the executable part
must be within opening and closing braces.

Every statement in the declaration part and executable part ends with a semicolon.

Subroutine Section:
This section is optional and consists of all the user-defined functions called in the main( ) function.
Example:
/*Program to find the area of a square*/
#include <stdio.h>
main()
{
float side, area ;
side=5;
area=side*side;
printf(―\nArea of a square=%f‘,area);
}
Output:
Area of a square = 25.0

C KEYWORDS:
There are some reserved words in C, called keywords. All the keywords have standard pre-defined
meanings and can be used only for the purpose intended. All keywords must be written in
lowercase. They cannot be used as user-defined identifiers. The standard keywords are listed
below
auto break case char const continue default do double else
enum extern float for goto if int longregister return
short signed sizeof static struct switch typedef union unsigned void
volatile while

IDENTIFIERS:
● Identifiers refer to the names of program elements such as variables, functions and arrays.
● Identifiers are sequence of characters chosen from the set A–Z, a–z, 0–9, and _

13
(underscore).
● C is a case sensitive language so that ALFA and Alfa are different.
● The underscore symbol _ is generally in the middle of an identifier (embedded).
● Identifiers may be of reasonable length of 8–10 characters though certain computers allow
up to 32 characters.
● Identifier names must start with an alphabet or underscore followed by letters, digit or a
combination of both.
● C has a list of keywords that cannot be used anywhere other than that predefined in the
language i.e., you can‘t have a variable named int. Also one must follow the practice of
choosing names for variables which indicate the roles of those variables in the program.

VARIABLES:
A variable is an identifier used to store a single data item. This data could be a numerical quantity
or a character constant. During execution of the program, data must be assigned to the variable.
Therefore a variable can take different values at different times during the execution of the
program. The data stored in the variable can be accessed any time, by referring to the variable
name.

The rules for naming a variable are the same as those for an identifier.
They are :
1. Variable names generally begin with a letter followed by letters, digits underscore or a
combination of all.
2. No special character except the underscore symbol ( _ ) is allowed. Underscore is generally
embedded in a variable name to make it more readable.
3. Maximum length of a variable name should not exceed 32 characters. Normally the length must
not exceed 8 characters since many compilers treat the first 8 characters as significant.
4. C variables are case sensitive, so that Counter, counter and COUNTER are 3 different variables.
5. C keywords cannot be used as variable names.
6. White spaces are not allowed in a variable name.
7. Appropriate variable names must be chosen to indicate their role in the program.

CONSTANTS:
Any fixed value that does not change during the execution of a program is known as a constant. C
consists of several types of constants.

Types of C constants:
C constants can be divided into two categories :
● Primary Constants
● Secondary Constants

These constants can further be divided as follows :

14
Integer Constants :
Integers and real constants are numbers and are generally referred to as numeric constants.
An integer constant consists of a sequence of digits and is an integer-valued number. There are 3
types of integer constants depending on the number system.
They are:
● Decimal (base 10)
● Octal (base 8)
● Hexadecimal (base 16)

Real Constants:
Quantities which are represented by numbers with fractional part are called real or floating point
constants.
(a) A real constant must have at least 1 digit.
(b) It must have a decimal point.
(c) It can be either positive or negative.
(d) No commas or blanks are allowed within a real constant.

Character Constants:
(a) A character constant is a single character within single quotes.
(b) The maximum length of a character constant is 1.
(c) Arithmetic operations are possible on character constant since they too represent integer values.
(d) C also recognizes all the backlash character constants (Escape sequences) available.

Note that the character constant ‗2‘ is not the same as the number 2. Every character has an
equivalent integer value known as the ASCII code. Some character constant & their equivalent
ASCII values are as below :
‗A‘ = 65
‗B‘ = 66
‗a‘ = 97
‗0‘ = 48
‗1‘ = 49

15
String Constants:
A string constant consists of zero or more number of characters enclosed within double quotes.
The characters within quotes could be digits, characters, special characters and blank spaces.
Ex: "Red", "Rs.20.25", " "

Note that ‗A‘ is not equal to ―A‖ since a string constant containing a single character does not have
a corresponding integer value. In fact it contains two characters, the specified character followed
by a null character represents by \0.

Coding constants:
There are 3 types of code constants used in programs:
● Literal constants
● Defined constants
● Memory constants

Literal constants: are used to specify data, which cannot be changed.


For example: x = y + 1 ;
In this statement 1 is a literal constant.

Defined Constants: are constants that can be defined using a preprocessor command #define.
This constant is placed at the beginning of a program since it is a preprocessor command.
For example :
# define MAX 30
The defined constants make the program easily modifiable and enhance the understandability of
the program.

Memory Constants: use a c type qualifier called const, to indicate that the data specified is a
constant and that it cannot be changed.
Its general format is :
const Datatype identifier = value ;
For example :
const float pi = 3.14159 ;
defines a memory constant pi of float type with a value of 3.14159.

I/O statements:
In C programming you can use scanf() and printf() predefined function to read and print data.
i) printf
This function is used for displaying the output on the screen i.e the data is moved from the
computer memory to the output device.

Syntax:
printf(―format string‖, arg1, arg2, …..);

In the above syntax, 'format string' will contain the information that is formatted. They are the
general characters which will be displayed as they are .
arg1, arg2 are the output data items.

16
Example: Demonstrating the printf function
printf(―Enter a value:‖);
● printf will generally examine from left to right of the string.
● The characters are displayed on the screen in the manner they are encountered until it comes
across % or \.
● Once it comes across the conversion specifiers it will take the first argument and print it in the
format given.
ii) scanf
scanf is used when we enter data by using an input device.

Syntax:
scanf (―format string‖, &arg1, &arg2, …..);

The number of items which are successful are returned.

Format string consists of the conversion specifier. Arguments can be variables or array name and
represent the address of the variable. Each variable must be preceded by an ampersand (&). Array
names should never begin with an ampersand.

Example: Demonstrating scanf


intavg;
float per;
char grade;
scanf(―%d %f %c‖,&avg, &per, &grade):
● scanf works totally opposite to printf. The input is read, interpret using the conversion specifier
and stores it in the given variable.
● The conversion specifier for scanf is the same as printf.
● scanf reads the characters from the input as long as the characters match or it will terminate. The
order of the characters that are entered are not important.
● It requires an enter key in order to accept an input.

OPERATORS IN C :
C provides several operators for elementary arithmetic operations like addition, subtraction,
multiplication, division, residue-modulo (the operation that gives the remainder after division of
one integer by another) and logical manipulations.
An operator is a symbol used for certain type of manipulations, logical or mathematical. The data
on which the operators act are called operands. An expression is a valid combination of operators
and operands that results in a value.
For example in the expression : 12*5
* is the multiplication operator,
12 and 5 are the operands.

Operators may be classified into 4 categories namely


(i) unary
(ii) Binary
(iii) Ternary
(iv) Special

17
Unary Operators:
Operators that operate on a single operand are known as unary operators. The unary operators
always precede the operand. The different unary operators available in C are :
(i) Unary plus (+)
(ii) Unary minus (–)
(iii) Increment (++)
(iv) Decrement (– –)
(v) Logical NOT (!)
(vi) Bitwise complement (~)
(vii)Address (&)
The unary minus operator is used for negation. It change sign of the quantity on its right i.e., it
multiplies its only operand by –1. Similarly unary plus multiplies its operand by +1.

Binary Operators:
Binary operators operate on two operands. They are classified into five categories as follows:
(i) Arithmetic
(ii) Relational
(iii) Logical
(iv) Assignment
(v) Bitwise

Ternary Operators:
Ternary operators act on three data elements. The conditional operator (?:) is a ternary operator

Special Operators:
Special operators include operators such as comma (,) and sizeof.

ARITHMETIC OPERATORS:
C supports five arithmetic operators.

Operator Purpose
+ Addition
– Subtraction or (unary)
* Multiplication
/ Division
% Remainder after integer division

There is no exponentiation operator available in C. However, the library function pow( ) is


provided to compute exponentiation.

Dividing one integer by another integer is called as integer division, which truncates, the fractional
part. The % operator gives the remainder of such a division.
For example, consider a = 10, b = 3.
a % b gives 10% 3 giving the result 1
and a/b gives 10/3 giving the result 3

18
% operator can have only integer operands.

Mixed-mode Arithmetic operations consists of a real and an integer operand. If one of the operand
is real, the result is also real.
For example :
15/2.0 = 7.5
However 15/2 = 7

RELATIONAL OPERATORS:
The relational operators are used to form relational expressions, representing conditions that are
either true or false. The result of the expression is an integer. Further, false is represented by zero
value and true in represented by non-zero value. For example expressions
50<200
x>y
are called relational expressions whose value can be either true or false i.e., 50<200 is true. when
x = 10 and y = 5, x > y is true. There are 6 relational operators in C.
They are:
Operator Meaning
> greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

Consider 3 integer variables, i = 1, j = 2 and k = 7


Expression Logical value Integral value
(i) 10.5<=12 true 1
(ii) i==20 false 0
(iii) 5>20 false 0
(iv) (i+j)>=k false 0
(v) (j+k+1)>(i+5) true 1
(vi) k!=7 false 0

In the 4th and 5th example given above the expressions contain arithmetic expression. Thus in the
relational expression (i+j)>=k, the arithmetic expression i+j will be evaluated and then the result is
compared with k. These arithmetic operators have higher priority over relational operators. The
relational operators are used to compare two quantities in decision statements.
LOGICAL OPERATORS:
Logical operators are used to combine two or more logical expressions. There are 3 logical
operators in C. They are logical AND, logical OR and logical NOT

Operator Meaning
! logical NOT
&& logical AND
|| logical OR

19
● The result of a logical AND is true only if both operands are true. The result is false if
either operand is false.
● The result of a logical OR is false only if both operands are false. The result is true if either
operand is true.
● C also consists of the unary operator ! (not) that negates the value of a logical expression
i.e., it causes true expression to become false and vice-versa. This operator is known as
logical NOT operator. Further like relational operators, a logical expression results in zero
or non-zero value depending on whether it is false or true.

Consider i = 8, x = 5.1, c = ‗a‘ where i is an integer variable, x is a floating point variable and c is a
char variable.
Expression Logical value Integer value
(i>6)&&(c==‘a‘) true 1 (or non-zero)
i<=6||(c==‘b‘) false 0
i>=6&&(c==97) true 1
!(i<=4) true 1

ASSIGNMENTOPERATORS
The assignment operator ‗=‘ is used to assign the value of a variable, constant or expression
to a variable. The syntax is :

variable=variable/constant/expression;

For example :
x=10; /*x is assigned a value 10 */

b=x; /*The value of x is assigned to b i.e.,10*/

sum=a+b; /*Thesumofa&bwhichis20isassignedtosum*/

C also provides abbreviated or shorthand assignment operators. They are of the


form:
Variable operator = Expression;

For example the statement


n = n + 5;
can be written using shorthand assignment operator as :
n + = 5;

Where += is the abbreviated or compound operator. In the above case + = means add
5ton.Thedifferentshorthandassignmentoperatorsare:

20
Normal Shorthand Operator Meaning
assignment assignment
n=n+1 n += 1 += sum & assign
n = n – 50 n –= 50 –= subtract & assign
n = n*10 n *= 10 *= multiply & assign
n=n/6 n /= 6 /= divide & assign
n=n%5 n %= 5 %= find modulo and assign

The priority of the above operators + =, –=, *=, /= and % = is the same as theassignment operator.
Difference between = = and = operator
1. == is an equality or relational operator, used for comparison = is an assignmentoperator
which assigns the resultant value on its right hand side to the variableon its left hand
side.
2. == operator does not change the value of the variable on the left hand side.However =
operator does change the value of the variable on the left hand side of the
assignmentstatement.
INCREMENT/DECREMENTOPERATOR
Theincrement and decrement operators are specifically used in C or C++.
They are not generally available in other languages.
Increment operator ++ is used to increment the value of the variable by 1.Decrement
operator – – is used to decrement the value of the variable by 1.
They are also called as unary operators Fig. 2.14. Since they operate on only one
dataelement.

Operator Meanings Usage


++ Increment a++ or ++ a means a = a + 1
–– Decrement a – – or – – a means a = a – 1

Consider the following statements :


int x,y;
:
x =10;
y = ++x;
x is increment by 1 so that x and y will have a value 11. Similarly in

21
int a, b;
:
a = 5;
b = --a;
will result in the value of a and b to be 4.

Post-increment operator ++ is written to the right of its operand as in n ++; which is the same
as n = n + 1;
Post-decrement operator – – is also written to the right of its operand as in n—
, and is equivalent to n = n – 1;
Pre-increment and pre-decrement operators ++ and – – are always placed to theleft of the
operand as follows :
++n; /* same as n =n+1*/
––n; /* same as n =n–1*/

The behavior of post and pre–increment or decrement operators are the same when used
with a single operand. However, they behave differently when the operand is embedded in an
expression.
Difference between postfix & prefixoperators
(i) The pre-increment or decrement operator first increments or decrements the value of
its operand by 1 and then assigns the resulting value to the variable onthe left hand
side. For example,consider
int a, b; a =
15;
b = ++a;
In this example, the value of a is incremented by 1 and then this value 16 is assigned to
b.
(ii) The post increment or decrement operator first assigns the value to the variable on the
left hand side and then increments or decrements the operand by 1. Consider the
following program segment:
intm,n; n = 2;
m = n– –;

The value of n is first assigned to m and then it is decremented i.e., n becomes 1, but value
of m is 2.
In subscripted variables.
a[j++]=5;
is equivalent to a[j]=5;
j++;

22
Similarly, a[++i]=5;
is equivalent to i = i+1;
a[i] = 5;
Consider the statement
x = n++/2;
where n = 5. After execution, n is 6 but x gets the value 5/2 which is 2.

TERNARY OPERATOR (CONDITIONALOPERATOR)


C consists of a very special operator known as ternary or conditional operator and
isrepresented by ? : The syntax is
expression1 ?expression2 : expression3;

and general usage is as


variable = expression1 ? expression2 :expression3;

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.

Consider the following statements :


n = 5;
m = 10;
big = (n > m) ? n :m;
Here n> m is evaluated first giving the result ‗false‘. Since the expression is false the value
of m is assigned to big. Thus big = 10. The same can be written in the form of if else statement
as follows :
if(n > m) big = n; else
big = m;
Some more examples :
(10 == 8) ? 2:4 //resultis4since10isnotequalto8
(10>8) ? 2:4 //result is 2 since 10 is greater than 8
(10==8+3) ? 2:4 //result is 4 since 10 is not equal to11
23
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
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;

For example, the statement:


result = (a = 5, b = 10, a + b);
⬥ firstassigns5toai.e.,a=5
⬥ nextassigns10tobi.e.,b=10
⬥ andfinallyassignsthevalueofa+bi.e.,10+5=15toresult.
(v) The comma operator needs parentheses, since it has the lowest precedence compared
to all otheroperator.
(vi) The comma operator is used in for( ) loops to separate more than one expression. It is

for (exp1a, exb1b; exp2; exp3a, exp3b)statement;


possible to write:
(vii) It can also be used in while loops to separate more than one expression. For example:
while(textchar=getchar( ),textchar ! = „\n‟)
putchar(textchar);
In this example, the end condition for input is checked first and then it waits for
input of a character. The program terminates as soon as the enter key is pressed.

The sizeofoperator
24
(i) Thesizeofoperatorreturnsthesizeinbytesoftheoperandontheright.
(ii) The syntaxis

sizeof(n)

where n can be a variable, a constant or a data type.


(iii) Itisaunaryoperatorwhichassociatesfromrighttoleft.
(iv) The size of operator is used to determine the size of an array or a structure. It is
alsousedfordynamicmemoryallocationofvariables.

Example 2.30
/* Program to show usage of sizeof operator
*/ #define STRING “Usage of sizeof
Operator” #include <stdio.h>
main()
{
char a = „p‟;
clrscr();
printf(“\n The size ofcharis : %d \n”,sizeof(char));
printf(“\n Therefore the size of char ais : %d \n”,sizeof(a));
printf(“\n However the size of„p‟is : %d \n”,sizeof(„p‟));
printf(“\nSTRING : \”%s\”
\n”,STRING); printf(“\n The number of bytes in STRINGis : %d
\n”,sizeof STRING); printf(“\n The size ofshortis : %d\n”,sizeof(short));
printf(“\n The size ofintis : %d\n”,sizeof(int));
printf(“\n The size oflongis : %d\n”,sizeof(long));
printf(“\n The size offloatis : %d\n”,sizeof(float));
printf(“\n The size ofdoubleis : %d
\n”,sizeof(double)); getch();
}

25
Output
The size ofcharis 1
Therefore the size of charais 1
However the size of„p‟is 2
STRING : “Usage of sizeof
Operator” The number of bytes inSTRINGis 25
The size ofshortis 2
The size ofintis 2
The size oflongis 4
The size offloatis 4
The size ofdoubleis 8

BITWISEOPERATORS:
C supports a powerful set of operators known as bitwise operators. The bitwise
operatorsare used for controlling and interacting with hardware and also for
manipulating data at the bit level.
The Bitwise operators are as shown below table.

Operator Description
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ one‘s complement

(i) Bitwise operators cannot be applied to float or double. They can be applied to
integersonly.
(ii) All except ~ operator are used in binary operations. Tilde (~) is a unaryoperator.
(iii) Bitwise operators perform bitwise logical AND, bitwise logical OR,
bitwiseexclusiveOR,bitwiseshiftleftandshiftright.
(iv) Bitwise operators work on their operands bit by bit starting from the least significant
bit. The truth table for logical bitwise operations is as shown in below
table.Trueistakentobe1andfalseaszero.

26
Operand Operand x & x|y x^y
1 2 y
x y
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Bitwise ANDOperator:
TheBitwise AND operator is represented by the symbol & (ampersand). The
result of AND operation is 1 if both operand bits are 1, otherwise, the result is zero.
Further,theANDoperationisdoneonthebinaryrepresentationoftheoperands.

4 & 5 results in 4
i.e., binary value of4is 0100
binary value of5is 0101
AfterANDoperation 0100 i.e.,4

Bitwise & operator is used to check whether a particular bit is 0 or 1. Consider the number
21. Its bit pattern is represented by
0001 0101
To check whether the fourth bit is 0 or 1, AND operation must be done withanother
4
operand whose value must be 2 i.e., 16, which can be represented as00010000.

Therefore, 00010101
0001 0000 & mask
0001 0000
th
result shows that 4 bit is 1 since the resultant value is 16.

Bitwise OROperator
The bitwise OR Operator is represented by the symbol | (vertical bar). It is also known as
inclusive OR. The result of a bitwise OR operation is 1 if either or bothcorresponding bits has a
value 1. Otherwise it is zero.

Consider x = 4, y = 9
xis 00000100 4
yis 00001001 9

27
x|yis 00001101 i.e.,13
The bitwise OR is used to set a particular bit on (set to 1).

Bitwise Exclusive OROperator


This operator is represented by the symbol ^ and is known as Exclusive ORoperator. The
result of a bitwise XOR operation is 1 if one of the corresponding bits is 1, otherwise it is0.
Consider the values x = 4, y = 9.
xis 00000100 4
yis 00001001 9
x^yis 00001101 i.e.,13
Bitiwse ComplementOperator
The complement operator is represented by ~(tilde) and is also known as one‘s
complement operator. It inverts all the bits. Thus all the zeros become 1 and all the ones
become 0.

Consider x = 4
x is 00000100
~x is 11111011

Bitwise ShiftOperator
The shift operators are used to push the bit patterns to the right or left by thenumber of bits given
by theirright operand
The Right shift operator is of the form :
expression>>n

where n is the number of bit positions to be shifted. However the rightmost n bitsare lost.
Further the left most n bits which are vacant will be filled with zero. For
examplex>>4shiftsallbitsby4placestotheright.
The Left shift operator is of the form
expression<<n
where n is the number of bit positions to be shifted. The left most n bits are lost andthe
rightmost n bits are vacated and filled with zeros.
Shift operators are used for multiplication and division by 2. For example, the statement
x = y << 2;
2
shifts two bit to the left in y. Further the value of x is equal to y multiplied by 2 .
Similarly, the statement
x = y >> 2;
28
2
shifts the bits in y to the right by 2. Also the value of x is equal to y divided by 2 .

PRECEDENCE OF ARITHMETICOPERATORS:
Any arithmetic expressionis evaluated according to the rule of precedence of operators. For
example in the expression.
4*5/2

Evaluation takes place from left to right i.e.,


First 4 is multiplied by 5 and the result 20 is divided by 2.
The order in which the expression is evaluated depends on the hierarchy ofoperators

Precedence level Operators Associativity


1 () Left to right
2 unary Right to left
3 *,/,% Left to right
4 +, – Left to right

⬥ In an arithmetic expression, the expression enclosed in parentheses is


evaluatedaccording to theprecedence.
⬥ 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

PRECEDENCE AND ASSOCIATIVITY OFOPERATORS


The precedence of operators comes into effect whenever there are more than one operators
involved in the expression to be evaluated.
⬥ Therearemanylevelsofprecedence,eachcontainingoneormoreoperator.
⬥ Theoperatorwiththehighestprecedencelevelisevaluatedfirst.
⬥ Operators in the same level are evaluated either from left to right or right to
leftdepending on their associativity. Associativity determines the operations to be
performed from right and from left, when several operators of the same priority level
exist in the sameexpression.
⬥ The order of precedence and associativity of operators are two very important
aspectsofevaluation.Forexample,considerthestatement

29
(a < 10&& a + b > 15)

where a = 20, b = 1.
The order of evaluation will be as follows.
(i) Since + operator has the highest priority in the expression, addition is computed first:
a < 10 && 21 > 15

(ii) Both the relational operators have higher priority compared to the logical operator &&.
Here the associativity of relational operators has to be considered which is leftto right.
Thus:
20 <10 && 21 > 15
False && True

(iii) Theresultoflogical&&isfalseor0.
A complete operator precedence summary is listed in Fig. 2.20, from highest to lowest.

Operator Operator category Associativity Rank


() Function call/Innermost parenthesis L to R 1
[] Array element
member selection
+ unary plus R to L 2
– unary minus
++ increment
–– decrement
! logicalNot
~ One's
* complement
& Pointer reference
sizeof Addressof
(type)
size of a variable
cast operator
*, /, % Multiplication, division and remainder L to R 3
+, – Addition and subtraction L to R 4
<< , >> Left shift and Right shift L to R 5

30
<,<=, >,>= Relational operators L to R 6
==, != Equality operators L to R 7
& Bitwise AND L to R 8
^ Bitwise XOR (Exclusive OR) L to R 9
Bitwise OR (Inclusive OR) L to R 10
&& Logical AND L to R 11
|| Logical OR L to R 12
?: Conditional operator R to L 13
=, Assignment R to L 14
*=, /=, operators
%=, += and
–= Abbreviated
&=, ^=, assignment
!=, <<=, >>= operators
, Comma operator L to R 15

Summary exercise:

1. Difference between algorithm and flowchart

2. The importance of C language.

3. Different types of datatypes

4. Different types of operators in C language and its working.

Review and revision:


Review and revision exercise (1) :

Lecture topic quiz / MCQs:

1. The smallest unit of data in computer is ________________


a) Byte b) Nibble c) Bit d) KB ----
Answer: c
Explanation: A bit is defined as the smallest unit of data in a computer system. It is used as a short
form of Binary Digit. A bit can have only two values 0 or 1. A nibble comprises of 4 bits; a byte is
31
a collection of 8 bits whereas KB (Kilobyte) is equal to 1024 bytes.

2. Which of the following is incorrect?


Algorithms can be represented:
a) as pseudo codes b) as syntax
c) as programs d) as flowcharts
Answer: b
3. What do you call a specific instruction designed to do a task?
a) Command b) Process c) Task d) Instruction
Answer: a
4. An Identifier may contain?
A) Letters a-z, A-Z in Basic character set.
B) Underscore _ symbol
C) Numbers 0 to 9
D) All the above
Answer: D
Explanation: an identifier contains letters, numbers and _ symbol.
5. Left shift (<<) and Right shift (>>) operators are equivalent to _____ and ________ by 2.
A) Multiplication and Division
B) Division and Multiplication
C) Multiplication and Remainder
D) Remainder and Multiplication
Answer: A
Explanation: Left shift by 1 return the multiplication by 2 and Right shift by 1 return the division
by 2.
Review and revision exercise (2) :

Discussion questions/ Expected Questions:


1. Draw and explain the block diagram of computer.

2. Write detailed notes on C data types

3. Write about conditional operator (ternary operator).

Course Code: 20CS C01

Course Title:PROGRAMMING FOR PROBLEM SOLVING


32
Instructors Name:
Name Email
Dr.T. Ratna Reddy tratnareddy_mech@cbit.ac.in

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:

(a) Text Book:

nd
Pradeep DeyandManasGhosh,―ProgramminginC‖,OxfordPress,2 Edition,2017

(b) Reference Books:

E.Balaguruswamy,ProgramminginANSIC,TataMcGraw-Hill.

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

33
L.10 Switch-Statement, Nested To understand else-if ladder, switch statement, use
Statements and Examples. for different situations

L.11 Loop ControlStatements: For, While, To understand Loop statements: while, do while and
Do-While and Examples. for statements, how to use with the combination of
other statements

L.12 Continue, Break and Go To To learn Jumping/ unconditional statements-


statements. break,continue,goto, to Use these with combination
of other statements, Understand nested loops.

L.13 Case Study on control structures. The general purpose of a case study is to:
→ describe an individual situation (case), in
detail;
→ identify the key issues of the case;
→ analyse the case using relevant theoretical
concepts from the module;
→ recommend a course of action for that
particular case.

Lecture : 9
Objectives: 1.What are various control structures
2. Classification
3. if, if else, nested if else

Control structures

34
Selective control statements:
1. if
2. if else
3. nested if else
4. else if ladder
5. switch
Iterative control statements :
1. for loop,
2. while loop,
3. do while loop

Simple if statement
1. Simple if statement is used to make a decision “yes or no”, based on the available choice. It
has the following form:

Syntax:
if ( condition )
{
stmt block;
}
stmt-x;

In this syntax,

● if is the keyword.
● <condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses and no terminator (;) at the end.
● The stmt block can be a simple statement or a compound statement or a null statement.
● stmt-x is any valid C statement.

35
1. flow chart for simple if.
Whenever simple if statement is encountered, first the condition is tested. It returns either
true or false. If the condition is false, the control transfers directly to stmt-x without considering
the stmt block. If the condition is true, the control enters into the stmt block. Once, the end of
stmt block is reached, the control transfers to stmt-x

1. Example Program for if statement:


#include<stdio.h>main()
{
int number;
printf("enter a number\n"); scanf("%d",&number);
if(number%2==0)
printf("Even number\n");

Output:
enter a number
12
Even number
if - else statement

if…else statement is used to make a decision based on two choices. It has the following
form:

1. Syntax:
if(condition)
{
true stmt block;
}
else
{
false stmt block;
}
Stmt-x;

In this syntax,
● if and else are the keywords.
36
● <condition>is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses .
● The true stmt block and falsestmtblock are simple statements or compound statements or
null statements.
● stmt-x is any valid C statement.

1. Flow chart:

Whenever if...else statement is encountered, first the condition is tested.


It returns either true or false.
If the condition is true, the control enters into the true stmt block.
Once, the end of true stmt block is reached, the control transfers to stmt-x without
considering else-body.

If the condition is false, the control enters into the false stmt block by skipping true stmt
block.
Once, the end of false stmt block is reached, the control transfers to stmt-x.

1. Program for if else statement:


/* odd or even */

#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");
}

Output: enter a number

37
11
ODD

More examples on if else

/* largest of two numbers */


#include <stdio.h>
main()
{
Int x,y,big;

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");

if(x<0 && y>0)


printf("SECOND QUADRANT\n");

if(x<0 && y<0)


printf("THIRD QUADRANT\n");

if(x>0 && y<0)


printf("FOURTH QUADRANT\n");

38
}

/* alphabet or not */
#include <stdio.h>
main()
{
charch;
printf("Enter a character\n");
scanf("%c",&ch);
if(ch>= 'a' &&ch<='z')
printf("alphabet\n");
else
printf("not a alphabet\n");
}

/* vowel or not */
#include <stdio.h>
main()
{
char ch;
printf("Enter a alphabet\n");
scanf("%c",&ch);
if(ch== 'a' || ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("vowel\n");
else
printf("not a vowel\n");
}

Nested if—else statement

Nested if…else statement is one of the conditional control-flow statements. If the body of if
statement contains at least one if statement, then that if statement is called as ―Nested if…else
statement‖. The nested if…else statement can be used in such a situation where at least two
conditions should be satisfied in order to execute particular set of instructions. It can also be
used to make a decision among multiple choices. The nested if…else statement has the
following form:
Syntax: if(condition1)
{
if(condition 2)
{
stmt1;
}
else
{
stmt2;

}
}
else
{

39
stmt 3;
}

stmt-x;

In this syntax,

● if and else are keywords.


● <condition1>,<condition2> … <condition>are relational expressions or logical
expressions or any other expressions that return true or false. It is important to note that
the condition should be enclosed within parentheses ( and ).
● if-body and else-body are simple statements or compound statements or empty
statements.
● stmt-x is a valid C statement.
The flow of control using Nested if...else statement is determined as follows

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.

Program for nested if… else statement:

#include<stdio.h>
40
#include<conio.h>
void main()
{

int a ,b,c;

printf("enter three values\n"); scanf("%d%d%d",&a,&b,&c); if(a>b)


{
if(a>c)
pintf("%d\n",a);
else
printf("%d\n",b);
}

else
{
if(c>b)
printf("%d\n",c);
else
printf("%d\n",b);
}

Output: enter three values 3 5 12


12

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)

41
Lecture- 10
Objectives:
1. To understand else-if ladder
2. To understand switch statement
3. Learn to use for different situations

if-else if STATEMENT OR else if ladder


Introduction
If we want to make one decisions out of many options, then we can use the if-else if statement.
Syntax
The general format for the if-else if statement is:

if (condition 1)
simple or compound statement // s1
else if (condition 2)
simple or compound statement // s2
else if ( condition 3)
simple or compound statement // s3
.....
else if ( conditon n )
simple or compound statement // sn

If condition 1 is true then s1 is executed.


If condition 1 is false and condition 2 is true then s2 is executed.
The else clause is always associated with the nearest unresolved if statement.

Whenever else if ladder is encountered, condition1 is tested first. If it is true, the statement 1 gets executed.
After then the control transfers to stmt-x.

42
If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are tested. If all are
false, the default stmt at the end gets executed. After then the control transfers to stmt-x.

If any one of all conditions is true, then the body associated with it gets executed. After that the control
transfers to stmt-x.

Points to Remember
1. We can use if-else if when you want to check several conditions but still execute one statement.
2. When writing an if-else if statement, be careful to associate else statement to the appropriate if
statement.
3. We must have parentheses around the condition.

Example program:
/* to find grade when percentage of marks are given */
#include<stdio.h>
void main()
{

int m1,m2,m3,avg,tot;
printf("enter three subject marks");
scanf("%d%d%d",&m1,&m2,&m);
tot=m1+m2+m3;
avg=tot/3;
if(avg>=75)
{
printf("distinction");

else if(avg>=60 &&avg<75)


{
printf("first class");
}
else if(avg>=50 &&avg<60)
{
printf("second class");
}
else if (avg<50)
{
printf("fail");
}
}

Output: enter three subject marks


85 80 81
Distinction

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.
43
Syntax
The general format for a switch statement is
switch(integer expression)
{
case 1:
statement;
break;
case 2:
statement;
break;
---------
default:
statement;
}

Example of a case constant expression and column:


switch (i/10)
{
case 0: printf ("Number less than 10"); // A
break;
case 1: printf ("Number less than 20"); // B
break;
case 2: printf ("Number less than 30"); // C
break;
default: printf ("Number greater than or equal to 40"); // D
break;
}

Explanation
1. The switch expression should be an integer expression and, when evaluated, it must have an integer
value.
2. The case constant expression must represent a particular integer value and no two case expressions
should have the same value.
3. The value of the switch expression is compared with the case constant expression in the order specified,
that is, from the top down.
4. The execution begins from the case where the switch expression is matched and it flows downward.
5. In the absence of a break statement, all statements that are followed by matched cases are executed.
6. If there is no matched case then the default is executed. You can have either zero or one default
statement.
7. In the case of a nested switch statement, the break statements break the inner switch statement.

44
Flow chart:

Whenever, switch statement is encountered, first the value of <exp> gets matched with case values. If
suitable match is found, the statements block related to that matched case gets executed. The break
statement at the end transfers the control to the Next-statement.

If suitable match is not found, the default statements block gets executed and then the control gets
transferred to Next-statement.

Point to Remember
1. case constructs need not be serial.
2. characters can be used.
3. combination of integers and characters is possible.
4. default is optional.
5. Brace in case block is optional

//switch 1
// to display name of the day
#include <stdio.h>
void main()
{
int day;
printf("Enter day number\n");
scanf("%d",&day);
switch(day)
{
case 1:
printf("monday\n");
break;
case 2:
printf("tuesday\n");
break;
45
case 3:
printf("wednesday\n");
break;
case 4:
printf("thursday\n");
break;
case 5:
printf("friday\n");
break;
case 6:
printf("saturday\n");
break;
case 7:
printf("sunday\n");
break;
default:
printf("Wrong entry\n");
}
}
//switch 2
// to display the gender
#include <stdio.h>
void main()
{
charch;
printf("Enter your gender\n");
scanf("%c",&ch);
switch(ch)
{
case 'm':
case 'M':
printf("so you are a male\n");
break;

case 'f':
case 'F':
printf("so you are a female\n ")
break;

default:
printf("Wrong entry\n");
}
}

Program exercises:
1. Developa C program to input week number and print week day.(L3)(CO3)
2. Developa C program to input month number and print number of days in that month.(L3)(CO3)
3. Develop a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and
Computer. Calculate percentage and grade according to following:(L3)(CO3)
Percentage >= 90% : Grade A
Percentage >= 80% : Grade B
Percentage >= 70% : Grade C
Percentage >= 60% : Grade D
46
Percentage >= 40% : Grade E
Percentage < 40% : Grade F
1. Develop a C program to input basic salary of an employee and calculate its Gross salary according
to following:(L3)(CO3)
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary >20000 : HRA = 30%, DA = 95%
1. Develop a C program to input electricity unit charges and calculate total electricity bill according to
the given condition:(L3)(CO3)
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill(L3)(CO3)
1. Develop a C program print total number of days in a month using switch case.(L3)(CO3)
1. Develop a C program to check whether an alphabet is vowel or consonant using switch
case.(L3)(CO3)
1. Develop a C program to find maximum between two numbers using switch case.(L3)(CO3)
1. Develop a C program to find roots of a quadratic equation using switch case.(L3)(CO3)
1. Develop a C program to create Simple Calculator using switch case.
(L3)(CO3)

Lecture-11
Objective:
1. Loop statements: while, do while and for statements
2. How to use with the combination of other statements.

while LOOP
Introduction
The while loop is used when we want to repeat the execution of a certain statement or a set of statements
(compound statement).
Syntax
The general format for a while loop is
while (condition)
simple or compound statement (body of the loop)
For example,
i = 0;
while (i<5)
{
printf(" the value of i is %d\n", i);
i = i + 1;
}
Explanation
1. Before entering into the loop, the while condition is evaluated. If it is true then only the loop body is
executed.
2. Before making an iteration, the while condition is checked. If it is true then the loop body is executed.
3. It is the responsibility of the programmer to ensure that the condition is false after certain iterations;
otherwise, the loop will make infinite iterations and it will not terminate.
4. The programmer should be aware of the final value of the looping variable. For example, in this case,
the final value of the looping variable is 5.
5. While writing the loop body, you have to be careful to decide whether the loop variable is updated at
the start of the body or at the end of the body.

47
#include<stdio.h>
#include<conio.h>
int main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;

while(i<=n)

{
printf("%d ",i);
i=i+1;
}
}

Output: enter the range 10


1 2 3 4 5 6 7 8 9 10

do-while LOOP
Introduction
The do-while loop is used when we want to execute the loop body at least once. The do-while loop executes
the loop body and then traces the condition.

Syntax
The general format for a do-while loop is
do
simple or compound statement
while (condition);

For example,

i = 0;
do
48
{
printf(" the value of i is %d\n", i);
i = i + 1;
}
while (i<5);

Explanation
1. The loop body is executed at least once.
2. The condition is checked after executing the loop body once.
3. If the condition is false then the loop is terminated.
4. In this example, the last value of i is printed as 5.

#include<stdio.h>

#include<conio.h> int main()


{
int i,n;
printf("enter the range\n"); scanf("%d",&n);
i=1;
do
{
printf("%d\n",i);
i=i+1;
}
while(i<=n);
}

Output: enter the range 5


1
2
3
4
5

for LOOP
Introduction
The for loop is used only when the number of iterations is predetermined, for example, 10 iterations or 100
iterations.
Syntax
49
The general format for the for loop is
for (initializing; continuation condition; update)
simple or compound statement
For example,
for (i = 1; i<=5; i++)
{
printf("%d”, i");
}
Explanation
1. The for loop has four components; three are given in parentheses and one in the loop body.
2. All three components between the parentheses are optional.
3. The initialization part is executed first and only once.
4. The condition is evaluated before the loop body is executed. If the condition is false then the loop
body is not executed.
5. The update part is executed only after the loop body is executed and is generally used for updating
the loop variables.
6. The absence of a condition is taken as true.
7. It is the responsibility of the programmer to make sure the condition is false after certain iterations.

Program to print n natural numbers using for loop


#include<stdio.h>

#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);
}
}

Output: enter the value 5


12345

THE for LOOP WITH A COMMA OPERATOR


Introduction

50
We may want to control the loop variables in the same for loop. We can use one for loop with a comma
operator in such situations.
Syntax
for (i = 0, j = 10; i< 3 && j > 8; i++, j-)
printf (" the value of i and j %d %d\n",i, j);
Explanation
1. First iis initialized to 0, and j is initialized to 10.
2. The conditions i<3 and j>8 are evaluated and the result is printed only if both conditions are true.
3. After executing the loop body, iis incremented by 1 and j is decremented by 1.
4. The comma operator also returns a value. It returns the value of the rightmost operand.
The value of (i = 0, j = 10) is 10.

1. Program to find the factorial of a number


#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;

printf( "\nHow many Fibonacci numbers required ? ");


scanf("%d", &n);
printf("\nThe first %3d Fibonacci numbers are\n", n);
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;
}
}
//3. Sine series
/* sin(x) = x - x /3! + x /5! + .. .. .. */
3 5

#include <stdio.h>
main()
{
int i, n;
float x,denom, term, sum,deg;
printf("Enter value of x in deg and number of
terms: \n");
51
scanf("%f%d", &deg, &n);
x=deg*3.14/180;
sum = term = x;
for ( i = 2; i<= n; i++)
{
denom = (2 * i - 2)*( 2 * i - 1);
term *= -(x*x)/ denom;
sum += term;
}
printf("\ndeg = %.1f, Sum = %.2f", deg, sum);
} /* end of main */

/* cos(x) = 1– x /2! + x /4! + .. .. */


2 4

// 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", &deg, &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 */

// to find the sum of digits of a number


#include <stdio.h>
main()
{
intn,sum=0,digit;;
printf("Enter a number\n");
scanf("%d",&n);
while(n!=0)
{
digit=n%10;
sum=sum+digit;
n=n/10;
}
printf("%d",sum)
}

// to convert decimal number to binary number


#include <stdio.h>
main()
{
intn,sum=0,digit,i=0;
printf("Enter a number\n");
52
scanf("%d",&n);
while(n!=0)
{
digit=n%2;
sum=sum+digit*pow(10,i);
n=n/2;
i++;
}
printf("%d",sum);
}

Programming exercises:

1.Write a program to find n Fibonacci number.


th

2.Write a program to generate first n terms of Fibonacci series.


3.Write a program to find factorial of a number.
4.Write a program to check whether the given number is prime or not.
5.Write a program to print first n prime numbers.
6.Write a program to print prime numbers upto n.
7.Write a program to print prime numbers between n1 and n2.
8.WAP to display menu for selecting addition, subtraction, multiplication and division and compute
according to menu chosen. (Use do-while).
9. 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.
For example: 153 = (1*1*1) + (5*5*5) + (3*3*3)
1. WAP to find whether the given number is strong or not using functions.
(Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145 )

Lecture- 12
Objectives:
1. Jumping/ unconditional statements- break,continue,goto
2. Use these with combination of other statements.
3. Understand nested loops.

break statement

The break statement is used within the looping control statements, switch statement and nested loops. When
it is used with the for, while or do-while statements, the control comes out of the corresponding loop and
continues with the next statement.
53
When it is used in the nested loop or switch statement, the control comes out of that loop / switch statement
within which it is used. But, it does not come out of the complete nesting.

Syntax for the ―break statement is:

break;

In this syntax, break is the keyword.

The following representation shows the transfer of control when break statement is used:

Any loop

{
statement_1;
statement_2;
:

break;

next_statement;

Program for break statement:

#include<stdio.h>

#include<conio.h>
int main()
{
int i;

for(i=1; i<=10; i++)


{
if(i==6)
break;
printf("%d",i);
}
}

Output: 12345

2. continue statement

A continue statement is used within loops to end the execution of the current iteration and proceed to the
next iteration. It provides a way of skipping the remaining statements in that iteration after the continue
statement. It is important to note that a continue statement should be used only in loop constructs and not in
selective control statements.

54
Syntax for continue statement is:

continue;

where continue is the keyword.

The following representation shows the transfer of control when continue statement is used:
Any loop

statement_1; statement_2;
:

continue;

next_statement;

Program for continue statement:

#include<stdio.h>
#include<conio.h>
int main()
{

int i, sum=0, n;
for(i=1; i<=10; i++)
{

printf("enter any no:");


scanf("%d",&n);
if(n<0)
continue;
else
sum=sum+n;
printf("%d\n",sum);
}

Output: enter any no:8


18

3. goto statement

The goto statement transfers the control to the specified location unconditionally. There are certain situations
where goto statement makes the program simpler. For example, if a deeply nested loop is to be exited
earlier, goto may be used for breaking more than one loop at a time. In this case, a break statement will not
serve the purpose because it only exits a single loop.
55
Syntax for goto statement is:

label:

statement_1; statement_2;
:

goto label;

In this syntax, goto is the keyword and label is any valid identifier and should be ended with a colon (:).

The identifier following goto is a statement label and need not be declared. The name of the statement or
label can also be used as a variable name in the same program if it is declared appropriately. The compiler
identifies the name as a label if it appears in a goto statement and as a variable if it appears in an expression.

If the block of statements that has label appears before the goto statement, then the control has to move to
backward and that goto is called as backward goto. If the block of

statements that has label appears after the goto statement, then the control has to move to forward and that
goto is called as forward goto.

Program for goto statement:


#include<stdio.h>

#include<conio.h> void main()


{

printf("www."); goto x;
y:

printf("expert"); goto z;
x:

printf("c programming"); goto y;


z:

printf(".com");

Output: www.c programming expert.com

PROGRAM 1
1
56
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n;
for(line=1;line<=3;line++)
{
for(n=1;n<=line; n++)
printf("%3d",n);
printf("\n");
}
}
PROGRAM2
1
1 2
1 2 3
#include <stdio.h>
void main()
{
int line ,n,gap;
for(line=1;line<=3;line++)
{
for(gap=1;gap<=20-line;gap++)
printf(" ");
for (n=1;n<=line;n++)
printf("%4d",n);
printf("\n");
}
}
PROGRAM 3
/* 1
12
123
1234
12345

*/
#include <stdio.h>
void main()
{
int line ,n,gap;

for(line=1;line<=5;line++)
{
for(gap=1;gap<=5-line;gap++)
printf(" ");
for(n=1;n<=line;n++)
printf("%2d",n);
printf("\n");
}
}
PROGRAM 4
1
121
12312
1234123
57
123451234

#include <stdio.h>
void main()
{
int line ,n,gap;

for(line=1;line<=5;line++)
{
for(gap=1;gap<=20-line;gap++)
printf(" ");

for(n=1;n<=line;n++)
printf("%2d",n);

for(n=1;n<line;n++)
printf("%2d",n);
printf("\n");
}
}
//program 5 :Pascal triangle
#include <stdio.h>
void main()
{
int binom,n,q,g,x;
binom=1;
q=0;
printf("enter no of rows\n");
scanf("%d",&n);
while(q<n)
{
for(g=40-3*q;g>0;g--)
printf(" ");
for(x=0;x<=q;x++)
{
if((x==0)||(q==0))
binom=1;
else
binom = (binom*(q-x+1))/x;
printf("%6d",binom);
}
printf("\n");
q++;
}
}

Programming exercises:

Develop programs to display the given patterns (L3)(CO3)

*****
58
* *
* *
* *
*****

*****
*****
*****
*****
*****

*
**
**
* *
*****

10101
01010
10101
01010
10101

555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555

59
Lecture-13
Case Study on control structures:

1. To display the given decimal number in words


2. To display the given decimal number in roman numbers
3. To find the day name when date is entered.

// to display the given number in words


#include <stdio.h>
void main()
{
intnum,digit,temp,rev=0;
printf("Enter a number\n");
scanf("%d",&num);
temp=num;
while(num!=0)
{
digit=num%10;
rev = rev*10 + digit;
num=num/10;
}
while(rev!=0)
{
digit=rev%10;
switch(digit)
{
case 1:
printf("ONE ");
break;
case 2:
printf("TWO ");
break;
case 3:
printf("THREE ");
break;
case 4:
printf("FOUR ");
break;
case 5:
printf("FIVE ");
break;
case 6:
printf("SIX ");
60
break;
case 7:
printf("SEVEN ");
break;
case 8:
printf("EIGHT ");
break;
case 9:
printf("NINE ");
break;
case 0:
printf("ZERO ");
}
rev=rev/10;
}

while(temp%10==0)
{
printf("ZERO ");
temp=temp/10;
}
}

Short answer questions


1. What are the control structures available in C(L1)(CO3)
If, if else, nested if else, switch, for loop, while loop, do while loop, break, continue and goto
1. Name the selective constructs in c(L1)(CO3)
If,ifelse,nested if else, else if ladder, switch
1. Distinguish between a pre test looping and post test looping(L4)(CO3)
1. Name the loop constructs in c. (L1)(CO3)
1. Name the unconditional control statements in C(L1)(CO3)
1. Name the conditional control structures in C. (L1)(CO3)
1. Explain in detail the different forms of if constructs in c. (L2)(CO3)
1. What is conditional expression(L1)(CO3)
1. Illustrate the use of ternary operations. (L2)(CO3)
1. Explain the while structure with examples(L2)(CO3)
1. Explain the do-while structure with examples(L2)(CO3)
1. Can the action of a do-while structure is simulated by if or if-else structures?
(L4)(CO3)
2. Explain with an example.(L2)(CO3)
1. Compare the while structure with do-while structure
1. Write the advantages of while loop over the do-while loop(L2)(CO3)
1. How is a for loop equivalently written using a while loop.(L2)(CO3)
1. Under what circumstances will the do-while be more appropriate than the for
loop.(L2)(CO3)
1. What is a comma expression?(L2)(CO3)
1. What is the purpose of continue statement?(L2)(CO3)
1. What is the propose of break statement?(L2)(CO3)
1. Differentiate between break and continue statements.(L4)(CO3)
61
1. What is meant by nested loop?(L2)(CO3)
1. Explain switch-case structure with example.(L2)(CO3)
1. Compare the switch-case with if else structure.(L4)(CO3)
1. Why goto statements are discouraged?(L2)(CO3)
1. Rewrite the following without using compound relations(L2)(CO3)
if(EM>90&&EG>95||Total>190)
printf(“SUCCESS”);
else
printf(“Failure”);
1. what is the output of the following program(L2)(CO3)
main()
{
int i;
for(;i;)
i--;
printf(“%d”,i);
}
1. Distinguish between source code, object code and executable code.(L4)(CO3)
1. Draw flow chart for various loops.(L3)(CO3)
1. Draw flow chart for various control constructs.(L3)(CO3)

Programs:

1. Develop a program to find sum of digits of a given integer number.(L3)(CO3)


2. Develop a program to print the given integer number in reverse order.(L3)(CO3)
3. Develop a program to check whether the given number is palindrome or not.(L3)(CO3)
4. Develop a program to find largest of given two numbers.(L3)(CO3)
5. Develop a program find largest of given three numbers by using simple if, nested if, else
if ladder(L3)(CO3)
6. Develop a program to check whether the given triangle is right triangle or not(L3)(CO3)
7. Develop a program to find the quadrant position of given coordinate.(L3)(CO3)
8. Develop a program to check whether the entered character is vowel or not.(L3)(CO3)
9. Develop a program to print CBIT twenty times by using for loop.(L3)(CO3)
10.Develop a program to find the sum of first n natural numbers.(L3)(CO3)
11.Develop a program to find the sum of first n even numbers.(L3)(CO3)
12.Develop a program to find the sum of given n numbers.(L3)(CO3)
13.Develop a program to print n table upto 10.(L3)(CO3)
th

14.Develop a program to print the following triangle of numbers by using nested


loops.(L3)(CO3)

1
1 2
1 2 3
1 2 3 4

1
1 2
1 2 3
1 2
1
62
1

1
1 2
1 2 3
1
1 2 1
1 2 3 2 1
1
2 1 2
3 2 1 2 3
1. Write a program to print the sum of first n terms of sine series.(L3)(CO3)
1. Write a program to print the sum of first n terms of cosine series.(L3)(CO3)
1. Write a program to print the Pascal triangle.(L6)(CO3)
1. Write a program to find n Fibonacci number.(L3)(CO3)
th

1. Write a program to generate first n terms of Fibonacci series.(L3)(CO3)


1. Write a program to find factorial of a number.(L3)(CO3)
1. Write a program to check whether the given number is prime or not.(L3)(CO3)
1. Write a program to print first n prime numbers.(L3)(CO3)
1. Write a program to print prime numbers upto n.(L3)(CO3)
1. Write a program to print prime numbers between n1 and n2.(L3)(CO3)
1. WAP to display menu for selecting addition, subtraction, multiplication and division and
compute according to menu chosen. (Use do-while).(L3)(CO3)
1. WAP to addition, subtraction, and multiplication of two complex numbers (a+ib) and
(x+iy).(L3)(CO3)
1. 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)

1. WAP to find whether the given number is strong or not using functions.(L3)(CO3)
(Example: 145 = 1! + 4! + 5! = 1 + 24 + 120 = 145 )

1. Input a year from keyboard and determine whether it is leap year or not using the
conditional operator.(L3)(CO3)
1. Accept three numbers from user and determine which of the two numbers or all three
numbers are equal or not using logical operators.(L3)(CO3)
1. WAP to calculate nPr= n!/(n-r)!(L3)(CO3)
1. WAP to calculate nCr =n! / n!*(n-r)!(L3)(CO3)
1. WAP to find whether the given number is perfect or not
Example ( 6 is perfect number since 6 = 1 + 2 + 3)(L3)(CO3)

1. WAP to convert given decimal number to binary number by using a function.(L3)(CO3)

63
Course Code: 20CS C01

Course Title: PROGRAMMING FOR PROBLEM SOLVING

Instructors Name:

Name Email
Smt. Venkata Sushma Chinta venkatasushmachinta_mech@cbit.ac.in

Objective:

The primary goals of the module functions are to introduce:


● The major objective is to provide students with understanding of code organization and
functional decomposition with using different data types.

Outcome:

On Successful completion of the module: functions, students will be able to:

● Decompose a problem into modules and use functions to implement the modules.

Scope:

The Module covers the following topics:Basics of Functions, User-defined Functions, Inter
Function Communication, Standard Functions. Storage Classes (Auto, Register, Static, Extern),
Scope Rules. While the topics are taught using a C language, the intent of the course is to teach
a programming methodology and also a laboratory component that involves development and
testing of iterative and procedural programs using functions.
64
Text andReference:
(a) Text Book:

nd
Pradeep DeyandManasGhosh,―ProgramminginC‖,OxfordPress,2 Edition,2017

(b) Reference Books:

E.Balaguruswamy,ProgramminginANSIC,TataMcGraw-Hill.

Module/ Theme Learning Objectives


Lecture
L.14 Basics ofFunctions, User-defined To learn basic representation of functions, and
Functions. the way they are declared.

L.15 Inter Function Communication, To learn basic types of standard functions and
Standard Functions. recursive functions

L.16 Parameter Passing-Call-by-value, To learn Parameter Passing-Call-by-value, call-


call-by-reference by-reference

L.17 Storage Classes (Auto, Register, To learn Storage Classes (Auto, Register, Static,
Static, Extern), Scope Rules. Extern), Scope Rules.

L.18 Case Study on Functions The general purpose of a case study is to:
→ describe an individual situation (case), in
detail;
→ identify the key issues of the case;
→ analyse the case using relevant theoretical
concepts from the module;
→ recommend a course of action for that
particular case.

65
Lecture title L.14 to L.18
Date
Key topics:Introduction,usesoffunctions,Functiondefinition,declaration,passing parameters to
functions, recursion, scope of variables and storageclasses.
Case study using functions.
Definition:
A function is a set of instructions under a name that carries out a specific task,
assigned to it.

CLASSIFICATION of functions:
1. User defined functions (UDF)
2. Library functions
USER DEFINED FUNCTIONS

Without arguments with arguments

Without return with return Without return with return

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

1. It avoids the need for redundant programming of the same instructions.


2. Logical clarity of the programming will be clear.
3. Easy to debug.
4. A library with user defined functions can be created.

Function prototype:
If we use any variable in the program, we declare that variable in the declaration section of the

program. Similarly, any function that is to be called should be declared before its call in the calling

function. This declaration of a function is called function prototype.

Function declaration should be done either in the declaration section of calling function or

before it. The function prototype should agree with definition of that function.

Prototype contains the data type returned by the function followed by the name of that

function and a pair of parentheses enclosing the data type of each parameter separately.

66
Optionally the name of each parameter may be given.

Ex: int fact(int); or int fact(int n);

If there are no parameters, void should be shown in parentheses. Similarly, if there is no

return value, return value type should be indicated as void.

Function definition

Writing code for the function is called function definition.

Function definition contains function header + body of function.

Syntax of function header :return type name of the function ( arguments)

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.

Difference between actual and formal parameters


Variables used in function calling are called actual parameters or arguments.
Variables used in function definition are called formal parameters or dummy parameters or
place holders.

There are two parameter passing mechanisms


1. call by value. Or passing by value
2. call by reference or passing by address or call by address.
Call by value:
Passing arguments by value means , the contents of the arguments in the calling
function are not changed , even if they are changed in the called function.
This is because the content of the variable is copied to the formal parameter of the function
definition, thus preventing the contents of the argument in the calling function.
67
Call by reference:
Call by reference means sending the address of variables as arguments to the function.
When addresses are sent, the changes occurred in the called function can also effect in the
calling function.

/* example to illustrate call by value and call by reference*/


#include <stdio.h>
void main()
{
void makezero(int,int*); /*function prototype*/
int x=50,y=100;
makezero(x,&y); /* function call by value and referene */
printf(“x=%d y=%d”, x,y);
}
/* function makezero */
void makezero(int a,int *b)
{
a=0;
*b=0;
}

OUTPUT
x=50 y=0
Example programs on functions
Factorial of number by using function
#include <stdio.h>
main()
{
long int fact(int);
int n;
long int f;
printf("Enter a number\n");
scanf("%d",&n);
f = fact(n);
printf("The factorial of %d is %ld",n,f);
} /*end of main */

/* function fact*/
long int fact(int x)
{

68
int i;
long int f1=1;
for(i=1;i<=x;i++)
f1 = f1*i;
return(f1);
}
Fibonacci series by function
main()
{
int n;
void fib(int);
printf( "\nHow many Fibonacci numbers
required ? ");
scanf("%d", &n);
printf("\nThe first %3d fibonaccinumbers are\n", n);
fib(n);
}

void fib(int n)
{
int i, f1, f2, f3;
f1 = f2 = 1;
printf("%5d\n", f1);
printf("%5d\n", f2);
for( i = 3; i<= n; i++)
{
f3 = f1 + f2;
printf("%5d\n", f3);
f1 = f2;
f2 = f3;
}
}
GCD of two numbers by function
void main()
{
int m,n,g;
int gcd(int,int);

printf("Enter two numbers\n");


scanf("%d%d",&m,&n);
g = gcd(m,n);
printf("GCD of %d and %d is %d", m,n,g);

69
} /* End of main() */
int gcd(int m,int n)
{
int r,g1;
do
{
r=m%n;
if(r!=0)
{
m=n;
n=r;
}
}while(r!=0);
g1=n;
return(g1);
} /* End of function gcd */
LCM of two numbers by function
main()
{
int m,n;
int lcm(int,int);

printf("Enter two numbers\n");


scanf("%d%d",&m,&n);
printf("LCM of %d and %d is %d", m,n,lcm(m,n));

} /* End of main() */

int lcm(int m,int n)


{
int i;
for(i=1;i<= m*n;i++)
{
if(i%m==0 &&i%n==0)
break;
}
return i;
} /* End of function lcm*/
Sum of digits by function
main()
{
int digitsum(int);
70
int num;
printf("Enter a number\n");
scanf("%d",&num);
printf("Sum of digits = %d\n",digitsum(num));
}
/* 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;

71
}

RECURSIVE FUNCTIONS
A function which calls itself until a certain condition is reached is called recursive function
/* to find factorial of a number recursively */
#include <stdio.h>
main()
{
int rfactorial(int);
int n,f;
printf("Enter a number\n");
scanf("%d",&n);
f=rfactorial(n);
printf("Factorial of %d is %d",n,f);

/* factorial */
int rfactorial(int n)
{
if(n==0)
return 1;
else return(n*rfactorial(n-1));
}
/* to find nth fib number recursively */
#include <stdio.h>
main()
{
int rfib(int);
int n,f;
printf("Enter a number\n");
scanf("%d",&n);
f=rfib(n);
printf("n thfibonacci number is %d",f);
}

/* rfib */
int rfib(int n)
{
if(n==1||n==2)
return 1;
else return(rfib(n-1)+rfib(n-2));
}
/* to find GCD of two numbers recursively */
#include <stdio.h>
main()
{
int rgcd(int,int);
int m,n,g;
72
printf("Enter two numbers\n");
scanf("%d%d",&m,&n);
g=rgcd(m,n);
printf("gcd is %d",g);

}
/* function rgcd */
int rgcd(int m,int n)
{
if(m%n==0)
return n;
else
return(rgcd(n,m%n));
}

/* to find nCr recursively */


#include <stdio.h>
#include <conio.h>
void main()
{
int rncr(int,int);
int n,r,s;
printf("Enter two numbers\n");
scanf("%d%d",&n,&r);
s=rncr(n,r);
printf("ncr =%d\n",s);
}
int rncr(int n,int r)
{
if(r==0 || n==r)
return 1;
else
return(rncr(n-1,r)+rncr(n-1,r-1));
}
/* to find sum of digits recursively */
#include <stdio.h>
#include <conio.h>
void main()
{
int rsum(int n);
int n,s;
printf("Enter a number\n");
scanf("%d",&n);
s=rsum(n);
printf("sum of digits =%d\n",s);
}

int rsum(int n)
73
{
if(n==0)
return n;
else return(n%10+rsum(n/10));
}

/* 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));
}

/* to find the sum of two numbers recursively */


#include <stdio.h>
#include <conio.h>
void main()
{
int rsum(int,int);
int m,n,s;

printf("Enter two numbers\n");


scanf("%d%d",&m,&n);
s=rsum(m,n);
printf("sum =%d\n",s);
}

int rsum(int m,int n)


{
if(n==0)
return m;
else
return(rsum(m+1,n-1));
}

74
STORAGE CLASSES
Normally the life of a variable is limited to a function as long as the function is alive. How
to make it alive in a file or throughout the program or limiting only to a block inside a
function or to make common to a desired couple of functions etc., The answer lies in
―STORAGE CLASSES‖ or ―VARIABLE TYPES‖.
There are four types of storage classes.
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.

AUTOMATIC VARIABLES:
Automatic variables are declared inside a function, in which they are to be
utilized. They are created when the function is called and destroyed automatically when
the function is exited. By default all variables are automatic variables. These are also
called local or internal variables.
EXTERNAL VARIABLES
Variables that are both alive and active throughout the entire program are called
external variables. These variables are available to all functions in that program.
Whatever changes that occur in a function, will effect the value of that variable.
STATIC VARIABLES
When a variable is declared as a static variable it is assigned the value zero. Static
variables are initialized only once. They will not be initialized for second time during the
program. When static is applied to a global variable, the global variable becomes
75
inaccessible outside the file.

REGISTER VARIABLES

This is local to a function or a block. If a compiler finds a physical register in the CPU free
for the time being, and also big enough to hold the value, then it may stick that variable
in that register. Otherwise, the compiler treats that variable as ordinary. It is machine
dependent. But compiler will not give error messages even if no register available in
reserve. If we know that a particular variable will be used often inside function-say the
variable inside a loop-then we can declare that variable with class register. So that the
interaction will be very fast.

//Write a program to demonstrate life cycle of auto


variable in nested blocks.
void main()
{
auto int x=1;
{
auto int x=2;
{
auto int x=3;
printf(“%d\n”, x);
}
printf(“%d\n”,x);
}
printf(“%d\n”,x);
}
Output
3
2
1
// program to illustrate automatic and external variables
#include <stdio.h>
int x=1;
int fun1()
{
x=x+10;
return x;
}

int fun2()
{
int x;
x=20;
return x;
}
76
int fun3()
{
x=1000;
return x;
}
void main()
{
int x=100;
printf("% d\n",fun1());
printf("%d\n",fun2());
printf("% d\n",fun3());
x=0;
printf("%d\n",x);
printf("% d\n",fun1());
printf("%d\n",fun2());
printf("% d\n",fun3());
}
OUTPUT
11
20
1000
0
1010
20
1000

// program to illustrate static variable

#include <stdio.h>
void main()
{
int fun();
int i;
for(i=1;i<5;i++)
printf("%d\n",fun());
}

int fun()
{
static int x=0;
x+=1;
return(x);
}
OUTPUT
77
1
2
3
4
// program to illustrate register variable
#include <stdio.h>
void main()
{
register inti;
int i;
for(i=1;i<1000;i++)
printf("% d",i);
}
automatic variable static variable

1. It is declared by auto int a = 10; 1. It is declared by static int a = 10;

2. It must be declared inside the function 2. It can be declared inside or outside the function
3. If it is not initialized, zero is stored
3. If it is not initialized, garbage value is stored 4. It is initialized once and only one but not every
4. It is initialized every time function is called that time when function is called
is repeated initialization 5. It is lost when program terminates but not when
5. It is lost when function terminates function terminates

Local variable Global variable

78
1. It is declaration inside the function 1.It is declaration outside the function
2.It is declared by 2. It is declared by int a=10
auto int a=10 or
int a = 10 (auto is default scope)
3. If it is not initialized. garbage value is 3. If it is not initialized zero is stored
stored Eg: int a; Eg: int a;
a is garbage value a=0
4. It is created when the function starts 4. It is created before program execution
execution and lost when the function starts and lost when program terminates
terminates
5. It is visible in only one function. 5. It is visible through out the program.

6. It can be accessed in only one function that is 6. It can be accessed in more than one function.
the

function where it is declared 7. Data sharing is possible that is


multiple functions can access the
7. Data sharing is not possible that is same global variable.
data of local variable can be accessed
by only one function 8. Parameters passing is not required
for global variable since global
variable is visible throughout the
8. Parameters passing is required for program
local variable that is local variable of
one variable 9. If value of global variable is modified
in one function changes are visible in
9. If value of local variable is modified rest of the program
in one function changes are
not visible in another functions

Iterative Recursive

79
1. Function calls some other functions 1. Function calls some itself

2. while loop, do while loop or for loop is 2. if statement is necessary in recursive function
necessary in iterative function
3. Fast in execution since one function call is 3. Slow in execution since several function calls are
enough to get the result involved to get the result, as number of function
increases execution will slow down.
4. Function call leads to value 4. Function call leads to another function call
Eg: fact(4) = 24 Eg: fact(4) = 4 x fact(3)

5. We require mathematical steps or procedure 5. We require a formula to write a recursive function.


to write an iterative function.
6. Stacks are used during execution of recursive
6. Stacks are not used during execution functions

Summary:
● All C programs contain main() function which is mandatory.
● main() function is the function from where every C program is started to execute.
● Name of the function is unique in a C program.
● C Functions can be invoked from anywhere within a C program.
● There can any number of functions be created in a program. There is no limit on this.
● There is no limit in calling C functions in a program.
● One function can be called within another function.
● C functions can be called with or without arguments/parameters. These arguments are
nothing but inputs to the functions.
● C functions may or may not return values to calling functions. These values are
nothing but output of the functions.
● When a function completes its task, program control is returned to the function from
where it is called.
● There can be functions within functions.
● Before calling and defining a function, we have to declare function prototype in order
to inform the compiler about the function name, function parameters and return value
type.
● C function can return only one value to the calling function.
● When return data type of a function is ―void‖, then, it won‘t return any values
● When return data type of a function is other than void such as ―int, float, double‖, it

80
returns value to the calling function.

Review and revision:

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

2. A function prototype is used for (L2) (CO4)


a) Declaring the function logic
b) Calling the function from the main body
c) Telling the compiler, the kind of arguments used in the function
d) Telling the user for proper use of syntax while calling the function
Answer: c

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

9. Identify which statement is correct about Passing by value parameters.(L3)(CO4)

a) It cannot change the actual parameter value


b) It can change the actual parameter value
c) Parameters is always in read-write mode
d) None of them
Answer: a
10. Which keyword is used to give back the value?(L5) (CO4)
a) static
b)void
c) return
d) const
Answer: b
11. Evaluate the output of the following program. (L5) (CO4)

#include <stdio.h>
void foo()
{
return 1;
}
void main()
{
int x = 0;
x = foo();
printf("%d", x);
}

a)Compile time error


b)0
c)1
83
d) run time error
Answer: a
12. Number of values a functionin C can return? (L2) (CO4)

a)2
b)0
c)1
d) 3

Answer: c

13. Types of functions in C language(L2) (CO4)

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

Review and revision exercise (2) :


Case Study:
1. To display the given decimal number in words using user defined function
84
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:

1. What is a function? What is the need for functions?(L1) (CO4)


2. Classify different types of functions. (L2) (CO4)
3. Explain the general form of defining a function. (L2) (CO4)
4. Define i) function prototype ii) function header iii) recursive function (L1) (CO4)
5. Differentiate between (L2) (CO4)
i) actual and formal parameters
ii) calling function and called function
iii) user defind function and library function
iv) call by value and call by reference
v) function prototype and function header
vi) local and global variables
6. Write about storage classes. (L1) (CO4)
7. What are different types of variables? Explain with examples. (L1) (CO4)
Long answer type:

8. Develop a C program to find factorial of a number? (L3) (CO4)


9. Develop a C program to find nth Fibonacci number? (L3) (CO4)
10. Develop a C program to find GCD of two numbers? (L3) (CO4)
11. Develop a C program to find sum of digits of a number? (L3) (CO4)
12. Develop a C program to findprime or not? (L3) (CO4)
13. Develop a C program to find palindrome or not? (L3) (CO4)
14. Develop a C program to find Fibonacci series? (L3) (CO4)
15. Develop a C program to find power of a number by using non recursive and recursive
functions? (L3)(CO4)

85
Course Code: 20CS C01

Course Title: PROGRAMMING FOR PROBLEM SOLVING

Instructors Name:

Name Email
Smt. A Sangeetha asangeetha_cse@cbit.ac.in

Objective:

The primary goals of the module: To understand:


● Arrays and different dimensional arrays and their needs.
● One dimensional and two dimensional arrays declaration, representation in memory, accessing the data and
performing operations on them.
● call by reference mechanism involved in array, passing to a function

Outcome:

On Successful completion of the module: Arrays, students will be able to:

● Learn about one-dimensional and two-dimensional arrays and the way they are declared, initialized,
manipulated, inputted, and displayed.
● Differentiate different dimensions of the array and able to choose appropriate array to store data and
perform operations on them in an application.

Scope:

The Module covers the following topics: Introduction to Arrays, Declaration using Arrays in C, Accessing and storage
of array elements, one dimensional arrays, Searching Algorithms (linear and binary search), Sorting Algorithms
(Selection and Bubble),Two dimensional arrays, matrix operations.

While these topics are taught using a C language, the intent of the course is to teach a programming methodology and
also a laboratory component that involves development and testing of iterative and procedural programs using one-
dimensional and two-dimensional arrays.

86
Text andReference:
(a) Text Book:

1. M.T. Somashekar “Problem Solving with C”, 2 nd Edition, Prentice Hall India Learning Private
Limited 2018
2. A K Sharma “Computer Fundamentals and Programming”, 2nd Edition, University Press, 2018
3. Pradeep Dey and Manas Ghosh, “Programming in C”, Oxford Press, 2nd Edition, 2017
(b) Reference Books:

1.Byron Gottfried, Schaum’s”Outline of Programming with C”, McGraw- Hill.

2. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of India.

3. E. Balaguruswamy, Programming in ANSI C, Tata McGraw-Hill.

4. ReemaTharaja “Introduction to C Programming”, Second Edition, OXFORD Press, 2015.

5. https://www.tutorialspoint.com/cprogramming/index.htm.

6. https://onlinecourses.nptel.ac.in/noc18-cs10/preview.

Module/ Theme Learning Objectives


Lecture
L.19 Introduction to Arrays, Declaration, Using To learn about the need of arrays and its
Arrays in C representation.Its declaration syntax

L.20 Accessing and storage of array To learn the memory allocation for arrays and accessing
elements, one dimensional arrays elements. Perform basic operations on array elements

L.21 Searching Algorithms (linear and binary Using search operation learner will learn accessing
search) element and apply operators on array elements

L.22 Sorting Algorithms (Selection and Bubble) Learn how nested loops can be used to access
elements in the arrays to perform sorting and analysis
each passes.

L.23 Two dimensional arrays, matrix operations Learn how multiple dimensional can be declared,
initialized, accessed and performing operations on
them

87
Lecture Title: L19 to L23
Date
Key topics : Integer one dimensional and multi-dimensional arrays and its storing, retrieving and memory locations

Introduction to Arrays
Till now you might have declared variables to hold data and to perform operations on it. Just like given below-
int a=10;
char ch=’a’;
These variables can hold only one data item at a time. Let us take some example where collection of data
items need to be stored….
● 60 students marks secured in a subject
● Salaries of 100 employees
So we are supposed to declare multiple variables to hold the above data for each example.
C language provides a derived data types called arrays.
Definition
An array is collection of homogeneous elements stored in continuous memory locations and shares a common
name.
There are several forms of an array used in C: one-dimensional or single-dimensional and multidimensional
array.
Declaration of one-dimensional or single-dimensional
Like any other variables, arrays must be declared before they are used. The general form of array declaration
is
Syntax: datatype array_name[sizeofarray];

⬥ The data type specifies the type of data/element that will be stored in the array, such as int, float, or
char.
⬥ The size indicates the maximum number of data/elements that can be stored in the array.
⬥ The size of array should be a int constant or constant expression.
Let us take the same example to declare suitable one dimensional array variable to hold the data.
● 60 students marks secured in a subject
unsigned short int PPS[60];
● Salaries of 100 employees
float salaries_of_employees[100];

Internal representation /Memory Allocation


int a[5];

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.

Accessing one-dimensional array elements


Array access involves store/initialize and retrieve the data items.

● Array is initialized with elements can be done at static time (while writing the code) or dynamic time(
at the time of executing the program).
Static Initialization
Example 1:
int a[5]; //array declaration
//array initialization
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;

Example 2:
int a[5]={10,20,30,40,50}; // array declaration and initialization

Dynamic Initialization
Example 3:
int a[5],i;
printf(“Enter 5 integer elements:”);
for(i=0;i<=4;i++)
scanf(“%d”,&a*i+);
89
At the time of execution user can give 5 data items which will be stored in the array.

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]);

Retrieving elements from an array using loop/iterative variable as subscript

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.

Let us write a program to store and retrieve element into/from an array.


# 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 are:”);
for(i=0; i< 5; i++)
printf(“%d ”, a*i+);

}
Output:

90
Variable length arrays
Previous version of C(C89) compilers, an array’s size must be an constant, so that compiler can calculate the
size/memory allocation at the compilation time itself. But from C99 onwards, C compilers allows the
programmers to declare an array variable with variable length ie size of an array can be given at execution
time/ run time.

/* Program to read and display using variable length arrays*/


int main()
{
intn,i;
printf("\n Enter the size of the array");
scanf("%d",&n);
int a[n]; // variable length array (VLA). The ‘n’ variable declaration should be before VLA
printf("\n Enter %d numbers:",n);
for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
printf("\n\n Given %d numbers are:",n);
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
Output:

Operations on array elements


Some operations are listed below
● c=a*0++a*1+ // adding elements at index ‘0’ and ‘1’ and store it in ‘c’ variable
● a[i]=a[i]+20 // adding a constant to the array element at index ‘i’ and store in same location
● a[i]> x // compare value at ‘x’ with value at ‘a*i+’
● a[i]=a[i]+1 // add ‘1’ to value at ‘a*i+’
● a[i]++ // add ‘1’ to value at ‘a*i+’
● a[i]+=1 // add ‘1’ to value at ‘a*i+’
● a[k]=a[i]; // ‘i’th indexed element stored at index ‘k’

/* Write a program to print the array elements in reverse order */

# include<stdio.h>
int main( )
{
int i , a[5];
91
printf(“Enter 5 integer elements: ”); /* reading values into Array */
for (i=0; i<5; i++)
scanf(“ %d ”, &a*i+);
/* printing of a[i] values */
printf(“The array elements in reverse order are:”);
for(i=4; i>=0 ; i--)
printf(“%d ”, a*i+);
return 0;

}
Output:

Searching operation on array elements

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.

/* Program to implement linear search */


#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10],n,i,key, FOUND=0;
printf(“\n How many numbers”);
scanf(“%d”,&n);
if(n>10)
{
printf(“\n Too many Numbers”);
exit(0);
}
printf(“\n Enter the array elements \n”);
for(i=0 ; i<n; i++)
scanf(“%d”, &a*i+);
printf(“\n Enter the key to be searched \n”);
scanf(“%d”,&key);

92
for(i=0 ; i<n; i++)
if(a[i] == key)
{
printf(“\n Found at %d”,i);
FOUND=1; break;
}
if(FOUND = = 0)
printf(“\n NOT FOUND...”);
return 0;
}
Output when more than the size of the array

Output when search is successful Logic for successful search

Output when search is unsuccessful Logic for unsuccessful search

In binary search method , halves the size of the list and searches only in half of the array by finding the mid
element index using first(low) and last(high) index of the array.
The procedure is as follows-
● Find mid element by using low and high
● If key is less than mid element then search will be done in left of the array by updating high
● Else If key is greater than mid element then search will be done in right of the array by updating low
● Otherwise mid element itself is the search element.
This will be continued until low is less than high. Unsuccessful search make low greater than high. To perform
binary search the elements should be increasing order in the array.
/* Program to implement linear search */

93
#include<stdio.h>
int main()
{
int n;
printf("\n Enter the size of the array:");
scanf("%d",&n);

int a[n],i,key,FOUND=0;

printf("\n Enter elements in increasing order");


for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("\n Enter element for searching:");


scanf("%d",&key);

int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(key>a[mid])
low=mid+1;
else if(key<a[mid])
high=mid-1;
else
{
printf("\n Found at %d",i);
FOUND=1; break;
}
}
if(FOUND == 0)
printf("\n NOT FOUND...");

return 0;
}
Output Binary search logic Interpretation for successful
search

Bubble Sorting
Sorting operation will keep the element in an order.
Basic principle of bubble sort is consecutive/adjacent elements are compared and exchanges their values if
94
they are not in the order. This process bubbles the smallest element in the array to ‘0’ index and largest to ‘n-
1’ index where ‘n’ is the size of the array.
The following depicts the different stages of the bubble sort.

Array elements are 44 22 -1 3 10

pass1 Comparison on
44 22 -1 3 10 44 , 22 (swap)
22 44 -1 3 10 44, -1 (swap)
22 -1 44 3 10 44 , 3 (swap)
22 -1 3 44 10 44, 10 (swap)
22 -1 3 10 44 Pass1 completed and largest element (44) placed in the correct position.
It is not going to be considered in the next iteration.
Pass2 Comparison on
-1 22 3 10 44 22, -1 (swap)
-1 3 22 10 44 22, 3 (swap)
-1 3 10 22 44 22, 10 (swap)
-1 3 10 22 44 Pass 2 completed . 22 is placed in the correct position. It is not going to
be considered in the next iteration.
Pass3 Comparison on
-1 3 10 22 44 -1, 3 (no swap)
-1 3 10 22 44 3,10 (no swap)
-1 3 10 22 44 Pass 3 completed . 10 is placed in the correct position .It is not going to
be considered in the next iteration.
Pass4 Comparison on
-1 3 10 22 44 -1, 3 (no swap)
-1 3 10 22 44 Pass 4 completed . 3 is placed in the correct position .It is not going to be
considered in the next iteration.
Always single element in the array will be in sorted order itself. So algorithm stops its passes.

/* Program to implement bubble sort*/


#include<stdio.h>
int main()
{
int n;
printf("\n Enter the size of the array:");
scanf("%d",&n);
int a[n],i,j,temp;
printf("\n Enter %d numbers for sorting",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Before Sorting ....\n");

for(i=0;i<n;i++)
printf("%5d",x[i]);

95
//sorting logic
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1]; /* swap */
a[j+1]=temp;
}

}
printf("\n After Sorting ....\n");
for(i=0;i<n;i++)
printf("%5d",x[i]);
return 0;
}

Selection Sorting
⬥ Selection sort finds the minimum element from the array and place it in the beginning.

Array elements are 44 22 -1 3 10


44 22 -1 3 10 Pass 1:
Find minimum element from index 0 to 4
and place at index 0 ie min=-1
Swap( 44,-1)
-1 22 44 3 10 Pass 2:
Find next minimum element from index 1 to 4
and place at index 1 ie min=3
Swap( 22,3)
-1 3 44 22 10 Pass 3:
Find next minimum element from index 2 to 4
and place at index 2 ie min=10
Swap( 44,10)
-1 3 10 22 44 Pass 4:
Find next minimum element from index 3 to 4
and place at index 3ie min=22
Swap( 22,22)
-1 3 10 22 44 Single element will be in sorted order

/* Program to implement Selection Sort*/

#include <stdio.h>
96
main()
{
int a[20],n,i, j, po,se,temp;
printf("How many elements\n");
scanf("%d",&n);

/* loop to read values into array */


printf("Enter %d numbers below:\n", n);
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);

/* loops of selection sort */


for(i=0;i<n-1;i++)
{
se=po=i;
for(j=i+1;j<n;j++)
{
if(a[j] <a[se])
se=j;
}
temp=a[po];
a[po]=a[se];
a[se]=temp;
}

/* loop to display sorted array */


printf("The sorted Array is: \n");
for ( i = 0; i< n; i++ )
printf("%d\n", a[i]);

TWO DIMENSIONAL ARRAYS

● Arrays with more than one dimension are called multidimensional arrays.
● Array of one dimensional array is called two dimensional array.

An array of two dimensions can be declared as follows:


Syntax:
data_typearray_name[size1][size2];
⬥ size1, size2 are constant , array subscript in both dimensions start from 0 to size1-1 and 0 to size2-1.
Size1 tells the information about number of rows and size2 tells about number of columns .
⬥ In other words, size1 gives how many one-dimensional arrays exists and size2 gives how many

97
elements in a one one-dimensional array.
⬥ Number of elements stored in the array will be size1 *size 2 .

Example:
int a[10][10];
float b[20][20];
● Two dimensions are useful to store data in a table form. Ie take the previous example 60 student
marks in a subject.
● In order to store 60 students’ marks obtained in 6 subjects then six one dimensional arrays need to be
declared for each subjects.
● It will be difficult to remember the variable name of each subject if multiple subjects exist.

Static initialization
initialization of an array: this can be done in two ways
1. int a[2][2] = { {3,6} , {2,9} }; // each 1D array enclosed in {} and separated with ,
2. int a[2][2] = { 3,6,2,9}; // based on 2nd dimension it will identify the number of
// elements in each row.
dynamic initialization
● To represent 2 dimensions we need two variable one for each dimension.

int a[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf(“%d”,&a*i+*j+);
}

Internal representation /Memory Allocation


● If array is declared as int a[3][3]

In the computer the array a[3][3] will looks as below

row1 row 2 row 3


User perception

int a[3][3]={1,2,3,4,5,6,7,8,9};
Then the array will be …

98
row1 row 2 row 3

⬥ To accesses the 2nd element at 3rd row we need to use the indexes as a[1][2]. So element in ith row jth
column will be accesses as a[i-1][j-1].
⬥ All the elements are stored in continuous locations. Two dimensional array is also called as array of
arrays.
⬥ First dimension in the 2D array tells about how many one dimensional arrays are required, second
dimension tells about how many elements in each one dimensional array .

Program to add two M x N matrices.


#include <stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;

printf("Enter the number of rows and


columns for A and B\n");
scanf("%d%d",&m,&n);
/* loop to read values of matrix A*/
printf("Enter the elements for matrix A\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

/* loop to read values matrix B*/


printf("Enter the elements for matrix B\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);

/* loop to add two matrices*/


for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j] = a[i][j] + b[i][j];

/* loop to print resultant matrix */


printf("The sum of A and B is\n");
for(i=0;i<m;i++)
99
{
for(j=0;j<n;j++)
printf("%3d",c[i][j]);
printf("\n");
}
}

Enter the number of rows and columns for A and B


2
2
Enter the elements for matrix A
1234
Enter the elements for matrix B
4321
The sum of A and B is
5 5
5 5

Program to multiply two M x N and P x Q matrices


#include <stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q,k;
printf("Enter the number of rows and columns for A \n");
scanf("%d%d",&m,&n);
printf("Enter the number of rows and columns for B \n");
scanf("%d%d",&p,&q);

/* loop to read values of matrix A*/


printf("Enter the elements for matrix A\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

/* loop to read values of matrix B*/


printf("Enter the elements for matrix B\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
/* loop to multiply two matrices*/
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j] = 0;
for(k=0;k<n;k++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
}

100
}

/* loop to display resultant matrix */


printf("The multiplication of A and B is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%3d",c[i][j]);
printf("\n");
}
}

Enter the number of rows and columns for A


23
Enter the number of rows and columns for B
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

Program to find Transpose of a matrix


#include <stdio.h>
main()
{
int a[5][5],b[5][5],i,j,r,c;
printf("Enter the size of matrix\n");
scanf("%d%d",&r,&c);

/* loop to read values of matrix A*/

printf(“Enter the matrix values\n”);


for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);

/* loop to find transpose of matrix A*/


for(i=0;i<r;i++)
for(j=0;j<c;j++)
b[j][i] = a[i][j];

/* loop to display the resultant matrix*/

101
printf("Transpose of a :\n");
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
printf("%3d",b[i][j]);
printf("\n");
}
}
Enter the size of matrix
23
Enter the matrix values
123
456
Transpose of a :
1 4
2 5
3 6

1 D ARRAYS AND FUNCTIONS

1. We can pass entire array to a function.


2. In the calling function we need to give only name of the array, subscript or square brackets are not
necessary.
3. When we pass array name to a function, base address of that array is passed, since array name refers
base address of that array. Therefore call by reference mechanism takes place.
4. It is optional to give size of the array in the function definition.

/* linear search by function */


#include <stdio.h>
main()
{
void lsearch(int [],int,int);
int a[10],n,i,key;
printf("enter how many elements\n");
scanf("%d",&n);
printf("Enter the values\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the key\n");
scanf("%d",&key);
lsearch(a,n,key);
}
/*Function lsearch */

void lsearch(int a[10],intn,int key)


{
inti,found=0;
for(i=0;i<n;i++)

102
{
if(a[i]==key)
{
printf("search is successful\n");
printf("location = %d\n",i+1);
found =1;
}
}
if(found==0)
printf(" element not found\n");
}
OUTPUT:
Enter how many numbers
8↵
Enter the number
34 5 89 54 7 15 77 23 ↵
Enter the key
77↵
Search is successful
Location =7

/* binary search by function */


#include <stdio.h>
main()
{
void input(int [ ],int);
void bsearch(int [],int,int);
int a[25],n,key;
printf("How many numbers ? ");
scanf("%d",&n);
printf("\nEnter %d numbers :\n", n);
input(a,n);
printf("Enter the key\n");
scanf("%d",&key);
bsearch(a,n,key);

} /* end of main */
/*Function input */
void input( int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */

/* Function Bsearch */
void bsearch (int a[],intn,int key)

103
{
intlow,high,mid,flag=0;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key < a[mid])
high=mid-1;
else if(key > a[mid])
low = mid+1;
else if(key == a[mid])
{
printf("search is successful\n");
printf("location = %d\n",mid+1);
flag=1;
break;
}
}
if(flag==0)
printf("search is unsuccessful\n");
} /* end of function bubblesort */
OUTPUT:
Enter how many numbers
10 ↵
Enter the number
3 5 8 54 7 15 76 23 79 11 ↵
Enter the key
79↵
Search is successful
Location =9

/*bubble sort by functions */


#include<stdio.h>
main()
{
void input(int [],int);
void output(int [],int);
void bubblesort(int [],int);

int a[25],n;
printf("How many numbers to sort ? ");
scanf("%d",&n);
printf("\nEnter %d numbers below:\n", n);
input(a,n);
bubblesort(a,n);

104
printf("\nThe sorted Array is: \n");
output(a,n);
} /* end of main */

/*Function input */
void input( int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
scanf("%d", &a[i]);
} /* end of function input */

/* Function Bubblesort */
void bubblesort (int a[],int n)
{
int pass, j, temp;
for ( pass = 1; pass < n; pass++ )
{
for ( j =0 ; j < n-1; j++ )
{
if( a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
} /* end of function bubblesort */

/* Function output */
void output (int a[],int n)
{
inti;
for ( i = 0; i< n; i++ )
printf("%5d\n", a[i]);
} /* end of function output */

Selection sort by function

#include <stdio.h>
main()
{
void ssort(int [],int);
void display(int [] ,int);
void readarray(int [],int);
int a[20],n;
printf("How many elements\n");
105
scanf("%d",&n);
printf("Enter the elements\n");
readarray(a,n);
ssort(a,n);
display(a,n);
}

void readarray(int a[],int n)


{
inti;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}

void ssort(int a[], int n)


{
inti,j,po,se,temp;
for(i=0;i<n-1;i++)
{
se=po=i;
for(j=i+1;j<n;j++)
{
if(a[j] <a[se])
se=j;
}
temp=a[po];
a[po]=a[se];
a[se]=temp;
}
}
void display(int a[],int n)
{
inti;
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
How many numbers to sort ?
7
Enter 7 numbers below:
55 4 -3 0 22 1 5
The sorted Array is:
-3
0
1
4
5

106
22
55

2 D ARRAYS AND FUNCTIONS

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.

/*Program to add two matrices by using functions*/

#include <stdio.h>
main()
{
void readmat(int [ ][10],int,int);
void matadd(int [ ][10],int [ ][10],int [ ][10],int,int);
void display(int [ ][10],int,int);

int A[10][10], B[10][10], C[10][10],m,n;

printf("\nEnter size of the matrix A and B: ");


scanf("%d%d", &m,&n);

printf("\nEnter elements of matrix A \n");


readmat (A, m,n);

printf("\nEnter elements of matrix B \n");


readmat (B,m,n);

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 */

/* Function to read the elements of a matrix row-wise */


void readmat(int X[10][10],introws,int cols)
{
inti, j;
for(i = 0; i< rows; i++)

107
for( j = 0; j < cols; j++)
scanf("%d", &X[i][j]);
} /* end of function read_matrix */

/*Function to add two mxn matrices */


void matadd (int A[10][10], int B[10][10], int C[10][10], int m, int n)
{
inti, j;
for(i = 0; i< m; i++)
{
for( j = 0; j < n; j++)
{
C[i ][ j] = A[i ][j ] +B[ i][j ] ;
}
}
} /* end of function matmul */

/*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 */

/*Program to multiply two matrices by using functions*/

#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);

int A[10][10], B[10][10], C[10][10],m,n,p,q;

printf("\nEnter size of the matrix A: ");


scanf("%d%d", &m,&n);
printf("\nEnter size of the matrix B: ");
scanf("%d%d", &p,&q);

if(n!=p)
printf("multiplication not possible\n");
else
{
108
printf("\nEnter elements of matrix A \n");
readmat (A, m,n);

printf("\nEnter elements of matrix B \n");


readmat (B,p,q);

matmul(A, B, C,m,q,n);

printf("Matrix A is :\n");
display(A, m,n);

printf("Matrix B is :\n");
display(B, p,q);

printf("\nMATRIX C (= A X B) is:\n");
display(C, m,q);
}
} /* end of main */

/* Function to read the elements of a matrix row-wise */


void readmat(int X[10][10],introws,int cols)
{
inti, j;
for(i = 0; i< rows; i++)
for( j = 0; j < cols; j++)
scanf("%d", &X[i][j]);
} /* end of function read_matrix */

/*Function to multiply m x n and p x q matrices */


void matmul (int A[10][10], int B[10][10], int C[10][10],
int m, int q, int n)
{
inti, j,k;
for(i = 0; i< m; i++)
{
for( j = 0; j < q; j++)
{
C[i][j] =0;
for(k=0; k<n; k++)
{
C[i][j] = C[i][j] +A[i][k] * B[k][j];
}
}
}
} /* end of function matmul */

/*Function to print the elements of a matrix */


void display(int X[10][10],int rows ,int cols)
109
{
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 */

Summary exercise:
1. Arrays hold homogeneous data and share a common name.
2. An array that contains single index is one dimensional array. An integer index is used to access the
elements from the range ‘0’ to ‘n-1’ where ‘n’ is the array size.
3. Multi-dimensional arrays contain multiple indexes.
4. Array name itself will give the base address of an array. So when a one dimensional array is passed to
function, call by reference mechanism takes place.
5. When two dimensional array is passed to function, in the function definition formal argument, the
size of the column is must and size of the row is optional.

Review and revision:


Review and revision exercise (1) :

Lecture topic quiz / MCQs: (All these quiz’s belongs to BL3 & BL4)
1. Test for the output of the following program, if the array begins at address 1200?
main()
{
intarr[] = {2,3,4,1,6};
printf("%d %d",arr, sizeof(arr));
}
2. Identify that the array name gives the base address in all the contexts?
3. Test for the output of the following program, if the array begins at address 65486 ?
main()
{
intarr[] = {12,14,15,23,45};
printf("%u %u",arr, &arr);
}
4. Experiment the expressions arr and &arrgives same for an array of 10 integers ? (arr is the array variable
name)
5. Test for the output of the following program, if the array begins at address 65486 ?

main()
{
intarr[] = {12,14,15,23,45};
printf("%u %u",arr + 1, &arr + 1);

110
}
6. Test for the output of the following program ?

main()
{
float a[] = {12.4,2.3,4.5,6.7};
printf("\n %d",sizeof(a) / sizeof(a[0]));
}
7. Test for the output of the following program if the array begins at 65472?

main()
{
int a[3][4] = {
1,2,3,4,
4,3,2,1,
7,8,9,0
};
printf("\n %u %u",a + 1, &a + 1);
}
8. Inspect if we pass the name of a 1-D int array to a function it decays into a pointer to an int. If we pass the
name of a 2-D array of integers to a function what would it decay into?

Multiple Choice Questions


(All MCQ’s belongs to (CO3,4,5))
1. An array ________ (BL1)
a) Is collection of similar data items
b) stored data in the continuous memory allocation
c) elements share a common name
d) All of the above
2. What will be the values of 8th element in the array if this is the declaration and initialization of the integer
array int a[10]={0};(BL1)
a) 0
b) Garbage Value
c) Value depends on compiler
d) Compilation error
3. Pick the correct declaration and initialization of 2 dimensional integer array(BL1)
a) int a[][]={1,2,2,4};
b) int a[3][] ={1,2,2,4};;
c) int []a[]={1,2,2,4};
d) int a[][3]={1,2,2,4};
4. Index of the first element in the arrays is ______(BL1)
a) 0
b) -1

111
c) 1
d) 2
5. printf(“%d”,a*3+*4+); In this statement which element is accesses?(BL1)
a) 4th element in the 3rd row of the matrix
b) 3rd element in the 4th row of the matrix
c) 5th element in the 4th row of the matrix
d) 4th element in the 5th row of the matrix

6. Elements in an array can be accessed___(BL2)


a) Sequentially
b) Randomly
c) Both
d) None
e)
7. We want to access the 8th element in a one dimensional array int a[50] . which statement is correct?
a) printf(“%d”, a*8+); (BL1)
b) printf(“%d”, a*7+);
c) printf(“%d”, a*6+);
d) printf(“%d”, a*5+);

8. In the binary search if the key exist in the middle of the array. How many comparison need to be done.
(BL2)
a) 1
b) n/2
c) n
d) 0
9. In the linear search if the key exist in the middle of the array. How many comparison need to be done.
(BL2)
a) 1
b) n/2
c) n
d) 0

10. Consider a two dimensional array int a[5][5]. Assume each element occupies 2 bytes. The base address of
the array is 1000, elements are stores in row major order. What is the address of a[3][2]?
a) 1034(BL3)
b) 1030
c) 1036
d) 1032
11. The maximum dimensional array variable that can be declared in C. (BL2)
a) 1
b) 2

112
c) 3
d) No limit
12. Pick the operations which cannot be done on an array variable ‘a’ (BL2)
a) ++a, a++
b) a+1, 1+a, a=a+1, a+=1
c) a[i]++, i[a]++, *(a+i)++, *(i+a)++
i. both a and b are not allowed
ii. both a and c are not allowed
iii. both c and b are not allowed
iv. none
13. Pick the uses of arrays (BL2)
a) No need to declare many separate variable to handle many data items
b) Using single variable and subscript all the data items can be accessed
c) Maintaining the code is easy and remembering of variables is reduced on programmers side
d) All
14. Pick the uses of multidimensional arrays (BL2)
a) Able to store data in rows and columns
b) It is an array of arrays
c) In all the dimensional the index will start from ‘0’ and ends at ‘sizeofthedimension-1’
d) All
15. In CBIT in the academic year 2020-2021 first year contains 20 sections, in each section 60 students exist,
each student is having 6 courses. The secured by all students in all subjects in 20 sections need to be
stored. Pick the suitable multidimensional variable to be used to store the data. If data to be stored in row
major order of sections, students and subjects (BL3)
a) Marks[20][60[6];
b) Marks[60][20[6];
c) Marks[20][6[60];
d) Marks[6][60[20];

Review and revision exercise (2) :


1. Write a program to find the determinant of a matrix. (CO3,4,5)
2. Write a program to count number of duplicate elements exist in an array.(CO3,4,5)
3. Write a program to display each element of the array in words.(CO3,4,5)
4. Write a program to display array elements in pyramid form.(CO3,4,5)
Example: 1 2 3 4 5 6 are array elements. Then output should be
1
2 3
4 5 6
5. Write a program to find the inverse of a square matrix.(CO3,4,5)
6. Write a program to perform the below operations on elements of a matrix(CO3,4,5)
● Find the minimum and maximum element
● Sort them in ascending order and store in another one dimensional variable
● Count how many zeros exist in the matrix

113
● Count how many duplicates exist
● Swap any two elements in the matrix based on user choice

Discussion questions / Expected Questions:

Questions under Blooms Level-1


1. List out the advantages of an array. (CO5)
2. Define an array. Declare an array which holds average of 60 students.(CO5)
3. What is the significance of index in an array. (CO5)
4. int a[n]; does this declaration is correct? Justify your answer. (CO5)
5. Outline the significance of array name. (CO5)
6. What is the significance of type and size in the array declaration? (CO5)
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

Course Title:PROGRAMMING FOR PROBLEM SOLVING

Instructors Name:

Name Email
Smt. E Kalpana ekalpana_cse@cbit.ac.in

Objective:

The primary goals of the module: Strings are to introduce:


● Basic representation of Strings and tolearn about one-dimensional strings and the way they
are declared, initialized, manipulated, inputted, and displayed.
● To know about array of strings, its declaration, initialization, other operations,
manipulations, and uses.

Outcome:

On Successful completion of the module: Strings, students will be able to:

● learn about one-dimensional and two-dimensional strings and the way they are declared,
initialized, manipulated, inputted, and displayed.
115
Scope:

The Module covers the following topics: Introduction to Strings, Strings representation, String
operations with examples, Case Study on arrays
While the topics are taught using a C language, the intent of the course is to teach a programming
methodology and also a laboratory component that involves development and testing of iterative
and procedural programs using one-dimensional and two-dimensional Strings.

Text andReference:
(a) Text Book:

nd
Pradeep DeyandManasGhosh,―ProgramminginC‖,OxfordPress,2 Edition,2017

(b) Reference Books:

E.Balaguruswamy,ProgramminginANSIC,TataMcGraw-Hill.

Module/ Theme Learning Objectives


Lecture
L.24 Introduction to Strings, Strings To learn basic representation of Strings and to
representation. learn about one-dimensional strings and the way
they are declared, initialized, manipulated,
inputted, and displayed.

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.

STRINGS: ONE-DIMENSIONAL CHARACTER ARRAYS


Definition:
Strings are defined as an array of characters. The difference between a character array and a string
is the string is terminated with a special character ‗\0‘ the null character, which is a character all of
whose bits are zero, i.e., a NUL (not a NULL). (The null character has no relation except in name
to the null pointer. In the ASCII character set, the null character is named NUL.)
Although C does not have a string data type, it allows string constants. For example: ‖hello
students‖ is a string constant.

Declaration of a String:
Strings can be declared like one-dimensional arrays. For example,
char str[30];
char text[80];

String Initialization:
Character arrays or strings allow a shorthand initialization,
for example,
char str[9] = ―I like C‖;
which is the same as
char str[9] = {‗I‘,‗ ‘,‗l‘,‗i‘,‗k‘,‗e‘,‗ ‘,‗C‘,‗\0‘};
Whenever a string, enclosed in double quotes, is written,C automatically creates an array of
characters containing that string, terminated by the \0 character. C language allows the alternative
notation
char msg[] = ―Hello‖;
that is always used in practice. It should be noted that the size of the aggregate ‗msg‘ is six bytes,
five for the letters and one for the terminating NUL. There is one special case where the null
character is
not automatically appended to the array. This is when the array size is explicitly specified and the
number of initializers completely fills the array size. For example, char c[4] = ―abcd‖; Here, the
array c holds only the four specified characters, a, b, c, and d. No null character terminates the
array.

String Representation:

117
String Input and Output:
Printing Strings:
The conversion type ‗s‘ may be used for output of strings using printf(). Width and precision
specifications may be used with the %s conversion specifier. The width specifies the minimum
output field width; if the string is shorter, then space padding is generated. The precision specifies
the maximum number of characters to display. If the string is too long, it is truncated. A negative
width implies left
justification of short strings rather than the default right justification. For example,
printf(―%7.3s‖,name);
This specifies that only the first three characters have to be printed in a total field width of seven
characters and right justified in the allocated width by default. We can include a minus sign to
make it left justified (%-7.3). The following points should be noted:
● When the field width is less than the length of the string, the entire string is printed.
● The integer value on the right side of the decimal point specifies the number of characters
to be printed.
● When the number of characters to be printed is specified as zero, nothing is printed.
● The minus sign in the specification causes the string to be printed as left justified.
Example program:

#include <stdio.h>
int main()
{
char s[]=―Hello, World‖;
printf(―>>%s<<\n‖,s);
printf(―>>%20s<<\n‖,s);
printf(―>>%-20s<<\n‖,s);
printf(―>>%.4s<<\n‖,s);
printf(―>>%-20.4s<<\n‖,s);
printf(―>>%20.4s<<\n‖,s);
return 0;
}
Output:

118
The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the
input/output operations of the strings.

Using %s control string with scanf()


Strings may be read by using the %s conversion with the function scanf() but there are some
irksome restrictions. The first is that scanf() only recognizes a sequence of characters delimited by
white space characters as an external string. The second is that it is the programmer‘s
responsibility to ensure that there is enough space to receive and store the incoming string along
with the terminating null which is automatically generated and stored by scanf() as part of the %s
conversion. The associated parameter in the value list must be the address of the first location in an
area of memory set aside to store the incoming string.
Of course, a field width may be specified and this is the maximum number of characters that are
read in, but remember that any extra characters are left unconsumed in the input buffer. A simple
use of scanf() with %s conversions is illustrated in the following program.
int main()
{
char str[50];
printf(―Enter a string‖);
scanf(―%s‖,str);
printf(―The string was :%s\n‖,str);
return 0;
}
Output of sample runs:
(a) Enter a string manas
The string was :manas
(b) Enter a string manasghosh
The string was :manas
(c) Enter a string manas and ghosh
The string was : ―manas‖

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;
}

Character Manipulation in the String:


Character functions in <ctype.h> where c is the character argument.

120
Example:
This program checks whether character is alphanumeric or not.
/* C example program of isalnum().*/
#include<stdio.h>
#include<ctype.h>

int main()
{
char ch;

printf("Enter a character: ");


scanf("%c",&ch);

if(isalnum(ch))
printf("%c is an alphanumeric character.\n",ch);
else
printf("%c is not an alphanumericcharacter.\n",ch);

return 0;
}

121
String Manipulation:
The string header, string.h, provides many functions useful for manipulating strings or character
arrays. Some of these are mentioned below:

Example programs:
The given code shows the use of the strcpy()function.
#include <string.h>
int main()
{
char s1[] =―Hello, world!‖;
char s2[20];
strcpy(s2, s1);
puts (s2);
return 0;
}
The following program illustrates the comparison of two strings.

122
#include <stdio.h>
#include <string.h>
int main()
{
char x[50],y[]=―a programming example‖;
strcpy(x,―A Programming Example‖);
if(strcmp(x,―A Programming Example‖) == 0)
printf(―Equal \n‖);
else
printf(―Unequal \n‖);
if( strcmp(y,x) == 0)
printf(―Equal \n‖);
else
printf(―Unequal \n‖);
return 0;
}

The following program illustrates the strings concatenation.

int main()
{
char s[30] =―Hello,‖;
charstr[] =―world!‖;
printf(―%s\n‖, s);
strcat(s, str);
printf(―%s\n‖, s);
return 0;
}

ARRAYS OF STRINGS: TWO-DIMENSIONAL CHARACTER ARRAY

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

char s[5][10] ={―Cow‖,‖Goat‖,‖Pig‖,‖Dog‖,‖Cat‖};


which is equivalent to

123
Here every row is a string. That is, s[i] is a string.

Note that the following declarations are invalid.


char s[5][] ={―Cow‖,―Goat‖,―Ram‖,‖Dog‖,―Cat‖};
char s[][] ={―Cow‖,―Goat‖,―Ram‖,―Dog‖,―Cat‖};

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.

Review and revision:

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");

a) str1 is not greater than str2


b) str2 is not greater than str1
c) both are equal
d) error in given code
Answer: b
11. Which function tests for any character for which isalpha or isdigit is true.(L1)(CO4)
a) isxdigit()
b) isspace()
c) isalnum()
d) isupper()
Answer: c
12. Which function returns true only for the characters defined as lowercase letters?(L1)(CO4)
a) islow()
b) islower()
c) isalpa()
d) isalnum()
Answer: b

Review and revision exercise (2) :


Case Study:
WAP to implement Timetable and Invigilation chart with the following options:
1. Class Timetable generation
(Input: Number of Theory and Lab subjects, No. of faculty and their names, each faculty workload )
theory – 3hrs/week, lab-4hrs/week(split of 2hrs)
2. Faculty Timetable generation
(Input: faculty ID)
3. Faculty free hours available
(Input: faculty ID)
4. Invigilation Chart generation
(Input: No. of days of examination, number of invigilators required per day)

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)

Long answer type:

19. Analyze appropriate string manipulation functions and develop a C program that deletes a
word from a sentence. Note that the word may appear any number of times.(L4,L3)(CO4)

127
20. Develop a C program that reads a line of text and counts all occurrences of a particular
word.(L6)(CO5)
21. Explain any four string manipulation functions from <string.h> library with examples.
(L2)(CO4)

128
Unit IV
Course Code: 20CSC01
Course Title: Programming for Problem Solving

Instructors Name: M Venkata Krishna Reddy

Name Email
M Venkata Krishna Reddy krishnareddy_cse@cbit.ac.in

Objective:

(The primary goals of the module)

The primary goals of the module/unit are to introduce:


● Basic representation of pointers and usage of pointers with arrays and functions
● Dynamic memory allocation strategy

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:

(a) Text Book:

TB1: M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India
129
Learning Private Limited 2018.
TB2: AKSharma―ComputerFundamentalsand Programming‖, 2nd Edition, University
Press,2018.
TB3: Pradeep DeyandManasGhosh,―ProgramminginC‖,OxfordPress,2nd Edition,2017.

(b) Reference Books:

RB1: Byron Gottfried ,Schaum’s”Outline of Programming with C”,McGraw- Hill


RB2: Brian W. Kernighan and Dennis M. Ritchie,The C Programming Language,
Prentice
Hall.
RB3: E.Balaguruswamy,Programmingin ANSI C,TataMcGraw-Hill .

Module/ Theme Learning Objectives


Lecture
L.27 Introduction to Pointers, Pointer To understand how to define, represent,
declaration, Pointer Variables. and how to use Pointers.

L.28 Arrays and Pointers, Pointer To know various Arithmetic operations


Arithmetic and Arrays. that can be performed on Pointers and to
understand how to use pointers with
arrays to solve complex problems.

L.29 Pointers and strings. To understand the concept of pointers and


strings
L.30 Array of pointers, Dynamic memory To know how to use dynamic memory
allocation. allocation for solving memory allocation
problems
L.31 Advantages and drawbacks of To understand pros and cons of pointers
pointers

Lecture title L27 to L31


Date
Key topics / themes of the lecture :

● Pointers
● Arrays and Pointers
● Dynamic Memory Allocation

Notes, comments and your own Examples with answers / questions


130
Pointer :
A pointer is a variable that stores the address of another variable. Unlike other variables that hold
values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you
can say stores) an integer value, however an integer pointer holds the address of a integer variable.

Definitions:
Call by address: facilitating the changes made to a variable in the called function to become permanently
available in the function from where the function is called.

Call-by-value :A particular way of implementing a function call, in which the arguments are passed by
their value (i.e., their copies).

Dangling pointer: A pointer pointing to a previously meaningful location that is no longer meaningful;
usually a result of a pointer pointing to an object that is de allocated without resetting the value of the
pointer.

Dynamic memory allocation :The process of requesting and obtaining additional memory segments
during the execution of a program.

Function pointer: A function has a physical location in memory that can be assigned to a pointer. Then it
is called function pointer. This address is the entry point of the function and it is the address used when
the function is called.

Garbage collection: If only implicit dynamic allocation is allowed then deallocation must also be done by
implicit means, which is often called garbage collection.

NULL : A special C constant, defined as macro in stdio.h as or 0, or (void*)), that can be


used as the null value for pointers.

131
Null pointer: A null pointer is a special pointer value that points nowhere. I is initialized with value 0 or
NULL.

Pointer : A value or a variable with two attributes:


● an address and
● a data type of what should be found at that address.
Static memory allocation: Memory layout for static data prepared by the compiler.

Void pointer :A void pointer is a special type of pointer that can point to any data type.

Understanding Memory Addresses :

132
Memory Layout:

1. Text/Code segment: code and read-only, sharable by several instances of processes


2. Data Segment: Storage for initialized global variables
3. BSS: storage for uninitialized global variables
4. Stack Segment
● Provides storage for local variables declared in functions
● Stores housekeeping information involved when function calls are made
● Needed for recursive calls
5. Heap: Reserved for dynamically(run-time) allocating memory for variables
6. Shared libraries: Contains the executable libraries being used by the program
Operators used with Pointer:
1. Address Operator (&) :


Attributes of variables
● Name
● Location (address)
● Type and value
● Scope, lifetime
● Operations
● The location of a variable is decided by the compiler and the operating system at run-time.

● The initial value of a variable without assigning a value, the result is a garbage value.

● The ampersand (&) operator is used to get the address of a variable


scanf(“%d”, &n);

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

2. Indirection Operator and Dereferencing :


133
● 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;

● A pointer provides a way of accessing a variable without referring to the variable directly.
● A pointer is a variable that holds the memory address of another variable.
● A pointer has two parts,
● The address that it holds and
● The value pointed by that address

Pointers can be used to:


● Call by address, thereby facilitating the changes made to a variable in the called function to become
permanently available in the function from where the function is called.
● Return more than one value from a function indirectly.
● Pass arrays and strings more conveniently from one function to another.
● Manipulate arrays more easily by moving pointers to them (or to parts of them) instead of moving
the arrays themselves.
● Create complex data structures, such as linked lists and binary trees, where one data structure must
contain references to other data structures.
● Communicate information about memory, as in the function malloc()
which returns the location of free memory by using a pointer.
● Compile faster, more efficient code than other derived data types such as arrays.

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.
134

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:

/* Program to illustrate Pointer Variable Declaration*/


#include<stdio.h>
int main( )
{
int *p;
float *q;
double *r;
printf(“\n the size of integer pointer is %d”, sizeof(p));
printf(“\n the size of fl oat pointer is %d”, sizeof(q));
printf(“\n the size of double pointer is %d”,sizeof(r));
printf(“\n the size of character pointer is %d”, sizeof(char *));
return 0;
}
Output :
In Turbo C:
the size of integer pointer is 2
the size of fl oat pointer is 2

135
the size of double pointer is 2
the size of character pointer is 2
In GCC:
the size of integer pointer is 4
the size of fl oat pointer is 4
the size of double pointer is 4
the size of character pointer is 4

Initializing Pointers :

A Pointer is similar to any other variable excepts that it holds only memory address and therefore
it needs to be initialized with a valid address before it can be used.

● Unlike a simple variable that stores a value, a pointer must be initialized with a specified
address prior to its use.
● A pointer should be initialized with another variable‘s memory address, with 0, or with the
keyword NULL prior to its use; otherwise the result may be a compiler error or a run-time
error.
Example :
#include <stdio.h>
int main()
{
int *p; /* a pointer to an integer */
printf(“%d\n”,*p);
return 0;
}

Assigning Pointers :

● A pointer is bound to a specific data type (except pointer to void) . A pointer to an int cannot
hold the address of a character variable in which case a compiler error would result.
● The following pointer initializations are invalid.
int a=6, *ip;
float *p;
char ch=’A’;
p=&a;
ip=&ch:
136
From the Below Figure :
● r points to the same address that p points to, which is the address of i.
● We can assign pointers to one another, and the address is copied from the right-hand
side to the left- hand side during the assignment.

Printing pointer value :

● To print the memory address stored in pointers and non-pointer variables using the %p conversion
specifier and to learn the use of the %p conversion specifier.
● Addresses must always be printed using %u or %p or %x. If %p is used, the address is printed in
hexadecimal form. If %u is used, address is printed in decimal form.

Example 1 :
/* Program to illustrate Pointer Initialization*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
*p=&a;
printf(“\n*p = %p”, *p);
return 0;
}

Example 2 :
/* Program to illustrate printing Pointer Value*/
#include <stdio.h>
int main(void)
{
int a=20, *p;
p=&a;
137
printf(“\n*p = %p”, *p);
return 0;
}
Output:
p = 0022FF2C

Is it possible to assign a constant to a pointer variable?

● 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 = &num;
printf(“ The value of a num is %d”, num);

num = 100;
printf(“ The value of a num after num=10 is %d”, num);

*iPtr = 25;
printf(“ The value of a num after *iPtr = 15 is %d”, num);

Output:
The value of num is 15
The value of num after num = 100 is 100
The value of num after *iPtr = 25 is 25

138
Void Pointer :
● A void pointer is a special type of pointer.
● It can point to any data type, from an integer value or a float to a string of characters.
● Its sole limitation is that the pointed data cannot be referenced directly (the asterisk * operator
cannot be used on them) since its length is always undetermined. Use type casting or
assignment
Example:
/* Program to illustrate Void Pointer */

int main()
{
int a=10,
double b=3.1415;
void *vp;
vp=&a;
printf(“\n a=%d”, *((int*)vp));
vp=&b;
printf(“\n a= %d”, *((double *)vp));
return 0;
}
Output :
a= 10
b= 3.141500
Null Pointer :
● Null pointer is a special pointer that points nowhere. That is, no other valid pointer to any other
variable or array cell or anything else will ever be equal to a null pointer.
#include <stdio.h>
int *ip = NULL;
● It is also possible to refer to the null pointer using a constant 0,
int *ip = 0;
● NULL is a constant that is defined in the standard library and is the equivalent of zero for a
pointer.
● NULL is a value that is guaranteed not to point to any location in memory.
Use of Pointers :

Call by reference : One of the typical applications of pointers is to support call by reference. However,
139
C does not support call by reference as do other programming languages such as PASCAL and
FORTRAN.
● Typically a function call is made to communicate some arguments to the function.
● C makes use of only one mechanism to communicate arguments to a function: call
by value.
● This means that when a function is called, a copy of the values of the arguments is
created and given to the function.
● Call by reference: Simulated by the use of pointers called ―call by address‖.

Example:
/* Program to illustrate call by Value*/
void swap(int a, int b)
{
int temp; temp=a; a=b; b=temp;
}
int main()
{
int x=5,y=10;
void swap(int,int); printf(“%d %d\n”,x,y);
swap(x,y);
printf(“%d %d\n”,x,y);
return 0;
}

Output:
5 10
5 10 No swapping

/* Program to illustrate call by Address*/


void swap(int *a, int *b)
{
int temp; temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x=5,y=10;

140
void swap(int *,int *);
printf(“%d %d\n”,x,y);
swap(&x, &y);
printf(“%d %d\n”,x,y); return 0;
}

Output:
5 10
10 5
Returning more than one value from a function:

● Pointers allow the programmer to return more than one value

Example :

/* Program to print area by illustrating returning more than one value from a function*/

#include <stdio.h>
int main()
{
float r, area, perimeter;
float compute(fl oat, fl oat *); //function prototype
printf(“\n enter the radius of the circle:”);
scanf(“%f”,&r);
area=compute(r, &perimeter); //function call
printf(“\n AREA = %f”, area);
printf(“\n PERIMETER = %f”, perimeter); return 0;
}
float compute(float r, fl oat *p)
{
float a;
a=(fl oat)3.1415 * r * r;
*p=(fl oat)3.1415 * 2 * r;
return a;
}

Arrays and Pointers :

141
One-dimensional Arrays and Pointers :

● An array is a non-empty set of sequentially indexed elements having the same type of data.
● Each element of an array has a unique identifying index number. Changes made to one
element of an array does not affect the other elements.
● An array occupies a contiguous block of memory. The array a is laid out in memory as a
contiguous block, as shown.

The below figure demonstrates the memory allocation strategy of Arrays :

● Array name is an pointer constant. It cannot be used as lvalue.


● Array names cannot be used as variables on the left of an assignment operator.
● Both array and &array would give the base address of the array, but the only difference is
under ANSI/ISO Standard C, &array yields a pointer, of type pointer to- array of-the data type
to the entire array.

Example :
/* Program to illustrate arrays*/
#include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u %u”, array, &array*0+);
return 0;
}
Output:
2147478270
2147478270

A pointer variable (of the appropriate type) can also be used to initialize or point to the
first element of the array.

142
Below figure depicts the equivalence among array notation and pointer notation.

Passing Array to a Function :

● For any one-dimensional array a and integer i, the following relationships are always true.
143
a*i+ ≡ *(a+i) ≡ *(i+a) ≡ i*a+
● An array may be passed to a function, and the elements of that array may be modified without
having to worry about referencing and dereferencing.

When an array is passed to a function, it degenerates to a pointer.

● All array names that are function parameters are always converted into pointers by the compiler.
● Because when passing an array to a function, the address of the zero-th element of the array is
copied to the pointer variable which is the formal parameter of the function.
● However, arrays and pointers are processed differently by the compiler, represented differently
at runtime.
Differences between Array Name & Pointer :
● When memory is allocated for the array, the starting address is fixed, i.e., it cannot be changed during
program execution. Therefore, array name is an address constant.
● The & (address of) operator normally returns the address of the operand. However, arrays are the
exception.
● When applied to an array (which is an address), it has the same value as the array reference without
the operator.
● This is not true of the equivalent pointers, which have an independent address.
● The sizeof operator returns the
● Size of the allocated space for arrays in case of arrays.
● 4 or 8 bytes depending on the machine architecture.

Difference Between Arrays and Pointers :


144
Arrays Pointers
Array allocate space automatically It is explicitly assigned to point to an allocated
space
It cannot be resized It can be resized using realloc( )
It cannot be reassigned It can be reassigned
sizeof(arrayname) gives the number of bytes sizeof(p) gives the number of bytes used to
occupied by the array store the pointer variable p

Pointer Arithmetic :

A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can on a numeric value. There are four arithmetic operators that
can be used on pointers: ++, --, +, and –

Pointer Arithmetic - Valid :


The only valid operations on pointers are as follows.
1) Assignment of pointers to the same type of pointers: the assignment of pointers is done
symbolically. Hence no integer constant except 0 can be assigned to a pointer.
2) Adding or subtracting a pointer and an integer.
3) Subtracting or comparing two pointers (within array limits) that point to the elements of an
array Pointer Arithmetic - Valid
4) Incrementing or decrementing the pointers (within array limits) that point to the elements of
an array.
• When a pointer to an integer is incremented by one, the address is incremented by
two (as two bytes are used for int).
• Such scaling factors necessary for the pointer arithmetic are taken care of
automatically by the compiler.
5) Assigning the value 0 to the pointer variable and comparing 0 with the pointer. The pointer
with address 0 points to nowhere at all.

Pointer Arithmetic- not Valid


1. Addition of two pointers
2. Multiplying a pointer with a number
3. Dividing a pointer with a number

Important Points - Pointer Arithmetic:

145
Pointers and Strings :
● Strings are one-dimensional arrays of type char. By convention, a string in C is terminated by
the end-of-string sentinel \0, or null character.
● A string constant is treated by the compiler as a pointer.
● For a string, the number of elements it has need not be passed to a function because it has the
terminating null character

Array of Pointers :
● An array of pointers can be declared very easily.
Example: int *p[20];
● Declares an array of 20 pointer, each of which points to an integer.
st nd
● 1 pointer is p[0], 2 is p[1], and so on up to p[19] .
● These start off as uninitialized—they point to some unknown point in memory. We
could make them point to integer variables in memory thus.

Example :

146
Pointers to Array :

We can declare a pointer to a simple integer value and make it point to the array as is done
normally.

Example :
int v[5] = {1004, 2201, 3000, 432, 500};
int *p = v;
printf(“%d \n”, *p);

This piece of code displays the number, which the pointer p points to, that is the first number in the
array, namely 1004.

we can use instructions such as += and -= to refer to different elements in the array.

147
Difference between an array of pointers and a pointer to an array

Array of Pointer Pointer to an Array


Declaration Declaration
Data_type * array_name[SIZE]; Data_type (* array_name)[SIZE];
Size represents the number of rows Size represents the number of columns
The space for columns may be allotted The space for rows may be dynamically allotted

148
Two-dimensional array and Pointers :

A two-dimensional array in C is treated as a one dimensional array whose elements are one-dimensional
arrays (the rows).
● C does not do run-time range checking of array subscripts.
● In C the rightmost subscript of a two-dimensional array varies faster than the leftmost.
● Multi-dimensional array is stored in a ‗row major addressing‘ format.
● The following expressions are equivalent for a two dimensional array
a[i][j]= *(a[i]+ j) = (*(a + i))[j] = *(*(a + i)+ j)
● Arrays of dimension higher than two work in a similar fashion.
● Let us describe how three-dimensional arrays work.
● If the following is declared
int a[7][9][2];
● In case of multi-dimensional arrays all sizes except the first must be specified.

Logical representation of a two-dimensional array

Physical representation of a two-dimensional array

Example 1 :

149
/* Program to illustrate matrix addition – two dimensional array*/

void getdata(int x[10][10], int m, int n)


{
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
scanf("%d",&x[i][j]); return;
}
void display(int x[10][10], int m, int n)
{
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j) printf("%4d",x[i][j]);
printf("\n");
}
return;
}
void add(int x[10][10],int y[10][10],int z[10][10],int m,int n)
{
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
z[i][j] = x[i][j] + y[i][j];
return;
}
int main()
{
int A[10][10],B[10][10],C[10][10],T[10][10],m,n;
printf("\nEnter the values of m and n: ");
scanf("%d %d",&m,&n);
150
printf("\nEnter the elements of A: ");
getdata(A,m,n);
printf("\nEnter the elements of B: ");
getdata(B,p,q);
printf("\nGiven matrix A is:\n");
display(A,m,n);
printf("\nGiven matrix B is:\n");
display(B,p,q);
add(A,B,C,m,n);
printf("\nGiven Resultant matrix C is:\n");
display(C,m,n);
return 0;
}

Example 2 :

/* matrix addition – Array of pointers*/

int *A[10],*B[10],*C[10],m, n, i;
printf("\nEnter the values of m and n: ");
scanf("%d %d",&m,&n); //read the values of m and n
for(i=0;i<m;++i) //allocate memory dynamically
{
A[i]=(int*)malloc(n*sizeof(int));
B[i]=(int *)malloc(n*sizeof(int));
C[i]=(int *)malloc(n*sizeof(int));
}
getdata(A,m,n);
getdata(B,m,n);
add(A,B,C,m,n);
display(C,m,n);

Example 3 :

/* matrix addition – Use of pointers*/

void getdata(int *x[10], int m, int n)


{

151
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
scanf("%d",x[i]+j); //or &x[i][j] or *(x+i)+j
return;
}
void display(int *x[10], int m, int n)
{
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
printf("%4d",*(x[i]+j)); //or x[i][j] or *(*(x+i)+j)

printf("\n");
}
return;
}

Example 4 :

/* matrix addition – Pointer to 2-D array */

int **A,**B,**C, i, m, n;
printf("\nEnter the values of m and n: "); scanf("%d %d",&m,&n);
//read the values of m and n
for(i=0;i<m;++i)
A[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;++i)
B[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;++i)
C[i]=(int *)malloc(n*sizeof(int));

Example 5 :

/* matrix addition – Using Pointers - Pointer to 2-D array */

void getdata(int **x, int m, int n)


{
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
152
scanf("%d", *(x+i)+j); //or &x[i][j] or *(x+i)+j or (x+i)[j]
return;
}
void display(int *x[10], int m, int n)
{
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
printf("%4d",*(*(x+i)+j)); //or x[i][j] or *(*(x+i)+j) or *(x+i)[j]

printf("\n");
}
return;
}

Pointers to Functions :
C also allows pointers to point to functions and it is one of the powerful feature
Declaration of a Pointer to a Function
return_type (*fptr) (argument_type1, argument_type2, ..);
Example:
int(*fp)(int, char, float); //fp is a pointer to a function that take one int, one char, one float
and returns an int

● Parenthesis are important and int *fp(); declares a function that returns an integer pointer

Initialization of Function Pointers:


For example , two functions are declared as:
int add(int, int); and int sub(int, int);

The names of these functions, add and sum, are pointers to those functions. These can be assigned
to pointer variables.
fptr = add;
fptr = sub;

Calling a Function using a Function Pointer :


For example:
fptr=add; then the function call via function pointer will be:
result1 = fptr(4, 5); will return 9
fptr=sub;
153
result2 = fptr(6, 2); will return 4.

Passing a Function to another Function:

A function pointer can be passed as a function‘s calling argument.


● How to Return a Function Pointer
float(*GetPtr1(char opCode))(float, float)
{
if(opCode == ‘+’) return &Add; if(opCode == ‘-’)
return &Sub;
}
A solution using a typedef defines a pointer to a function that takes two float values and returns a float.

Arrays of Function Pointers:


Example :

/* Program – Arrays of Function Pointers */

void Add(int a, int b)


{
printf(“\n Result of Addition = %d”,a+b);
}
void Sub(int a, int b)
{
printf(“\n Result of Subtraction = %d”,a-b);
}
void Mul(int a, int b)
{
printf(“\n Result of Multiplication = %d”,a*b);
}
int main()
{
void(*p[3])(int, int);
int i;
void Add(int, int);
void Sub(int, int);
void Mul(int, int);
p[0] = Add;
p[1] = Sub;
p[2] = Mul;
154
for(i = 0; i <= 2; i++)
(*p[i])(10, 5);
return 0;
}

Dynamic Memory Allocation :

Static memory allocation :



Compiler allocates the required memory space for a declared variable.

By using the address of operator, the reserved address is obtained that maybe assigned to a
pointer variable.

Since most declared variables have static memory, this way of assigning pointer value to a
pointer variable is known as static memory allocation.
Dynamic memory allocation :

A dynamic memory allocation uses functions such as malloc() or calloc() realloc() to get
memory dynamically.

If these functions are used to get memory dynamically and the values returned by these functions
are assigned to pointer variables, such assignments are known as dynamic memory allocation.

Memory is assigned during run-time.
● In dynamic memory allocation, memory is allocated at runtime from heap.According to
● ANSI compiler, the malloc() and calloc() returns a void pointer on successful allocation of
memory. If sufficient memory is not available, the malloc() and calloc() returns a NULL.
● calloc() initializes all the bits in the allocated space set to zero where as malloc() does not do
this.
● When dynamically allocated, arrays are no longer needed, it is recommended to free them
immediately.

Dynamic Allocation of Arrays:


To allocate a one-dimensional array of length N of some particular type where N is given by
the user, simply use malloc() to allocate enough memory to hold N elements of the particular type.
Example :

/* Program – Dynamic memory Allocation */

#includestdio.h>
#include<stdlib.h>
int main()
{
155
int N,*a,i,s=0;
printf(“\n enter no. of elements of the array:”);
scanf(“%d”,&N);
a=(int *)malloc(N*sizeof(int));
if(a==NULL)
{
printf(“\n memory allocation unsuccessful...”);
exit(0);
}
printf(“\n enter the array elements one by one”);
for(i=0; i<N;++i)
{
scanf(“%d”,&a*i+)); /* equivalent statement
scanf(“%d”,(a+i));*/
s+=a[i];
}
printf(“\n sum is %d ”,s); return 0;
}

Freeing Memory :

● Dynamically allocated memory is de-allocated with the free function. If p contains a pointer
previously returned by malloc(), a call such as free(p);
● calloc() requires two parameters, the first for the number of elements to be allocated and the
second for the size of each element, whereas malloc() requires one parameters.
● calloc() initializes all the bits in the allocated space set to zero whereas malloc() does not do this.
● P=calloc(m, n) is essentially equivalent to p = malloc(m * n);
● malloc(0) results are unpredictable. It may return some other pointer or it may return some other
implementation-dependent value.

Reallocating Memory Blocks :

● malloc() will not work. It is the realloc() function that is required


ip = realloc(ip, 200 * sizeof(int));

Implementing Multidimensional Arrays using Pointers:


It is usually best to allocate an array of pointers, and then initialize each pointer to a dynamically
allocated ‗row‘.

156
Memory Leak and Memory Corruption

Dangling pointer :
A pointer may be used to hold the address of dynamically allocated memory. After this memory is
freed with the free() function (in C), the pointer itself will still contain the address of the released
block. This is referred to as a dangling pointer.

Memory corruption :
Memory when altered without an explicit assignment due to the inadvertent and unexpected altering of
data held in memory or the altering of a pointer to a specific place in memory is known as memory
corruption.

Advantages of Pointers :
● Pointers save memory space
● Execution time with pointer is fast because data is manipulated with address i.e directly
with memory location.
● Memory is accessed efficiently with pointers
● Dynamic memory is allocated
● Pointers are used with data structures.
● Pointers are useful for representing two dimensional and multi dimensional Arrays.

Drawbacks of Pointers :

● A programmer is likely to commit mistakes such as typographical mistakes and providing wrong
offsets.
● Porting the code to other implementations would require changes, if data type sizes differ. This
would lead to portability issues.
157
● Pointers have data types but the size of a pointer variable is always 4-bytes (in a 32-bit machine)
8-bytes (in a 64-bt machine) whatever the data type is used in declaring it.
Summary exercise:
6. [Pointer is a memory variable that holds address of another variable.
7. Certain Arithmetic Operations can be performed on Pointers.
8. An array name itself is a pointer. Whenever address are stored as array elements, such an
array is called as array of pointers. 2D arrays can be represented using pointers.
9. Dynamic Memory Allocation is the process by which the required memory address is obtained
without an explicit declaration.

Review and revision:


Review and revision exercise (1) :

Lecture topic quiz / MCQs:


1.(*FP)(INT, INT) REPRESENTS .......... L2
A. FUNCTION POINTER
B. ARRAY OF PINTERS
C. POINTER ARRAY
D. ARRAY OF FUNCTION POINTER

2._____ IS THE MEMORY VARIABLE USED TO STORE ADDRESS OF ANOTHER VARIABLE.


L1
A. FUNCTION
B. VARIABLE
C. POINTER
D. IDENTIFIER

3.INT *P; L3
INT A=100;
P=&A;
PRINTF("%d %d",*P,P);
A.100,1000
B. 10,1000
C. 10
D. 1000

4.Address stored in pointer variable is of ________ type L1


A. Integer
B.character
C. Float

158
D.Double

5.* is called as ___________ L1


A.Value at pointer
B.Address operator
C.Scope resolution operator
D.None

6.int *p1,*p2; find out valid statement L2


A.p1-p2
B.p1*p2
C.p1+p2
D.p1/p2

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)

9.A pointer is ...... L1


A.A keyword used to create variables
B.A variable that stores address of an instruction
C.A variable that stores address of other variable
D.All of the above

10.What will be the output? L4


main()
{
char *p;
printf(―%d %d‖,sizeof(*p),sizeof(p));
}
A.1 1
B.1 2
C.2 1
159
D.2 2

Review and revision exercise (2) :


Discussion questions / Expected Questions:
Short Questions :
1. Define pointer. How can you declare it? L2
2. What is pointer arithmetic? L2
3. Define pointer array. L1
4. What is pointer to pointer? L1
5. Define Void Pointer. L1
6. Define Null Pointer. L1
7. Write about operators used with pointers. L2
8. Differentiate Pointers and Arrays. L3

Long Questions :
1. Write a program to calculate length of the string using pointers. L6
2. Write a C program to illustrate the use of indirection operator to access the value pointed by a
pointer. L6
3. What are the features of pointers? Write a C program to print address of a variable. L3
4. Explain the declaration of pointers and pointer to pointer with examples. L4
5. Explain the concept of array of pointers with examples. L3
6. With proper examples explain different arithmetic operations on pointers. L3
7. Explain the concept of functions returning pointers with example. L3
8. Write a C program to read and print an array of elements using pointers. L6
9. Write a C program to read and display multiple strings using pointers. L6
10.Write a C Program to perform matrix addition using dynamic memory allocation. L6

160
UNIT IV

Course Code: 20CSC01

Course Title: Programming for Problem Solving

Instructors Name: G.Shanmukhi Rama

Name Email
G.Shanmukhi Rama Shanmukhi.rama_cse@cbit.ac.in

Objective:

(The primary goals of the module/unit)


The primary goals of the module/unit are to introduce:

● Basic representation of Structures and usage of Structures along with functions


● Self Referential structures which helps to understand various data structures in further
courses.
● Basic representation of Unions and enumerated datatypes

Outcome:
1. On Successful completion of the course, students will be able to Apply structures, and
unions to solve mathematical and scientific problems.

161
Scope:
The Module/Unit covers the following topics: Structure definition, initialization and accessing the
members of a structure, nested structures, structures and functions, self- referential structures,
unions, and enumerated data types.

While the topics are taught using a C language, the intent of the course is to teach the usage of
Structures along with functions to solve large complex problems.

Text and Reference:

(a) Text Book:

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.
TB3:Pradeep DeyandManasGhosh,“ProgramminginC”,OxfordPress,2nd Edition,2017.

(b) Reference Books:

RB1: Byron Gottfried ,Schaum’s”Outline of Programming with C”,McGraw- Hill

RB2: Brian W. Kernighan and Dennis M. Ritchie,The C Programming Language, Prentice

Hall.

RB3: E.Balaguruswamy,Programmingin ANSI C,TataMcGraw-Hill .


RB4:ReemaTharaja “Introduction to C Programming”, Second Edition, OXFORD Press,
2015.
RB5:https://www.tutorialspoint.com/cprogramming/index.htm.

Module Theme Learning Objectives


/Lecture
L.32 Structures: Definition and To understand how to define, represent,
Initialization of Structures. and how to use Structure.

162
L.33 Accessing Members of Structures, To know how to access members of
Nested Structures. structures and to understand how to use
nested structures.
L.34 Self Referential Structures. To understand the concept of self
Referential Structures
L.35 Structures and Functions. To know how to pass and return structure
as argument in functions
L.36 Unions and Enumerated Types. To understand how to define, represent,
and how to use Unions and Enumerated
Types.

Lecture title ( L1 etc)


Date [ You Can Write During the Course]
Key topics / themes of the lecture :

Structure definition, initialization and accessing the members of a structure, nested


structures, structures and functions, self- referential structures, unions, and enumerated data
types.

Notes, comments and your own Examples with answers / questions

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−

Title Author Subject Book ID

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 –

struct structure_name{ data_type struct_member1; data_typestruct_member2;

163
data_typestruct_member n;
} [one or more structure variables separated by comma];

The structure_nameis optional and each struct_memberis a normal variable definition, such as int
i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final
semicolon, you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure –

struct Books
{
char title[50]; char author[50]; char subject[100]; intbook_id;
}book;

Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we
wish to access. You would use the keyword structto define variables of structure type.

The following example shows how to use a structure in a program

#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( )
{

Struct Books Book1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare Book2
of type Book*/
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
164
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n",Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n",Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id); return 0;
}

When the above code is compiled and executed, it produces the following result
Book 1 title : C Programming
Book 1 author :Nuha Ali

Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407


Book 2 title : Telecom Billing

Book 2 author : Zara Ali


Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700

Nested structures
Structure written inside another structure is called as nesting of two structures. Nested Structures
are allowed in C Programming Language. We can write one Structure inside another structure as member
of another structure.
Example:
structdate
{
int date;
int month;
int year;
};

struct Employee

165
{
charename[20];
intssn;
float salary;
struct date doj;
}emp1;

Accessing the nested elements

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)

Explanation of nested elements:

Accessing Month Field : emp1.doj.month Accessing day Field : emp1.doj.day Accessing year Field
:emp1.doj.year

The following example shows how to use nested structure in a program

#include <stdio.h>
struct Employee
{
charename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};

int main(intargc, char *argv[])


{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployeeSSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployeeDOJ : %d/%d/%d", \ emp.doj.date,emp.doj.month,emp.doj.year);
return0;
}

166
When the above code is compiled and executed, it produces the following result

Employee Name :Pritesh Employee SSN : 1000 Employee Salary : 1000.500000 EmployeeDOJ :
22/6/1990

Arrays of Structures
We may declare the structure variable as an array by using index. Arrays of structures are passed
using the following syntax,
structstructure_name{ data_type struct_member1; data_typestruct_member2;

data_typestruct_membern;
};
structstructure_namestruct_variable[index_value];

Example: #include<stdio.h> #include<conio.h> void main()


{
struct student
{
intrno;
char name[20]; char course[20]; float fees;
};
struct student s[20]; clrscr();
s[0].rno=10; gets(s[0].name);
gets(s[0].course); s[0].fees=1000.50;
printf("\n %d\t %s\t%s\t%f",s[0].rno,s[0].name,s[0].course,s[0].fees);
getch();
}

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.

Passing Structure Members as arguments to Function

We can pass individual members to a function just like ordinary variables.The following program
demonstrates how to pass structure members as arguments to the function.

167
1
2
3
4
5
6
7
8 #include<stdio.h>
9
1 /*
0 structure is defined above all functions so it is
1 global.
1 */
1
2 structstudent
1 {
3 charname[20];
1 introll_no;
4 intmarks;
1 };
5
1 voidprint_struct(charname[],introll_no,intmarks);
6
1 intmain()
7 {
1 structstudentstu={"Tim",1,78};
8 print_struct(stu.name,stu.roll_no,stu.marks);
1 return0;
9 }
2
0 voidprint_struct(charname[],introll_no,intmarks)
2 {
1 printf("Name: %s\n",name);
2 printf("Roll no: %d\n",roll_no);
2 printf("Marks: %d\n",marks);
2 printf("\n");
3 }
2
4
2
5
2
6
2

168
7
2
8
2
9
When the above code is compiled and executed, it produces the following result
Name: Tim
Roll no: 1
Marks: 78

Flow of Execution of the above code :

● In lines 7-12, a structure student is declared with three members


namely name, roll_no and marks.
● In line 14, a prototype of function print_struct() is declared which accepts three
arguments namely name of type pointer to char, roll_no of type int and marks is of
type int.
● In line 18, a structure variable stu of type struct student is declared and initialized.
● In line 19, all the three members of structure variable stu are passed to
the print_struct() function. The formal arguments of print_struct() function are initialized
with the values of the actual arguments.
● From lines 25-27, three printf() statement prints name, roll_no and marks of the student.
● The most important thing to note about this program is that stu.name is passed as a
reference because name of the array is a constant pointer. So the formal argument
of print_struct() function i.e name and stu.name both are pointing to the same array. As a
result, any changes made by the function print_struct() will affect the original array. We
can verify this fact by making the following amendments to our program.

Passing Structure variable as argument to a Function


In the earlier section, we have learned how to pass structure members as arguments to a
function. If a structure contains two-three members then we can easily pass them to function but
what if there are 9-10 or more members? Certainly passing 9-10 members is a tiresome and
error-prone process. So in such cases instead of passing members individually, we can pass
structure variable itself.
The following program demonstrates how we can pass structure variable as an argument to the
function.
1 #include<stdio.h>
2
3 /*
4 structure is defined above all functions so it is
169
5 global.
6 */
7
8 structstudent
9{
1 charname[20];
0 introll_no;
1 intmarks;
1 };
1
2 voidprint_struct(structstudentstu);
1
3 intmain()
1 {
4 structstudentstu={"George",10,69};
1 print_struct(stu);
5 return0;
1 }
6
1 voidprint_struct(structstudentstu)
7 {
1 printf("Name: %s\n",stu.name);
8 printf("Roll no: %d\n",stu.roll_no);
1 printf("Marks: %d\n",stu.marks);
9 printf("\n");
2 }
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2

170
9
When the above code is compiled and executed, it produces the following result
Name: George
Roll no: 10
Marks: 69

Flow of Execution of the above code

● In lines 7-12, a structure student is declared with three members


namely: name, roll_no and marks.
● In line 14, the prototype of function print_struct() is declared which accepts an argument
of type struct student.
● In line 18, a structure variable stu of type struct student is declared and initialized.
● In line 19, print_struct() function is called along with argument stu. Unlike arrays, the
name of structure variable is not a pointer, so when we pass a structure variable to a
function, the formal argument of print_struct() is assigned a copy of the original structure.
Both structures reside in different memory locations and hence they are completely
independent of each other. Any changes made by function print_struct() doesn't affect
the original structure variable in the main() function.
● The printf() statements from lines 25-27 prints the details of the student.

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
171
5 global.
6 */
7
8 structplayer
9{
1 charname[20];
0 floatheight;
1 floatweight;
1 floatfees;
1 };
2
1 voidprint_struct(structplayerp);
3 structplayerdeduct_fees(structplayerp);
1
4 intmain()
1 {
5 structplayerp={"Joe",5.9,59,5000};
1 print_struct(p);
6 p=deduct_fees(p);
1 print_struct(p);
7
1 return0;
8 }
1
9 structplayerdeduct_fees(structplayerp)
2 {
0 p.fees-=1000;
2 returnp;
1 }
2
2 voidprint_struct(conststructplayerp)
2 {
3 printf("Name: %s\n",p.name);
2 printf("Height: %.2f\n",p.height);
4 printf("Weight: %.2f\n",p.weight);
2 printf("Fees: %.2f\n",p.fees);
5
2 printf("\n");
6 }
2
7
2
8
2

172
9
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
When the above code is compiled and executed, it produces the following result
Name: Joe
Height: 5.90
Weight:
59.00
Fees: 5000.00

Name: Joe
Height: 5.90
Weight:
59.00
Fees: 4000.00

Flow of Execution of the above code

● In lines 7-13, a structure of type player is declared with 4 members


namely name, height, weight and fees.
173
● In line 15, the prototype of print_struct() is declared which accepts an argument of
type struct player and returns nothing.
● In line 16, the prototype of deduct_fees() is declared which accepts an argument of
type struct player and returns a structure of type struct player.
● In line 20, a structure variable p of type struct player is declared and initialized.
● In line 21, the print_struct() function is passed an argument of type struct player. The
function prints the details of the player and passes the control back to main() function.
● In line 22, deduct_fees() function is called with an argument of type struct player. The
function decrements the fees of the player by 1000 using the statement.
● p.fees -= 1000;
● and then returns the structure variable p to the called function i.e main(), where it is
assigned back to the variable p.
● In line 23, the print_struct() is called again with the same argument as before to check
whether the details have been modified by deduct_fees() or not.
● After printing the details of the function the control passes back to main() function and
the program terminates.

Pointers to Structures

You can define pointers to structures in the same way as you define pointer to any other variable

struct Books *struct_pointer;

Now, you can store the address of a structure variable in the above defined pointer variable. To
find the address of a structure variable, place the '&'; operator before the structure's name as follows –

struct_pointer = &Book1;

To access the members of a structure using a pointer to that structure, you must use the
→ operator as follows –
struct_pointer->title;

The following program demonstrates how to access structure members using pointers.
#include <stdio.h>
#include <string.h>
struct Books{
chartitle[50];
char author[50];
char subject[100];
int book_id;
};
174
/* function declaration */ voidprintBook(struct Books *book ); int main( ) {
structBooksBook1; /* Declare Book1 of type Book */ structBooksBook2; /* Declare Book2
of type Book*/

/* book 1 specification */
strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* 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

Self Referential Structures


Self Referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member.

175
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
structnode {
intdata1;
chardata2;
structnode* link;
};

intmain()
{
structnode ob;
return0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’
is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing,
as by default it contains garbage value.

The following Program to demonstrate Self referential structure.


#include <stdio.h>

structnode {
intdata1;
chardata2;
structnode* link;
};

Int main()
176
{
structnode ob1; // Node1

// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2


ob1.link = &ob2;

// Accessing data members of ob2 using ob1


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–

union [union tag] { member definition; member definition;


...
member definition;

177
} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int i;
or float f; or any other valid variable definition. At the end of the union's definition, before the final
semicolon, you can specify one or more union variables but it is optional. Here is the way you would
define a union type named Data having three members i, f, and str–

union Data { int i;


float f;
char str[20]
} data;

Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple types of
data. You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by a character string.

The following example displays the total memory size occupied by the above union –

#include <stdio.h>
#include <string.h>
union Data {
inti; float f;
char str[20];
};

Int main( )
{
union Data data;
printf("Memorysizeoccupiedbydata:%d\n",sizeof(data));
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult– Memorysizeoccupiedbydata:20
Accessing Union Members

To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish to
access. You would use the keyword union to define variables of union type.

178
The following example shows how to use unions in a program −

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy(data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result – data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the value of
str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the
main purpose of having unions –

#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;

179
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy(data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result – data.i : 10
data.f : 220.500000
data.str : C Programming

Here, all the members are getting printed very well because one member is being used at a time.

Enumerated data types


Enumeration is a user defined data type in C language. It is used to assign names to the
integral constants which makes a program easy to read and maintain. The keyword “enum” is
used to declare an enumeration.
Here is the syntax of enum in C language,
Enum enum_name{const1, const2, ....... };

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.

enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};


enum week day;

The following example demonstrate the use of enum in the program

#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main()
{
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri,
Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn,
Thurs, Frid, Satu, Sund);
return 0;
180
}

When the above code is compiled and executed, it produces the following result –

The value of enum week: 10111213101617


The default value of enum day: 0123181112
In the above program, two enums are declared as week and day outside the main() function. In
the main() function, the values of enum elements are printed.

Summary exercise:

1. Structures Declaration and Usage

2. Usage of Structures for Complex Problems

3. Unions and their Importance, difference from structures

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.

Lecture topic quiz / MCQs:

1. Which of the following is true for definition of a structure


A) Items of the same data type B) Items of the different data type
C)Integers with user defined names D) List of Strings
L1
2. The keyword used to define a structure is
A) stru B)struct C)structure D)STRUC
L1
3. The operator used to access the structure member is
A)* B)& C). D)|
L1
4. The operator exclusively used with pointer to structure is
A). B)[] C)� D)* L1
5. Which of the following is correct for a Structure definition?
A) Scalar data type B) Derived data type
B) C)Enumerated type D) Null Type
L1
6. When accessing a structure member, the identifier to the left of the dot operator is
181
A) A structure ember B) The structure tag
C) A structure variable D) The keyword struct
L2
7. When a structure is an element to another structure, it is called asa
A) Union B) Structure within a structure
C) Pointer to Structure D) Array of Structures
L1
8. A structure is one which contains a pointer to its own type.
A) Self-referential B)Nested
B) C)Array D)Pointer
L1
C)
9. Consider the following declaration
of union st
{
char c;
int x;
float y;
}p;
How many bytes are allocated to union variable p?
A) 7bytes B)4bytes C)1byte D) 2bytes
L2
10. The size of structure and union is same when they contain
A) Single member B) any number of members
C) Arrays of different types D) Pointers to different types
L2
11. The operator used to find the size of any variable
A) sizeof() B)sizof() C) sizeof() D) size()
L1

12. The operator ⬥ is same as the combination of the operators


A) *and . B) &and. C) *and & D) & and|
L1
13. Union can store number of values at a time
A) All its members B) Only 1
B) C) 2 D) Cannot hold value
L1
14. ‗C‗ provides a facility for user defined data type using concept
A) Array B)Function C) Pointer D) Structure
L1
15. In the expression p⬥ value, p is a
182
A) Address B)Pointer C)Structure D) Header
L1
16. In C language the expression(*ps).x is equal to
A) ps->x B)x->ps C)ps->*x D)None
L1
17. Which of the following is a list of named integer constants?
A) typedef B)enumeration C)structure D)union
L1
18. Which of the following is a memory location that is shared by two or more
different types of variables?
A) typedef B)enumeration C)structure D)union
L2

Review and revision exercise (2) :


Discussion questions / Expected Questions:
Short Questions :

1. Define Structure? How to Initialize a Structure? L2


2. How to represent self-referential structures? L2
3. Define Union? How to represent an union? L2
4. Write some of the differences between Structure and Union? L1
5. What are the Different ways of representing Structures and Functions? L2

Long Questions :

1. Define Structure and write the general syntax for declaring and accessing members. L1
2. How to copy and compare structure variables? Illustrate with example. L2
3. Write a C program that defines a structure employee containing the details such as empno,emp
name, department name and salary. The structure has to store 20 employees in anorganization.
Use the appropriate method to define the above details and define a function thatwill display
the contents? L3
4. Explain the Nested structures L2
5. Write a C program to read and display student details using structure. L3
6. Define union. Give the general template for union. L1
7. List out the differences between unions, structures and arrays L4
8. How data elements are stored under unions, explain with example? L3
9. Write a C program to illustrate the concept of structure within structure. L3

183
Course Code: 20CS C01
Course Title: PROGRAMMING FOR PROBLEM SOLVING

Instructors Name:

Name Email
Smt.B.PoonguzharSelvi poonguzharselvi_cse@cbit.ac.in

Objective:

The primary goals of the module/unit are to introduce:


● File concepts and how to read from a file which is stored in our computer and how to
write data to a file in a computer.

Outcome:

On Successful completion of the course, students will be able to develop applications with
files.

Scope:
184
The Module/Unit covers the following topics:
Files: Introduction to files, file operations, reading data from files, writing data to files, error
handing during file operations – Basic files concepts and manipulation of data stored in a file.
While the topics are taught using a C language, the intent of the course is to teach a
programming methodology to handle files and also a laboratory component that involves
development and testing of programs to manipulate data in files.

Text and Reference:


(a) Text Book:

TB1. M.T. Somashekar “Problem Solving with C”, 2nd Edition, Prentice Hall India Learning
Private Limited 2018
nd
TB2. A K Sharma “Computer Fundamentals and Programming”, 2 Edition, University
Press, 2018
nd
TB3. Pradeep Dey and Manas Ghosh, “Programming in C”, Oxford Press, 2 Edition,
2017

(b) Reference Books:

RB1. ByronGottfried ,Schaum’s”OutlineofProgrammingwithC”,McGraw- Hill

RB2.Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language,


Prentice Hall of India.
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

Module Theme Learning Objectives


/Lectur
e
I Introduction to files, file To understand the basics of files and all
operations possible operations on files

II Reading data from files To under how to read data from a file.
III Writing data to files, error handing To under how to write data to a file with
during file operations. different error handling approaches.

185
Lecture title L.37
Date
Key topics / themes of the lecture : Introduction to files, file operations

INTRODUCTION TO FILES:
In real world application when data is large then it is necessary to stored on the disk in files.
A file represents a sequence of bytes. file is created in secondary storage. Files are of two types
text file and binary file.
C language provides access on files with high/low level functions .FILE is a structure defined
in standard input/output library.
The file pointer is created and used as FILE *fp; where fp is a file pointer
Types of files
1. Text File :
A text stream consist of a sequence of characters. they are grouped in line. stores the
data in the text form
2. Binary File :
It stores the data in the binary form (1's and 0's). A binary stream consists of a
sequence of data. They are stored in their memory representation.

Operations on Files
C language support a number of functions to perform basic operation on file
● creating a file
● opening a file
● writing into the file
● reading from the file
● close the file
files I/O functions to manipulate data in file :
fopen() : create a file or open an existing file
fclose() : close a file
getc() : read a character
putc() : write a character
fprintf() : write a formatted values
fscanf() : read set of values
getw() : read an integer
putw() :write an integer

How to open a file?


fopen() function is used to open a file . This function creates a new file if the file does
not exist. .
Syntax: fopen(filename,mode)
Here, the first argument is file name and second argument is access mode.
The following are the different access modes in C,
r : read mode
w : writing mode
186
a : append mode
r+ : First reading then writing
w+: reading and writing and content is truncated
a+ : reading and writing and content is not truncated

Example: Demonstrate the opening of a file


#include<stdio.h>
int main()
{
FILE *fp; //creating a file pointer
fp=fopen("abc.txt","r"); // open a file
return 0;
}

How to close a file?


fclose()is used for closing the file. The fclose() function returns zero on success, or
EOF if there is an error in closing the file.
Syntax: fclose(filepointer)

Example:
#include<stdio.h>
int main()
{
FILE *fp; //creating a file pointer
fp=fopen("abc.txt","r"); // open a file
fclose(fp); // at the end close the file
return 0;
}

Summary exercise:
1. File pointer is created using FILE structure which is defined in stdio.h header file.
2. There 2 types of files: Text file, binary file
3. files can be opened in different modes to manipulate data using fopen() function.

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.

Lecture topic quiz / MCQs:


1. Choose correct syntax for opening a file. (CO6)(BT1)
a) FILE *fopen(const *filename, const char *mode)
b) FILE *fopen(const *filename)
187
c) FILE *open(const *filename, const char *mode)
d) FILE open(const*filename)
Answer: a) FILE *fopen(const *filename, const char *mode)

2. Outline the function of the mode ‘ w+’? (CO6) (BT 2)


a) create text file for writing, discard previous contents if any
b) create text file for update, discard previous contents if any
c) create text file for writing, do not discard previous contents if any
d) create text file for update, do not discard previous contents if any
Answer:b) create text file for update, discard previous contents if any
3. Before we can read or write to a file in C, what do we need to do? (CO6)(BT 1)
a) open the file
b) close the file
c) print the content of the file
d) NONE
Answer:a) open the file
4. Which flag is used in fopen function to append data to an existing file instead of recreating
the file?(CO6)(BT 1)
a) a
b) r
c) w
d) W+
Answer:a) a

5. If the mode includes b after the initial letter in fopen function then what does it
indicates?(CO6)(BT 1)
a) text file
b) big text file
c) binary file
d) empty text
Answer: c) binary file

6. Select the correct statement about FILE *fp. (CO6)(BT 3)


a) FILE is a keyword in C for representing files and fp is a variable of FILE type.
b) FILE is a stream
c) FILE is a buffered stream
d) FILE is a structure and fp is a pointer to the structure of FILE type
Answer: d) FILE is a structure and fp is a pointer to the structure of FILE type
7. Summarize the first and second arguments of fopen().(CO6)(BT 2)
a) name of the file,mode
b) name of the user,mode
c) file pointer , mode
d) None

188
Answer:a) a) name of the file,mode

8. Find the type of FILE. (CO6) (BT1)

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

Review and revision exercise (2) :

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)

Lecture title L.38


Date
Key topics / themes of the lecture : Reading data from files
We can read both text files as well as binary files.
Reading data from text file:
189
The following 3 functions are used for reading data from a Text File.
1. fgetc():
The fgetc() function reads a character from the input file referenced by file pointer. The
return value is the character read, or in case of any error, it returns EOF.
Syntax: int fgetc( FILE * fp );

Example: Write a program to read data from file using fgetc() method
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("myfile.txt","r");
do {
c = fgetc(fp);
if( c==EOF ) {
break ;
}
printf("%c", c);
} while(1);

fclose(fp);
return(0);
}
2. fgets():
It reads a string from a stream.

Syntax: char *fgets( char *buf, int n, FILE *fp );


The functions fgets() reads up to n-1 characters from the input stream referenced by
file pointer fp. It copies the read string into the buffer buf, appending a null character to
terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before
they have read the maximum number of characters, then it returns only the characters
read up to that point including the new line character.
Example: Write a program to read data from file using fgets() method
#include <stdio.h>
void main() {
FILE *fp;
char output[255];
fp = fopen(“myfile.txt”, “r”);
fgets(buff, 255, fp);

190
printf(" %s\n", output );
fclose(fp);

3. fscanf()
This function is to read strings from a file, but it stops reading after encountering the
first space character.
Syntax: int fscanf(FILE *fp, const char *format, [ argument, ...])

Example: Write a program to read data from file using fscanf() method
#include <stdio.h>
void main() {

FILE *fp;
char name[255];
int rollnum;
fp = fopen(“myfile.txt”, “r”);
fscanf(fp, "%s", name);
fscanf(fp, "%d", rollnum);

printf(" Name: %s\nRoll No.:%d", name, rollnum );


fclose(fp);

}
Reading data from binary file:

The following function is used for reading data from a Binary File.
1. fread()
Reads data from the given stream into the array .
Syntax: size_t fread(void *ptr, size_t sizeOfElements, size_t numberOfElements, FILE *fp);
Here,
ptr − the pointer to a block of memory with a minimum size of sizeOfElements *
numberOfElements bytes.
sizeOfElements − the size in bytes of each element to be read.
numberOfElements − the number of elements, each one with a size of size bytes.
fp − the pointer to a FILE object that specifies an input stream.

Example: Write a program to read data from file using fread() method
#include <stdio.h>
int main () {
FILE *fp;
char output[100];

191
/* Open file for reading */
fp = fopen("myfile.txt", "r");

/* Read and display data */


fread(output, 1, 100, fp);
printf("%s\n", output);
fclose(fp);
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. single character, a word or a line can be read at a time from a file.


2. fgetc(), fgets() and fscanf() methods are used to read data from text file
3. fread() method is used for reading data from binary file

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.

Lecture topic quiz / MCQs:


1. choose the correct difference between fscanf() and scanf() methods (CO6) (BT 3)
a) fscanf() can read from standard input whereas scanf() specifies a stream from which to
read
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

192
3. Infer the statement: "fwrite() can be used only with files that are opened in binary
mode".(CO6) (BT 2)
a) true
b) false
Answer: a) true

4. Recall the function of fputs()?(CO6)(BT1)


a) read a line from a file
b) read a character from a file
c) write a character to a file
d) write a line to a file
Answer:d) write a line to a file

5. Summarize the action done by the following C code snippet.(CO6)(BT1)


char *gets(char *s)
a) reads the next input line into the array s
b) writes the line into the array s
c) reads the next input character into the array s
d) write a character into the array
Answer:a) reads the next input line into the array s

Review and revision exercise (2) :

Discussion questions / Expected Questions:


1. Outline the functions which are used to read data from a text file. (CO6)(BT2)
2. Infer the statement: “Reading from a text file and reading from a binary file can be done
using same function X”. Are you agreeing with this statement? Summarize your opinion.
Outline the functions which are used to read data from a text file. (CO6)(BT2)
3. Develop a C program to read from text file which contains student name, roll no and
marks of 3 subjects. Calculate and Display the percentage of marks for each student.
(CO6)(BT3)

Lecture title L.39


Date
Key topics / themes of the lecture : Writing data to files, error handing during file operations

193
WRITING DATA TO FILES
We can write data to both text files as well as binary files.
Writing data to a text file:

The following 3 functions are used for writing data to a Text File.
1. fputc():
The fputc() function writes the character value of the argument c to the output stream
referenced by file pointer. It returns the written character written on success otherwise
EOF if there is an error.
Syntax: int fputc(int c, FILE * fp );
Example: Write a program to write data to a file using fputc() method

#include <stdio.h>

int main () {
FILE *fp;
int ch;

fp = fopen("myfile.txt", "w");
for( ch = 65 ; ch <= 92; ch++ ) {
fputc(ch, fp);
}
fclose(fp);

return 0 ;
}

2. fputs():
It writes the string to the output stream referenced by file pointer.
Syntax: char *fgets( char *str, FILE *fp );

Example: Write a program to write data to a file using fputs() method

#include <stdio.h>

main() {
FILE *fp;

194
fp = fopen(“myfilet.txt", "w");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

3. fprintf()
It sends formatted output to a stream..
Syntax: int fprintf(FILE *fp, const char *format, [ argument, ...])

Example: Demonstrate a program to write data to a file using fprintf() method

#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.

Example: Demonstrate a program to write data to a file using fwrite() method

#include<stdio.h>
int main () {
FILE *fp;
char str[] = "AI department is No.1";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );

195
fclose(fp);
return 0;
}

RANDOM FILE ACCESS


We can take the file pointer to any part of the file for reading or writing. This can be done
using the following functions:
1. fseek():
It sets the file position of the stream to the given offset.
Syntax: int fseek(FILE *fp, long int offset, int whence)
Where, fp - the pointer to a FILE object that identifies the stream.
offset − number of bytes to offset from whence.
whence − the position from where offset is added.
● It is specified by one of the following constants:
SEEK_SET - represents Beginning of file
SEEK_CUR - represents Current position of the file pointer
SEEK_END - represents End of file
2. ftell():
It returns the current file position of the given stream.
Syntax: long int ftell(FILE *filepointer)
3. rewind():
It sets the file position to the beginning of the file of the given stream.
Syntax: void rewind(FILE *stream)

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;
}

ERROR HANDING DURING FILE OPERATIONS


The following file status functions are used for handling errors during file operation:
1. feof() : it is used to check if end of the file has been reached
syntax: int feof(FILE *fp);
2. ferror(): it is used to check the error status of the file. it returns true if it finds error,
otherwise false.
syntax: int ferror(FILE *fp);

196
3. clearerr(): this function is used to change the status of the file from error state
syntax: void clearerr(FILE *fp);

Summary exercise:
[At the end of the lecture, briefly look back over your notes and give summarizing the top three
‘take-away’ points (these might include key knowledge and/or any suggested further reading the
lecturer recommends etc)]:

1. fputc(), fprintf() and fwrite() methods are used for writing data to a file
2. fseek(),ftell() and rewind() methods used to access data from a file at random locations
3. feof() function is used for checking the end of file status
Review and revision:
Review and revision exercise (1) :

Look over your lecture notes and create a quiz and/or discussion exercise based on the content.
Doing this will help when students are preparing for exams.

Lecture topic quiz / MCQs:


1. Tell the function which will return the current file position for stream?(CO6)(BT1)
a) fgetpos()
b) fseek()
c) ftell()
d) fsetpos()
Answer:c) ftell()
2. Identify the main reason to prefer fseek() over rewind().(CO6) (BT3)
a) rewind() doesn't work for empty files
b) rewind() may fail for large files
c) In rewind, there is no way to check if the operations completed successfully
d) All of the above
Answer:c) In rewind, there is no way to check if the operations completed successfully
3. Choose the correct C functions to read or write to a Text file. (CO6)(BT1)
a) fprintf(), fscanf()
b) fread(), fwrite()
c) fprint(), scanf()
d) read(), write()
Answer:a) fprintf(), fscanf()
4. Choose the correct C functions to read or write to a binary file. (CO6)(BT1)
a) fprintf(), fscanf()
b) fread(), fwrite()
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)
197
b) rewind(fp)
c) ftell(fp)
d) frewind(fp)
Answer:b) rewind(fp)

Review and revision exercise (2) :

Discussion questions / Expected Questions:


1. 1. Discuss in detail how files are accessed randomly in C with suitable example. (CO6)(BT3)
2. Develop a C program to copy the content of one file to another file. (CO6)(BT3)
3. Show how to write data to a binary file. (CO6)(BT2)

Course Code: 20CSC01


Course Title: PROGRAMMING FOR PROBLEM SOLVING

Instructors Name:

Name Email
J Shiva Sai Jshivasai_cse@cbit.ac.in

Objective:

The primary goals of the module/unit are to introduce


● Basic representation of preprocessor directives and its types.
● To includes files directive, error directive and macro directive .

Outcome:

1. Develop applications using file I/O(inclusion of file directive)


198
Scope:

The Module/Unit covers the following topics:


Types of preprocessor directives, examples.

Text and Reference:


(a) Text Book:

1. M.T. Somashekar ―Problem Solving with C‖, 2 nd Edition, Prentice Hall India Learning Private Limited 2018
nd
2. AKSharma―ComputerFundamentalsandProgramming‖,2 Edition, University Press,2018
nd
3. PradeepDeyandManasGhosh,―ProgramminginC‖,OxfordPress,2 Edition,2017

(b) Reference Books:

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.

Module/ Theme Learning Objectives


Lecture
40 Types of preprocessor directives, examples. Able to learn preprocessor directives and structure
of preprocessing

Lecture title L40-Preprocessor Directives: Types of preprocessor directives, examples.


Date

Lecture Notes

PRE PROCESSOR DIRECTIVES

The C preprocessor is a macro processor that is used automatically by the C compiler to


transform programmer defined programs before actual compilation takes place. It is called a macro
processor because it allows the user to define macros, which are short abbreviations for longer constructs.
So, it can be also be referred to as pre compiled fragments of code. Some possible actions are the
inclusions of other files in the file being compiled, definitions of symbolic constants and macros and
conditional compilation of program code and conditional execution of preprocessor directives.
List of Preprocessor directives which starts with #: #include, #define, #undef, #ifdef, #ifndef, #if, #else,
#elif, #endif, #error, #pragma

199
# include preprocessor directive:

Only defined at the top of the program definition and only white space and comments may appear before
preprocessor directive line. This directive includes a copy of the specified file or library. And is written
like so-
# include <filename>
or

#include “file name”,

If included inside <> then the compiler looks for the file in an implementation defined manner (or
system directory paths). If included inside a quote ― ‖ statement then it searches for the file in the same
directory as the program being written.

So if we include a file named file1 while writing a program name code.c which is being stored in
a folder called test. Then inclusion like so -- #include ―file1‖ will tell the compiler to look for the file
inside the test folder, It looks at neighboring folders or subfolders too but it starts its search in the test
folder.(This sub search option is compiler dependent).

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define
directive. There are two types of macros: Object-like Macros, Function-like Macros

Object-like Macros (Symbolic constants)

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.

#define identifier replacement-text

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.

For example: #define PI 3.14159

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

The function-like macro looks like function call. For example:

#define MIN(a,b) ((a)<(b)?(a):(b))

200
Here, MIN is the macro name.

201
Example for Function-like Macros :
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
Output:
Minimum between 10 and 20 is: 10

Differences between MACRO and FUNCTION:

Macro Function
Macro is Preprocessed Function is Compiled
No Type Checking Type Checking is Done
Code Length Increases Code Length remains Same
Speed of Execution is Speed of Execution is Slower
Faster
Before Compilation macro name is replaced by During function call , Transfer of
macro value Control takes place
Useful where small code appears many time Useful where large code appears many
time
Generally Macros do not extend beyond one line Function can be of any number of lines

Macro does not Check Compile Errors Function Checks Compile Errors

Preprocessor Formatting

A preprocessing directive cannot be more than one line in normal circumstances. It may be split
cosmetically with Backslash-Newline. Comments containing Newlines can also divide the directive into
multiple lines.
for example, you can split a line cosmetically with Backslash-Newline anywhere:
/*
*/ # /*
*/ defi\
ne FO\
O 10\
20
is equivalent into #define FOO 1020.
#undef
To undefine a macro means to cancel its definition. This is done with the #undef directive.
Syntax:
#undef token
define and undefine example
#include <stdio.h>
#define PI 3.1415
#undef PI

202
main() {
printf("%f",PI);
}
Output:
Compile Time Error: 'PI' undeclared

#ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code.
Syntax:
#ifdef MACRO
//code
#endif

#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code.
Syntax:
#ifndef MACRO
/
/
c
o
#if d
e

#
e
n
d
i
f
The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the
code.
Syntax:
#if expression
//code
#endif

#else
The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be
used with #if, #elif, #ifdef and #ifndef directives.
Syntax:

Example
Syntax with #elif

203
#if expression l
/ s
/ e
i /
f /
e
c l
o s
d e
e
c
# o
e d
l e
s
e #
/ e
/ n
e d
l i
s f
e
#
c i
o n
d c
e l
u
# d
e e
n
d <
i s
f t
d
#if expression i
//if code o
#elif expression .
/ h
/ >
e
l #
i i
f n
c
c l
o u
d d
e e

# <
e c
204
o
n
i
o
.
h
>

#
d
e
f
i
n
e

N
U
M
B
E
R

v
o
i
d

m
a
i
n
(
)

{
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);

205
#else
p
r
i
n
Output t
(
"
V
a
l
u
e
o
f
N
u
m
b
e
r
i
s
n
o
n
-
z
e
r
o
"
)
;
#
e
n
d
i
f
getch();
}
Value of Number is non-zero

Example Code:

#include<stdio.h> -- Include external source code file


#include ―file1‖ - Include a file which is in the same folder as the parent file
#define BUFFER_SIZE 250
int maint(){

206
char array[BUFFER_SIZE] = [0]; int I
= 9;

printf(“%d”,i);

printf(“%s”,array);
return 0;

}//end main body

Conditional Compilation:

Conditional compilation enables the coder to control the execution of preprocessor directives and
the compilation of program code. Conditional preprocessor directives evaluate constant integer
expressions. The ones that cannot be evaluated in preprocessor directives are sizeof expressions and
enumeration constants.
Every #if construct ends with #endif

207
Example
#if !defined(MY_CONSTANT) #define MY_CONSTANT 0 #endif

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.

Example: conditional compilation

#include <stdio.h>

#define MEMBER

int main()

float amount,total;

printf("enter amount\n");

scanf("%f",&amount);

#ifdef MEMBER

total= amount*0.8;

printf("Amount to be paid=%f",total);

#else

printf("Amount to be paid=%f",amount);

#endif

208
Summary exercise:

Following table will show you various directives that we have studied in this chapter:

Directives Description
#define It substitutes a preprocessor macro.
#include It inserts a particular header file from another file.
#undef A preprocessor macro is undefined.
#ifdef It returns true if the macro is defined.
#ifndef It returns true if the macro is not defined.
#if It tests if the compile time condition is true.
#else It is an alternative for #if.
#elif It has #else and #if in one statement.
#endif The conditional preprocessor is ended.
#error It prints the error message on stderr.
#pragma It issues special commands to the compiler by using a standardized method.

Questions:

1. What are preprocessor commands? Give examples.

2. Difference between Macro and Function.

3. Distinguish between function and preprocessor directive.

4. Difference between #ifdef and #ifndef with example .

5. Give a brief note about Error directive.

MCQ

1. What will be the output of the program?


#include<stdio.h>

#define int char

void main()

209
{

int i = 65;

printf("sizeof(i)=%d", sizeof(i));

A. Sizeof(i)=2;
B. Sizeof(i)=1;
C. Compilation error
D. None
Answer:B

2. What will be the output of the program?


#include<stdio.h>
#define a 10
void main()
{
#define a 50
printf("%d", a);
}
A. 50
B. 10
C. Compilation error
D. None
Answer: A

3. What will be the output of the program?

#include <stdio.h>
#define p 17;
int main()
{
printf("%d",p);
return 0;
}
A. 17
B. Run-time error
C. Compilation error
D. Garbage value
Answer: A

4. In which stage the following code


#include<stdio.h>
gets replaced by the contents of the file stdio.h

210
A. During editing
B. During linking
C. During Preprocessor
D. During execution
Answer: C

5. What will be the output of the program?

#include<stdio.h>
#define SQR(x)(x*x)
int main()
{
int a, b=3;
a = SQR(b+2);
printf("%d\n", a);
return 0;
}
A. 25
B. 11
C. Error
D. Garbage value
Answer: B

211

You might also like