You are on page 1of 129

LECTURE NOTES

ON
COMPUTER PROGRAMMING
2018 – 2019

I B.Tech I Semester (Autonomous-R17)

Mr. V. SambaSiva., Assistant Professor

CHADALAWADA RAMANAMMA ENGINEERING COLLEGE


(AUTONOMOUS)
Chadalawada Nagar, Renigunta Road, Tirupati – 517 506

Department of Computer Science Engineering

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 1


COMPUTER PROGRAMMING

SYLLABUS
I B. Tech – I Semester: Common for All Branches

Course Code Category Hours/Week Credits Maximum Marks

17CA05101 Foundation L T P C CIA SEE Total

2 2 - 3 30 70 100

Practical Classes:
Contact Classes:34 Tutorial Classes:34 Total Classes:68
Nil

Objectives:

I. Understand problem solving techniques


II. Understand representation of a solution to a problem
III. Understand the syntax and semantics of C programming language
IV. Understand the significance of Control structures
V. Learn the features of C language
UNIT - I INTRODUCTION TO COMPUTERS AND C LANGUAGE Classes:14

Introduction to Computers, Introduction to Programming, Algorithms, Flowcharts, Software


Development Method. Introduction to C Language, C Language Elements, Variables, Data Types,
Operators and Expressions, Constants, Declarations, Operators, Type Conversions, Precedence and
Order of Evaluation.

UNIT - II CONTROL STATEMENTS, LOOPS AND ARRAYS Classes:13

Statements: Selection Statements, Iteration Statements, Jump statements: Break, Continue, goto,
Arrays: Accessing Array Elements, Single & Multi Dimensional Arrays.

UNIT - III STRINGS AND POINTERS Classes:13

Strings: Declaring, Initialization of a String, Reading and Writing Strings, String manipulation
functions from the standard Library, String I/O Functions: gets(), puts().

Pointers: Pointer Variables, Pointer Expressions, Pointers And Arrays, Pointers to Strings. Problems
with Pointers.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 2


UNIT - IV FUNCTIONS, STRUCTURES AND UNIONS Classes:14

Functions: Definition, Function Call- Call by Value, Call by Reference, Storage Class Specifiers,
Understanding the scope of Functions with its Types, the Return Statement, Recursion, C’s Dynamic
Allocation Functions.Command Line Arguments.

Structures and Unions: Accessing structure members, Array of structures, Passing Structures to
Functions, Structure Pointers, Structures within Structures, Bit Fields, Enumerations, Typedef.

UNIT –V FILE I/O Classes:14

Streams and File, File System Basics: File pointer, opening a file using fopen(), closing a file, getc(),
putc(), fclose(), feof(), fputs, fgets(), ferror(), fread(), fwrite(), fseek(), Formatted Console I/O:
fprintf, fscanf, the Preprocessor Directives: #define and #include.

Text Books:

1. The Complete Reference C, Fourth Edition, Herbert Schildt, McGraw-Hill Education.


2. The C Programming Language” Second Edition, Brain W. Kernighan, Dennis
M. Ritchie, Prentice Hall, India.
References:

1. Programming with C Second Edition, Byron Gottfried, Schaum’s outline, McGraw-Hill


Education.
2. Computer Fundamentals and C programming, B. L Juneja, A Seth, Cengage Learning India.
3. Programming in C and Data Structures”, Hanly, Koffman, Kamthane, Ananda Rao, Pearson.
4. A BOOK ON C, Kelly pohl, Pearson Education.
5. Computer Fundamentals and C Programming, By Dr. P. Chenna Reddy, Pothi.com
(Self Publishing).
Web References

1. https://www.tutorialspoint.com/cprogramming/
2. www.studytonight.com/c/
3. fresh2refresh.com/c-programming/
4. www.cprogramming.com/tutorial/c/
E-Text Books:

1. bookboon.com/en/c-cpp-csharp-ebooks
2. electronicsforu.com › Resources › Cool Stuff
3. https://en.wikibooks.org/wiki/C_Programming
4. www.e-booksdirectory.com › Computers & Internet

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 3


COMPUTER PROGRAMMING
UNIT-1
INTRODUCTION TO COMPUTERS AND C LANGUAGE

Introduction to Computers:

Definition of Computers:
 The word computer has been derived from the word “Compute” which means to
calculate.
 It is an electronic device which inputs the data, stores the data, processes the data
and gives the result accurately at a very high speed according to the instructions
provided.

Characteristics of computers:
The following are the some of the characteristics of a typical computer.
Speed:
 Computer operates at very high speed.
 Even the speed of slowest personal computer is very high as compared to that of a
human being.
 There are several different types of computers they have different speeds ranging
from high to very very high.
 The speed of the computer is specified in “Million Instructions Per Second” {MIPS}
Accuracy:
 It performs with a degree of high consistent accuracy.
 The degree of accuracy of a particular computer depends upon its design.
 Each and every calculation is performed with same accuracy.
 Errors may occur in computer due to either undetected error in the design (or) it they
aren‟t programmed properly.
Storage and Retrieval of data:
 A computer can store huge amount of data in its memory.
 We can store any type of data such as letters, pictures, sounds etc in a computer.
 We can also retrieve the stored data from the computer as per the user requirement.
 The information can be stored in computers memory for several years.
Resource Sharing:-

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 4


 With the tremendous growth in computer technologies, computer today have the
capability to connect to each other. This has made the sharing of resources like
printers, scanners……….
 Apart from device sharing, data and information can also be shared among groups
of computers, thus creating a large information and knowledge base.

Block Diagram of a Computer (or) Logical organization of a computer:

CPU

ALU
ALU

Input MU Output

CU

Input Unit:
Computers need to receive data and instructions in order to solve any problem.
 The input unit consists of one or more input devices like keyboard, mouse,
joystick etc.
 Regardless of the type of the input device used in a computer system, all input
devices perform the following functions.
o Accept the data
o Convert data to computer understandable form.
o Supply converted data for further processing.
CPU:
 CPU stands for “Central Processing Unit.”
 CPU is like a computer Brain. It performs the following operations.
o It performs all calculations.
o It takes all decisions.
o It controls all units of computer.
 Control unit, Memory unit and Arithmetic logic unit of the computers are together
known as central processing unit.
Memory Unit:
 Memory Unit of the computer holds data and instructions that we enter through
the input unit.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 5


 It is also used to preserve intermediate and final results before they are sent to
the output unit.
 It is used to preserve the data for later usage.
 The various storage devices used for storage can be classified in to a categories
namely
o Primary Memory
o Secondary Memory
 Primary memory stores and provides information very fast but it loses the
contents when we switch off the computer. Ex:- RAM
 Secondary memory stores the data permanently. The program that we want to
run on the computer is first transferred to the primary memory from secondary.
Ex: HDD
Control Unit:
 The control unit controls all other units in the computer.
 The control unit instructs the input unit where to store data after receiving it from
the user.
 It also controls the flow of data and instructions from the memory unit to “ALU”.
 It controls the flow of results from ALU to output unit.
Arithmetic Logic Unit:
 All calculations are performed in ALU.
 It does comparisons and takes decisions.
 It can perform Basic Arithmetic operations like addition, subtraction as well as
logical operations like less than greater than.
 After performing calculations the result is stored in memory unit.
Output Unit:
 The output unit of a computer provides information and results of an operation to
the outside world.
 The output unit also converts Binary data to a form that uses can understand.
 The commonly used to output devices are Monitors, Printers, and Plotters.

INTRODUCTION TO PROGRAMMING:

 As programmer prefer to write their programs in one of the High Level Languages
{HLL} because it is much easier to understand the code easily.
 However, the computer doesn‟t understand any language other than “Binary
Language.” It becomes necessary to process a HLL program me so as to make it
understandable to the computer.
 The system program which performs the above job is called language processors.
 Assembler, Interpreter and Compliers are some of the language processors.
Assembler:
 The code written by the user in order to perform a task is called source code.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 6


 The source code can‟t be understood by computer. Computer can understand only
machine language code i.e., 0‟s & 1‟s. The code understood by the computer is
called object code.
 The software which converts source code to object code is called “Translator”.
 In order to convert an Assembly level language code in to object code we use a
translator called “Assembler”.
 Assembler: It is a Translator which converts Assembly level language code to
Machine language code.
Compiler and Interpreter
 The code in a source file stored on the disk must be translated into machine
language. This is the job of the translator.
 Compiler and interpreters are translators. Compiler compiles the entire program
at once where as the interpreter interprets the program line by line.
 The translator reads the program and writes the resulting object module to a file
that can then be combined with other precompiled units to form the final program.

ALGORITHM:

Algorithm is a very popular technique used to obtain solution for a given problem.
Definition: - An algorithm is defined as a finite set of steps for solving a problem.
Procedure for writing an algorithm:-
An Algorithm is a well organized and textual computational module
that receives one or more input values and provides one or more output values.
 These well defined steps are arranged in a sequence that processes given input
into output.
 The steps of the algorithm are written using English like statements which are
easy to understand.
 This will enable the reader to translate each step into a program.
 Every step is known as instruction.
 If the procedure is lengthy then sub divided the procedure into small parts as it
make easy to solve the problem.
Analyzing an Algorithm:-
When one writes an algorithm, it is essential to know how to analyses the
algorithm.
 Analyzing the algorithm refers to calculating the resources such as usage of
computer memory, processing time and so on …..
 Time is most important resource because the program developed should be
faster in processing.
 The analysis can also be made by reading the algorithm for logical accuracy,
tracing the algorithm and checking with the data.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 7


Categories of Algorithm
The steps in an algorithm can be divided into three categories, namely
 Sequence
 Selection and
 Iteration

Sequence
 The steps described in an algorithm are performed successively one by one without
skipping any step.
 The sequence of steps defined in an algorithm should be simple and easy to
understand.
Example:
// adding two timings
Step 1: start
Step 2: read h1, m1, h2, m2
Step 3: m=m1+m2
Step 4: h= h1 + h2 + m/60
Step 5: m=m mod 60
Step 6: write him
Step 7: stop

Selection
 We understand that the algorithms written in sequence fashion are not reliable.
There must be a procedure to handle operation failure occurring during execution.
 The selection of statements can be shown as follows
if(condition)
Statement-1;
else
Statement-2;
 The above syntax specifies that if the condition is true , statement-1 will be
executed otherwise statement-2 will be executed.

 In case the operation is unsuccessful. Then sequence of algorithm should be


changed/ corrected in such a way that the system will re-execute until the operation
is successful.
Example:
// Person eligibility for vote
Step 1 : start
Step 2 : read age

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 8


Step 3 : if age > = 18 then step_4 else step_5
Step 4 : write “person is eligible for vote”
Step 5 : write “ person is not eligible for vote”
Step 6 : stop

Iteration
 In a program, sometimes it is very necessary to perform the same action for a
number of times.
 If the same statement is written repetitively, it will increase the program code.
 To avoid this problem, iteration mechanism is applied.
 The statement written in an iteration block is executed for a given number of times
based on certain condition.
Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat step 4 until n>0
Step 4 : (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop
FLOWCHART
Introduction:-
A flowchart is an alternative technique for solving a problem.
Instead of descriptive steps, we use pictorial representation for every step.
Definition:-
Flowchart is a diagrammatic or pictorial representation of various steps
involved in the Algorithm.

 A complete flowchart enables us to organize the problem into a plan of actions


i.e. it specifies what comes first, second, third . . . .
 Flowchart also represents the flow of data.
 It is an easy way to solve the complex problems because it makes the reader to
flow the process quickly from the flowchart incited of going through text.
 A flowchart is a set of symbols that indicates various operations in a program.
 For every process there is a corresponding symbol in the flowchart.
 Once the algorithm is written, its pictorial representation can be done using
flowchart symbol.

Some of the commonly used flowchart symbols are listed below.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 9


Symbol Description

Start/Stop

Decision

Connector

Process

Input/output

Loop

Data Flow Direction


Lines

Predefined Process

SOFTWARE DEVELOPMENT LIFE CYCLE


Introduction:-
A Disciplined approach is essential to create programs that are easy to
read, understand and maintains.
 Programming is a problem-solving activity.
 Programmers use a methodology to solve the program and that methodology
is referred to as software development method.
Steps in Software Development Life Cycle:-
The software development method includes the following steps.
i) Problem specification( requirement)
ii) Analysis
iii) Design
iv) Implementation(Coding)

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 10


v) Testing
vi) Maintenance

System Requirements
Problem should be explained clearly with required input/output
and objectives of the problem. It makes easy to understand the problem to be solved.
Thus system requirement is always the first step towards development of a program.
Analysis
Analysis is the first technical steps in the program development process. To
find a better solution for a problem analyst must understand the problem statement
objectives and required tools for it.
Design
Designing phase will begin after the software analysis process. It is a multi
step process. Mainly it focuses on data, architecture, user interfaces, and program
components.
The importance of the designing is to get the quality of the product.

Developing code
New system will be implemented based on the designing part. It
includes coding and building of ne software using a programming language and
software tools.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 11


clear and detailed designing greatly helps in generate effective code with less
implementing time.
Debugging
There is a possibility of occurrence of errors in programs. These errors
must be removed to ensure proper working of programs .hence error check is made.
This process is known as “Debugging”.
Types of errors:
1. Syntactic errors -usage of wrong syntax.
2. Runtime errors -execution time of the program.
3. Logical errors -incorrect usage of instructions in the program
Testing
Testing is performed to check whether the program is producing correct result
or not for different values of input.
Testing will be performed in two technical ways:
1. Black box testing.
2. White box testing.
Documentation:
Documentation is the process of collecting, organizing and maintaining, in
written the complete information of the program for future references.
Maintenance:
Maintenance is the process of upgrading the program according to the
changing requirements.

INTRODUCTION TO C LANGUAGE

 „C‟ is a Structured Programming Language


 It is considered as a middle level language as it supports some of the features of
low level language also.
 „C‟ is a case sensitive language i.e., upper case letters and lower case letters are
distinct.
 It is well suitable for developing application software as well as system software.
 It supports the concept of “Modular Programming”, which means that a larger task
is divided in to a number of sub tasks each subtask is referred to as a “module” or a
“function”.
 Due to this modular programming, it is easy to identify and rectifies the errors.
Execution speed also increases.
 „C‟ language is highly portable. i.e., a „C‟ program written for one computer can be
easily run in another computer under certain conditions.
 The power of „C‟ is increased due to the support of a number of library (or) inbuilt
functions.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 12


 C‟ is a general purpose structured programming language.
 „C‟ was originally developed in „1972‟ by “Dennis Ritchie” at “AT&T” Bell
Laboratories.
 It is an outgrowth of two earlier languages called “BCPL” {Basic Common
Programming Language} & “B” which were also developed at Bell laboratories.
Structure of „C‟ Program:
 Every programming language has a certain structure which has to be followed while
writing programs in that language.
 „C‟ language also contains a structure to write programs.
 As this language supports modular programming, it contains one or more functions.
 One of those functions that should be mentioned in every c-program is “main
function”.
 „C‟ language contains one or more sections in a program. The structure of „C‟
program is given below.

Documentation Section

Preprocessor Directives

Global Declarations
Other functions as required

int main ()

{
Local Declarations;

Statements;

Documentation Section:
 In general documentation section consists of information about the program. It
contains details like author of the program, task of the program, date compiled, date
written ,etc .
 All the above information is placed as comments.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 13


 This section is “optional”.

Preprocessor Directives:
 This section provides the instructions to the compiler about library functions by
linking to various header files.
 Eg: #include <stdio.h>
#include <conio.h>
#define PI 3.14

Global Declaration:
 When a variable is declared inside a function the variable scope is within that
function only. These variables are called local variables.
 If we want to make a variable available throughout the program irrespective of the
function then the variable is declared as global.
 Any variable declared above the main function is considered as “global variables”.

main ():
 Every „C‟ program execution starts at main().
 Every program must include main().
 The entire „c‟ program instructions are divided in to two parts namely
o Declarations
o Executable statements

Local Declarations:
Any variable which is used in the program should be declared first. „C‟ program
doesn‟t allow to declare the variables at the middle of the program.

Statements:
It contains various executable statements that perform a specific task.
 The above two parts must be placed in a pair of braces ({ and }).
 Note that each and every statement in a „c‟ program must end with semicolon
except the pre-processor statements.

C LANGUAGE ELEMENTS

 The „C‟ elements contains Alphabets, Digits and Special characters.


Alphabets: A, B . . . . . . . . . . . Z {upper case, ASCII – 65-90}.
a, b . . . . . . . . . . . . z {lower case ASCII 97 – 122}.
Digits: 0 . . . . . . . . 9 {ASCII - 48-57}.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 14


Special Characters:
+, <, >, {}, ., &, *, :, [,], @, ~{tilde}, %, \{Back slash}, /, ,, ?, =, ;, |, #, “, !, ^, -.
 „C‟ uses certain combinations of above characters to represent special characters
like backspace, new line, horizontal tab, vertical tab and form feed.
 White space is also allowed by the „C‟. It is also considered as a character.
Identifiers :
 These are the names that are given to the various program elements such as
variables, functions, arrays, structures, etc.
 These are user defined names.
Limitations:
 It allows alphabets, digits and the special character underscore (_).
 Both upper case & lower case letters are permitted.
 Upper case & lower case aren‟t interchangeable
 An identifier name should not start with a digit.
 It can start with either an alphabet (or) underscore. [An identifier starting with
underscore is rarely done in practice].
 Keywords (or) reserved words should not used as identifiers.
Eg: area, Max_Price ,_total -Valid Identifiers
Min area, „a‟, “college” –not valid Identifiers.
 Identifiers can be arbitrarily long but some c-compilers recognize only the first eight
characters.
Key words:
 These are also called “reserved words”.
 They have standard and pre-defined meaning in „c‟. These keywords can be used
only for their intended purpose. They can‟t used as programmer defined identifiers.
 In general the keywords are represented by using lower case letters.
 „C‟ language supports nearly 37 key words.

auto double int Struct

Break else long Switch

Case enum register typedef

Char extern return Union

Const float short unsigned

Continue for signed Void

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 15


Default go to size of volatile

Do if static While

Variable:
 A variable is an identifier that is used to represent a data item.
 The data may be numerical quantity (or) a character constant.
 The data item must be assigned a value to the variable at some point in the
program. Then data item can be accessed by referring to the variable name
 In other words, a variable is an identifier which changes its value during the
execution of the program.
Rules for Constructing a Variable:
 A variable name is a combination of alphabets, digits and underscore.
 Other than the underscore no special characters is allowed.
 The first character in the variable name must be an alphabet.
 The variable name should not be of keyword.

Declaration of a Variable:
 Any variable which is used in the program should be declared first. A declaration of
a variable specifies two things:
o It tells the compiler about the name of the variable.
o It specifies about the type of data that a variable can hold.
Syntax: data type variable 1, variable 2 , . . . . . . . . variable;
Eg: int a, b, c;
 The above declaration results in declaring the variables a, b, c as integer data type.

DATA TYPES
Data Types

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 16


Primary data type User defined data type Derived data type Empty data type

Integer Type def Arrays Void

Functions
Charater
Enum Structures
Float
Pointers
Double
Unions

Primary
Data Type Size (in bytes) Range
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed 2 -32768 to 32767
short 2 -32768 to 32767
unsigned short 2 0 to 65535
signed short 2 -32768 to 32767
long 4 -2147483648 to 2147483647
unsigned long 4 0 to 4294967295
signed long 4 -2147483648 to 2147483647
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
float 4 3.4E-38 to 3.4E +38
double 8 1.7E -308 to 1.7E +308
long double 10 34E -4932 to 34E +4932

Note:
 Float is a single precision value. {After decimal 7 digits has been considered}
 Double is a double precision value. {After decimal 14 digits has been considered}
 In-Built data Types are supported by „C‟ compiler by default.

1. Character (Denoted as "char" in C programming language)

Description: A character denotes any alphabet, digit or special symbol used to


represent in formation and it is used to store a single character.
V. SambaSiva., Assistant Professor, Department of CSE, CREC. 17
Storage space: 1 byte
Format: %c
Range of Values: ASCII Character Set.

2. Integer (Denoted as "int" in C programming language)

Description: Integer type is used to store positive and negative integer.


Storage space: 2 bytes.
Format: %d
Range of values: -327687 to +32767.
The storage space may vary depending on the operating system

3. Float point (Denoted as "float" in C programming language)

Description: It is used to store real number, with single precision floating point number
(precision of 6 digits after decimal points.)
Storage space: 4 bytes.
Format: %f
Range of values: -3.4*1038 to +3.4*1038.

4. Double (Denoted as "double" in C programming language)

Description: It stores real numbers with double precision. The use of double doesn't
guarantee to double the number of significant digits in our result, but it improves the
accuracy of the arithmetic and reduces the accumulation of rounding errors.
Storage Space: 8 bytes.
Format: %ld
Range of values: -1.7*10308 to +1.7*10308.

void:
 It is a special data type used for
o To specify that a function doesn‟t returns any value.
o To specify a function takes no arguments.
o To create generic pointers.
Eg: 1. void print (void)
3. void *ptr

Constants:
 These are fixed values that will not change during the execution of program.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 18


 There are 4 basic types of constants in „C‟. They are

Constants

Numeric character

Integer Float string single


Constants character constants

Octal Decimal Hexadecimal

Integer Constant:
An integer constant is an integer valued numbers.

Rules for Constructing Integer Constant:


 It shouldn‟t have a decimal point.
 An integer constant must have at least one digit.
 Commas, Blank spaces, special characters can‟t be included with in the constants.
 The constant can be preceded by a minus sign if desired.
 The range of integer constants is -32,768 to 32,767

Types of Integer Constants:


 Integer Constants can be written in 3 different number systems, namely
o Decimal {Base = 10}
o Octal {Base = 8}
o Hexa Decimal {Base = 16}
Decimal Numbers:
 A Decimal integer constant can consists of any combinations of digits taken from
the set 0-9.
 If the constant contains 2 (or) more digits, the first digit must be something other
than zero.
Eg: 0,1,723,32156.
Octal Constants:

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 19


 An Octal integer constant can consist of any combination of digits taken from the
set 0-7.
 The first digit must be zero in order to identify the constant as an octal number.
Eg: 0,01,0723.
Hexa Decimal Numbers:
 A Hexa Decimal integer constant must begin with either 0x, (or) 0x.
 It can be consists of the digits taken from the set 0-9, and a-f {either upper case (or)
lower case}.
 The letters a-f, represent the quantities 10-15 respectively.
Eg: 0x, 0x, 0x7.
Unsigned & Long Integer Constants:
 An Unsigned integer constant can be identified by appending the letter „u‟. {either
upper or lower case}
 Long interval constants can be identified by appending the letter „L‟ {either upper or
lower case} to the end of the constant.
 An unsigned long interval constant can be specified by appending the letters UL
{either upper case (or) lower case} to the end of the constants.
 Note that „u‟ must precede the „L‟.
Eg: 234U – Unsigned Decimal Constant
0427UL – Unsigned Long Octal Constant
0X72FL – Long Hexa Decimal Constant
Floating Point Constants:
 A floating point constant is a decimal number that contains a decimal point.
Rules:
 Commas and Blank spaces can‟t be included.
 It can contain of either decimal point (or) Exponent.
 The constant can be preceded by minus sign it desired.
Eg: 0, 1., 12.3.
Scientific Notation:
 When we want to represent very large values (or) very small values, instead of
representing the value of sequence of digits we can represent a floating point
constant value in a scientific notation as follows.
Mantissa E (or) e exponent.
Eg: 1.2E + 3 => 1.2 * (10^3)
 Note that if no sign is represented after „E‟ it will be treated as positive.
 Floating point constants are identified by appending the letter F {either upper case
(or) lower case} to the end of the constants.
Eg: 3E5F = 300000F.

Character Constants:

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 20


 A character constant is a single character enclosed in single quotation marks. The
Max length of character constant is “one”. The single character can be either
alphabet (or) Digit (or) a special symbol.
 Eg: „a‟, „1‟, „?‟.
Note: Most computers make use of the “ASCII” {American Standard Code for
Information Interchange”}, character set, in which each individual character is
numerically encoded.
 ASCII code is a 7 bit code. ASCII values ranges from 0-127.

Operators and Expressions


Operators
 An operator is a symbol that informs to the computer to perform a particular task.
 The data items that operators act upon are called “operands”.
 If the operator requires only one operant then it is called “unary operator”. If it
requires two then it is called “Binary Operator”.
 „C‟ language supports a different set of operators which are listed below.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Assignment Operators
o Increment / Decrement Operators
o Bit wise Operators
o Unary Operators
o Conditional Operators
o Special Operators

Arithmetic Operators:
 Arithmetic operators are basic and common operations performed using and
computer language.
 There are five arithmetic Operators available in „C‟. They are

Operator Purpose Examples

+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modular Division a%b

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 21


Relational Operators:
 Relational Operators are used to perform comparison between two values.
 These operators‟ returns true (1) if the comparison condition is true otherwise false
(0).
 The operators used for comparison in „C‟ are listed below.
perator Description or Action
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

Eg: 35<5 false (0)


10<=10 true (1)
45>5 true (1)
11>=5 true (1)
35= = 10 false (0)
35! =10 true (1)
(10+5)= = (5*3) true (1)

 Write a program to use various relational operators and display their return
values?

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\condition\t:Return values\n");
printf("\n10!=10\t\t:%5d",10!=10);
printf("\n10==10\t\t:%5d",10==10);
printf("\n10>=10\t\t:%5d",10>=10);
printf("\n10<=100\t\t:%5d",10<=100);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 22


printf("\n10!=9\t\t:%5d",10!=9);
getch();
}

Logical Operator:
 When we want to take a decision basing on 2 (or) more conditions then we will use
logical operators.
 There are three logical operators available in „C‟

Operator purpose
&& Logical AND
|| Logical OR
! Logical NOT

Logical and: (&&)


 Logical And results in true if both the conditions are true otherwise the result is
false.

Truth Table:
A B A&B
T T T
T F F
F T F
F F F
Logical Or: (||)
 Logical Or results in true if either of the conditions is true.
 The result is false if all the conditions are false.

Truth Table:
A B A||B
T T T
T F T
F T T
F F F
Logical not: (!)

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 23


 If the condition is true then the result is false and if the condition is false the result is
true.

Truth Table:
A !A
T F
F T

Examples:
8>6&&6<10 true (1)
9>4||7<3 true (1)
8! =8 false (0)
10! =9 true (1)

 Write an example program using logical operators?

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("condition : Return values\n");
printf("\n9>5&&8<10:%5d",9>5&&8<10);
printf("\n10<9&&3>7:%5d",10<9&&3>7);
printf("\n9>6||6<2 :%5d",9>5||8<3);
printf("\n8!=8 :%5d",8!=8);
printf("\n9!=10 :%5d",9!=10);
getch();

Assignment Operators:
 This operator is used to assign a constant value (or) the result of an expression to a
variable.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 24


 In this operation Right hand side expression is evaluated first and then the result is
assigned to left hand side variable.
Operator Meaning
= Assign Right Hand value to LHS value
+= Value of LHS add to value of RHS and assign it back to the variable
in LHS Eg: a+=2 => a = a+2
-= Value of RHS variable will be subtracted from the value of LHS and
assign it back to the variable in LHS.
Eg: a-=2 => a = a-2
*= Value of LHS variable will be multiplied to the value of RHS and
Assign it back to the variable in LHS.
Eg: a*=2 => a=a*2
/= Value of LHS variable will be divided by the value of RHS and
Assign it back to the variable in LHS.
Eg: a/=2 => a=a/2
%= The Remainder will be stored back to the LHS after integer, division
Is carried out between the LHS variable and RHS variable.
Eg: a%=2 => a=a%2
>>= Right shift and assign the value to the LHS.
Eg: a>> =2 => a=a>>2.
<<= Left shift and assign the value to the LHS.
Eg: a<<=2 => a=a<<2.
&= Bit wise AND operation and assign the value to the LHS.
Eg: a&=b => a=a&b.
|= Bit wise OR operation and assign the value to LHS.
Eg: a|=b => a=a | b
~= Bit wise complement and assign the value to LHS.

Increment/Decrement Operator {++/- -}


 Increment operator increases the value by „1‟ where as decrement operator
decreases the value by „1‟.
 This operator can be used in two forms namely Prefix and Postfix.
 In case of Prefix notation the operator precedes the operant {++a}.
 In case of Postfix notation the operator is followed by operand {a++}.
 In Prefix notation increment operation will be given the highest priority i.e., first the
value is incremented by „1‟ and other operations are performed later.
 In Postfix notation, increment operator will be given the least priority i.e., the
increment operation is performed at last after all operations are performed.
 The above points are applicable to the decrement operator also.
Eg: 1) a=5 2) a=5

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 25


c= ++a c=a++
c=6,a=6 c=5, a=6.

Explanation:
 In above expression-1, c= ++a two operations namely assignment and increment
are involved. Since the operator ++ is used as prefix, first we perform incrimination
i.e., a=a+1 and then this value is assigned to „C‟.
 In the expression-2, c= a++ two operations namely assignment and increment are
involved. Since the operator ++ is used as postfix, first we assign the value of „a‟ to
„c‟. i.e., c=a => a=5 and then the value of „a‟ is incremented i.e., a=a+1=6

Bitwise Operators:
 Bitwise operators are one of the salient features of „C‟ language.
 These are specially designed to manipulate the data at Bit level.
 The Bitwise operators are not applicable for float (or) Double data type.
 The following are the some of the Bit wise operators available in „C‟ language.
Operator Meaning

& Bitwise Logical AND


| Bitwise Logical OR
^ Bitwise Logical XOR
<< Left Shift
>> Right Shift
~ 1’s Compliment

Bitwise AND: (&)


 To generate a „1‟ bit in the result, Bitwise AND need a „1‟ in both the numbers.
 Bitwise AND operator is called “MASK” operator.
Eg: a=28, b=17
a =11100
b =10001
a&b =10000
a&b =16
Bitwise OR: (|)
 The Bitwise OR result is „1‟ if at least one of the numbers is „1‟.
Eg: a=28,b=17
a= 11100
b= 10001
a|b =11101 => a|b = 29
V. SambaSiva., Assistant Professor, Department of CSE, CREC. 26
Bitwise Exclusive OR: (^)
 It is similar to task Bitwise OR and the result „1‟ is produced if 1 is present in either
but not both.
Eg: a=28, b=17
a= 11100
b= 10001
a^b=01101 => a^b =13
Bitwise 1‟s complement: (~)
 The complement operator switches all the Bits in a binary pattern i.e., all 0‟s
becomes 1‟s and all 1‟s becomes 0‟s.
Eg: i) Bitwise complement of 12 is -13
ii) Bitwise complement of 0 is -1.
Shift Operations:
 The shift operations take binary patterns and shift the bits to the left (or) right.
 Keeping the same number of bits by dropping the shifted bits at the end and filling
in with 0‟s at other end.
 C-language provides 2 types of shift operators namely left and right shift.
Left Shift: {<<}
 This operator is used for left shifting .
Eg: a=00011100
a<<1 = 00111000
a<<2 = 01110000 => a<<2 =112
Right Shift: {>>}
 This operator used for right shifting.
Eg: a = 00011100
a>>1 = 00001110
a>>2 = 00000111 => a>>2 = 7
Conditional Operator: (? :)
 „C‟ includes a very special type of operator called conditional operator.
 It is also called “ternary” operator since it requires three expressions. It acts like a
short hand version of if-else construction.
 Syntax: exp1? exp2: exp3
 In exp1 is true then exp2 is evaluated otherwise exp3 will be evaluated.
Eg: a>b? a=b

Special Operators:
 In addition to the above operators „C‟ language supports some special operators
like comma operator, parenthesis for grouping expression, membership operators.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 27


C supports some special operators of interest such as comma operator, sizeof
operator.

Comma Operator:
This operator is used to link the related expression together the
expression is separated by the, operator.

e.g.: a=(x=6,y=7,x+y);
This expression first assigns 6 to x and 7 to y then assigns (6+7) to a.

Size of Operator:
The size of operator returns a number of bytes the operand occupies in memory.
The operand may be a variable, a constant or a data type qualifier. It is a compile
time operator.
Syntax: sizeof(operand)
e.g.: y=sizeof(int); here value of y will be 2bytes
z=sizeof(a);her value of z depends on data type of a

Member operator:
These are used to access member of structures and unions.
e.g.:
var member 1;
When var is a structure variable.

var member 2;
When var is pointer to structure variable.

Precedence and Associativity


 Every operator has a precedence value. An expression containing more than one
operator is known as a complex expression.
 Complex expressions are executed according to precedence of operators.
 Associativity specifies the order in which the operators are evaluated with the same
precedence in a complex expression.
 Associativity is of two ways i.e., left-to-right and right-to-left.
 Left-to-right associativity evaluates an expression stating from left and moving
towards right.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 28


 Right-to-left associativity proceeds from right to left.
The precedence and associativity of various operators in C are as shown in the
following table

Operators Operation Associativity Precedence


() Function call
[] Array expression or square
-> bracket
Left to right 1st
. Structure Operator
Structure Operator
+ Unary plus
_ Unary minus
++ Increment
-- Decrement
! Not operator Right to left 2nd
~ One‟s complement
* Pointer operator
& Address operator
Sizeof Size of an object
Type Type cast
* Multiplication
Left to right
/ Division 3rd
% Modular division
+ Addition Left to right 4th
- Subtraction
<< Left shift Left to right 5th
>> Right shift
< Less than
<= Less than or equal to 6th
Left to Right
> Greater than
>= Greater than or equal to
== Equality 7th
Left to right
!= Inequality
& Bitwise AND Left to right 8th
^ Bitwise XOR Left to right 9th
| Bitwise OR Left to right 10th
&& Logical AND Left to right 11th
|| Logical OR Left to right 12th
?: Conditional Operator Right to Left 13th

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 29


=, *=, -=, &=, Assignment Operators
+= Right to Left
14th
^=, |=, <<=,
>>=
, Comma Operator Left to right 15th

Type Conversion:
 In some situations, some variables are declared as integers and while performing
an operation on these variables we require the result as floating point type. In such
situations we use type conversion.
 The type conversion is used to convert the set of declared data types to some other
required types.
 Conversion can be carried out in 2 ways
o Converting by using assignment (Implicit casting).
o Using cast operator (Explicit casting).
Converting by Assignment:
 The usual way of converting a value from one data type to another is by using
the assignment operator.
int a;
float b;
a=b;
 In this method, if a larger data type value is assigned to smaller data type then the
value will be truncated {cut off}. This method is called “Narrowing”.
Cast Operator:
 The cast operator is a technique to forcefully to convert one data type to another.
 The operator used to force this conversion is known as “Cast Operator” and the
process is known as type casting.

Syntax: x= (cast) expression


(or)
X= cast (expression)
Eg: int a, b;
float f;
f= (float) a/b;
(or)
f= float (a)/b;

Expressions:-

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 30


An expression is a combination of operators and operands which reduces to a
single value. An operator indicates an operation to be performed on data that yields a
value. An operand is a data item on which an operation is performed.
A simple expression contains only one operator.foe example 3+5 is a simple
expression which yields a value 8, -a is also a single expression . A complex
expression contains more than one operator. An example of complex expression is
6+2*7.
An expression can be divided into six categories based on the number of
operators, positions of the operands and operators, and the precedence of operator.
Expression

Primary postfix prefix unary binary ternary

Primary Expressions
In C, the operand in the primary expression can be a Name, a Constant, or an
Parenthesized Expression. Name is any identifier for a variable. A constant is the one
whose value cannot be changed during program execution. Any value enclosed within
parenthesis must be reduced to single value. A complex Expression can be converted
into primary expression by enclosing it with parenthesis. The following is an example
(3*5+8) ; (c=a=5*c);
Postfix Expressions
The postfix expression consists of one operand and one operator.
Example: A Function Call, The function name is operand and parenthesis is the
operator.
The other examples are post increment and post decrement. In post increment
the variable is increased by 1, a++ results in the variable increment by 1.
Similarly in post decrement, the variable is decreased by 1, a--results in the
variable decreased by 1.
Prefix Expressions
Prefix Expressions consists of one operand and one operator, the operand
comes after the operator.
Examples of prefix expressions are prefix increment and prefix decrement i.e.,
++a,--a.
The only difference between postfix and prefix operators is, in the prefix operator, the
effect take place before the expression that contains operators is evaluated. It is other
way in case of postfix expressions
Unary Expressions

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 31


A unary expression is like a prefix expression consists of one operand and one
operator and the operand comes after the operator.
Example: ++a; -b; -c; +d;
Binary Expressions
Binary Expressions are the combinations of two operands and an operator. Any
two variables added, subtracted, multiplied or divided is a binary expression
Example: a+b; c*d;
Ternary Expressions
Ternary Expressions is an expression which consists of a ternary operator pair
“?:”
Example: exp1:exp2:exp3;
In the example, if exp1 is true exp2 is executed else exp3 is executed.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 32


UNIT-2
Control Structures
Control Constructs specify the order in which the various instructions in a
program are to be executed by the Computer.

There are 4 types of control statement in C. They are:


1. Selection Control Statements.
2. Iteration Control Statements
3. Case control statements.
4. Jump Control Statements

1. Selection Control Statements.


Selection Control Statements also called as Decision control statements and
Conditional Statements allow the computer to take decision. And force to work under
given condition:
A Selection Control Statement gives the control to the computer for taking the decisions.

Four selection control instruction which are implemented in C are following:


a) if statement.
b) if-else statement.
c) Nested if-else statement.
d) if-else Ladder.

Simple if statement.

Syntax:
if (condition is true)
{
Statement;
}

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 33


An example programs for if statement:

#include<stdio.h>
#include<conio.h>
void main( )
{
int m,n;
clrscr( );
printf(“Enter any two number:\n”);
scanf(“%d %d”,&m,&n);
if(m-n==0)
printf(“ the entered numbers are equal \n”);
getch( );
}
Output:
Enter any two number 50 50
You have entered numbers are equal

if – else statements.
The if-else statement is an extension of the if statement. The if-else
statement takes care of true as well as false conditions. It has two blocks.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 34


 One block is for if and it is executed when the condition is true.
 The other block is of else and it is executed when the condition is false.
 The else statement cannot be used without if.
 No multiple else statements are allowed without one if.
Syntax:
if(expression is true)
{
Statement-A;
Statement-B
}
else
{
Statement-C;
}

1.An example programs for if-else statement:

#include<stdio.h>
#include<conio.h>
void main( )
{
int age;
clrscr( );
printf(“Enter candidate age :\n”);
scanf(“%d”,&age);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 35


if(age>17)
printf(“Eligible for voting \n“);
else
printf(“Not Eligible for voting”\n);
getch();
}
Output:
Enter age: 20
Eligible for voting

Enter age: 16
Not Eligible for voting
2. Write a program to determine whether a given value is positive or negative?

#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf("Enter a number");
scanf("%d",&num);
if(num>0)
{
printf("\n%d is a positive number",num);
}
else
{
printf("%d is a negative number",num);
}
getch();

Output:
Enter a number -9
-9 is a negative number

Enter a number 67
67 is a negative number

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 36


Nested if-else statements:
The numbers of Logical conditions are checked for executing
various statements by using nested if-else statements.

Syntax:
if(condition)
{
if(condition)
{
Statement-A;
}
else
{
Statement-B;
}
}
else
{
Statement-C;
}
Statement-x;

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 37


Write a program to find largest number out of three numbers. Read the numbers
through the keyboard?

#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,z;
clrscr();
printf("\nEnter the values of x,y,z");
scanf("%d %d %d",&x,&y,&z);
printf("\n Largest out of three numbers is:");
if(x>y)
{
if(x>z)
{
printf("x=%d\n",x);
}
else
{

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 38


printf("z=%d\n",z);
}
}
else
{
if(z>y)
{
printf("z=%d\n",z);
}
else
{
printf("y=%d\n",y);
}
}
getch();
}
Output:
Enter three numbers x, y, z: 56 89 78
Largest out of three numbers is: y=89
The else-if Ladder
There is another way of putting if‟s together when multipath decisions
are involved .A multipath decision is a chain of if‟s in which the statement associated
with each else is an if.

Syntax:
if(condition-1)
Statement-1;
else if(condition-2)
Statement-2;
else if(condition-3)
Statement-3;
else if(condition-n)
Statement-n;
else
Default statement;
Statement-x;

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 39


Write a program to find the average of six subjects and display the results as
follows.

AVERAGE RESULT

< 40 FAIL
>=40 & <50 THIRD CLASS
>=50 & <60 SECOND CLASS
>=60 & <75 FIRST CLASS
>=75 & <100 DISTINCTION

#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,tel,eng,math,hin,pys,chem;
float avg;
clrscr();
printf("\n Enter marks\nTelugu:\nEnglish:\nMaths:\nHindi:\nPhysics:\nChemistry:\n\n");
scanf("%d%d%d%d%d%d",&tel,&eng,&math,&hin,&pys,&chem);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 40


sum=tel+eng+math+hin+pys+chem;
avg=sum/6;
printf("Total :%d\nAverage:%.2f",sum,avg);
if(tel<40||eng<40||math<40||hin<40||pys<40||chem<40)
{
printf("\n Result:fail");
}
else if(avg>=40&&avg<50)
{
printf("\n Result:Third class");
}
else if(avg>=50&&avg<60)
{
printf("\nResult:second class");
}
else if(avg>=60&&avg<75)
{
printf("\n Result:first class");
}
else if(avg>=75&&avg<100)
{
printf("\nResult:Distinction");
}
getch();
}
Output:
Enter marks
Telugu: 96
English: 86
Maths: 77
Hindi: 66
Physics: 65
Chemistry: 88

Total: 478
Average: 79.00
Result: Distinction
Case control or switch statement
The Case control statements allow the computer to take
decision as to be which statements are to be executed next.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 41


 It is a multi way decision construct facilitate number of alternatives has multi way
decision statement known as “switch statements”..
Syntax:
switch(expression)
{
case constant_1:
statements;
break;
case constant_2:
statements;
break;
case constant_n:
statements;
break;
default:
statements;
break;
}
Explanation:
First in expression parentheses we give the condition. This condition
checks to match, one by one with case constant. If value match then its statement will
be executed. Otherwise the default statement will appear.Every case statement
terminates with‟:

Write a program to convert years into Minutes, Hours, Days, Months, and
Seconds using switch statements.

#include<stdio.h>

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 42


void main()
{
long int ch,min,hrs,ds,mon,yrs,se;
clrscr();
printf("\n[1]MINUTES");
printf("\n[2]HOURS");
printf("\n[3]DAYS");
printf("\n[4]MONTHS");
printf("\n[5]SECONDS");
printf("\n[0]EXIT");
printf("\n Enter your choice:");
scanf("%ld",&ch);

if(ch>0&&ch<6)
{
printf("Enter years:");
scanf("%ld",&yrs);
}
mon=yrs*12;
ds=mon*30;
ds=ds+yrs*5;
hrs=ds*24;
min=hrs*60;
se=min*60;
switch(ch)
{
case 1:
printf("\n MINUTES:%ld",min);
break;
case 2:
printf("\n Hours:%ld",hrs);
break;
case 3:
printf("\nDays:%ld",ds);
break;
case 4:
printf("\n Months:%ld",mon);
break;
case 5:
printf("\n seconds:%ld",se);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 43


break;
case 0:
printf("\terminated by choice");
exit();
break;
default:
printf("\n invalid choice");
}
getch();
}

Output:
[1]MINUTES
[2]HOURS
[3]DAYS
[4]MONTHS
[5]SECONDS
[0]EXIT
Enter your choice: 2
Enter years: 1
Hours: 8760

ITERAION CONTROL STATEMENTS

Iteration Control Statements also called as Repetition or Loop Control Statements. This
type of statements helps the computer to execute a group of statements repeatedly.
This allows a set of instruction to be performed until a certain condition is reached.
What is a loop?
A loop is defined as a block of statements which are repeatedly executed
for certain number of times.
 There are three types of loops in C:
1. for loop
2. while loop
3. do-while loop

The for loop


There are three parts of for loop:
a) Counter initialization.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 44


b) Check condition.
c) Modification of counter.

Syntax:
for (variable initialize; check condition; modify counter)
{
statements 1;
-----------;
-----------;
statements n;
}

Explanation:
1. The initialization is usually an assignment that is used to set the loop control variable.
2. The condition is a relational expression that determines when the loop will exit.
3. The modify counter defines how loop control variables will change each time the loop
is repeated.
 These three sections are separated by semicolon (;).
 The for loop is executed as long as the condition is true. When, the condition
becomes false the program execution will resume on the statement following the
block.
 Advantage of for loop over other loops:
All three parts of for loop (i.e. counter initialization, check condition,
modification
of counter) are implemented on a single line.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 45


Something more about for loop:

1. for (p=1,n=2;n<17;n++):- we can assign multiple variable together in for loop.


2. for (n=1,m=50;n<=m;n=n+1,m=m-1):-The increment section may also have more
than one part as given.
3. for (i=1,sum=0;i<20&&sum<100;++i):-The test condition may have any compound
relation as given.
4. for (x=(m;n)/2;x>0;x=x/2):-It is also permissible to use expressions in the assignment
statements of initialization and increment section as given.
5. for (; m!=100;):-we can omitted the initialization and increment section to set up time
delay.

An example program to print a message 5 times using for loop:

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

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 46


{
int i=1;
clrscr( );
for(i=1;i<5;i++)
{
printf(“C R E C %d times \n”,i);
}
getch( );
}

Output:
CREC1
CREC2
CREC3
CREC4
CREC5
Explanation of the program:
The o/p will be C R E C 1 time, 2times till 5 times.

WAP to display numbers from 1 to 16.use increment operation in the body of


the loop for more than once.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,c=0;
clrscr();
for(i=0;i<=15;)
{
i++;
printf("%3d",i);
i=i+1;
printf("%3d",i);
c++;
}
printf("\n The body of the loop is executed for %d times",c);
getch();
}

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 47


Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
The body of the loop is executed for 8 times

while loop
It is a primitive type looping control because it repeats the loop a fixed no. of
time. It is also called entry controlled loop statements.

Syntax:
while (test condition)
{
body of loop
}

Explanation:
The test condition is evaluated if the condition is true, the body of loop will be
executed.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 48


Write a program to print the entered number in reverse order?

#include<stdio.h>
void main()
{
int n,d,x=1;
int i;
clrscr();
printf("Enter the number of digits:-");
scanf("%d",&d);
printf("\nEnter the number which is to be reversed:");
scanf("%d",&n);
printf("\n the reversed number is :-");
while(x<=d)
{
i=n%10;
printf("%d",i);
n=n/10;
x++;
}
getch();
}

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 49


Output:
Enter the number of digits: 4
Enter the number which is to be reversed: 7896
The reversed number is: 6987

Enter the number of digits: 4


Enter the number which is to be reversed: 3692
The reversed number is: 2963

The do-while loop

The minor Difference between the working of while and do-while


loop is the place where the condition is tested. The while tests the condition before
executing any of the statements within the while loop .As against this, the do-while loop
tests the condition after having executed the statement within the loop.

syntax:
do
{
body of loop;
}
while (test condition);

Explanation:
It first executes the body of the loop, and then evaluates the test condition.
If the condition is true, the body of loop will executed again and again until the condition
becomes false.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 50


Write a program to find the numbers using do while loop.

#include<stdio.h>
#include<math.h>
void main()
{
int y,x=1;
clrscr();
printf("\nPrint the numbers and cubes");
printf("\n");
do
{
y=pow(x,3);
printf("%5d %27d\n",x,y);
x++;
}
while(x<=10);
getch();
}

Output:

Printf the numbers and their cubes


1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000

Jump Control Statements:


The break Statement
We have already met break in the discussion of the switch
statement. It is used to exit from a loop or a switch, passing control to the first statement
beyond the loop or a switch.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 51


With loops, break can be used to force an early exit from the loop, or to
implement a loop with a test to exit in the middle of the loop body. A break within a loop
should always be protected within an if statement which provides the test to control the
exit condition.
Syntax: Statements;
break;
It can be used with for, while, do-while and switch statement.

The continue Statement


This is similar to break but is encountered less frequently. It
only works within loops where its effect is to force an immediate jump to the loop control
statement.
Syntax: {
statement 1;
continue;
statement 2;
}
 In a while loop, jump to the test statement.
 In a do while loop, jump to the test statement.
 In a for loop, jump to the test, and perform the iteration (looping).
Like a break, continue should be protected by an if statement. You are unlikely to use it
very often.

The goto Statement


C has a goto statement which permits unstructured jumps to be
made. It requires a label in order to identify the place where the branch is to be made. A
label is any valid variable name, and must be followed by a colon (:).
Syntax: goto label;
..................
label:
statement;
The label can be anywhere in the program either before or after the goto
label; statement.Another use of the goto statement is to transfer the control out of a loop
(or nested loops) when certain particular conditions are encountered.

Note: We should try to avoid using goto as far as possible because, it is not good for
readability of the program or to improve the program execution speed.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 52


ARRAYS
So far we have used only the fundamental data types, namely
char, float, int, double and variations of int and double. A variable of these types can
store only one value at any given time. Therefore, they can be used only to handle
limited amounts of data.

To Process such large amounts of data, we need a powerful data type that
would facilitate efficient storing, accessing and manipulation of data items. Array is a
secondary or Derived Data type
At some important areas the concept arrays are used
 To maintain list of employees in a company.
 In pharmacy to maintain list of Drugs‟ and their cost.
 To maintain test scores of a class of students.
Def: An array is a collection of elements of the same data type and it can be referred
with a single name.
OR
Def: An array is fixed –size sequence collection of elements of the same data type.

Array Declaration:
Arrays are defined in the same manner as ordinary variables, except that
each array name must be accompanied by the size specification.
 The general form of array declaration is:
Syntax:
data type array –name [size];

Data type specifies the type of array; size is a positive integer number or symbolic
constant that indicates the maximum number of elements that can be stored in the
array.
E.g. float kick [50];
 This declaration declares an array named height containing 50 elements of type
float.
 Here 50 is an integer enclosed in brackets is the array subscript, and its value
range from zero to one less than the number of memory cells in the array.
 Above statement instructs the compiler to associate 50 memory cells with the
name kick, these cells will be adjacent to each other in memory. The memory
format as fallows

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 53


i.e. Array elements are stored in memory as a sequential form

Initialization of Arrays:
The elements of array are initialized in the same way as the ordinary
variables.
Syntax:
data type array-name [size]={list of elements};

The values in the list are separated by commas.


e.g. int y[10]={205, 207,208,209,210,211};

From the above statements the array -name „y‟ elements are stored in memory as
follows.

Compiler will allocates two bytes of space for each array elements, totally 4 bytes of
space is allocated for array name y.

e.g. 2: char N [10] = {“WELCOME”};

Array Subscripts:

A value or expression enclosed in brackets after the array name, specifying


which array element to access.
e.g.: double R [8];

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 54


The integer enclosed in brackets is the “Array Subscript” and its value must be in the
range from zero to one less than the number of memory cells in the array.

Write a program to find Average of Student marks

#include<stdio.h>
#include<conio.h>
void main()
{
int marks[50],i,sum=0,average,count=0;
clrscr();
printf("Enter the Student marks");

for(i=0;i<5;i++)
{
scanf("%d",&marks[i]);
sum=sum+marks[i];
}
average=sum/5;
for(i=0;i<5;i++)
if(marks[i]>average)
count++;
printf("No of students who scored more than average marks:%d",count);
getch();
}
Output:
Enter the Student marks:
96 56 86 76 36
No of students who scored more than average marks: 3
An array can be of
1. One dimensional array.
2. Two dimensional arrays.
3. Multi dimensional arrays.

One –Dimensional Arrays:


A list of values can be given one variable name using only one
subscript and such a variable is called a single subscripted variable (or) one-
dimensional array.
Declaration of one-dimensional array:

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 55


Syntax:
type array name [size];

e.g: int bull [10];


char b[10];
C language treats character strings that represents the maximum number of
characters. The size in a character string represents the maximum number of character
that the string can hold.

Write a program to print space required for storing them in memory using arrays.

#include<stdio.h>
void main()
{
int i[9];
char j[95];
long l[7];
clrscr( );
printf("%d location for i\n",sizeof(i));
printf("%d location for j\n",sizeof(j));
printf("%d location for l\n", sizeof(l));
getch( );
}
Output:
18 locations for i
95 locations for j
28 locations for l
Write a program to arrange the numbers in increasing and decreasing order using
loops.

#include<stdio.h>
#include<math.h>
void main()
{
int i,j,sum=0,a[10];
clrscr();
printf("Enter ten numbers");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 56


}
printf("Number in increasing order\n");
for(i=0;i<=sum;i++)
{
for(j=0;j<10;j++)
{
if(i==a[j])
printf("%d\n",a[j]);
} }
printf("Numbers in decreasing order");
for(i=sum;i>=0;i--)
{
for(j=0;j<10;j++)
{
if(i==a[j])
printf("%d",a[j]);
} }
getch( );
}
Output:
Enter ten numbers 1 2 3 4 5 6 7 8 9 0
Number in increasing order: 1 2 3 4 5 6 7 8 9 0
Numbers in decreasing order: 0 9 8 7 6 5 4 3 2 1
Two –Dimensional arrays
So far we have discussed the array variables that can store a list of
values. There could be situations where a table of values will have to be stored. In such
situations this concept is useful.

 An array with two dimensions are called “Two dimensional array”


 An array with two dimensions‟ are called matrix.
 When the data must be stored in the form of a matrix we use two dimensional
arrays.

Declaration of Two –Dimensional array:

Syntax:
datatype array-name [row- size] [column- size];
For example a two dimensional array consisting of 5 rows and 3 columns. So the
total number of elements which can be stored in this array are 5*3 i.e. 15

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 57


Initialization of 2-D array:
Two –D array can also be initialized at the place of declaration itself.

Syntax:
Data-type array-name [row-size] [column-size] = {{row1 list}, {row2 list},
…………. {row n
list}};

e.g. int mkm[2][3]={ {2,3,4},{5,6,7} };

Here 2, 3 and 4 are assigned to there columns of first row and 5, 6, 7


are assigned to three columns of second row in order. If the values are missing in
initialization, they are set to garbage values.

We can also initialize a 2-D array in the form of a matrix.


e.g. int table[2][3]={ 1,2,3,4,5,6};
(Or)
int table[2][3]={ {1,2,3},{4,5,6} };
(Or)
int table [2][3]={ {1,2,3},
{4, 5, 6}
};
(Or)
int table[ ][ ]={ 1,2,3,4,5,6 };
(Or)
int table [2] [3] = {{1, 2}, {3}};

Storage Representation of two –Dimensional array:

When speaking of two-dimensional arrays, we are logically saying that, it


consists of two rows and columns but when it is stored in memory, the memory is linear.
 Hence, the actual storage differs from our matrix representation.

Two major types of representation can be used for 2-D array


1. Row representation
2. Column representation

e.g. int a[3][3]

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 58


Logical view of a [3] [4];

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 59


Write a program to perform Addition of Matrices
#include<stdio.h>
void main()
{
int i,j,m,n,p,q;
int a[10][10],b[10][10],c[10][10];
clrscr();
printf(" <---ADDITION OF TWO MATRICES---->\n");
printf("Enter the size of matrix1:");
scanf("%d%d",&p,&q);
printf("Enter the elements of matrix2:");
scanf("%d%d",&m,&n);
printf("Enter elements of matrix 1:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements of matrix B:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
}
if(m!=p || n!=q)
printf("Matrix addition not possible");
else
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
}
printf("The resultant MATRIX is :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%5d",c[i][j]);
printf("\n");
}
getch();

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 60


}

Output:
<----------ADDITION OF TWO MATRICES------------>

Enter the size of matrix1: 3 3

Enter the elements of matrix2: 3 3

Enter elements of matrix 1:

1 2 3

4 5 6

7 8 9

Enter elements of matrix B:

1 2 3

4 5 6

7 8 9

The resultant MATRIX is:

2 4 6

8 10 12

14 16 18

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 61


UNIT-3
STRINGS AND POINTERS
Strings: Declaring, Initialization of a String, Reading and Writing Strings, String
manipulation functions from the standard Library, String I/O Functions: gets(), puts().

Pointers: Pointer Variables, Pointer Expressions, Pointers And Arrays, Pointers to


Strings. Problems with Pointers.

STRINGS

A set (or) group of characters, digits and symbols enclosed with


in quotation marks, double quotations are called “strings”.
A string is an array of characters in other words character arrays are called
strings.
Every string is terminated with „\0‟ (null) character.

Declaration and Initialization of Strings:

The general format of declaring string variable is as follows:


Syntax:
datatype string–name[size];

Declaration of strings is also same as Array declaration.


E.g.: char name [8] = “TITANIC”;

From above statement “name” is char type and size is 7, but assigned
string “TITANIC” has 6 characters 7 th is null characters. That is you must leave an extra
space for null characters, when we deal with character strings.

The „c‟ compiler inserts the null (\0) character automatically at the end of the string
so initialization of null character is not essential.

Above example is also can be initialized as follows

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 62


Char name [8] = {„T‟,‟I‟,‟T‟,‟A‟,‟N‟,‟I‟,‟C‟};

Write a program to display the output when null is not considered


#include<stdio.h>
#include<string.h>
Void main ( )
{
char name [5] = {“INDIA”};
clrscr( );
printf(“Name=%s”,name);
getch( );
}

Output:

India along with garbage values

Reading and Writing Strings

The scanf( ) and printf( ) functions are used to read and print string
respectively for formatted input and output.

scanf( ) function:
The familiar input functions scanf() can be used with „%s‟ format specification to
be read in a string of characters.
Syntax:
char name [25]= {“POKIRI”};
scanf (“% s”, name);
To read string, ampersand (&) is not required before the string variable. The
name of the string itself acts as a base address.
To eliminate the disadvantage of using a „scanf‟ function to read a line we use
getchar() or gets( )functions.
getchar( ): This function reads string character by character until terminating
condition is satisfied .
gets( ): This function reads the entire line of text.
E.g:
char m[30];
gets(m);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 63


Printf( ) function:

 The commonly used output function is printf().The function can also be used for
writing string, but „% s‟ should be used as format specification.
E.g.:
char name [30] =”chadalawada”;
printf (“%s”, name);
Here the output produced will be chadalawada.
 We are going to use as output functions puts (),putchar().
 Puts( ):
This function prints line on the screen.
Syntax:
char name [30] =”chadalawada”;
puts(name);

 Putchar( ); when putchar function is used, single character is printed on screen at


a time until the terminating condition occurs.

Write a program to print a string in different ways.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
char a[10];
clrscr();
gets(a);
printf("\n");
puts(a);
printf("%0.5s\n",a);
printf("%0.3s\n",a);
printf("%-7.4s\n",a);
printf("%+7.4s\n",a);
getch();
}

Output:

TITANIC

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 64


TITANIC
TITAN
TIT
TITA
TITA
Note:

 „-„(Negative sign) indicates that specified string is printed left(left justified).


 „+‟(positive sign) indicates that specified string is printed right side(right justified).

String Library Functions

„C‟ library supports a large no. of string – handling functions


that can be used to carry out many of the string manipulations.

All this functions are defined in the <string.h> file.


The following table gives a list of string functions.

Strcat( )  string concatenate


Strcmp( ) compares two strings.
Strncmp( ) compares first n characters of two strings.
Strcpy( ) copies strings into another.
Strncpy( ) copies first n characters of a strings into another.
Strlen( )  returns the length of string not counting the null character.
Strlwr( ) converts string into lower case.
Strupr( ) converts string into upper case.
Strdup( ) copies string into a newly created location.
Strrev( ) reverse string.

1. strlen( ):
Determines the length of string that is it counts the no. of characters in a given
string.
Syntax:
strlen (string);

Write a program to count the number of character in a given string.

#include<stdio.h>

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 65


#include<string.h>
void main()
{
char text[10];
int len;

printf("Enter the text:");


gets(text);
len=strlen(text);
printf("length of the string:%d",len);
getch();
}
Output:
Enter the text: GOVINDA

Length of the string: 7

2. Strcpy ( ):
This function copies the contents of one string to another.
Syntax:
Strcpy(string1,string2);

Here string2 is copied into string1.

Write a program to copy the contents of one string to another

#include<string.h>
void main()
{
char a[10],b[10];
clrscr();
printf("Enter the string A:");
gets(a);
printf("Enter the String B:");
gets(b);
strcpy(a,b);
printf("After string copy a=%s\n",a);
printf("After string copy b= %s",b);
getch();
}

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 66


Output:

Enter the string A: TIRUPATHY


Enter the String B: TIRUMALA
After string copy a= TIRUMALA

After string copy b= TIRUMALA

3. Strncpy ( );
This function performs same as strcpy( ).The only difference is that this
function copy string to string with specified length.

Syntax:
strncpy(string1,string2,n);

Write a program to copy source string to destination string up to a specified


length.
#include<string.h>
void main()
{
char x[10]="TITANIC";
char y[10]="WANTED";
int n=4;
clrscr();
strncpy(x,y,n);
printf("source string y=%s\n",y);
printf(" Destination string x=%s",x);
getch();
}

Output:

Source string y= WANTED

Destination string x= WANTNIC

4. Strcat ( )
This function appends the target string to source string. Concatenation of
two strings can be done using this function.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 67


Syntax:
Strcat(string1,string2);
Write a program to append second string at the end of first string using strcat( ).
#include<string.h>
void main()
{
char s[10],s1[20];
clrscr();
printf("Enter the string s,s1");
scanf("%s%s",s,s1);
strcat(s,s1);
printf("After the strcat() %s",s);
getch();
}

Output:

Enter the string s,s1: Mech


Electronics
After the strcat() : MechElectronics
5. Strncat ( );
This function is used to Concatenation of the strings to another up to
specified length.

Syntax:
Strncat(string1,string2,n);
Where,‟n‟ is the number of character to append.

Write a program to append second string with specified length of character at


thew end of first string using strncat( ).

#include<string.h>
void main()
{
char x[10],y[10];
int n;
clrscr();
printf("Enter the string x and y ");
scanf("%s %s",x,y);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 68


printf("Enter the length");
scanf("%d",&n);
strncat(x,y,n);
printf("%s",x);
getch();
}

Output:
Enter the string x and y TIRUPATHY TIRUMALA
Enter the length 4

TIRUPATHYTIRU

6.Strcmp ( )

This function compares two strings with case. The characters of the strings
must be in lower case (or) uppercase .If the strings are same it returns “Zero”, other
wise 1(non zero).

Syntax:
Strcmp(string1,string2);

Write a program to the two strings using strcmp().

#include<string.h>
void main()
{
char a[10];
char b[10];
int d;
clrscr();
printf("Enter the string a:");
scanf("%s",a);
printf("Enter the string b:");
scanf("%s",b);
d=strcmp(a,b);
if(d==0)
printf("Two Strings are identical ");
else
printf("Different");

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 69


getch();
}

Output:
Enter the string a: Rajesh
Enter the string b: Ramu
Different

Enter the string a: Rajesh


Enter the string b: Rajesh
Two Strings are identical

POINTERS
Def:
pointer is a variable which stores address of another variable.
Or
Pointer is variable which stores address of a variable.
Or
A pointer is a memory variable that stores a memory address.

We can take an example to view about pointers.

Pointers are widely used in programming; they are used to refer to memory location of
another variable without using variable identifier itself.
To declare pointer variable we need to use * operator (indirection/dereferencing
operator) before the variable identifier and after data type.
Pointer can only point to variable of the same data type.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 70


Features of pointers
Pointers are used frequently in c, as they offer a number of benefits to the
programmers.
1. Pointers save the memory space.
2. Execution time with pointer is faster because data is manipulated with the
address i.e direct access to memory address.
3. Pointers reduce length and complexity of programs.
4. A pointer allows C to support dynamic memory management.
5. Pointers are useful for representing two-dimensional and multi-dimensional
arrays.
6. Pointers are used with data structures.

Syntax; datatype *pointer_variable;

 The pointer variable is needed to store the memory address of any variable.
 The pointer is denoted by (*) asterisk symbol.
 It is also called “Indirection/Deference operator”.
 By using pointer variable always we can store address only, not values i.e.
directly we don‟t assign a value to pointer variable.
 By using ordinary variable only we can directly assign a value.
Declaration and Initialization
Pointer variables are declared in the same way as normal variables. But pointers
must declared along „*‟ operator.
Syntax:
Data type * variable –name;
E.g.:
int * n;
Hear n is a pointer variable of type variable of type integer, and it tells to
compiler that it holds the address of any integer variable only.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 71


an example program

#include<stdio.h>
#include<conio.h>
main()
{
int u=3;
int v;
int *pu;
int *pv;
clrscr();
pu=&u;
v=*pu;
pv=&v;
printf("\n u=%d &u=%u pu=%u *pu=%d",u,&u,pu,*pu);
printf("\n\n v=%d &v=%X pv=%X *pv=%d ",v,&v,pv,*pv);
getch();
}
Output:

Note that pu is a pointer to u, and pv is a pointer to v. therefore pu represent the


address of u, and pv represents the address of v.
The output shown above is, in the first printf we have printed the address of variables
output with unsigned integer (%u) , and in the
Second printf the address of variables is printed with hexa decimal values (%X).
Write a program to display the addresses of different variables together with their
values.
#include<stdio.h>
void main()
{
char c;
int i;
float f;
clrscr();
printf("Enter the Alphabet,Number,Float=");
scanf("%c %d %f",&c,&i,&f);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 72


printf("Value of c=%c i=%d f=%f\n",c,i,f);
printf("\n Address of c %c=%u",c,&c);
printf("\n Address of i %d=%u",i,&i);
printf("\nAddresss of f %.2f=%u",f,&f);
getche();
}
Output:

Enter the Alphabet, Number, Float= R 10 6.7


Value of C = R i=10 f=6.700000
Address of c R=65489
Address of i 10=65490
Address of f 6.700000=65492

Arithmetic operation with Pointers


Arithmetic operations on pointer variables are also possible. Increase, Decrease prefix,
postfix operations can be performed with the help of the pointers. The effect of these
operations are shown in the below given.

Pointer and Arithmetic operation

Data Initial Operation Address of after operations Required


type address bytes

int i=2 4046 ++ - 4048 4044 2


-

char c=‟x‟ 4053 ++ - 4054 4052 1


-

float 4058 ++ - 4062 4054 4


f=4.2 -

long l=2 4060 ++ - 4064 4056 4


-

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 73


From the above table we can observe that on increase of pointer variable for integers
the address is increased by two 4046 is original address and on increase its value will
be 4048 because integer requires two bytes.
Similarly characters, float numbers and long integers requires 1,4and 4 bytes
respectively.

Write a program different Arithmetic operation using pointers.

/*pointers using arithmetic operations*/


#include<stdio.h>
#include<conio.h>
void main()
{
int a=25,b=10,*p,*j;
clrscr();
p=&a;
j=&b;
printf("Addition a+b=%d\n",*p+b);
printf("sub a-b=%d\n",*p-b);
printf("product a*b=%d\n",*p**j);
printf("division a/b=%d\n",*p / *j);
printf(" a mod b=%d\n", *p%*j);
getch();
}

Output:

Addition a+b= 35
sub a-b=15
Product a*b=250
Division a/b=2
a mod b=5

Pointers and Arrays

Array name by itself is an address or pointer. it points to the address of the first element
(0th element of array).The element of the array together with their addresses can
displayed by using array name itself. Array elements are always are always stored in
contiguous memory locations.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 74


For example see in the following figure.

in the above figure we have taken 3 array elements i.e array[3]={0,1,2}, in the second
line we have directly assigned array to the pointer variable without using ampersand
operator.
*ptr is pointing to array[0] th element and by incrementing the pointer variable we can
access the array[1],array[2] elements.
Here is an example program to explain the one dimensional array
Therefore if x is a one dimensional array, then the address of the first element can be
expressed as either &x[0] or simply as x.
The address of the second array element can be written as either &x[1]or as (x+1), and
so on…
In general the address of array element (i+1) can be expressed as either &x[i] or as
(x+i). thus we have two different ways to write the address of any array element.
#include<stdio.h>
#include<conio.h>
void main()
{
static int x[10]={10,11,12,13,14,15,16,17,18,19};
int i;
clrscr();
for(i=0;i<=9;i++)
{ /* dispaly an array eleemnt */
printf("\n i=%d x[i]=%d *(x+i)=%d\n",i,x[i],*(x+i));
/* display the corresponding array address*/
printf(" &x[i]=%X x+i=%X ",&x[i],(x+i));
}
getch();
}

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 75


Output:

This program defines a one dimensional, 10- element integer array x, whose elements
are assigned the values 10,11,12,13,…19.here the value of each element is specified in
two different ways as x[i] and as *(x+i), in order to illustrates their equivalence .
Similarly the address of each array element is specified in two different ways as &x[i]
and as (x+i).
The output clearly illustrates the distinction between x[i], which represents the value of
the ith array element , and &x[i], which represent its address.
Similarly the value of the ith array element can be represented by either x[i] or *(x+i),
and the address of the ith element can be represented by either &x[i] or x+i
Pointer to Strings

A pointer which pointing to an array is known as pointer to array of strings.

In this example

ptr : It is pointer to array of string of size 4.


array[4] : It is an array and its content are string.
1 : Printing Address of the Character Array
#include<stdio.h>
int main()

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 76


{
int i;
char *arr[4] = {"C","C++","Java","VBA"};
char *(*ptr)[4] = &arr;
for(i=0;i<4;i++)
printf("Address of String %d : %u\n",i+1,(*ptr)[i]);
return 0;
}
Output :

Address of String 1 = 178


Address of String 2 = 180
Address of String 3 = 184
Address of String 4 = 189
2. Printing Contents of character array

#include<stdio.h>

int main()
{
int i;

char *arr[4] = {"C","C++","Java","VBA"};


char *(*ptr)[4] = &arr;

for(i=0;i<4;i++)
printf("String %d : %s\n",i+1,(*ptr)[i]);

return 0;
}
Output :

String 1 = C
String 2 = C++
String 3 = Java
String 4 = VBA
Problems with pointers
When a pointer is used incorrectly, or contains the wrong value, it can be a very difficult
to bug to find. To help you avoid them, a few of the more common errors are discussed
here.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 77


Example1:
int x=10,*p;
*p=x; /*error, p not initialized*/
Example2:
int x=10,*p;
p=x; /*here, assign the value, but assign the address */
Example3:
char s[50],y[80];
char *p1,*p2;
p1=s;
p2=y;
if(p1<p2)…
Is generally an invalid concept.(in very unusual situations, you might use something like
this to determine the relative position of the variables. but this would be rare.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 78


UNIT-4
FUNCTIONS, STRUCTURES AND UNIONS
Functions: Definition, Function Call- Call by Value, Call by Reference, Storage Class
Specifiers, Understanding the scope of Functions with its Types, the Return Statement,
Recursion, C‟s Dynamic Allocation Functions. Command Line Arguments.

Structures and Unions: Accessing structure members, Array of structures, Passing


Structures to Functions, Structure Pointers, Structures within Structures, Bit Fields,
Enumerations, Typedef.

A function is a self contained block of statements that performs a coherent


task of some kind.
 How a function is defined?
 How a function is integrated into a program?
 How two or more functions are not put together?
 How they communicate with one another.
 Functions are self contained program segments that carry out some specific
well defined task.
 We include the header files like stdio, conio,string etc. These files contain
number of library functions which are as follows:
printf(),scanf(),getch(),getchar(),gets(),puts() etc.
 Every „c‟ program must have a function. One of the functions must be main().
Why should we use a function?
a) By using function, it becomes easy to write program and keep trace of what they
are doing.
b) Length of the program can be reduced by using function.
c) Debugging is easier.
d) It facilitates top – down modular programming.
Using functions avoids rewriting
„C‟ functions can be classified into two categories.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 79


Library functions:
They are predefined in the standard library of „c‟. We need to include
the library functions such as sin(x), cos(x), pow(x), sqrt(n) etc. The code of these
functions is not available to the user. So they can not modify these functions.

User defined functions:


These functions are used need to be developed by the user at the
time of program writing.
Functions break large computing tasks into smaller ones, which help in the modular
development of big program.
There are three steps involved in creating and using of User Defined functions.
1. Declaring of function prototype.
2. Defining a function.
3. Calling a function.
User defined functions:
These functions allow user to define their own function according to
the requirement of program. Any „c‟ function is defined in the following formats.

Syntax:
Return-type func-name(datatype arg1,datatype arg2 ,………..datatype argn)
{
Local variables;
Executable_stmt 1;
Executable_stmt 2;
----------------
-----------------
V. SambaSiva., Assistant Professor, Department of CSE, CREC. 80
return (expression);
}

e.g:
int sum(int a, int b)
{
int s;
s=a+b;
return(s);
}

Func- name:
Each function is recognized by its name. In the given examples „sum‟ is a
function name. It follows of an identifier.
Arguments:
The arguments in function are always variables. They can be declared in
two ways as shown in format and format 2.
Return statement:
It can be written in two ways depending on the requirements.
return (expression);
Or
return;

return (expression):
This statement returns the value of expression to be called function.
E.g: return (a, b)
return (a);
return:
This specifies returns control to calling function but not return any value. There
can be any number of return statements in the program but each statement can return
only one value.
 If no value is returned to the calling function then the return type is declared as
void.

Function call:
The statement which is used to call a function is called as “function
call”.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 81


Function definition:
Actual code of a function is known as “function definition”.

Function declaration:
All identities in „c‟ need to be declared before they are used .This is
true for functions as well as variables, for function the declaration needs to be done
before the function call.

e.g:
void main()
{
void greet ();
greet ();
}
void greet ( )
{
printf(“Happy New Year”);
}

Arguments used in function:


Depending on the location of argument in functions they are
categorized as actual parameter and formal parameter.

Actual Parameters:
The parameters which are passed in function call are known as
actual parameters. They are defined in calling function and they can be expressions,
constants or variables.

Formal parameters:
The parameters which are used in function defined are called formal
functional parameters.
 Formal parameters can only be variables. They can not be expressions or
constants.
 The value of actual parameters is passed to formal parameters.

Void main( )
{
Statements;
function (a1,a2,………..an);
Statements;

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 82


}
function (f1,f2,…….fn)
Statements;
{
Statements;
}

Parameter passing techniques:


There are two types of passing parameters to functions
1. Call by value
2. Call by reference

Call by values:
The process of passing the actual values of variables is known as “call by
values”.

#include<stdio.h>
int sum(int,int);
void main()
{
int a=10,b=20,c;
c=sum(a,b);
printf("sum of 2 no is %d",c);
}
int sum(int x,int y)
{
int z;
z=x+y;
return(z);
}

Call by reference:
The process of calling a function using pointers to pass the address of
variables is known as “call by reference”.
#include<stdio.h>
void main()
{
int x,y;
int swap(int,int);
printf(“enter x,y values\n”);
scanf(“%d%d”,&x,&y);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 83


swap(&x,&y);
printf(“after swapping x=%d\t y=%d\n ”,x,y);
}
int swap(int *a,int *b)
{
int *temp;
*temp=*a;
*a=*b;
*b=*temp;
return();
}
Storage classes in „c‟

Storage class refers to the class of variables depending on


how long the variables are retained in program execution.
 Storage class determines in which part of program the variables can be
accessed and how long they exist in a program.
Storage classes in „c‟ divided into four types:
1. Automatic storage classes.
2. Register storage classes.
3. Static storage classes.
4. External storage classes.
The above storage classes are identified by the key words auto, static, register, extern.
Automatic storage classes:
By defining a variable as automatic storage class it is
stored in the memory. The default value of the variable will be garbage value.
To define a variable as automatic storage class, the keyword auto is used.
Syntax:
auto int i;
e.g:
auto int a, b;
The key word is not mandatory because the default storage class in „c‟ is auto.

Example program.
#include<stdio.h>
void fun();
void main()
{
auto int a,b;
a=5;

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 84


printf("a=%d,b=%d",a,b);
fun();
getch();
}
void fun()
{
auto int c=10;
printf("\nc= %d",c);
}
Output:
A=5 b=4567 c=10

Register storage class:


When a variable is declared as register it is stored in the
registers. The default value of the variable will be garbage value.

Syntax: register data type variable;


e.g :
register int j;
 To define a variable as register storage class the key word register is used.
 If CPU cannot store the variables in CPU register then the variables are assumed
as auto and stored in the memory.

#include<stdio.h>
void main()
{
register int j=1;
do
{
printf("%d",j);
j++;
}
while(j<=10);
}
Output:
1 2 3 4 5 6 7 8 9 1

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 85


Static storage classes:
When a variable is declared as static it is store in the memory.
The default value of the variable can be initialized only once it cannot be reinitialized.
Syntax: static data type variable;
e.g :
static int j;

Example program

#include<stdio.h>
void main()
{
static int b;
int a;
clrscr();
printf("a=%d,b=%d",a,b);
getch();
}
Output:
a=2654 b=0

Extern storage classes:


When a variable is declared as entry it is stored in the memory the
default value is initialized to zero.
 The scope of the variable is global and the life of the variable is until the program
execution comes to an end.
Syntax: extern data type variable;
e.g :
extern int j;

 To define a variable as extern storage class the key word extern is used.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 86


#include<stdio.h>
int e=20;
void main()
{
fun1();
fun2();
printf("\n e is in main=%d\n",e);
}
fun1()
{
extern int e;
printf("e in fun1=%d\n",e);
}
fun2()
{
printf("e is in fun2=%d\n",e);
}
Output:
e is in main=20
e is in fun2=20
e in fun1=20
Scope
Scope determines the region of the program in which a defined object is
visible.
To discuss the concept of scope we need to review two concepts.
1. Block
2. Global

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 87


Global scope:
Any object defined in the global area of a program is visible from its
definition until the end of the program.
Local scope:
Variables defined with in a block have local shape.
Types of functions:
Depending on the return value and arguments passed as functions
can be classified into 4 categories.

Functions without arguments and with out return values:


These are the functions in which no parameters are passed from
calling function to called function and values are returned from called function to calling
function.

#include<stdio.h>
void sum( );
void main()
{
sum( );
getch();
}
void sum()
{
int a=10,b=20,c;
c=a+b;

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 88


printf("Sum of 2 numbers is %d",c);
}

Function with arguments and with out return values:


These are the functions in which arguments are passed from called function
to calling function.
#include<stdio.h>
void sum(int x,int y);
void main()
{
int a=10,b=20;
sum(a,b);
getch();
}

void sum(int x,int y)


{
int z;
z=x+y;
printf("sum of 2 numbers is %d",z);
}

Function with out arguments and with return values:


In this no arguments are passed from called function to calling function
but values are returned from called function to calling function.

#include<stdio.h>
int sum();
void main()
{
int z;
clrscr();
z=sum();
printf("sum of 2 numbers is %d",z);
getch();
}
int sum()
{

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 89


int a=10,b=20,c;
c=a+b;
return(c);
}

Functions with arguments and with return values:


These are the functions in which parameters are passed from calling function
to called function and the values are returned from called function to calling function.
#include<stdio.h>
int sum(int,int);
void main()
{
int a=10,b=20,c;
c=sum(a,b);
printf("sum of 2 no is %d",c);
}
int sum(int x,int y)
{
int z;
z=x+y;
return(z);
}
Recursion
Recursion is a technique to be used to call itself.
 A function which involves repeatedly until a same condition is satisfied is called a
recursive functions.
 Two or more functions which involve each other are called “mutually recursive
function”.

->Write a program to display 1 to 10 numbers using recursion.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 90


#include<stdio.h>
void main()
{
static int i=1;
printf("%d",i);
i++;
if(i<=10)
main();
}

Output:
1 2 3 4 5 6 7 8 9 10

Dynamic Memory Allocation Functions

„C‟ gives us two choices when we want to reserve memory for an object.

Static Memory Allocation:

In static memory allocation memory is allocated to the variable and arrays at compile
time. The no. of bytes required cannot be changed during run time.

Dynamic Memory Allocation:

Allocation memory to the objects at the run time is called Dynamic memory allocation.
To access the dynamic data pointers are used.

 Four types of functions have been defined for D.M.A.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 91


Memory Management functions
1. MallocBlock memory functions
2. Calloc Contiguous memory allocation.
3. Reallok Reallocation of memory.
4. FreeReleasing memory.
First three functions are used to allocate memory and the last one is to free the
memory that is not in use.
 All these functions are included in standard library functions <stdlib.h> file

malloc( )
Malloc function is to allocate a block of memory and it returns void
pointers to the address of first byte the memory.

The declaration of malloc function is


Syntax:
void* malloc(size-t size);
 Size-t represents the data type it is usually an un signed integer.
 The size of the malloc‟s actual parameter is defined by using size of operator.
E.g:
int M=void * malloc(size(int))

Calloc()
Calloc function is used to allocate memory dynamically for arrays.The only
difference between calloc and malloc doesn‟t.

The Declaration of calloc is as follows .


Syntax:
Void * calloc (size –t element – counter , size-t element- size);
E.g:
int c[]=(int*) calloc(50,size of (int));
Here an array of 50 integers is allocated.
V. SambaSiva., Assistant Professor, Department of CSE, CREC. 92
realloc()
Relloc re sizes the bloc of memory either by deleting or extending the
memory block. It allocates new block if the extending block can not be extended and
copies the existing memory allocation to the new block and deletes the old one.

The declaration of realloc function is as follows.


Syntax:
Void* realloc(void * ptr, size-t new size):
free()
Free function is used to free the memory alloction by malloc , calloc when
they are no longer in use and the memory bloc can be reused later.

The declaration of free function is as below


Syntax:
void free(void* ptr)

Command Line Arguments

All the programs we have written have been coded with no parameters for main.

 But main is a function and as a function, it may have parameters.


 When all the programs we have written have been coded with no parameters for
main.
 But main is a function and as a function it may have parameters.
 When main has parameters they are known as “common – line arguments”.
 Command line arguments are parameters to main when the program.
 Although the names of the arguments are your choice traditionally they are called
argc (arguments count) and argv (argument vector).
Note: The value of argc is determined from the user typed values for argv‟s.

Write a program to demonstrate the use of command line argument.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(int argc,char *argv[])


{

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 93


int i;
printf("The number of arguments:%d\n",argc);
printf("The name of the program :%s\n",argv[0]);
for(i=1;i<argc;i++)
printf("User value no %d:%s\n",i,argv[i]);
getch();
}

Output:

Structures
You are aware that a variable store a single value of a datatype.Arrays can store many
values of similar data type.In real life we need to have different data types for example
to maintain employees information we should have information such as name, age,
qualification, salary etc.
Here, to maintain the information of employees is dissimilar data types are
required. To handle such kind of data „C‟ provides a derived data type known as
“Structure”.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 94


Definition of Structure:
A Structure is a collection of one or more variables of different data types, grouped
together under a single name.
(Or)
A Structure is a collection of data items of different data types under a single name.
Features of Structures:
 Structures are used to hold related data belonging to different data types.
 Nesting of Structures is possible.
 It is also possible to pass Structure elements to a function.
 It is also possible to create Structure pointers.

Declaration of Structure:
Structure can be declared as given below.
Syntax:
Struct <Structure-name>
{
Data type1 member 1;
Data type1 member 2;
---------------------------
Data type member n;
};
Struct <structure-name> variable;
 Structure declaration always starts with struct keyword, Here Structure-name
is known as tag.
 The struct declaration is enclosed with in a, pair of curly braces.
 Each member of structure may belong to different types of data.
 The individual members can be ordinary variables, arrays, pointers or other
structures.
E.g.:
Struct kick
{
Char m;
Int a, b, c;
Float d;
};
Struct kick p;
 In the above declaration kick is the structure- name.
 It contains five members. The p is a variable of kick. They have members called
m, a, b, c, d.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 95


 Members of structure themselves do not occupy any space. Memory is allocated
only after declaring structure variables.
 All the members of structure are related to variable p.
 The period sign (or) dot operator (.) is used to access the structure member.

Write an example program on structures.


#include<stdio.h>
#include<conio.h>
void main()
{
struct jack
{
int a,b,c;
float g;
char t;
};
struct jack p={ 4,6,8,5.5,'h'};
printf(" %d %d %d %f %c",p.a,p.b,p.c,p.g,p.t);
getch();
}
Output:

4,6,8,5.5,h
Write a program to display student details

#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
char name[30];
char course[40];
int age;
int year;
};
struct student s= {"yuva","cse",20,2010};
printf(" %s %s %d %d \n",s.name,s.course,s.age,s.year);
getch();
}

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 96


Output:

Yuva cse 20 2010

Array of structures

The Structures that we have defined can only contain one record. In
practical applications. There may be a number of records that need to be stored and
manipulated.
Array of structures can be declared as follow.
Syntax:
struct student
{
int rno;
char name [10];
float attd;
};
struct student s [60];

The members of the structure variable are referred and accessed as follows.
( s[i].rno,s[i].name,s[i].attd )
Write a program to enter the details of student rollno, name, and marks.

#include<stdio.h>
#include<conio.h>
void main()
{
int num,i=0;
struct student
{
char name[20];
int rollno;
int marks;
};
struct student s[10];
clrscr();
printf(" Enter the number of students:");
scanf("%d",&num);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 97


for(i=0;i<num;i++)
{
printf("\n Enter the details for %d student",i+1);

printf("\n NAME: ");


scanf("%s",s[i].name);
printf("\n Roll.No: ");
scanf("%d",&s[i].rollno);
printf("\n Total Marks:");
scanf("%d",&s[i].marks);
}
printf("\n press R to display the student details");
getch();
for(i=0;i<num;i++)
printf("\n Student %d \n Name: %s \n Roll.No: %d \n Total marks: %d\n",
i+1,s[i].name,s[i].rollno,s[i].marks);
getch();
}

Output:
Enter the number of students: 2
Enter the details for 1 student
Name: Rita
Roll No: 639
Total Marks: 66
Enter the details for 1 student
Name: Mita
Roll No: 639
Total Marks: 88
Press R to display the student details

Student 1
Name: Rita
Roll No: 639
Total Marks: 66

Student 2
Name: Mita
Roll No: 739
Total Marks: 88

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 98


Pointer to Structure
We know that pointer is a variable that holds the address of
another data variables .The variable may be of any data type i.e. int, float, or double. In
the same way we can also define pointer to structure. Here, starting address of the
member variables can be accessed. Thus, such pointers are called structure pointers.

Syntax:
struct book
{
Char name [18];
Char author [19];
int pages;
};
struct book *ptr;
*ptr is pointer to structure book. The syntax for using pointer with member is as given
below.

Ptr->name, ptr->author, ptr->pages.


By executing these statements starting address of each member can be estimated.

Write a program to declare pointer to structure and display the contents of the
structure.

#include<stdio.h>
void main()
{
struct book
{
char name[35];
char author[35];
int pages;
};
struct book bk={ "Java","James",999};
struct book *ptr;
ptr=&bk;
clrscr();
printf("%s by %s of %d pages",ptr->name,ptr->author,ptr->pages);
getch( );
}

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 99


Output:

Java by James of 999 pages


Structure and Functions

Structure variables also can be passed to the function by value or address. The syntax
of the same is as under.

Syntax:
Struct books
{
Char name[33];
Char author[44];
Int pages;
};
Void main()
{
---------
jack(&b1);
---------
}
Jack(struct book *b2)
{
--------;
--------;
}

When ever a structure elements is to be passed to any other function, it is essential to


declare the structure outside the main( ) function i.e. global

Write a program to pass structure elements to function print () and print the
elements.

#include<stdio.h>
#include<conio.h>
#include<string.h>

struct boy
{

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 100


char name[25];
int age;
int wt;
};
void main()
{
struct boy b1={"amit",34,66};
print (b1);
}
print (struct boy b)
{
clrscr();
printf("\n %s %d %d", b.name,b.age,b.wt);
getch();
}

Output:

Ricky 34 66

Pointer to Structure
We know that pointer is a variable that holds the address of
another data variables .The variable may be of any data type i.e. int, float, or double. In
the same way we can also define pointer to structure. Here, starting address of the
member variables can be accessed. Thus, such pointers are called structure pointers.

Syntax:
struct book
{
Char name [18];
Char author [19];
int pages;
};
struct book *ptr;
*ptr is pointer to structure book. The syntax for using pointer with member is as given
below.

Ptr->name, ptr->author, ptr->pages.


By executing these statements starting address of each member can be estimated.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 101


Write a program to declare pointer to structure and display the contents of the
structure.

#include<stdio.h>
void main()
{
struct book
{
char name[35];
char author[35];
int pages;
};
struct book bk={ "Java","James",999};
struct book *ptr;
ptr=&bk;
clrscr();
printf("%s by %s of %d pages",ptr->name,ptr->author,ptr->pages);
getch( );
}

Output:

Java by James of 999 pages


Structure with in Structure

We can take any data type for declaring structure members like int, float, char etc. In
the same way we can also take object of one structure as member in another structure.
Thus, structure with in structure can be used to create complex data applications.

Syntax:

Struct time
{
int second;
int minute;
int hour;
};
Struct t
{
int carno;

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 102


struct time st;
struct time et;
};
struct t player;
Write a program to enter full name and data of birth of a person and display the
same use nested structure.

#include<stdio.h>
#include<conio.h>
void main()
{
struct name
{
char first[10];
char second[10];
char last[10];
};
struct bdata
{
int day;
int month;
int year;
};
struct data
{
struct name nm;
struct bdata bt;
};
struct data r1;
clrscr();
printf("\n Enter the name (first /second/last)\n");
scanf("%s %s %s",r1.nm.first,r1.nm.second,r1.nm.last);
printf("\n enter Birth date day/month/year)\n");
scanf(" %d %d %d ", &r1.bt.day,&r1.bt.month,&r1.bt.year);
printf("Name: %s %s %s \n",r1.nm.first,r1.nm.second,r1.nm.last);
printf("Birth date : %d %d %d",r1.bt.day,r1.bt.month,r1.bt.year);
getch();
}

Output:

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 103


Enter the Name: (first/second/last)
Sachin Tendulkar k
Enter birth day (day/month/year)
12 12 1976
Name: sachin Tendulkar k
Birth Date: 12.12.1976
Typedef

By using typedef we can create new data type. The statement typedef is to used while
defining new data type.
Syntax:
typedef data_type data_name;
Here type is a data type and data name is the user defined name for that type.
E.g:
typedef int hours;
Here, hours is another name for int and now we cam use hours instead of int in the
program as follows.
hours hrs;

Write a program to create user-defined data type hours on int data type and use it
in the program.

#define h 60
Void main ( )
{
typedef int hours;
Hours hrs;
clrscr( );
printf(“Enter hours”);
scanf(“%d”,&hrs);
printf(\n MINUTES=%d”,hrs*H);
printf(“\n SECONDS=%D”,hrs*H*H);
getch( );
}

Output:
Enter hours: 2
Minutes=120
Seconds = 200

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 104


Bit fields
Bit fields provide exact amount bits required for storage of values. If a variable value is
1 or 0 we need a single bit to store it.
 In the same way if the variable is expressed between 0 and 3 then the two bits
are sufficient for storing these values and so on.
 To hold the information we use variables the variables occupy a minimum of one
byte for char and two bytes for integer instead of using complete integer if bits
are used, space of memory can be saved.

Def: A bit field set of adjacent bits whose size can be from 1 to 16 bits in length.
Syntax:
Struct tag_ name
{
Data type name 1: bit _length;
Data type name 2: bit _length;
---------------------
---------------------
Data type name n: bit-length;
};

Enumerated data type:


enum is a enumerated data type supported by „C‟.
Syntax:
enum identifier { v1,v2,v3…….vn);
The „identifier‟ is a user defined enumerated data type which can be used to declare
variables that can have one of the values enclosed with in the braces (known as
enumeration constants).
enum kick {k1,k2,k3..kn};
k1, k2, k3 are the enumerated variables.
e.g :
enum month {jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};

The above statement creates a user-defined data type.The keyword enum is followed
by the tag name month.
 The enumerated variables are Jan, Feb, mar------ dec.
 The identifiers are not to be enclosed with in quotation marks.
 Note that integer constants are also not permitted.

Write a program to create enumerated data type for 12 month. Display their
values in integer constants.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 105


#include<conio.h>
void main()
{
enum month {jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
clrscr();
printf("\njan=%d",jan);
printf("\nfeb=%d",feb);
printf("\njul=%d",jul);
printf("\ndec=%d",dec);
getch();
}

Output:

Jan=0
Feb=1
Jul=6
Dec=11
Unions
Union is a variable. This is similar to the structure. It contains number of members like
structure but it holds only one object at a time.
 In the structure each member has its own memory locations whereas; members
of unions have same memory locations.
 It can accommodate one member at a time in a single area of storage.
 The union requires bytes that are equal to the number of bytes required for the
largest members.

Def:
“A union is a collection of data items of different data type. It is similar to that of
structure”.
A union is declared as shown below

Syntax:
Union <union tag name>
{
Data type member1;
Data type member2;
----------------
----------------

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 106


Data type member n;
};

 Here union is a keyword.


 Member 1, member 2, member n are members of union.
 The variables of union are declared as

Union tag variable 1;

 Declaration of union variables and union is similar to that of structure variables


and structures respectively.
 Accessing of members of union is done similar to that of structure it is done by
using dot ( .) operator for unions and using‟‟ for pointers to unions.

Uses of unions:

1. In general, the unions are used to give the memory area occupied by the
program.
2. Unions are used when all members need not exist in the memory at the same
time.

Write a simple program to demonstrate the use of unions.

#include<stdio.h>
#include<conio.h>
void main()
{
union student
{
int rollno;
char result;
};
union student st1,st2;
clrscr();
st1.rollno=234;
st2.result='F';

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 107


printf("\n Roll no:%d",st1.rollno);
printf("\n Result:%c",st2.result);
printf("\n Rollno:%d",st2.rollno);
printf("\n Result :%c",st1.result);
getch();
}

Output:
Roll no: 234
Result: F
Roll no: 26438
Result: $

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 108


UNIT-5
FILE I/O
Streams and File, File System Basics: File pointer, opening a file using fopen(), closing
a file, getc(), putc(), fclose(), feof(), fputs, fgets(), ferror(), fread(), fwrite(), fseek(),
Formatted Console I/O: fprintf, fscanf, the Preprocessor Directives: #define and
#include.

We frequently use files for storing information which can be processed by our
programs. Such files are called data files. In order to store information permanently and
retrieve it, we need to use data files. Our programs are also stored in files.

Def:

File is asset of records that can be accessed through the set of library functions
Or
A file is a place on disk where a group of related data is stored
It is advantageous to use files in the following.

 When large volumes of data are handled by the program.


 When the data need to be stored permanently without getting destroyed when
program is terminated.

Streams and files

Stream means reading and writing of data.

 The streams are designed to allow the user to access the files efficiently.
 A stream is file or physical device like keyboard, printer and monitor.

Data source

F
Input text stream Data
Keyboard

F Output text stream Data

monitor

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 109


Data destination
Files types

Files can be classified on the basis of the mode of access into two types.
1. Sequential files.
2. Random access files.
„C‟ supports both sequential and random files.

Sequential file
In this type, data are kept sequentially. If we want to read the last record of the
file we need to read all the records before that record. It takes time.
Random access files
In his type data can be read and modified randomly. In this type if we want o read
last records of the file, we can read if directly. It takes less time as compared to
sequential file.
File operations
There are three steps for file operations in „C‟.
1. Opening of file.
2. Reading or writing file.
3. Closing file.
A „C‟ language supports many more file handling functions that are available in standard
library.
File function Operation

fopen() Creates a new file for read/write operations.

fclose() Close a file associated with file pointer.

closeall() Closes all opened files with fopen().

fgetc() Reads a character from a file.

fputc() Writes a character to a file.

fprintf() Writes all types of data values to a file.

fscanf() Reads all types of data values from a file.

putw() Writes an integer to the file.

getw() Reads an integer from the file

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 110


feof() Detects the end of file.

fseek() Sets the pointer position anywhere in the file.

ferror() Reports error occurred while read/write operations.

Unlink() Removes the specified file from the disk.

Modes and operations in file

Mode Operations

„r‟ read Open for reading only

„w‟ write Creates a new file for writing or open an existing file for writing

„a‟ append Open for writing at the EOF.

r+ Open an existing file for reading and writing the file must exist.

w+ Open an empty file for reading and writing

a+ Open for reading and appending

Opening a file

A file has to be opened before beginning of read and write operations of file
creates a link between the operating system and the file functions.
We have to specify the name of file and its mode to the operating system.

FILE *fp;
Fp=fopen(“data.txt”,”r”);

Here fp is file pointer variable that contains address of the structure file that has
been defined in the header file “stdio.h”. The function fopen() will open a file “data.txt” in
read mode.

Write a program to write data to text file and read it.

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

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 111


FILE *fp;
char c=‟ „;
clrscr();
fp=fopen(“data.txt”,”w”);
if(fp==NULL)
{
printf (“\n Cannot open file”);
exit(1);
}
printf (“write data & to stop press ‟ .‟:\n”);
while (c!=‟.‟)
{
c=getche();
fput(c,fp);
}
fclose(fp);
printf(“\n Contents read :”);
fp=fopen(“data.txt”,”r”);
while(!feof(fp))
printf(“%c”,getc(fp));
}

Output:
Write data & to stop press „.‟

Sambasiva.

Contents read: Sambasiva.

Reading a file

Once the file is opened using fopen() its contents are loaded into the memory.
The fgetc() function is used to read the contents of the file.

Syntax: - for reading a file

ch=fgetc(fp);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 112


Closing a file

The file that is opened using fopen() should be closed after the work is over I,e
we need to close the file after reading and writing operation are over.

E.g.:- fclose(fp);

The following statement closes all the file associated with the file pointer fp.

E.g.:- fcloseall();
File I/o functions

fprintf() fgetc putw

fscanf() fputc getw

getc fgets

putc fputs

fprintf()

This function is used for writing characters strings integers float etc. to the
file.It contains one more parameter that is file pointer which points the opened file.

WAP by using printf() function.

# include<stdio.h>
void main()
{
file *fp;
char text(30);
fp=fopen (“text , fnt,””w”);
clrscr();
printf(“ enter text here:‟);
gets(text);
fprintf(fp ,“%s”,text);
fclose(fp);
}
Output:
Enter text here have a nice day.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 113


fscanf()

This function reads character, Strings integer, float etc. from the file pointed by
pile pointer.

WAP to enter data into the text file and read the same use‟w” file mode.

#include <stdio.h>
void main()
{
file *fp;
char text[5];
int age;
fp=fopen(“Text.txt”,”w+”);
clrscr();
printf(“Name \t ge \n”);
scanf(“%s %d”,text,&age);
fprintf(fp,”%s %d”,text,age);
printf(“Name \t age \n”);
fscanf(“fp,”%s %d”,text,&age);
printf(“%s \t %d\n”,text,age);
Fclose(fp);
}

Output:
Name Age
Rakhi 15
Name Age
Rakhi 15
getc()

This function reads single characters from the opened file and moves the
file pointer.It returns EOF,if end of the file is reached.

WAP to read the contents of the file using getc() function.

#include<stdio.h>
void main()
{
file *f;
char c;
clrscr();
f=fopen(*”list.txt”,”r”);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 114


if(f==NULL)
{
printf(“\n cannot open file”);
exit(1);
}
while((c=getc(f))!=EOF)
printf(“%c”,c);
fclose(f);
}
Output:
KICK
WANTED
ANIL

putc()
This function is used to write a single character into a file.if an error occurs
it returns EOF.

WAP to write some text into the file using putc.


#include<stdio.h>
void main()
{
int c;
FILE *fp;
clrscr();
printf(“\n Enter few words „*‟ to exist \n”);
fp=fopen(“words.doc”,”w”);
while((c=getchar())!=‟8‟)
putc(c,fp);
fclose(fp);
}
Output:
Enter the few words „*‟ to exist
This is saved into the file *.

fgetc()

This function is similar to getc() function.It also reads a character and


increases the file pointer position.If any error or end of file is reached it returns a EOF.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 115


WAP to read a „C‟ program file and count the following in the program
Total number of statements.
Total number of included files.
Total number of blocks and brackets.

#include<stdio.h>
void main ()
{
FILE *fs;
int i=0,x,y,c=0,sb=0,b=0;
clrscr();
fs=fopen(“prg2.c”,”r”);
if(s==NULL)
{
printf(“\n File opening error:”);
exit(1);
}
while((x=fgetc(fs))!=EOF)
{
switch(x)
{
case „;‟ :c++;
break;
case „{‟ : sb++;
break;
case „(„ : b++;
break;
case „#‟ : i++;
break;
}
}
fclose(fs);
printf(“\n Summary of C program \n”);
printf(“\n Total statements %d”,c+i);
printf(“\n Include statement:%d”,i);
printf(“\n Total blocks { }:%d”,sb);
printf(“\n Total brackets ():%d”,b);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 116


OUTPUT:
Total statements:25
Include statements:4
Total blocks{ }:5
Total brackets ( ):25

fputc()

This function writes the character to the file shown by the file pointer. It also
increases the file pointer.

Example:

#include<stdio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen(“list.txt”,”w”);
if(fp==NULL)
return;
else
{
while((c=getche())!=‟*‟)
fputc(c,fp);
}
fclose(fp);
}
OUTPUT:
India is my country

fgets()

This function reads string from a file pointed by file pointer. It also copies
the string to a memory location referred by an array.

Write a program to read text from the given file using fgets()
#include<stdio.h>
#include<conio.h>

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 117


void main()
{
FILE *fp;
char file[20],text[50];
int i=0;
printf(“Enter File name:”);
scanf(“%s”,file);
fp=fopen(file,”r”);
if(fp==NULL)
{
printf(“FILE is not found\n”);
return;
}
else
{
if(fgets(text,50,fp)!=NULL)
while(text[i]!=‟\0‟)
{
putchar(text[i]);
i++;
}
}
}
OUTPUT:
Enter file name:10.c
#include<stdio.h>

fputs()

This function is useful when we want to write a string into the opened.

Write a program to write a string into a file using fputs() function.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char file[12],text[50];
clrscr();
printf(“\n Enter the name of file:”);
scanf(“%s”,File);
V. SambaSiva., Assistant Professor, Department of CSE, CREC. 118
fp=fopen(file,”w”);

if(fp==NULL)
{
printf(“\n FILE cannot opened\n”);
return;
}
else
{
printf(“\n Enter text here:”);
scanf(“%s”,text);
fputs(text,fp);
}
fclose(fp);
}

OUTPUT:
Enter the name of file: data.dat
Enter the text here: Good morning.

getw()

This function returns the integer value from a file and increases the file pointer.

Example:

Write a program to read integers from the using getw() function

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
int v;
clrscr();
fp=fopen("num.txt","r");
if(fp==NULL)
{
printf("\n File does not exit");
exit(1);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 119


}
else
{
printf("\n Enter number");
while((v=getw(fp))!=EOF)
printf("%2d",v);
fclose(fp);
}
}

Output:

Enter number: 1 2 3

putw()

This function is used to write an integer value to file pointed by file pointer.

Write a program to enter integers and write them in the file using putw().

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
int v;
clrscr();
fp=fopen("num.txt","w");
if(fp==NULL)
{
printf("\n File does not exit");
exit(1);
}
else
{
printf("\nEnter number:");
while(1)
{
scanf("%d",&v);
if(v==0)
{
fclose(fp);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 120


exit(1);
}
putw(v,fp);
} }
}
Output:

Enter numbers: 5 6 7 3 9 0

The fseek () function

It is a file function. It positions file pointer on the stream. We can pass


three arguments through this function.

1. File pointer.
2. Negative or positive long integer number to reposition the
file pointer.
3. The current position of file pointer.

Integer value Constant Location in the file

0 Seek_Set Beginning of the file

1 Seek_Cur Current position of the file


point

2 Seek_End End of the file

E.g.: fseek (fp, 10, seek_set)

The file pointer is repositioned in the forward direction by 10 bytes.

Write a program to read the text file containing some sentence .use fseek() and
text after skipping n characters from beginning of the file

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
int n,ch;

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 121


clrscr();
fp=fopen("text.txt","r");
printf("\ncontents of a file\n");

while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
printf("\n How many characters including spaces would you like to skip?:");
scanf("%d",&n);
fseek(fp,n,SEEK_SET);
printf("\n information after %d bytes \n",n);
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}

Output:

Contents of a file
My name is khan
How many characters including spaces would you like to skip? :3

Name is khan

Structure read and writes functions

 It is important to know how numerical data is stored on the disk by fprintf()


function.
 Text and characters require one byte for storing them with fprintf().
 Similarly for storing numbers in memory two bytes and for floats four bytes are
required.
 All data types are treated as characters for example the data 3456,it occupies
two bytes in memory.
 But when it is transferred to the disk file using fprintf() function it would occupy
four bytes.
 Thus, large amount of integers or float data requires large space on the disk.
 The files should be read and written in binary mode for which we use functions
fread() & fwrite()

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 122


fwrite()

This function is used for writing an entire structure block to a given file.

fread()

This function is used for reading an entire block from a given file.

Write a program to write and read the information about the player containing
players name, age and runs

#include<stdio.h>
#include<conio.h>
#include<process.h>
struct record
{
char player[20];
int age;
int runs;
};
void main()
{
FILE *fp;
struct record emp;
fp=fopen("record.dat","w");
if(fp==NULL)
{
printf("\ncan not open the file");
exit(1);
}
clrscr();
printf("Enter player name,age &runs scored\n");
printf("===================================\n");
scanf("%s %d %d",emp.player,&emp.age,&emp.runs);
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
if((fp=fopen("record.dat","r"))==NULL)
{
printf("\n Error on openingfile");
exit(1);
}
printf("\nrecord entered is\n");

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 123


fread(&emp,sizeof(emp),1,fp);
printf("\n %s %d %d",emp.player,emp.age,emp.runs);
fclose(fp);
}
Output:

Enter player name, age & runs scored


===================================

Sachin 25 10000
Record entered is
Sachin 25 10000

feof()
The macro feof() is used for detecting file pointer whether it is at the end of the
file or not. It returns non-zero if the file pointer is at the end of the otherwise it returns
zero.

Write a program to detect the end of file using function feof().Display the file
pointer position for detecting end of file .

#include<conio.h>
#include<stdio.h>

void main()
{
FILE *fp;
char c;
fp=fopen("text.txt","r");
c=feof(fp);
clrscr();
printf("File pointer at the beginning of the file :%d\n",c);
while(!feof(fp))
{
printf("%c",c);
c=getc(fp);
}
c=feof(fp);
printf("File pointer at the end of the file %d",c);

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 124


}
Output:

File pointer at the beginning of the file


World cup winner India
File pointer at the end of the file: 22
C Preprocessor Directives

The C preprocessor is a macro preprocessor (allows you to define macros) that


transforms your program before it is compiled. These transformations can be inclusion
of header file, macro expansions etc.
All preprocessing directives begins with a # symbol. For example,

#define PI 3.14

Some of the common uses of C preprocessor are:


Include header
files

Define Macros

Conditional
Compilation

Diagnostics

Line Control

Pragmas

Other Directives

Preprocessor
Output

Including Header Files

The #include preprocessor is used to include header files to a C program. For example,

#include <stdio.h>

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 125


Here, "stdio.h" is a header file. The #include preprocessor directive replaces the above
line with the contents of stdio.h header file which contains function and macro
definitions.
That's the reason why you need to use #include <stdio.h> before you can use functions
like scanf() and printf().
You can also create your own header file containing function declaration and include it
in your program using this preprocessor directive.

#include "my_header.h"

Macros using #define

You can define a macro in C using #define preprocessor directive.


A macro is a fragment of code that is given a name. You can use that fragment of code
in your program by using the name. For example,

#define c 299792458 // speed of light

Here, when we use c in our program, it's replaced by 3.1415.

Example 1: Using #define preprocessor

#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%d", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
You can also define macros that works like a function call, known as function-like
macros. For example,

#define circleArea(r) (3.1415*r*r)

Every time the program encounters circleArea(argument), it is replaced


by (3.1415*(argument)*(argument)).
Suppose, we passed 5 as an argument then, it expands as below:

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 126


circleArea(5) expands to (3.1415*5*5)

Example 2: Using #define preprocessor

#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)

int main()
{
int radius;
float area;

printf("Enter the radius: ");


scanf("%d", &radius);
area = circleArea(radius);
printf("Area = %.2f", area);

return 0;
}

Conditional Compilation

In C programming, you can instruct preprocessor whether to include certain chuck of


code or not. To do so, conditional directives can be used.
It's similar like a if statement. However, there is a big difference you need to understand.
The if statement is tested during the execution time to check whether a block of code
should be executed or not whereas, the conditionals is used to include (or skip) certain
chucks of code in your program before execution.

Uses of Conditional

 use different code depending on the machine, operating system


 compile same source file in two different programs
 to exclude certain code from the program but to keep it as reference for future
purpose

How to use conditional?

To use conditional, #ifdef, #if, #defined, #else and #elseif directives are used.

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 127


#ifdef Directive

#ifdef MACRO
conditional codes
#endif

Here, the conditional codes are included in the program only if MACRO is defined.
#if, #elif and #else Directive

#if expression
conditional codes
#endif

Here, expression is a expression of integer type (can be integers, characters, arithmetic


expression, macros and so on). The conditional codes are included in the program only
if the expression is evaluated to a non-zero value.
The optional #else directive can used with #if directive.

#if expression
conditional codes if expression is non-zero
#else
conditional if expression is 0
#endif

You can also add nested conditional to your #if...#else using #elif

#if expression
conditional codes if expression is non-zero
#elif expression1
conditional codes if expression is non-zero
#elif expression2
conditional codes if expression is non-zero
... .. ...
else
conditional if all expressions are 0
#endif

#defined
The special operator #defined is used to test whether certain macro is defined or not.
It's often used with #if directive.

#if defined BUFFER_SIZE && BUFFER_SIZE >= 2048


conditional codes

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 128


Predefined Macros

There are some predefined macros which are readily for use in C programming.

Predefined macro Value

__DATE__ String containing the current date

__FILE__ String containing the file name

__LINE__ Integer representing the current line number

__STDC__ If follows ANSI standard C, then value is a nonzero integer

__TIME__ String containing the current date.

Example #3: predefined Macros

C Program to find the current time


#include <stdio.h>
int main()
{
printf("Current time: %s",__TIME__); //calculate the current time
}
Output

Current time: 19:54:39

V. SambaSiva., Assistant Professor, Department of CSE, CREC. 129

You might also like