Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 117

1

INDEX
S.NO TOPIC PAGE NO
PREFACE 5
1.1 INTRODUCTION TO C PROGRAMMING 6
1.1.2 CHARACTERISTICS OF PROGRAMMING LANGUAGE
1.2 HISTORY OF ‘C’ LANGUAGE: 6
1.2.1 FEATURES OF ‘C’. 7
1.2.2 APPLICATION OF C PROGRAMMING/ USES OF C PROGRAMMING 7
GENERATIONS AND CLASSIFICATION OF PROGRAMMING 7
1.3
LANGUAGE
1.3.1 PROGRAMMING LANGUAGE CAN BE CLASSIFIED INTO 5 TYPES. 8
1.3.1.1 MACHINE LANGUAGE : 1ST GENERATION LANGUAGE(1GL) 8
1.3.1.2 ASSEMBLY LANGUAGE : 2ND GENERATION LANGUAGE(2GL) 8
1.3.1.3 HIGH LEVEL LANGUAGES : 3RD GENERATION LANGUAGE(3GL) 8
1.3.1.4 FOURTH GENERATION LANGUAGES : 4GL 8
1.3.1.5 FIFTH GENERATION LANGUAGES : 5GL 9
DEVELOPING A PROGRAM IN "C": EXECUTION PROCESS 9
1.4
OF C PROGRAM
1.4.1 IMPORTANT POINTS 11
1.4.2 DIFFERENCE BETWEEN COMPILER AND INTERPRETER 12
1.5 COMMENTS IN C PROGRAMMING 12
1.6 ALGORITHMS AND FLOWCHART 13
1.6.1 ALGORITHMS 14
1.6.2 FLOWCHART 14
PROGRAMMING EXPLANATION / UNDERSTANDING THE 16
1.7
PROGRAM
1.8 STRUCTURE OF C PROGRAM: 17
1.9 PROGRAMMING RULES 19
1.10 CHARACTER SET : 20
1.11 C TOKENS 20
1.11.1 IDENTIFIERS 21
1.11.2 KEYWORDS 21
1.11.3 CONSTANTS 22
1.11.4 STRING CONSTANT 23
1.11.5 VARIABLES 23
1.11.6 DATA TYPES: 24
2

1.11.7 OPERATORS 26
1.12 EXPRESSIONS 33
1.12.1 OPERATOR PRECEDENCE AND ASSOCIATIVITY IN C 34
1.13 TYPE CONVERSION: 36
1.13.1 1. IMPLICIT TYPE CONVERSION 37
1.13.2 2. EXPLICIT TYPE CONVERSION 37
1.14 C – LIBRARY FUNCTIONS 38
1.15 C PREPROCESSOR DIRECTIVES: 39
1.16 TYPES OF ERRORS ; 39
ESCAPE CHARACTERS OR BACKSLASH CHARACTERS OR 42
1.17
ESCAPE SEQUENCES :
2.1.1 FORMATTED INPUT/OUTPUT FUNCTIONS 42
2.1.2 UNFORMATTED INPUT/OUTPUT FUNCTIONS 43
2.2 CONTROL STATEMENTS IN C LANGUAGE 43
2.2.1 DECISION STATEMENTS / SELECTION STATEMENTS 44
2.2.2 IF STATEMENT IN C: 44
2.2.3 SWITCH STATEMENT IN C 48
LOOPING STATEMENTS/ REPETITION STATEMENTS / 49
2.3
LOOPS
2.3.1 . WHILE LOOP: 50
2.3.2 FOR LOOP: 50
2.3.3 DO-WHILE LOOP: 51
2.4 BREAK AND CONTINUE STATEMENTS: 52
2.5 GOTO STATEMENT: 53
2.6 NESTING OF LOOPS 53
2.7 FUNCTIONS 56
2.7.2 ADVANTAGES OF USER DEFINED FUNCTIONS : 56
THE FUNCTIONS CAN BE CLASSIFIED INTO TWO CATEGORIES. OR 56
2.7.3
TYPES OF FUNCTIONS
2.7.3.1 BUILT-IN FUNCTIONS (OR) LIBRARY FUNCTIONS : 56
2.7.3.2 USER DEFINED FUNCTIONS : 56
2.7.4 ELEMENTS OF USER-DEFINED FUNCTIONS : 57
2.7.5 PARAMETERS : 59
2.7.6 FUNCTION VARIABLES : 60
2.7.7 CATEGORY OF FUNCTIONS / TYPES OF USER DEFINED FUNCTIONS : 61
2.8 RECURSION 64
2.8.1 RECURSION LIMITATIONS : 65
2.8.2 ADVANTAGES OF RECURSION 65
3

2.9 ARRAYS 65
2.9.1 DECLARATION OF AN ARRAY / DEFINING AN ARRAY 66
2.9.2 INITIALIZING ARRAYS : 66
2.9.3 ONE – DIMENSIONAL ARRAYS:- 67
2.9.4 TWO - DIMENSIONAL ARRAYS:- 68
2.9.5 TWO DIMENSIONAL ARRAYS OR MULTI DIMMESIONAL ARRAY 69
3.1 STRINGS: OR CHARACTER ARRAYS 71
3.1.1 DECLARATION OF STRINGS:- 71
3.1.2 INITIALIZATION OF STRINGS 71
3.1.3 READING STRINGS: 71
3.1.4 WRITING OR PRINTING OF STRINGS TO SCREEN:- 72
STRING HANDLING FUNCTIONS:- OR STRING 72
3.2
MANIPULATION FUNCTIONS OR STRING.H FUNCTIONS
3.3 POINTERS AND STRINGS: OR CHARACTER POINTER 75
3.4 ARRAYS OF STRINGS: 76
3.5 STRING INPUT OUTPUT FUNCTIONS: 76
UNFORMATED I/O FUNCTIONS 80
3.6
BUILT IN FUNCTIONS :
3.7 MATH.H 80
3.8 DATE FUNCTIONS IN C 81
3.9 POINTERS: 82
3.9.1 INTRODUCTION 82
3.9.2 USES OF POINTERS : 82
DECLARATION AND INITIALIZATION OF POINTER 82
3.10
VARIABLES:-
3.11 POINTER EXPRESSIONS OR POINTER ARITHMETIC 84
3.12 POINTER TO POINTER 85
3.13 POINTERS TO FUNCTIONS: 86
VOID POINTER ( OR ) GENERAL PURPOSE POINTER (OR) 88
3.14
GENERIC POINTER OR POINTERS TO VOID
MEMORY ALLOCATION FUNCTIONS OR DYNAMIC 89
3.15
MEMORY ALLOCATIONS (DMA)
4.0 USER DEFINED DATA TYPES STRUCTURES & FILES 93
4.1 USER DEFINED DATA TYPES : 93
4.1.1 DEFINITION OF STRUCTURES : 94
4.1.2 DECLARATION OF STRUCTURES : 95
4.1.3 INITILIZATION OF STRUCTURES : 95
4

4.1.4 ACCESSING STRUCTURES : 96


ARRAY OF STRUCTURES OR STRUCTURE AND ARRAYS 97
4.2
AND STRUCTURE CONTAINING ARRAYS
4.3 TYPEDEF 99
4.4 ENUMERATED TYPES : AN ENUMERATED DATA TYPE 99
4.5 UNION : 100
4.6.1 DECLARATION OF UNION : 103
4.6.2 DIFFERENCE BETWEEN STRUCTURE AND UNION 104
4.7 COMMAND LINE ARGUMENT
4.8 FILE MANAGEMENT IN C 105
4.8.1 TYPES OF FILES 105
4.8.2 WHY USE FILE HANDLING IN C ( USES OF FILES) 106
4.8.3 HOW TO ACHIEVE FILE HANDLING 106
4.8.4 WORKING WITH FILES 107
4.8.5 CLOSING A FILE 107
4.9 FILE I/O FUNCTIONS :- 108
FILE HANDLING FUNCTIONS IN ‘C’ LIBRARY / FILE 108
4.10
MANAGEMENT OR MANIPULATION FUNCTIONS IN C
4.11 FILE OF RECORDS: 109
RANDOM ACCESS TO FILES (OR) POSITIONING 112
4.12
FUNCTIONS IN C:-
5

PREFACE

C language is a simple and beautiful programming language that is a choice of a


rapidly increasing number of programmers. By learning C language, we can learn all the
high level programming languages such as Java, Python, etc very easily.

To understand C Programming basics, this book is designed in a simple easy


language.

This book is organized which includes theory as well as programs for each topic.

I have put my best efforts in preparing this book, but if any errors or mistakes and
if any topic has been skipped out, please let me know your suggestions through email
provided below.

My special thanks to proof reader and co-author for helping me out.

Wish you all Happy Learning……

Proof reader / co-author Author


Mr. M. Dayakar M.Tech Mr. D.Praneeth (Ph.D)
Assistant Professor Associate Professor
dayakarmudugula@gmail.com praneeth040@gmail.com

1.1 Introduction to C Programming


6

C Programming Language is a very popular computer programming language through


which users and computers can communicate.

In simple terms program is a set of instructions, software is a collection of programs.

What is C?

C is a computer programming language used to design computer software and


applications.

Why do we use C?

We use the C programming language to design computer software and applications.

1.1.2 Characteristics of programming language

a) The language must allow the programmer to write simple, clear and concise
programs.
b) The language must be simple to use so that a programmer can learn it without any
explicit training.
c) The language must be platform independent. That is, the program developed using
the programming language can run on any computer system.
d) The Graphical User Interface (GUI) of the language must be attractive, user-
friendly, and self-explanatory.
e) The programs developed in the language must make efficient use of memory as
well as other computer resources.

1.2 History of ‘C’ Language:


Definition: C is a general-purpose high-level structured programming language. ‘C’ is
one of the most popular programming language, it was developed by Dennis Ritchie at
AT & T’s Bell Laboratories at USA in 1972.
It is an upgraded version of two earlier languages, called BCPL and B, which were also
developed at Bell laboratories.

1.2.1 Features of ‘C’.


7

1. ‘C’ is a general purpose, structured programming language.


2. ‘C’ is powerful, efficient, compact and flexible.
3. ‘C’ is highly portable. This means that C programs written for one computer can be run
on another with little or no modification. Portability is important if we plan to use a
new computer with a different operating system.
4. ‘C’ language allows reference to a memory allocation with the help of pointers, which
holds the address of the memory location.
5. ‘C’ language allows dynamic memory allocation i.e, a program can request the
operating system to allocate or release memory at runtime.
6.‘C’ programs are fast and efficient.
7. ‘C’ has a set of operators.
8. ‘C’ can be applied in systems programming areas like Compilers, Interpreters and
Assemblers.

1.2.2 Application of C Programming/ USES of C programming

a) C language is used for creating computer applications 


b) Used in writing Embedded software’s
c) Firmware for various electronics, industrial and communications products which
use micro-controllers.
d) It is also used in developing verification software, test code, simulators etc. for
various applications and hardware products.
e) For Creating Compiles of different Languages which can take input from other
language and convert it into lower level machine dependent language.
f) C is used to implement different Operating System Operations.
g) UNIX kernel is completely developed in C Language.

1.3 Generations and classification of Programming Languages:


Programming Language : A programming language is use to develop software
programs, scripts, or other sets of instructions for computers to execute.

Programming language can be classified into 5 types.


8

1 : Machine Language : 1st generation language(1GL)

The language which uses all instructions and data should be written using binary codes 1
and 0 . The binary code is called machine code or machine language. Computers do not
understand English, Hindi and Tamil. They respond only to machine language. each
computer has its own machine language.

Disadvantages : 1 : It id difficult to understand and remember the various combinations


of 1’s and 0’s representing data and instructions.

2 . Assembly Language : 2nd generation language(2GL)

1. The assembly language also referred to as the second generation language(2GL)


and also called as Low level language.
2. The assembly language the 0’s and 1’s of machine language are replaced with
abbreviations or mnemonic code.
3. An assembly language instruction consist of a mnemonic code . The mnemonic
code is called operation code or opcode.
Ex : mnemonic codes are LOAD, ADD, SUB, STORE, AND

3. High level languages : 3rd generation language(3GL)

High level languages are like C , C++ are easier to use, and more portable across
platforms , as compared to low-level language.
Examples of high level languages: C, C++, Java etc

4. Fourth Generation Languages : 4GL


9

The languages of this generation were considered as very high-level programming


languages.
These are languages that consist of statements that are similar to statements in the human
language. These are used mainly in database programming and scripting. Example of
these languages include Perl, Python, Ruby, SQL, MatLab(MatrixLaboratory).

5. Fifth Generation Languages : 5GL

The programming languages of this generation mainly focus on constraint programming.


The major fields in which the fifth-generation programming language are employed are
Artificial Intelligence and Artificial Neural Networks

1.4 Developing a Program in "C": Execution process of c program

Software used to create and execute a C Program

Following are the applications and software used to create and execute C programs.

 Turbo C
 Turbo C++
 GNU C
 Code Blocks
 Net Beans

To create and execute C programs in the Windows Operating System, we need to install
Turbo C software.

STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:

Below are the steps to be followed for any C program to create and get the output. This is
common to all C program and there is no exception whether its a very small C program
or very large C program.

1. Create
2. Compile
3. Execute or Run
4. Get the Output
Step 1: Creating a Source Code
10

Source code is a file with C programming instructions in a high-level language. To create


source code, we use any text editor to write the program instructions.
The following steps are used to create a source code file in Windows OS…

Click on the Start button


Select Run
Type cmd and press Enter
Type cd c:\TC\bin in the command prompt and press Enter
Type TC press Enter
Click on File -> New in C Editor window
Type the program
Save it as FileName.c (Use shortcut key F2 to save)

Step 2: Compile Source Code (Alt + F9)


The compilation is the process of converting high-level language instructions into low-
level language instructions. We use the shortcut key Alt + F9 to compile a C program in
Turbo C.

Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On
receiving a source file, the compiler first checks for the Errors. If there are any Errors
then compiler returns List of Errors, if there are no errors then the source code is
converted into object code and stores it as a file with .obj extension. Then the object code
is given to the Linker. The Linker combines both the object code and specified header file
code and generates an Executable file with a .exe extension.

Step 3: Executing / Running Executable File (Ctrl + F9)


After completing compilation successfully, an executable file is created with a .exe
extension. The processor can understand this .exe file content so that it can perform the
task specified in the source file.

We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the
.exe file is submitted to the CPU. On receiving .exe file, CPU performs the task
according to the instruction written in the file. The result generated from the execution is
placed in a window called User Screen.

Step 4: Check Result (Alt + F5)


After running the program, the result is placed into User Screen. Just we need to open the
User Screen to check the result of the program execution. We use the shortcut key Alt +
F5 to open the User Screen and check the result.
Overall Process
11

 Type the program in C editor and save with .c extension (Press F2 to save).
 Press Alt + F9 to compile the program.
 If there are errors, correct the errors and recompile the program.
 If there are no errors, then press Ctrl + F9 to execute/run the program.
 Press Alt + F5 to open User Screen and check the result.

1.4.1 Important Points

 C program file (Source file) must save with .c extension.


 The compiler converts complete program at a time from high-level language to
low-level language.
 Input to the compiler is .c file and output from the compiler is .exe file, but it also
generates .obj file in this process.
 The compiler converts the file only if there are no errors in the source code.
 CPU places the result in User Screen window.

 Editor
This program is used for Writing the Source Code, the first thing that any
programmer writing a program in any language would be doing.

 Pre-Processer
There are certain special instructions within the source code identified by the #
symbol that are carried on by a special program called a preprocessor.

 Compiler: A compiler is a computer program which is used to convert the high-


level language programs into machine language.
12

 Assembler: It is a program which is used to convert the assembly level language


programs into machine language

 Interpreter: It is a program, it takes one statement of a high-level language


program, translates it into machine language instruction and then immediately
executes the resulting machine language instruction and so on.

 Linker: Linker is a computer program that links and merges various object files/
header files together in order to make an executable file. All these files might have
been compiled by separate assembler.

 Loader: Loader is a part of operating system and is responsible for loading


executable files into memory and execute them.

 It calculates the size of a program (instructions and data) and create memory space
for it. It initializes various registers to initiate execution.

1.4.2 Difference between Compiler and Interpreter

COMPILER INTERPRETER
A Compiler is used to compile an entire An interpreter is used to translate each
program and an executable program is line of the program code immediately as
generated through the object program it is entered
The executable program is stored in a The executable program is generated in
disk for future use or to run it in another RAM and the interpreter is required for
computer each run of the program
The compiled programs run faster The Interpreted programs run slower
Most of the Languages use compiler A very few languages use interpreters.

1.5 Comments in C programming:


Generally Comments are used to provide the description about the Logic written in
program. Comments are not display on output screen.

When we are used the comments, then that specific part will be ignored by compiler.

In 'C' language two types of comments are possible


13

 Single line comments


 Multiple line comments

Single line comments


Single line comments begin with // double forward slash character. Characters
following // is treated as comment and is not executed by the compiler.

Ex: //---------

Multi-line comments

Multi-line comments are used to add a detailed description about the code. It begins
with /* character and ends with */. Characters between /* */ are treated as comments.

Multi-line comments can span upto multiple lines. In addition, you can use multi-line
comments for both single as well as multiple line commenting.

ex: /* --------
--------
-------- */

1.6 Algorithms and Flowchart

1.6.1 Algorithms :

Algorithm is a method of representing the step-by-step procedure for solving a problem.


An algorithm is very useful for finding the correct answer to a simple problem or a
diffcult problem by breaking the problem into simple cases.

Characteristics of Algorithms :

1 : Each and every instruction(step) should be precise .


2 : The algorithm should not be repeated infinitely..
3 : Ensure that the algorithm will ultimately terminate.
4 : The algorithm should be written in sequence.
5 : The desired result should be obtained only after the algorithm terminates.

Examples for Algorithm:


14

1. Write an algorithm to add two numbers entered by user.

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

2. Write an algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

1.6.2 Flowchart:

The pictorial representation of algorithm is called flowchart or diagrammatical


representation of a program/ algorithm

Uses of flow chart:

1 : flow chart helps to understand the program easily.


2 : as different symbols are used to specify the type of operation performed, it is easier to
understand the complex programs with the help of flowcharts.

Flowchart Symbols
15

S.N Description Symbols


O
Flowlines : These are the left to right
or top to bottom lines connection
1
symbols. These lines shows the flow
of control through the program.
Terminal Symbol : The oval shaped Start
symbol always begins and ends the
End
2 flowchart. Every flow chart starting
and ending symbol is terminal
symbol.
Input / Output symbol : The
parallelogram is used for both input
(Read) and Output (Write) is called
3
I/O symbol. This symbol is used to
denote any function of an I/O device
in the program.
Process Symbol : The rectangle
symbol is called process symbol. It is
4
used for calculations and
initialization/ declaration
Decision symbol : The diamond
shaped symbol is called decision
symbol. This box is used for decision
5
making. There will be always two
exists from a decision symbol one is
labeled YES and other labeled NO.
Connectors : The connector symbol is
represented by a circle. Whenever a
complex flowchart is morethan one
6
page, in such a situation, the
connector symbols are used to
connect the flowchart.
16

Examples for flowchart :

Draw a flowchart to add two numbers


entered by user.
Draw flowchart to find the largest among
three different numbers entered by user.

1.7 Programming explanation / understanding the program

Let us look at a simple code that would print the words "Hello World" −

#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0; }

 The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
17

 The next line int main() is the main function where the program execution begins.

 The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.

 The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.

 The next line return 0; terminates the main() function and returns the value 0.

1.8 STRUCTURE OF C PROGRAM:

Every ‘C’ program may contain one or more sections given below.

1 : Documentation section : It consist of a set of comment lines giving the name of the
program, the author and other details etc. Documentation section is a optional section.
18

Comments : means are very helpful in identifying the program features and underlaying
logic of the program. The lines begins with ‘/*’ and ending with ‘*/’ are known as
comment lines. These are not executable, the compiler is ignored any thing in between /*
and */.
// for single line comment

2 : Linker section : is also called preprocessor section. It provides instructions to the


compiler to link functions from the system library.
Ex : #include<stdio.h> ( standared input output header file ).
#include<conio.h> ( console input output header file )

3 : Definition section : This section defines all symbolic constants.

Ex : #define PI 3.14

4 : Global Declaration : There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all the
user-defined functions.

5 : main() function : Every C program must have one main(0 function. This section
contains two parts.

a : Declaration part b : Executable part.

a : Declaration part : This part is used to declare all the variables that are used in
the executable part of the program and these are called local variables.

b : Executable part : It contains atleast one valid ‘C’ statement. The execution of
a program begins with opening brace ‘{‘ and ends with closing brace ‘}’. The
closing brace of the main() function is the logical end of the program.
All the statements in the program ends with a semicolon except conditional and
control statements.

6 : Sub Program section : This contains all the user defined functions that are called in
the main() function. User defined functions are generally placed immediately after the
main() function.

1.9 Programming Rules :


19

The following rules should follow while writing a ‘C’ program.

1. All statements in ‘C’ program should be written in lower case letters. Upper case
letters are only used for symbolic constants.
2. The program statement can write anywhere between the two braces following the
declaration part.
3. The user can also write one or more statements in one line separating them with a
semicolon.
4. Blank spaces are not used while declaring a variable, keyword, constant, and
function.
5. every statement in c language should end with semi colon
6. every c program should have one main function.

Symbolic Constants : The constants which will be used no of places in a program can be
defined using define statement.

The general format of define statement is

Syntax : #define symbolic-name constant-value

Ex : #define PI 3.142
#define HUNDRED 100

Rules for defining a symbolic constant :

1 : #sign must be the first character in the line.


2 : No blank spaces between #sign and define word.
3 : A blank space is required between the #define and symbolic-name and between the
symbolic-name and a constant value.
4 : There is no semicolon at the end of #define statement.
5 : The Symbolic name should not be assigned any other value with the program.
6 : Symbolic names have the same form as variable
7: Symbolic names are written in CAPITALS to distinguish them from normal variables

1.10 CHARACTER SET :


20

The C character set consist of upper and lowel case alphabets, digits, special characters
and white spaces. The alphabets and digits are together called the alphanumeric
characters.

1. Alphabets :

ABCDEF...................XYZ
abcdef......................xyz

2. Digits : 0 1 2 3 4 5 6 7 8 9

3. Special characers :

, comma < opening angle bracket > closing angle bracket


. period _ under score ( left parenthesis
; semicolon $ dollar sign ) right parenthesis
: colon % percent sing [ left bracket
# number sign ? question mark ] right bracket
‘ apostrophe & ampersand { left brace
“ quotation mark ^ caret } right brace
! exclamation mark * asterisk / slash
| vertical bar - minus sign \ backslash
~ tilde + plus sign

4. White space characters :

Blank space, Horizontal tab, Vertical tab, Newline, Formfeed

1.11 C TOKENS :

The smallest individual units are known as tokens. C has six types of tokens.

1 : Identifiers
2 : Keywords
3 : Constants
4 : Strings
5 : Variables
6: Data types
7 : Operators.
21

1.11.1: Identifiers : Identifiers refer to the names of variables, functions and arrays.
These are user-defined names is called Identifiers.

Rules :
1 : Identifier names must be a sequence of letters and digits.
2 : The first character must be a letter/character or may begin with underscore ( _ ).
3 : The underscore character ( ‘ _ ‘) is considered a letter.
4 : Both upper/lower cases are permitted although uppercase character is not equilent
to corresponding lowercase character.
5 : ‘C’ compiler recognizes only the first 31 characters of an identifiers.
6 : No space and special symbols are allowed between the identifier.
7 : Identifier cannot be a keyword.

Ex : Valid Invalid
STDNAME Return
SUB $stay
TOT_MARKS 1RECORD
_TEMP STD NAME.
Y2K

1.11.2: Keywords : All keywords have fixed that means cannot be changed. Keywords
serve as basic building blocks for program statements. All keywords must be written in
lowercase.The ‘C’ keywords are listed below.

auto break case char


const continue default do
double enum else extern
float for goto if
int long return register
signed short static sizeof
struct switch typedef union
unsigned void volatile while

1.11.3: Constants : Constants refer to fixed values that do not change during the
execution of a program.
22

C supports several kinds of constants.


CONSTANTS

Numeric Constants Character Constants

Integer Constants Real Constants SingleCharacter Constants String Constants

1. Integer Constants : An integer constants can be specified in 3 ways

1 : Decimal Integer
2 : Octal
3 : Hexadecimal

 Decimal Integer : the rules for represent decimal integer.

Decimal Integer value which consist of digits from 0-9.

Ex : 777 -77

 Octal : An integer constants with base 8 is called octal. These rules are :

it consist of digits from 0 to 7.

 Hexadecimal : An integer constant with base value 16 is called


Hexadecimal.

It consist of digits from 0-9,a-f(capital letters & small leters.)

2. Real Constants : Real constant is base 10 number, which is represented in decimal 0r


scientific/exponential notation.
23

Real Notation : The real notation is represented by an integer followed by a


decimal point and the fractional(decimal) part. It is possible to omit digits before or
after the decimal point.

Ex : 15.25

3. Single Character Constant : A character constant is either a single alphabet, a single


digit, a single special symbol enclosed within single inverted commas.

a) it is value represent in ‘ ‘ (single quote).


b) The maximam length of a character constant can be 1 character.
EX : VALID
‘a’
‘A’
1.11.4.String constant : A string constant is a sequence of characters enclosed in double
quote, the characters may be letters, numbers, special characters and blank space etc

EX : “rama” , “a” , “+123” , “1-/a” .

Escape characters or backslash characters or Escape sequences :

a) \n newline
b) \r carriage return
c) \t tab
d) \v vertical tab
e) \b backspace
f) \f form feed (page feed)
g) \a alert (beep)
h) \’ single quote(‘)
i) \” double quote(“)
j) \? Question mark (?)
k) \\ backslash (\)

1.11.5. Variables : A variable is a memory location used to store any date value.
Variable is also called as an identifier

Variable Rules : / Identifier rules

1 : A variable name can be any combination of alphabets, digits or underscore.


24

2 : The first character must be an alphabet or underscore ( ‘-‘ ).


3 : Variables cannot be a keyword.
4 : The length of the variable cannot exceed upto 8 characters. And some of the ‘C’
compilers can be recognized upto 31 characters.
5 : Uppercase and lowercase are significant. That is the variable Total is not the same as
total or TOTAL.

Ex Mark StudentName class_mark name1

Declaration of Variables :

The declaration of variables must be done before they are used in the program. The
general format for declaring a variable.

Syntax : data_type variable-1,variable-2,------, variable-n;

Variables are separated by commas and declaration statement ends with a


semicolon.

Ex : int x,y,z;
float a,b;
char m,n;

Assigning values to variables :

values can be assigned to variables using the assignment operator (=). The general
format statement is :

Syntax : variable = constant;

Ex : x=100;

1.11.6.Data Types:

Datatype is used to specify what type of data can be stores in a variable. C Data Types
are used to:

 Identify the type of a variable when it declared.


 Identify the type of the return value of a function.
25

 Identify the type of a parameter expected by a function.

1. Primary(Built-in) Data Types: int, char, double and float.


2. Derived Data Types: Array and Pointers.
3. User Defined Data Types: Structure, Union, and Enumeration

Primary data types:

1. int: Used to denote an integer type.


2. char: Used to denote a character type.
3. float: double: Used to denote a floating point type.

 Derived data types:

Arrays : Arrays are sequences of data items having homogeneous values. They
have adjacent memory locations to store values.
Pointers : These are powerful C features which are used to access the memory and deal
with their addresses.

 User Defined Data Types:

Structure: It is a package of variables of different types under a single name. This is


done to handle data efficiently. "struct" keyword is used to define a structure.
26

Union: These allow storing various data types in the same memory location.
Programmers can define a union with different members, but only a single member can
contain a value at a given time.

Enum: Enumeration is a special data type that consists of integral constants, and
each of them is assigned with a specific name. "enum" keyword is used to define the
enumerated data type.

Size and Ranges of Data Types with Type Qualifiers


Format
Type Size (bytes) Range specifier or
control string
char or signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
int or signed int 2 -32768 to 32767 %d or %i
unsigned int 2 0 to 65535 %u
short int or signed 1 -128 to 127 %d or %i
short int
unsigned short int 1 0 to 255 %d or %i
long int or signed 4 -2147483648 to %ld
long int 2147483647
unsigned long int 4 0 to 4294967295 %lu
float 4 3.4E-38 to 3.4E+38 %f or %g
double 8 1.7E-308 to 1.7E+308 %lf
long double 10 3.4E-4932 to 1.1E+4932 %Lf

1.11.7.Operators : An operator is a Symbol used to perform a specific task.

Operators are used in C language program to operate on data and variables. C has a rich
set of operators which can be classified as

Types of Operators :

1) Arithmetic Operators.
2) Relational Operators.
3) Logical Operators.
4) Assignment Operators.
27

5) Bitwise Operators.
6). Unary Operators. Increment and decrement
7) Conditional Operators. Terinary
8) Special Operators.

1) Arithmetic Operators : The arithmetic operators perform arithmetic operations


Basic arithmetic operators are: +, -, *, /, %

Example #1: Arithmetic Operators example program


#include <stdio.h>
void main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b; }
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c); Output
c=a%b; a+b = 13
printf("Remainder when a divided by b = a-b = 5
%d ",c); a*b = 36
getch(); a/b = 2
28

Remainder when a divided by b=1


2) Relational Operators : Relational Operators are used to compare two or more
operands. Operands may be variables, constants or expressions.
We have six relational operators in C: >, <, >=, <=,==, !=

Relational Operators example program

#include <stdio.h>
void main()
{
int a = 15, b = 5, result;
clrscr();
result = (a < b);
printf("result is %d \n", result);
result = (a >b);
printf("result is %d \n", result);
result = (a >=b) ;
printf("result is %d \n", result);
result = (a <=b) ;
printf("result is %d \n", result);
result = (a==b) ;
printf("result is %d \n", result);
result = (a != b);
printf("result is %d \n", result);
getch();
}
29

3) Logical Operators :
These operators are used to combine the results of two or more conditions. ‘C’ has
the following logical operators. The symbols are :

Operator Meaning Example Return value


&& Logical (9>2)&&(17>2) 1
AND
|| Logical OR (9>2) || (17 = = 1
7)
! Logical 29!=29 0
NOT

C Program to demonstrate the working of logical operators

#include <stdio.h>
Void main()
{
int a = 15, b = 5, c = 10, result;
result = (a < b) && (c > b);
printf("result is %d \n", result);
result = (a >b) && (c < b);
printf("result is %d \n", result);
result = (a >b) || (c < b);
printf("result is %d \n", result);
result = (a != b) || (c < b);
printf("result is %d \n", result);
result = !(a != b);
printf("result is %d \n", result);
}

4 ) Assignment Operator :
Assignment operators are used to assign a value (or) an expression (or) a value of a
variable to another variable.

Syntax : variable name=expression (or) value


30

Ex : x=10;
y=20;

Compound assignment operator : ‘C’ provides compound assignment operators to assign


a value to variable in order to assign a new value to a variable after performing a
specified operation.

Operator Example Meaning


+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y X=x%y

// C Program to demonstrate the working of assignment operators

#include <stdio.h>
void main()
{
int a = 5, c; c %= a; // c = c%a
c = a; printf("c = %d \n", c);
printf("c = %d \n", c); }
c += a; // c = c+a
printf("c = %d \n", c); Output
c -= a; // c = c-a c=5
printf("c = %d \n", c); c = 10
c *= a; // c = c*a c=5
printf("c = %d \n", c); c = 25
c /= a; // c = c/a c=5
printf("c = %d \n", c); c=0

5 ) Increment and Decrement Operator (Unary Operators) :


The increment and decrement operators are very useful in ‘C’ language.They are
extensively used in for and while loop.

The syntax of the operators is given below.

++<variable name> --<variable name>


<variable name>++ <variable name>--
31

The operator ++ adds 1 to the operand and – subtracts 1 from the operand. These
operators in two forms : prefix (++x) and postfix(x++).

Operator Meaning
++x Pre increment
- -x Pre
decrement
x++ Post
increment
x-- Post
decrement

Where

1 : ++x : Pre increment, first increment and then do the operation.


2 : - -x : Pre decrement, first decrements and then do the operation.
3 : x++ : Post increment, first do the operation and then increment.
4 : x- - : Post decrement, first do the operation and then decrement.

// C Program to demonstrate the working of increment and decrement operators


#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a); Output
printf("--b = %d \n", --b); ++a = 11
printf("++c = %f \n", ++c); --b = 99
printf("--d = %f \n", --d); ++c = 11.500000
return 0; ++d = 99.500000
}

6 ) Conditional (or) Ternary Operator : Conditional operator checks the condition and
executes the statement depending of the condition. Conditional operator consist of two
symbols.

1 : question mark (?).


2 : colon ( : ).
32

Syntax : condition ? exp1 : exp2;

It first evaluate the condition, if it is true (non-zero) then the “exp1” is


evaluated, if the condition is false (zero) then the “exp2” is evaluated.

Conditional Operator example program

#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
}

7 ) Special Operators :

i. Comma Operator :The comma operator is used to separate the statement elements
such as variables, constants or expressions
Ex: int a,b

ii) Sizeof Operator : The sizeof() is a unary operator, that returns the length in bytes o
the specified variable, and it is very useful to find the bytes occupied by the specified
variable in the memory.

Syntax : sizeof(variable-name);

int a;
Ex : sizeof(a); //OUTPUT-----2bytes

iii ) Pointer Operators :

& : This symbol specifies the address of the variable.


* : This symbol specifies the value of the variable.

Example : sizeof Operator

#include<stdio.h>
33

int main() {
printf("%d", sizeof(int));
printf("%d", sizeof(char));
printf("%d", sizeof(float));
return 0;
}

8) Bitwise Operators :

Bitwise operator s are used to manipulate the data at bit level. It operates on integers
only. It may not be applied to float.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement.

Example 8 : Bitwise :

#include <stdio.h>
Void main()
{
Int a,b,c;
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
c = a & b; /* 12 = 0000 1100 */
printf("Value of c is %d\n", c ); c = a >> 2; /* 15 = 0000 1111 */
c = a | b; /* 61 = 0011 1101 */ printf("Value of c is %d\n", c );
printf("Value of c is %d\n", c ); }
c = a ^ b; /* 49 = 0011 0001 */
printf("Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Value of c is %d\n", c ); Output:
c = a << 2; /* 240 = 1111 0000 */
printf("Value of c is %d\n", c ); Value of c is 12
34

Value of c is 61 Value of c is 240


Value of c is 49 Value of c is 15
Value of c is -61

1.12 EXPRESSIONS:

An expression is a collection of operators and operands that represents a specific value

In C programming language, expressions are divided into THREE types. They are as
follows...

1. Infix Expression 2. Postfix Expression 3..Prefix Expression

Infix Expression
The expression in which operator is used between operands is called as infix expression.
The infix expression has the following general structure...

Postfix Expression
The expression in which operator is used after operands is called as postfix expression.
The postfix expression has the following general structure...

Prefix Expression
The expression in which operator is used before operands is called as prefix expression.
The prefix expression has the following general structure...

1.12.1 Operator Precedence and Associativity in C

What is Operator Precedence?

Operator precedence is used to determine the order of operators evaluated in an


expression. In c programming language every operator has precedence (priority). When
there is more than one operator in an expression the operator with higher precedence is
evaluated first and the operator with least precedence is evaluated last.
35

What is Operator Associativity?

Operator associativity is used to determine the order of operators with equal precedence
evaluated in an expression. In c programming language, when an expression contains
multiple operators with equal precedence, we use associativity to determine the order of
evaluation of those operators.

In c programming language the operator precedence and associativity is as shown in the


following table...

Precedence Operator Operator Meaning Associativity


() function call
[] array reference
1 Left to Right
-> structure member access
. structure member access
! negation
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
2 Right to Left
-- decrement operator
& address of operator
* pointer
sizeof returns size of a variable
(type) type conversion
* multiplication
3 / division Left to Right
% remainder
+ addition
4 Left to Right
- subtraction
<< left shift
5 Left to Right
>> right shift
< less than
<= less than or equal to
6 Left to Right
> greater than
>= greater than or equal to
== equal to
7 Left to Right
!= not equal to
36

8 & bitwise AND Left to Right


9 ^ bitwise EXCLUSIVE OR Left to Right
10 | bitwise OR Left to Right
11 && logical AND Left to Right
12 || logical OR Left to Right
13 ?: conditional operator Left to Right
= assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign additon
14 -= assign subtraction Right to Left
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift
15 , Separator Left to Right

In the above table, the operator precedence decrease from top to bottom and increase
from bottom to top.

Expression Evaluation in C

An expression is evaluated based on the precedence and associativity of the operators in


that expression.

To understand expression evaluation in c, let us consider the following simple example


expression...

10 + 4 * 3 / 2

In the above expression there are three operators +, * and /. Among these three operators,
both multiplication and division have same higher precedence and addition has lower
precedence. So, according to the operator precedence both multiplication and division are
evaluated first and then addition is evaluated. As multiplication and division have same
precedence they are evaluated based on the associativity. Here, the associativity of
multiplication and division is left to right. So, multiplication is performed first, then
37

division and finally addition. So, the above expression is evaluated in the order of * / and
+. It is evaluated as follows...

4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.

1.13 Type Conversion:


The type conversion process in C is basically converting one type of data type to other
type

1. Implicit Type Conversion

2. Explicit Type Conversion

1. Implicit Type Conversion

This type of conversion is usually performed by the compiler when necessary without
any commands by the user. Thus it is also called "Automatic Type Conversion".

1. Implicit Type Conversion example

When the type conversion is performed automatically by the compiler without


programmers intervention, such type of conversion is known as implicit type conversion
or type promotion.
int x;
for(x=97; x<=122; x++)
{
printf("%c", x); /*Implicit casting from int to char thanks to %c*/
}
38

2. Explicit Type Conversion

The type conversion performed by the programmer by posing the data type of the
expression of specific type is known as explicit type conversion. The explicit type
conversion is also known as type casting.

Type casting in c is done in the following form:


(data_type)expression;

#include <stdio.h>
#include <conio.h> printf("Result = %d\n", result);
void main() getch();
{ }
float x = 24.5, y = 7.2;
int result; Output
clrscr();
result = (int) x / (int) y; Result = 3

In the above code (int) x converts the value 24.5 into 24 and (int) y converts the value
7.2 into 7 so, we get 24/7 i.e.,
3 as result because result is of type int and hence the decimal part is truncated

1.14 C – Library functions

 Library functions in C language are inbuilt functions which are grouped


together and placed in a common place called library.
 Each library function in C performs specific operation.
 We can make use of these library functions to get the pre-defined output
instead of writing our own code to get those outputs.
 These library functions are created by the persons who designed and created
C compilers.
 All C standard library functions are declared in many header files which are
saved as file_name.h.
 Actually, function declaration, definition for macros are given in all header
files.
39

 We are including these header files in our C program using


“#include<file_name.h>” command to make use of the functions those are
declared in the header files.
 When we include header files in our C program using
“#include<filename.h>” command, all C code of the header files are included
in C program. Then, this C program is compiled by compiler and executed.

Header file Description


This is standard input/output header file in which
stdio.h
Input/Output functions are declared
conio.h This is console input/output header file
string.h All string related functions are defined in this header file
This header file contains general functions used in C
stdlib.h
programs
math.h All maths related functions are defined in this header file
This header file contains time and clock related
time.h
functions
All character handling functions are defined in this
ctype.h
header file

1.15 C PREPROCESSOR DIRECTIVES:


 Before a C program is compiled in a compiler, source code is processed by a
program called preprocessor. This process is called preprocessing.

 Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.
Below is the list of preprocessor directives that C programming language offers.

Mainly 3 preprocessor are there :

 Macro
 Header file inclusion
 Conditional
40

Preprocessor Description
Syntax: #define
Macro This macro defines constant value and can be any of the basic
data types.
Syntax: #include <file_name>
Headerfile
The source code of the file “file_name” is included in the
inclusion
main program at the specified place.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Conditional
Set of commands are included or excluded in source program
compilation
before compilation with respect to the condition.

1.16 Types of Errors ;


In C or C++, we face different kinds of errors. These errors can be categorized into five
different types. These are like below −

 Syntax Error
 Run-Time Error
 Linker Error
 Logical Error
 Semantic Error

Let us see these errors one by one −


Syntax error
This kind of errors are occurred, when it violates the rule of C++ writing techniques or
syntaxes. This kind of errors are generally indicated by the compiler before compilation.
Sometimes these are known as compile time error.
In the below example, we will see how to get syntax error if we do not put semicolon
after one line.
Example
#include<stdio.h>
main() {
printf("Hello World")
}
Output
Error.... expected ';' before '}' token

Runtime error
41

This kind of errors are occurred, when the program is executing. As this is not
compilation error, so the compilation will be successfully done. We can check this error
if we try to divide a number with 0.
Example
#include<stdio.h>
main() {
int x = 52;
int y = 0;
printf("Div : %f", x/y);
}
Output
Program crashes during runtime. since division is not possible

Linker error
This kind of errors are occurred, when the program is compiled successfully, and trying
to link the different object file with the main object file. When this error is occurred, the
executable is not generated, For example some wrong function prototyping, incorrect
header file etc. If the main() is written as Main(), this will generate linked error.
Example
#include<stdio.h>
main() {
int x = 52;
int y = 0;
printf("Div : %f", x/y);
}
Output : C:\crossdev\src\mingw-w64-v3-git\mingw-w64-crt\crt\crt0_c.cundefined
reference to `WinMain'
Logical error
Sometimes, we may not get the desired output. If the syntax and other things are correct,
then also, we may not get correct output due to some logical issues. These are called the
logical error. Sometimes, we put a semicolon after a loop, that is syntactically correct, but
will create one blank loop. In that case, it will show desired output.

Example
#include<stdio.h>
main() {
int i;
for(i = 0; i<5; i++);
{
printf("Hello World");
42

}
}

Output
Here we want the line will be printed five times. But only one time it will be printed for
the block of code.

Semantic error
This kind of error occurs when it is syntactically correct but has no meaning. This is like
grammatical mistakes. If some expression is given at the left side of assignment operator,
this may generate semantic error.

Example
#include<stdio.h>

main() {
int x, y, z;
x = 10;
y = 20;
x + y = z;
}

Output
[Error] lvalue required as left operand of assignment

1.17 Escape characters or backslash characters or Escape sequences :


a) \n newline
b) \r carriage return
c) \t tab
d) \v vertical tab
e) \b backspace
f) \f form feed (page feed)
g) \a alert (beep)
h) \’ single quote(‘)
43

i) \” double quote(“)
j) \? Question mark (?)
k) \\ backslash (\)

2.1.1 Formatted input/output functions


Formatted console input/output functions are used to take one or more inputs from the
user at console and it also allows us to display one or multiple values in the output to the
user at the console.

Functions Description
This function is used to read one or multiple inputs
scanf()
from the user at the console.
This function is used to display one or
printf() multiple values in the output to the user at the
console.
This function is used to read the characters from a
sscanf()
string and stores them in variables.
This function is used to read the values stored in
sprintf() different variables and store these values in a
character array.

Why these functions are called  formatted  console input/output functions?

While calling any of the formatted console input/output functions, we must use a


specific format specifiers in them, which allow us to read or display any value of a
specific primitive data type. Let's see what are these format specifiers.

a) %d for integer (decimal) b) %c for character


C) %f for floating point d) %s for string

2.1.2Unformatted input/output functions

Unformatted console input/output functions are used to read a single input from the user
at console and it also allows us to display the value in the output to the user at the
console.
44

Some of the most important formatted console input/output functions are -

Functions Description
Reads a single character from the user at the
getch()
console, without echoing it.
Reads a single character from the user at the console, and
getche()
echoing it.
Reads a single character from the user at the console, and
getchar() echoing it, but needs an Enter key to be pressed at the
end.

gets() Reads a single string entered by the user at the console.

puts() Displays a single string's value at the console.


putch() Displays a single character value at the console.
putchar() Displays a single character value at the console.

2.2 Control statemetns in C language


Control statements enable us to specify the flow of program control; ie, the order in
which the instructions in a program must be executed. They make it possible to make
decisions, to perform tasks repeatedly or to jump from one section of code to another.

Below figure 2 shows types of control statements in C:


45

Figure 2 Control Statements in c

2.2.1. DECISION STATEMENTS / SELECTION STATEMENTS:

Decision making statements are the statements that are used to verify a given
condition and decides whether a block of statements gets executed or not based on the
condition result.
In c programming language, there are two decision making statements they are as
follows...
1. if statement
2. switch statement

2.2.2 if statement in c:

In c, if statement is used to make decisions based on a condition. The if statement


verifies the given condition and decides whether a block of statements are executed or not
based on the condition result. In c, if statement is classified into four types as follows...

1) Simple if statement
2) if - else statement
3) Nested if statement
46

4) if-else-if statement (if-else ladder)

Simple if statement

Simple if statement is used to verify the given condition and executes the block of
statements based on the condition result. The simple if statement evaluates specified
condition. If it is TRUE, it executes the next statement or block of statements. If the
condition is FALSE, it skips the execution of the next statement or block of statements.
The general syntax and execution flow of the simple if statement is as follows...

Simple if statement is used when we have only one option that is executed or skipped
based on a condition.

#include <stdio.h>
#include<conio.h>
void main()
{
int n ; clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;

if ( n> 0 ) }
printf("Given number is natural
number ") ; O/P: Enter any integer number: 4
getch(); Given number is natural number
47

if - else statement

The if - else statement is used to verify the given condition and executes only one out of
the two blocks of statements based on the condition result. The if-else statement evaluates
the specified condition. If it is TRUE, it executes a block of statements (True block). If
the condition is FALSE, it executes another block of statements (False block). The
general syntax and execution flow of the if-else statement is as follows...

The if-else statement is used when we have two options and only one option has to be
executed based on a condition result (TRUE or FALSE).

Example Program | Test whether given number is even or odd.

#include <stdio.h>
#include<conio.h>
void main(){
int year ;
clrscr() ;
printf("Enter year: ") ;
scanf("%d", &year) ;
if ( year%4 == 0 ) }
printf("Given year is leap year\n") ; Output :
else
printf("Given year is not leap Enter year: 2017
year\n") ; Given year is not leap year
48

Nested if statement

Writing a if statement inside another if statement is called nested if statement. The


general syntax of the nested if statement is as follows..

Like the name indicate, nested else if contains if statement inside an if statement. If we
want to check a condition even a condition is hold, then we use nested if.

Let us see with an example:

  
#include <stdio.h> Output :
#include <stdlib.h>
int main()
{ Largest is 30
     int n1 = 30,n2 = 20 ,n3 = 10;        Here n1(30) is greater than n2(20), so
     if(n1 > n2) again check with the value of n3(10).
     { Then decided a decision( printf("Largest
       if(n1>n3) is %d",n1); )
         {
           printf("Largest is %d",n1);
         }
      }
}
49

if - else - if statement (if-else ladder)

Writing a if statement inside else of a if statement is called if - else - if statement. The


general syntax of the if-else-if statement is as follows...

Example Program | Find the largest of three numbers.

#include <stdio.h> printf("%d is the largest number",


#include<conio.h> b) ;
void main() { else if(c>a && c>b)
int a, b, c ; clrscr() ; printf("%d is the largest number", c)
printf("Enter any three integer ;
numbers: ") ; }
scanf("%d%d%d", &a, &b, &c) ; Output :
if( a>b && a>c)
printf("%d is the largest number", a) Enter any three integer numbers: 55 60
; 20
else if (b>a && b>c) 60 is the largest number

2.2.3 Switch statement in C

Using switch statement, one can select only one option from more number of options
very easily. In switch statement, we provide a value that is to be compared with a value
associated with each option. Whenever the given value matches with the value associated
with an option, the execution starts from that option. In switch statement every option is
defined as a case.
50

The switch statement contains one or more number of cases and each case has a value
associated with it. At first switch statement compares the first case value with the
switchValue, if it gets matched the execution starts from the first case. If it doesn't match
the switch statement compares the second case value with the switchValue and if it is
matched the execution starts from the second case. This process continues until it finds a
match. If no case value matches with the switchValue specified in the switch statement,
then a special case called default is executed.

When a case value matches with the switchValue, the execution starts from that particular
case. This execution flow continues with next case statements also. To avoid this, we use
"break" statement at the end of each case. That means the break statement is used to
terminate the switch statement. However it is optional.

Syntax Switch program example :


#include<stdio.h> #include
Switch(expression) <conio.h>
{ int main() {
case 1: int nmbr;
block 1; printf("Enter a number: ");
break; scanf("%d",&nmbr) ;
case 2: switch(nmbr)
block 2; {
break; case 1: printf("One");
case 3: break;
block 3; case 2: printf("Two");
break; break;
…………………… case 3: printf("Three");
…………………… break;
default: default: printf("Number is not 1,2
} or 3");
}
getch(); }

2.3 Looping Statements/ Repetition statements / Loops


51

Loops provide a way to repeat a set of statements and control how many times they are
repeated.

C supports three looping statements.

They are while, do-while and for.

Both while and for statements are called as entry-controlled loops because they evaluate
the expression and based on the value of the expression they transfer the control of the
program to a particular set of statements.

Do-while is an example of exit-controlled loop as the body of the loop will be executed
once and then the expression is evaluated.

Loops are used to repeat a block of code.

2.3.1 While loop:

This is an entry controlled looping statement. It is used to repeat a block of statements


until the expression / condition becomes satisfied. Also called as Pre test loop.
Syntax: While Loop example program:
#include <stdio.h>
while(expression/condition) void main()
{ {
statements; int x = 0;
increment/decrement; while ( x <= 10 )
} {
printf( "%d\n", x );
x++;
}
getch();
}
o/p: 0 1 2 3 4 5 6 7 8 9 10

2.3.2 for loop:


52

 This is an entry controlled looping statement.


 In this loop structure, more than one variable can be initialized.
 One of the most important features of this loop is that the three actions can be
taken at a time like variable initialization, condition checking and
increment/decrement.
 The for loop can be more concise and flexible than that of while and do-while
loops.
Syntax:
for(initialization; test-condition; increment/decrement)
{
statements;
}

In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the loop and executes the block of statements associated with it. At the end of
loop increment or decrement is done to change in variable value. This process continues
until test condition satisfies
For loop example program:
#include <stdio.h>
Void main()
{
int x;
for ( x = 0; x < =10; x++ )
{
printf( "%d\n", x );
}
getch();
}
o/p: 0 1 2 3 4 5 6 7 8 9 10

2.3.3 Do-While loop:


 This is an exit controlled looping statement. Also called as Pre test loop
 Sometimes, there is need to execute a block of statements first then to check
condition. At that time such type of a loop is used. In this, block of statements are
executed first and then condition is checked.
Syntax:
53

do
{
statements;
(increment/decrement);
} while (expression/condition);

 In above syntax, the first the block of statements are executed.


 At the end of loop, while statement is executed. If the expression is evaluated to
nonzero value then program control goes to evaluate the body of a loop once again.
 This process continues till expression evaluates to a zero. When it evaluates to
zero, then the loop terminates.

Do while example program:


#include <stdio.h>
void main()
{
int x; x =1;
do
{
printf( "%d\n", x );
x++;
}
while ( x <= 10 );
getch();
}
o/p : 0 1 2 3 4 5 6 7 8 9 10

2.4 Break and continue statements:


BREAK statement is used to terminate any type of loop such as while loop, do while
loop and for loop. C break statement terminates the loop body immediately and passes
control to the next statement after the loop.

Break program example:


54

#include<stdio.h> if(i==5)
#include<conio.h> break;
void main() { }
int i;clrscr(); getch();
for(i=1; i<=100; i++) }
{ o/p: 1 2 3 4 5
printf("%d\t,i");
CONTINUE
Continue is a keyword . the continue statement is used to skip over the rest of the
current iteration. After continue statement, the control returns to the top of the loop.

#include<stdio.h> #include<conio.h>
void main() {
int i; clrscr();
for(i=1; i<=10; i++)
{
if(i==5)
continue;
printf("%d",i);
}
getch();
}
o/p: 1 2 3 4 6 7 8 9 10
Example program for Continue :
2.5 Goto statement:
A goto statement is used to branch (transfer control) to another location in a program.

Syntax:
55

The label can be any valid identifier name and it should be included in the program
followed by a colon.
Example program

Output :
Hello World
Hope you are fine

Note : Break, continue ad goto statements are also called as jumping statements.

2.6 Nesting of Loops


A loop inside another loop is called nesting of loops. There can be any number of loops
inside one another with any of the three combinations depending on the complexity of the
given problem. Let us have a look at the different combinations.

Syntax :

outer_loop
{
inner_loop
{
// Inner loop statement/s
}

// Outer loop statement/s


}

Nested for loop


for(initialization; condition; update)
56

{
// statements

for(initialization; condition; update)


{
// Inner loop statements
}

// statements
}

Nested while loop


while(condition)
{
// statements

while(condition)
{
// Inner loop statements
}

// statements
}
Nested do...while loop
do
{
// statements

do
{
// Inner loop statements
}
while(condition);

// statements
}

Example:
Print number 1 to 10, 5 times
57

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

C code

#include <stdio.h>
int main()
{
int i; //for outer loop counter
int j; //for inner loop counter

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


{
for( j=1; j<=10; j++)
{
printf("%d ",j);
}
printf("\n");
}
}

Points to remember for nested loops:

1. Till the inner loop condition fails the control iterates inside the inner loop, when
inner loop condition fails the control moves to the outer loop
2. When ever the control is moving from outer loop to inner loop the value

2.7.1 FUNCTIONS

2.7.1 Functions
58

Function means, a large program can be divided into a series of individual related
programs called modules. These modules are called functions.
function is set of program to perform some specific and well defined tasks.

2.7.2 Advantages of User Defined Functions:

a) Reusability: The function writes once and use many times is called Reusability.
b) Modular Program Approach: A large program is divided into smaller sub
programs. so that each sub program performs a specific task. This approach makes
the program development more manageable.
c) Efficiency: means by avoiding redundant instructions the size of program can be
reduced. Which increase efficiency of program.
d) Function sharing: A function can be shared by many programmers.
e) It is very easy to identify the logical errors and correct.
f) It is very easy to read and understand.

2.7.3 The functions can be classified into two categories. Or types of functions

1 : Built in Functions (OR) Library Functions or Predefined


functions
2 : User-defined Functions.

1 : Built-in Functions (OR) Library Functions :


The standard C library is a collection of various types of functions which perform some
standared and predefined tasks. These function which part of the C compiler that have
been written for general purpose are called library functions. They are also called built-in
functions.
Examples :
1 : The function sqrt() is used for to find square root of a given number.
2 : The function scanf() is used to read data from the keyboard.
3 : The function printf() is used to print the result on the display.
59

Advantages :
1 : The programmer’s job is made easier because the functions are already available.
2 : The library functions can be used whenever required.

Disadvantages : The standared library functions are limited, programmes can not
completely on these library functions. The programmer has to write his own programs.

2 : User Defined Functions : These functions which are written by the programmer to
do some specific tasks are called User Defined Functions.

2.7.4 ELEMENTS OF USER-DEFINED FUNCTINS : In order to write an efficient


user defined function, the programmer must familiar with the following three elements.
1 : Function Declaration. (Function Prototype).
2 : Function Call.
3 : Function Definition

1 : Function Declaration (Function Prototype) : Like variable, all functions in a C


program must be declared, before they are invoked(call). The declaration of each function
should end with semicolon. Ths is called function prototype or function declaration.
The function declaration/prototype tells the compiler about the return type, the
name of the function and type of parameters which will be called and defined later in the
program.

Syntax : type function-name(parameter list);


type function-name();

Ex : int add(int a,int b);


int add();
Where
type : is the return type of function.
function-name : is the name of the function.
parameter-list : Parameter list declares the variables that will receive the data sent by
the calling program.
60

2 : Function Call : The function can be called by simply using the function name.

Syntax : function-name();
function-name(parameters);
return value = function-name(parameters);

Ex : add(); // function without arguments


add(a,b); // function with arguments.
c=fun(a,b); // function with arguments and return values

3 : Function Definition : The program module that is written to achieve a specific task is
called function definition.

Syntax : type function-name(parameter list) // function header.


{
declaration of variables;
body of function; // Function body
return statement;
}
Where
type : return type can be int ,float,double,void etc. This is the type of the value that the
function is expected to return. If the function is not returning any value, then we need to
specify the return types as void.
function-name : is the name of the function.
parameter-list : Parameter list declares the variables that will receive the data sent by the
calling program.
Example of User Defined Function :

#include<stdio.h> {
void add(); //function int a,b,c;
declaration/prototype printf(“Enter the values of a and b”);
void main() scanf(“%d%d”,&a,&b);
{ c=a+b;
add(); //Function call printf(“the sum is %d”,c);
} }
void add() // function definition
61

Output : 5
5
Enter the values of a and b the sum is 10

How to Execute the program.


1 : Execution of the program starts from main().
2 : The function add() is invoked.
3 : Control is transferred from function main() to function add().
4 : The function add() accepts two numbers, adds those numbers and print the result.
5 : Then control is transferrd from function add() to function main().
6 : in the function main(), there is no other function/ statement to be executed and hence
execution of the function main() is terminated.

2.7.5 PARAMETERS : parameters provides the data communication between the


calling function and called function.
They are two types of parametes 1 : Actual parameters. 2 : Formal
parameters.
1 : Actual Parameters : These are the parameters transferred from the calling
function (main program) to the called function (function).
2 : Formal Parameters :These are the parameters transferred into the calling function
(main program) from the called function(function).

Ex : main()
{
fun1( a , b ); //Calling function / main fun
}
fun1( x, y ) //called function / user def fun
{
..... .
}
Where
a, b are the Actual Parameters
62

x, y are the Formal Parameters

Difference between Actual Parameters and Formal Parameters

Actual Parameters Formal Parameters


1 : Actual parameters are used in 1 : Formal parameters are used in the
calling function when a function is function header of a called function.
invoked. Ex : int add(int m,int n);
Ex : c=add(a,b); Here m,n are called formal
Here a,b are actual parameters. parameters.
2 : Actual parameters can be 2 : Formal parametes should be only
constants, variables or expression. variable. Expression and constants
Ex : c=add(a,b) //variable are not allowed.
c=add(a+5,b); //expression. Ex : int add(int m,n);
c=add(10,20); //constants. //CORRECT
int add(int m+n,int n)
//WRONG
int add(int m,10);
//WRONG
3 : Actual parameters sends values to 3 : Formal parametes receive values
the formal parameters. from the actual parametes.
Ex : c=add(4,5); Ex : int add(int m,int n);
Here m will have the value 4 and n
will have the value 5.
4 : Address of actual parameters can 4 : if formal parameters contains
be sent to formal parameters address, they should be declared as
pointers.

2.7.6 FUNCTION VARIABLES : They are two types of variables.

1 : Local Variable. 2 : Global Variable.

1 : Local Variable : The local variables are defined within the body of the function or
block. These variables can access by that function only, other functions can not access
these ariables.

Ex : fun1(int a,int b)
{
int c,d; // Here c and d are the Local variable
63

}
2 : Global Variable : Global variables are defined outside the main() function and
multiple functions can use these variables.

Ex : int m=5, n=10; //Global Variable


main()
{
int a,b;
}
Here the variables ‘m’ and ‘n’ are defined outside the main() function. Hence they are
global variables.

Return Statement : The return statement may or may not send back any values to the
calling function(main program).
Syntax : return; // does not return any value
or
return(exp); // the specified exp value to calling function.
A function can contain more than one return statements, when the return value can return
values based on certain condition.
If a function can return some values other than int type, then we must specify the
data type to be return.

2.7.7 CATEGORY OF FUNCTIONS / TYPES OF USER DEFINED


FUNCTIONS : A function, depending on whether arguments are present or not and
whether a value is returned or not. The following are the function prototypes.
1 : Functions with no Parameters and no Return Values.
2 : Functions with no Parameters and Return Values.
3 : Functions with Parameters and no Return Values.
4 : Functions with Parameters and Return Values.

1 : Functions with no Parameters and no Return Values :

1) In this category, there is no data transfer between the calling function and called
function.
2) But there is flow of control from calling function to the called function.
3) When no parameters are there , the function cannot receive any value from the calling
function.
64

4) When the function does not return a value, the calling function cannot receive any
value from the called function.

Ex #include<stdio.h> printf("enter the values of a and b");


#include<conio.h> scanf("%d%d",&a,&b);
void sum(); c=a+b;
void main() printf("sum=%d",c);
{ }
sum(); Output :
getch(); Enter the values of a and b
}
void sum() 5
{ 5
int a,b,c; sum= 10

2 : Functions with no Parameters and Return Values.

1) In this category, there is no data transfer between the calling function and called
function.
2) But there is data transfer from called function to the calling function.
3) When no parameters are there , the function cannot receive any values from the
calling function.
4) When the function returns a value, the calling function receives one value from the
called function.

Ex : #include<stdio.h> int sum()


#include<conio.h> {
int sum(); int a,b,c;
int main()
{
int c;
clrscr(); printf("enter the values of
c=sum(); a and b”);
printf("sum=%d",c); scanf("%d
} %d",&a,&b);
c=a+b;
return c;
65

} 5
5
Output : sum= 10
enter the values of a and b

3 : Functions with Parameters and no Return Values.

1) In this category, there is data transfer from the calling function to the called function
using parameters.
2) But there is no data transfer from called function to the calling function.
3) When parameters are there , the function can receive any values from the calling
function.
4) When the function does not return a value, the calling function cannot receive any
value from the called function.

Ex : #include<stdio.h> }
#include<conio.h>
void sum(int a,int b); void sum(int a,int b)
void main()
{ {
int m,n; int c;
clrscr(); c=a+b;
printf("Enter m and n printf("sum=%d",c);
values:"); }
scanf("%d Output :
%d",&m,&n); Enter the values of a and b
sum(m,n); 5
getch(); 5
sum= 10

4 : Functions with Parameters and Return Values.

1) In this category, there is data transfer from the calling function to the called function
using parameters.
2) But there is no data transfer from called function to the calling function.
66

3) When parameters are there, the function can receive any values from the calling
function.
4) When the function returns a value, the calling function receives a value from the
called function.

Ex : getch();
#include<stdio.h> }
#include<conio.h> int sum(int a,int b)
int sum(int a,int b); {
void main() int c;
{ c=a+b;
int m,n,c; return c;
clrscr(); }
printf("Enter m and n
values"); Output :
scanf("%d%d",&m,&n);
c=sum(m,n); Enter the values of a and b
5
printf("sum=%d",c); 5
sum= 10

2.8 Recursion
A function that calls itself is known as a recursive function. And, this technique is known
as recursion.

Syntax : Recursion is the process of repeating items in a self-similar way. In


programming languages, if a program allows you to call a function inside the same
function, then it is called a recursive call of the function.

void main()
{
recursion();
}

void recursion()
67

{
recursion(); /* function calls itself */
}

The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number

Example program on recursion to find factorial of a given number using recursion:

#include<stdio.h>
int factorial(int); getch();
int main() }
{ int factorial(n)
int factorial(int n); {
int fact; int fact;
clrscr(); if(n==1)
printf(“enter the number”); return 1;
scanf(“%d”,&n); else
fact=factoria(n); fact=n*factorial(n-1);
printf("factorial of a given number is return fact;
%d",fact); }
O/P: Enter the number 5 : factorial of a given number is 120

2.8.1 Recursion Limitations :

Whenever we are using recursive functions in our programming there are some
limitations
1) The recursive functions may involve extensive overhead because they use function
calls repeatedly.
2) Whenever we make a call we need to use some separate memory allocations
3) If the program has a large number of recursive calls then we need to run the
program may be out of memory.

2.8.2 Advantages of recursion


68

1. Using recursion, the length of the program can be reduced.


2. The recursion is very flexible in data structure like stacks, queues, linked list and
quick sort.
3. Using recursion we can avoid unnecessary calling of functions.
4. Recursion is used to divide the problem into same problem of subtypes and hence
replaces complex nesting code.
5. Through Recursion one can solve problems in easy way while its iterative solution
is very big and complex.

Disadvantages (Limitations) of recursion

1. It requires extra storage space. The recursive calls and automatic variables are
stored on the stack. For every recursive calls separate memory is allocated to
automatic variables with the same name.
2. Too many recursive functions there may be confusion in the code.
3. The recursion function is not efficient in execution speed and time.
4. Recursive solution is always logical and it is very difficult to trace. (Debug and
understand). Recursion takes a lot of stack space.

2.9 ARRAYS
Definition:
C supports a derived data type known as array that can be used to handle large
amounts of data (multiple values) at a time.
 An array is a collection of elements of the same data type, which share a common
name.
 Array elements are always stored in contiguous memory locations.
 Each element in the group is referred by its position called index.
 The first element in the array is numbered 0, so the last element is one less than the
size of the array.
 Before using an array its type and dimension must be declared, so that the compiler
will know what kind of an array and how large an array.

2.9.1 Declaration of an Array / Defining an array


Arrays must be declared before they can be used in the program. Standard array
declaration is as:
Datatype variable_name[lengthofarray];
Here type specifies the variable type of the element which is going to be stored in the
array.
69

Ex: int height[10];


float width[20];

2.9.2 Initializing Arrays :


The following is an example which declares and initializes an array of nine elements of
type int. Array can also be initialized after declaration.
int scores[9]={23,45,12,67,95,45,56,34,83};

We have different types of arrays based on its dimension.


1. One-dimensional arrays / Single-dimensional arrays
2. Two-dimensional arrays / Double-dimensional arrays
3. Multi-dimensional arrays

2.9.3 One – Dimensional arrays:-

A list of items can be given one variable name using only one subscript and such a
variable is called one-dimensional array or single-dimensional variable.

Syntax: The general form of array declaration is:

datatype array-name[size];

The data-type specifies the type of elements such as int, float or char. And the size
indicates the maximum number of elements that can be stored in that array.
Eg:
int a[5] ; here a is an array containing 5 integer elements.
float height[10]; here height is array containing 10 real elements.
70

char name[20]; here name is an array containing 20 characters.

Note: C language character strings are as simple as array of characters. And every string
should be terminated by null character (‘\0’).

Initialization of one-dimensional arrays:-

After an array is declared its elements must be initialized. Otherwise they will
contain garbage values. An array can be initialized at either of the following stages.
At compile time
At run time

Compile time initialization:-

We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared. The values in the list must and should be separated by comma.

i.e data-type array-name [ size ] = { list of values };

Eg:

 int a [ 6 ] = { 3, 5, 23, 28, 6, 11 }; will initialize the given values to array a.

2.9.4 Two - Dimensional Arrays:-

C allows us to define the data in the form of table of items by using two-
dimensional arrays.

Syntax: syntax to declare two dimensional array


data-type array-name [ row size ] [ column size ];

Eg: int a [ 3] [ 4 ] ; Here a is two dimensional array with row size 3 and column
size 4., and the total elements we can store in this array a is 12 (i.e. 3 * 4 ).

Each dimension of the array is indexed from zero to its maximum size minus one;
the first index selects the row and the second index selects the column with in that row.
Two dimensional arrays are stored in memory as follows:
71

Eg:

[0] [0] [0][1] [0][2] [0][3]

[1] [0] [1][1] [1][2] [1][3]

[2][0] [2][1] [2][2] [2][3]

******Representation of two dimensional array in memory******

Example program on 1 dimmensional array


Accessing an array elements
#include<stdio.h>
void main()
{
int i;
int arr[3] = {12, 3, 34}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
O/P : 12 3 34
Read and write an array or Runtime Array initialization
An array can also be initialized at runtime using scanf() function.
Example:

#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
72

{
printf("%d\n", arr[j]);
}
}

2.9.5 Two dimensional Arrays or multi dimmesional array


C language supports multidimensional arrays also. The simplest form of a
multidimensional array is the two-dimensional array. Both the row's and column's index
begins from 0.
Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
/* Example */
Int a[3][4];

Example for two Dimensional Array / Multi Dimensional Array

#include<stdio.h>
Void main ()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}

Example Program on Arrays :


73

#include<stdio.h>
void main()
{
int i;
int arr[3] = {2, 3, 4}; // Compile time array initialization
printf("%d %d %d \t",arr[0],arr[1],arr[2]);
}

O/P: 2 3 4

Run time array initialization example

#include<stdio.h>
void main()
{
int i;
int arr[3] ;
printf(“Enter array elements “); // //Run time array initialization
scanf("%d %d %d \t",&arr[0],&arr[1],&arr[2]);
printf("%d %d %d \t",arr[0],arr[1],arr[2]);
}
O/P : Enter array elements 1 2 3
the elements are : 1 2 3

O/P: 2 3 4
3.1 STRINGS: or Character Arrays
A string is an array of characters. (Or) A string is a one-dimensional array of characters
terminated by a null character (‘\0’).

Each character of the string occupies one-byte of memory. The characters of the string
are stored in contiguous memory locations.

3.1.1 Declaration of Strings:-

Syntax: char string-name [size];


Eg: char city [20];
3.1.2 Initialization of Strings
74

We can initialize a character array as total string at a time.

char city [10] = “HYDERABAD”;

3.1.3 Reading Strings:

 The input function scanf ( ) can be used with %s format specification to read a
string.
Eg: char name[30];
scanf(“%s”, name);
 The scanf() function to read single word.
 So multi word strings can’t read by using scanf() function.

Eg: char city[30];


scanf(“%s”, city);
If the input string is “NEW DELHI”, then the variable city can store only “NEW”, it
ignores the rest because white space is occurred after NEW.
 To read multi word strings, we can use gets( ) function or getchar( ) function
repeatedly.
Eg: char city[20];
gets(city);

3.1.4 Writing or Printing of Strings to Screen:-


 The printf() function with %s specification is used to print strings to the screen.
Eg: printf(”%s”,city);
We can also print strings by using puts () function and putchar () function repeatedly.
Eg: puts(name)

/* PROGRAM TO READ A STRING AND PRINT IT */ string ex prog

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
75

scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Enter name: Dennis Ritchie


Your name is Dennis.

3.2 String handling functions:- or string manipulation functions or


string.h functions

Operators can’t work with strings directly. So to manipulate strings we have a large
number of string handling functions in C standard library and the responsible header file
is “string.h”. Some of those functions are:
strcpy ( ), strcmp ( ), strcat ( ), strlen ( ), strrev ( ) etc.

Library functions for


Library Description
strings Function
strcpy(s1, s2) string.h Copies the value of s2 into s1
Copies n characters of s2 into s1. Does
strncpy(s1, s2, n) string.h
not add a null.
strcat(s1, s2) string.h Appends s2 to the end of s1
Appends n characters of s2 onto the
strncat(s1, s2, n) string.h
end of s1
Compared s1 and s2 alphabetically;
returns a negative value if s1 should
strcmp(s1, s2) string.h
be first, a zero if they are equal, or a
positive value if s2 sbould be first
Compares the first n characters of s1
strncmp(s1, s2) string.h
and s2 in the same manner as strcmp
Returns the number of characters in s1
strlen(s1) string.h
not counting the null

strcpy( ):- It is to copy one string into another, and it returns the resultant string.
Syntax: strcpy ( string1, string2);
String2 is copied into string1.
76

Eg: char city1[10] = “HYDERABAD”;


char city2[12] = “BANGLORE”;
strcpy (city1, city2);
Here city2 is copied into city1. So city1=“ HYDERABAD”andcity2=”BANGLORE”.
The size of the array city1 should be large enough to receive the contents of city2

strcmp( ):- It is to compare two strings to check their equality. If they are equal it
returns zero, otherwise it returns the numeric difference between the first non matching
characters in the strings. (i.e. +ve if first one is greater, -ve if first one is lesser).
Syntax: strcmp (string1, string2);
Eg: char city1[10] = “HYDERABAD”;
char city2[12] = “BANGLORE”;
strcmp (city1, city2);
Here city1 and city2 are compared, and returns the numeric difference between ASCII
value of ‘H’ and ASCII value of ‘B’ as they are not equal.
Strcmp(“RAM”,ROM”);  It returns some –ve value.
Strcmp(“RAM”,RAM”):  It returns 0 as they are equal.

strcat ( ):- This function is used to join two strings together, and it returns the resultant
string.
Syntax: strcat ( string1, string2);
String1 is appended with string2 by removing the null character of string1 and string2
remains unchanged. The resultant string is stored in string1.
Eg: char city1[10] = “HELLO”;
char city2[12] = “WORLD”;
strcat (city1, city2);
Here city2 is appended to city1. So city1= “HELLOWORLD” and city2=”WORLD”.

strlen( ):- It is to find out the length of the given string and it returns an integer value,
that is the number of characters in the given string. It takes only one parameter
Syntax: strlen ( string1);
It gives the length of string1.
Eg: char city[10] = “HYDERABAD”;
strlen (city);  it gives the value 9.
77

strrev ( ):- This function is to find out the reverse of a given string.
Syntax: strrev (string);
Eg: char city[10] = “HYDERABAD”;
strrev (city);  it give the string “DABAREDYH”

Example program on string copy else


printf("not equal");
#include<stdio.h> getch();
#include<conio.h> }
#include<string.h> Example program on string reverse
void main()
{ #include<stdio.h>
int i; #include<conio.h>
char st[25]="virat #include<string.h>
kohli",st1[25]="dhoni"; void main()
clrscr(); {
strcpy(st,st1); char name[20];
printf("%s",st); clrscr();
getch(); printf("enter name\n");
} gets(name);
strrev(name);
puts(name);
Example program on string compare getch();
#include<stdio.h> }
#include<conio.h>
#include<string.h> Example program on string
void main() Concatenation
{ #include<conio.h>
char name1[10]; #include<string.h>
char name2[10]; void main()
clrscr(); {
printf("enter name1 and enter char city1[10]="hyderabad";
name2"); char city2[10]="bangalore";
scanf("%s%s",name1,name2); clrscr();
if(strcmp(name1,name2)==0) strncat(city1,city2,1);
printf("both are equal"); printf("%s",city1);
78

getch(); char city1[10]="hyder";


} char city2[10]="bad";
int a,b;
Example program on string length clrscr();
a=strlen(city1);
#include<stdio.h> printf("length of city 1 is%d\n",a);
#include<conio.h> b=strlen(city2);
#include<string.h> printf("length is%d",b);
void main() getch();
{ }

3.3 POINTERS AND STRINGS: or Character Pointer


We can read and print the string using character pointer
Ex: write a c program to read string from keyword and display it using character
pointer (or)
Write a c program to accept string using character pointer and display it

void main()
{
char name[15],*ch; Output:
printf(“enter your name: ”);
gets(name); enter your name: dennis
ch=name; dennis
printf("%s",*ch);
}
3.4 Arrays of strings:
Consider, for example, the need to store the days of the week in their textual format. We
could create a two-dimensional array of seven days by ten characters, but this wastes
space.
Program on array of strings

#include<stdio.h> int i;
#include<conio.h> char color[4]
#include<string.h> [10]={"Red","Green","Blue","yellow"};
void main() clrscr();
{ printf("the entered array is : \n");
for(i=0;i<4;i++)
79

{ O/P:
printf("%s\n ",color+i); Red
} Green
getch(); Blue
} yellow

3.5 String input output functions:


The strings can be read from the keyboard and can be displayed onto the
monitor using various functions.

The various input and output functions that are associated with can be classified as
I / O Functions

Formated I/O Functions Unformated I/O Functions

Input Output Input Output


scanf() print() getc() putc()
fscanf() fprintf() getchar() putchar()
gets() puts()
getch() getche()

3.5.1 Unformated I/O Functions

1 : getchar() function : A single character can be given to the computer using ‘C’ input
library function getchar().
Syntax : char variable=getchar();
Example program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char x;
80

clrscr();
x=getchar();
printf("th given character is%c",x);
getch();
}
The getchar() function is written in standared I/O library. It reads a single character
from a standared input device. This function do not require any arguments, through a pair
of parantheses, must follow the statements getchar().

2 : putchar() function :The putchar() function is used to display one character at a time
on the standared output device. This function does the reverse operation of the single
character input function.
Syntax : putchar(character varaiable);
Example program
#include<stdio.h>
void main()
{
int c;
printf("enter a character");
c=getchar();
putchar(c);
getch();
}

3 : gets() : The gets() function is used to read the string (String is a group of characters)
from the standard input device (keyboard).
Syntax : gets(char type of array variable);

4 : puts() :The puts() function is used to display the string to the standared output device
(Monitor).
Syntax : puts(char type of array variable);
Example program on gets and puts
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char x[20];
clrscr();
printf("enter string\n");
81

gets(x);
puts("the string stored in x is:");
puts(x);
getch();
}

getch() function :The getch function reads a single character directly from the keyboard,
without echoing to the screen. Example program
void main()
{
char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
Syntax : int getch();

getche() function :The getche() function reads a single character from the keyboard and
echoes it to the current text window.
Syntax : int getche();
Example program
void main()
{
char ch;
ch = getche();
printf("Input Char Is :%c",ch);
}

getc() function : This function is used to accept a single character from the standared
input to a character variable.
Syntax : character variable=getc();

putc() function :This function is used to display a single character in a character variable
to standared output device.
Syntax : putc(character variable);
Ex:
#include <stdio.h>
int main()
{
   char ch;
   FILE *fp;
82

   if (fp = fopen("test.c", "r"))


   {
     ch = getc(fp);
     while (ch != EOF)
     {
        putc(ch, stdout);
        ch = getc(fp);
     }
     fclose(fp);
     return 0;
   }
   return 1;
}

Example program for palindrome string or number

#include<stdio.h>
#include<conio.h>
void main()
{
char a[22],b[22];
clrscr();
printf("Enter string\n");
gets(a);
strcpy(b,a);
strrev(b);
if(strcmp(a,b)==0)
printf("string is palindrome");
else
printf("string is not a palindrome");
getch();
}

O/P:
Enter string : amma
string is palindrome

3.6 Built in functions :


83

C <ctype.h> header or C type functions or character type functions in c


The functions that operate on single-byte characters are defined in ctype.h header file

Header file <ctype.h> includes numerous standard library functions to handle characters
(especially test characters).
You will find various library functions defined under <ctype.h> for character handling

All C inbuilt functions which are declared in ctype.h header file are given below.

Function Description

C isalnum() checks alphanumeric character

C isalpha() checks whether a character is an alphabet or not

C isdigit() checks numeric character

C islower() checks lowercase alphabet

C isspace() check white-space character

C isupper() checks uppercase alphabet

C tolower() converts alphabet to lowercase

C toupper() converts to lowercase alphabet

3.7 Math.h
The standard math library, math.h, contains a large number of mathematical tools. This
includes trigonometry (sine, cosine, tangent, etc.), exponential functions, logarithmic
functions, absolute values, square roots, etc. We've included a table for reference, but let's
look at a few commonly used functions.

Function Description Example


sqrt(x) square root of x sqrt(4.0) is 2.0
ceil(x) rounds x to smallest ceil(9.2) is 10.0
84

integer not less than x ceil(-9.2) is -9.0


rounds x to largest floor(9.2) is 9.0
floor(x)
integer not greater than x floor(-9.2) is -10.0
pow(x,y) x raised to power y (xy) pow(2,2) is 4.0
sin(x) sine of x (x in radian) sin(0.0) is 0.0
cos(x) cosine of x (x in radian) cos(0.0) is 1.0

3.8 Date functions in c


Time functions in C are used to interact with system time routine and formatted time
outputs are displayed. Example programs for the time functions are given below.

Function Description
setdate() This function used to modify the system date
getdate() This function is used to get the CPU time
clock() This function is used to get current system time
This function is used to get current system time as
time()
structure
This function is used to get the difference between two
difftime()
given times
strftime() This function is used to modify the actual time format
mktime() This function interprets tm structure as calendar time
This function shares the tm structure that contains date
localtime()
and time informations
This function shares the tm structure that contains date
gmtime()
and time informations
This function is used to return string that contains date
ctime()
and time informations
Tm structure contents are interpreted by this function
asctime()
as calendar time. This time is converted into string.

POINTERS:
85

3.9.1: INTRODUCTION
 A pointer is a derived data type in C
 Pointer is a variable which contains memory addresses as its value.
 Pointer which can hold the address of primitive data type like char, int, float,
double or user defined data type like function, pointer etc. or derived data type like
array, structure, union, enum.
 Pointer stores a reference to another value.
 Pointers are frequently used in C language, as they offer a number of advantages to
the programmers.

They are:

3.9.2.Uses of pointers :
a. Pointers reduce the length and complexity of programs.
b. They increase the execution speed and thus reduce the program execution time.
Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where the pointer is used.
Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces the
code and improves the performance.
Pointers provide direct access to memory
They save memory space. Instead of referring values we can refer to the addresses at
which they are stored.
Handling array values is easy using pointer.

3.10 Declaration and Initialization of pointer variables:-


The declaration of a pointer variable takes the following form.
Syntax: data-type * pointer variable name;
Ex: int *p;
Here, the pointer variable proceeded by the symbol *, which tells the compiler that it
is a pointer variable.
Eg: int * p; p is a pointer variable that points to an integer data type.
float *q; q is a pointer to a floating-point variable.
The process of assigning the address of a variable to a pointer is known as
initialization of pointer.
Eg: int a = 5;
int *p; /*declaration of pointer variable
p = & a; /*initialization of pointer variable
86

 We must ensure that the pointer variable always pointing to the corresponding type
of data.
Eg: float a; int x, *p;
p = &a this is not allowed as p is integer pointer and a is float variable.
 We could also define a pointer variable with an initial value of NULL or zero.
int *p = NULL; int *p = 0;

Example program on pointer:


void main( )
{
int x, a, *p;
float b, *q; clrscr();
a = 5;
p = &a;
b = 8.2;
q = &b;
x = *p;
printf("\n Value of a is : %d", a);
printf("\n Value of a is : %d", *p);
printf("\n Value of a is : %d", *(&a));
printf("\n %d is stored at %u", a, &a);
printf("\n %d is stored at %u", *p, p);
printf("\n Value of b is : %f", b);
printf("\n Value of b is : %f", *q);
printf("\n Value of b is : %f", *(&b));
printf("\n Value of x is : %d", x);
printf("\n %f is stored at %u", b, &b);
printf("\n %f is stored at %u", *q, q);
printf("\n %x is stored at %u", x, &x);
printf("\n %u is stored at %u", p, &p);
printf("\n %u is stored at %u", q, &q);
getch();
}
87

o/p:

3.11 Pointer Expressions or pointer arithmetic Like other variables pointer


variables can also be used in expressions.
We can also use pointer in arithmetic operations , In normal variables the operation is
performed on values , but in pointer variables the operation is performed on addresses .
Example:
Array and pointer arithmetic
A pointer in c is an address, which is a numeric value. Therefore, you can perform
arithmetic operations on a pointer just as you can on a numeric value.
But operations are performed on addresses.
There are four arithmetic operators that can be used on pointers: ++, --, +, and –

Sample Code

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5]={5,3,6,2,7};
int l,*p,*q;
clrscr();
p=&arr[0]; q=&arr[3];

printf("adress of p is : %u\n",p);
p=p+2;
88

printf("address of p after adding number is: %u\n",p);


printf("address of q is : %u\n",q);
q=q-2;
printf("address of q after subtracting is: %u\n",q);
p++;
printf("address of p after incrementing : %u\n",p);
q--;
printf("address of q after decrementing: %u\n",q);
l=p-q;
printf("subtracting after pointer : %d",l);
getch();
}

O/P :

3.12 Pointer to Pointer

 A pointer to a pointer is a pointer to store the address of another pointer. Such pointer is
known as a double pointer (pointer to pointer).
The first pointer is used to store the address of a variable whereas the second pointer is
used to store the address of the first pointer.
Let's understand it by the diagram given below.

declaration declares a pointer to a pointer of type int −


int **var;
89

Fig. pointer to pointer or double pointer

Example program for pointer to pointer or dual pointer or double


pointer

#include<stdio.h>
#include<conio.h>
void main()
{
int x=10, *p,**q;
clrscr();
p=&x;
q=&p;
printf("x values is %d \n",x);
printf("address of x is %u\n",&x);
printf("values of p is %u\n",p);
printf("address of p %u \n",&p);
printf("value at pointer p is %d",*p);
printf("value of q % u \n",q);
printf("the address of q is %u \n",&q);
printf("the value of x by using pointer to pointer %d",**q);
getch();
}
O/P
90

3.13 Pointers to Functions: or inter function communication in c or


pointers or call by value or call by reference or Passing Argument to
Function or passing parameters to functions

1. In C Programming we have different ways of parameter passing schemes such as


Call by Value and Call by Reference.
2. Function is good programming style in which we can write reusable code that can
be called whenever require.
3. Whenever we call a function then sequence of executable statements gets executed.
We can pass some of the information to the function for processing called argument.

Two Ways of Passing Argument to Function in C Language :

1. Call by Reference
2. Call by Value
Call by Value

1. While Passing Parameters using call by value , xerox copy of original parameter
is created and passed to the called function.
2. Any update made inside method will not affect the original value of variable in
calling function.
3. In the above example num1 and num2 are the original values and xerox copy of
these values is passed to the function and these values are copied into
number1,number2 variable of sum function respectively.
4. As their scope is limited to only function so they cannot alter the values inside
main function.

Example program :
91

#include<stdio.h>
#include<conio.h>
void swap(int ,int );
void main()
{
int i,j; clrscr();
i=10;j=20;
swap(i,j);
printf("After swapping in main function:%d %d\n",i,j);
getch();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("values after swapping in user function : %d %d\n",a,b);
}
O/P:
After swapping in main function : 10 20
Values after swapping in user function: 20 10
Call by Address / call by reference
1. While passing parameter using call by address scheme , we are passing the actual
address of the variable to the called function.
2. Any updates made inside the called function will modify the original copy since
we are directly modifying the content of the exact memory location.

Example program:
#include<stdio.h>
#include<conio.h>
void swap(int* ,int* );
void main()
{
int i,j; clrscr();
i=10;j=20;
swap(&i,&j);
printf("After swapping in main function:%d %d\n",i,j);
getch();
92

}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
printf("values after swapping in user function : %d %d\n",*a,*b);
}
Output :
After swapping in main function : 20 10
values after swapping in user function :20 10

3.14 void pointer or general purpose pointer or generic pointer or


pointers to void

 pointers can also be declared as void type.


 Suppose we have to declare integer pointer,character pointer and float pointer then
we need to declare 3 pointer variables.
 Instead of declaring different types of pointer variable it is feasible to declare
single pointer variable which can act as integer pointer,character pointer.

Example program :
#include<stdio.h>
void main()
{
int a=20;
float b=20.5;
char c='c';
void *p;
clrscr();
p=&a;
printf("value of int is : %d\n",*((int*)p));
p=&b;
printf("value of float is :%f\n",*((float*)p));
p=&c;
printf("value of char is :%c",*((char*)p));
93

getch();
}
Output :

value of int is : 20
value of float is :20.500000
value of char is : c

3.15 Memory allocation functions or Dynamic memory allocations


(DMA)

In C, the exact size of array is unknown until compile time, i.e., the time when a compiler
compiles your code into a computer understandable language. So, sometimes the size of
the array can be insufficient or more than required.

Dynamic memory allocation allows your program to obtain more memory space while
running, or to release it if it's not required.

In simple terms, Dynamic memory allocation allows you to manually handle memory
space for your program.

Although, C language inherently does not have any technique to allocate memory
dynamically, there are 4 library functions under "stdlib.h" for dynamic memory
allocation.

C language offers 4 dynamic memory allocation functions. They are,

1. malloc()
2. calloc()
3. realloc()
4. free()

1)Malloc :

malloc(); function is used for allocating block of memory at runtime. This function
reserves a block of memory of given size and returns a pointer of type void. This means
that we can assign it to any type of pointer using typecasting. If it fails to locate enough
space it returns a NULL pointer. The name malloc stands for "memory allocation".
94

Syntax : malloc (number *sizeof(int)); or ptr = (cast-type*) malloc(byte-size)


Here ptr is variable name

Example progam on malloc :

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

void main()
{
int num, i, *ptr, sum = 0;
clrscr();
printf("Enter number of elements: ");
scanf("%d", &num);

ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc


if(ptr == NULL)
{
printf("Error! memory not allocated.");
}
else

printf("Enter elements of array: ");


for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i); //sum=sum+*(ptr+i);
}

printf("Sum = %d", sum);


free(ptr);
getch();
}

O/P :
Enter number of elements:
5
Enter elements of array:
1 2 3 4 5
95

Sum : 15

2)Calloc :
calloc() is another memory allocation function that is used for allocating memory at
runtime. calloc function is normally used for allocating memory to derived data types
such as arrays and structures. If it fails to locate enough space it returns a NULL pointer.

Syntax: calloc (number , sizeof(int)); or ptr= (cast_type *)calloc(blocks ,


size_of_block)
Here ptr is variable name

Example program for calloc


#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num , sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
}
else
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i); //sum=sum+*(ptr+i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
96

O/P :
Enter number of elements:
5
Enter elements of array:
1 2 3 4 5
Sum : 15

3)realloc
By using realloc we can increase or decrease the size of an allocated memory block by
calling the function realloc.
The function realloc() reallocates a memory block with a specific new size. If you call
realloc() the size of the memory block pointed to by the pointer is changed to the given
size in bytes. This way you are able to expand and reduce the amount of memory you
want to use 

Syntax: void * realloc ( void * ptr, size );

Example program for realloc


#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str;
clrscr();
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, "tutorialspoint");
printf("String= %s, Address = %u\n", str, str);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}
97

O/P :

4) Free(): free () function frees the allocated memory by malloc (), calloc (), realloc ()
functions and returns the memory to the system.

Declaration of free function


Following is the declaration for free() function.
void free(void *ptr)

Difference between malloc and calloc


malloc() calloc()

It allocates only single block of requested It allocates multiple blocks of


memory requested memory

It contains single argument It contains 2 arguments

malloc () doesn’t initializes the allocated calloc () initializes the allocated


memory. It contains garbage values memory to zero

type cast must be done since this function Same as malloc () function int
returns void pointer int *ptr;ptr = *ptr;ptr = (int*)calloc( 20, 20 *
(int*)malloc(sizeof(int)*20 ); sizeof(int) );

USER DEFINED DATA TYPES STRUCTURES & FILES

4.1 User Defined data Types :

User Defined data Types : Sometimes, the basic set of data types defined in the C
language such as int, float etc. may be insufficient for your application.  In circumstances
such as these, you can create your own data types which are based on the standard ones.

The various User Defined data types are


98

1 : Enumerated.
2 : Structure.
3 : Union.
4. typedef

4.1.1 Definition of Structures : A Structure is a user defined data type. A structure


contains one or more data items of same or different data types in which the individual
elements can differ in type.
A simple structure may contain the integer elements, float elements, character elements
etc. The individual structure elements are called members.

The general format / syntax is :

struct <identity>
{
type1 member1;
type2 member2;
: :
: :
typeN memberN;
};

Where,
1 : struct : struct is the keyword which tells the compiler that a structure is being defined.
2 : identity : is the name of the structure.
3 : member1,member2, ….. , memberN are called members of the structure. They are
also called fields of the structure.
4 : The members are declared within curly braces. The members can be any of the data
types such as int, char, flat, etc.
5 : There should be semicolon at the end of closing brace.

Ex : struct student
{
char name[10];
int roll_number;
float average_marks;
};
99

The structure definition does not reserve any space in memory for the
members. So, it is called a structure template and memory will not be allocated for the
template.

4.1.2 Declaration of Structures : After defining a structure format we can declare


variables of that type. A structure variable declaration is similar to the declaration of
variables of any other data types.

The declaration of a structure varaiable has four parts,

1 : struct : is the keyword.


2 : identity : is the structure name.
3 : list of varaibels : followed by list of varaiables separated by commas.
4 : Followed by terminating semicolon.

Syntax : struct identity list of variables;

Ex : struct student emp1, emp2;

The complete structure definition along with structure declaration.


struct student
{
char name[10];
int roll_number; //structure definition.
float average_marks;
};
struct student emp1; //structure declaration.

Once the structure definition is associated with variables such as, the compiler
allocates memory for the structure variables. The number of bytes allocated for the
variable emp1 is
- 10 bytes are allocated for the field name
- 2 bytes for the field roll_number.
- 4 bytes for the field average_marks.
So, totally 16 bytes are reserved for the variable ece1 and another 16 bytes are reserved
for the variable ece2.
100

4.1.3 Initilization of Structures : The initializing structure variable is similar to that of


arrays i.e, all the elements will be enclosed within curly braces i.e, ‘{‘ and ‘}’ and are
separated by commas.
Syntax : struct identity variable={v1,v2,…vn};
Where,
1 : “struct identity” is user defined data type.
2 : v1,v2..vn are all the initial values. These values are called initilizers, they should be
separated by commas and should be enclosed between ‘{‘ and ‘}’.

Examples
1 : Initilization during structure declartion.
struct student
{
char name[10];
int roll_number;
float average_marks;
};

struct student ece1={“abc”, 1000, 75};

Initilization during structure declaration with more than one variable.


struct student
{
char name[10];
int roll_number;
float average_marks;

};
struct student ece1={“abc”, 1000, 75};
struct student ece2={“abc”, 1000, 75};

4.1.4 Accessing Structures : After declaring the structure type, variables and members,
the members of the structure can be accessed by using the structure variable along with
dot(.) operator.

To access any member of a structure, we use the member access operator (.).Use this
Operator in between “Structure name” & “member name”

Syntax : variable.member;
101

Ex : struct student
{
char name[10];
int roll_number;
float average_marks;

};
struct student ece1;
For accessing the structure members from the

ece1.name; ece1.roll_number; ece1.average_marks;

Where ‘ece1’ is the structure variable.

Write a program to print the student number, name and marks through accessing
structure elements.

#include<stdio.h>
#include<conio.h> scanf("%d",&s.marks);
struct std printf("Rollno Name Marks \n");
{ printf("%d %s
int no; %d”,s.no,s.name,s.marks);
char name[10]; getch();
int marks;
}; }
struct std s;
void main()
{
float total,avg;
printf("Enter student details:\n");

printf("\nEnter the student no:");


scanf("%d",&s.no); OUTPUT :Enter student details :
printf("\nEnter the student name:"); Enter the student no :5
scanf("%s",&s.name); Enter the student name
printf("\nEnter the student marks:"); :dennis
Enter the student marks :85
102

5 dennis 85
Rollno Name Marks

4.2 Array of structures or Structure and Arrays and Structure


containing Arrays
ray of Structure
Structure is collection of different data type. An object of structure represents a single
record in memory, if we want more than one record of structure type, we have to create
an array of structure variable or object. As we know, an array is a collection of similar
type, therefore an array can be of structure type.
Syntax for declaring structure array

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
struct struct-name var [ size ];

The following example shows a structure called student that takes the roll number and
name of a student as an input, then stores each record in an array st, which stores three
elements. Each element will hold a mixed record.

#include<stdio.h> {
struct student printf("\nEnter Rollno:");
{ scanf("%d",&st[i].rollno);
int rollno; printf("\nEnter Name:");
char name[10]; scanf("%s",&st[i].name);
}; }
void main() printf("\nStudent Information List:");
{ for(i=0;i<3;i++)
int i; {
struct student st[3];
printf("Enter Records of 3 students");
for(i=0;i<3;i++)
103

printf("\nRollno:%d, Name: Enter Name:Jenny


%s",st[i].rollno,st[i].name); Enter Rollno:2
} Enter Name:Angela
getch(); Enter Rollno:3
} Enter Name:Rory

Student Information List:


Rollno:1, Name: Jenny
Output: Rollno:2, Name: Angela
Enter Records of 3 students Rollno:3, Name: Rory
Enter Rollno:1

4.3 Typedef

Declaration : The typedef is a keyword that allows the programmer to create a new data
type name for an existing data type. So, the purpose of typedef is to redefine the name of
an existing variable type.

Syntax : typedef data_type newname1,new name2,…new nameN;

Where

1) typedef : is a keyword.
2) data type : any Existing Data Type.
3) New Names for the existing Data Type.

Ex : typedef int MARKS;


MARKS sub1,sub2,sub3;

Advantages of typedef :

1 : Provides a meaningful way of declaring the variable.


2 : Increase the readability of the program.
104

Typedef example: check in class notes

4.4 Enumerated Types : An enumerated data type

Enumeration (enum) is a user-defined datatype (same as structure). It consists of various


elements . There is no such specific use of enum, It is used to assign names to the
integral constants .

An enum is defined in the same way as structure with the keyword struct replaced by the
keyword enum and the elements separated by 'comma' as follows.
syntax/declaration of enum

enum enum_name
{
element1,
element2,
element3,
element4,
};

#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
enum week today;
today = Wednesday;
printf("Day is %d",today);
}

Output Day is 4

The default value of 'sun' will be 0, 'mon' will be 1, 'tue' will be 2 and so on. for example,
if we define the value of tue as 5. So the values of 'wed', 'thurs', 'fri' and 'sat' will become
105

6, 7, 8 and 9 respectively. There will be no effect on the values of sun and mon which
will remain 0 and 1 respectively. Thus the value of thurs i.e. 7 will get printed.

4.5 Union:
Union is a derived type and it is declared like structure. The difference between union
and structure is in terms of storage. In structure each member has its own storage
location, whereas all the members of union use the same location, although a union may
contain many members of different types. When we use union the compiler allocates a
piece of storage that is larger enough to hold. Like structures, union is also declared by
using the keyword union.

Syntax: union union_name


{
type1 member1;
type2 member2;
: :
: :
typeN memberN;
};
Where,

1) union : is the keyword.


2) union_name : is the name of union.
3) member1,member2, ….. , memberN are called members of the structure. They are
also called fields of the structure.
4) The members are declared within curly braces. The members can be any of the data
types such as int, char, flat, etc.
5) There should be semicolon at the end of closing brace.

Ex : union student
{
int sno,smarks;
char sname[10];
};

4.6.1 Declaration of union :


106

Syntax : union union_name list of variables;

Ex : union student ece1;

Example :
Union un
{
Short a;
Short b;
};
Union un val;
Void main()
{ clrscr();
Val.a=10;
Printf(“value is %d \n”,val.b);
Val.b=20;
Printf(“value is %d”,val.a);
Getch();
}
O/P:
Value is 10
Value is 20

4.6.2 Difference between Structure and union

Structure Union
1 : The keword struct is used to define 1 : The keyword union is used to
a structure.y define a union.
2 : When a variable is associated with 2 : When a variable is associated with a
a structure, the compiler allocates the union, the compiler allocates the
memory for each member. The size of memory by considering the size of the
structure is greater than or equal to the largest member. So size of union is
sum of sizes of its members. The equal to the size of largest number.
smaller members may end with unused
slack bytes.
3 : Each member within a structure is 3 : Memory allocated is shared by
assigned unique storage area. individual members of union.
4 : The address of each member will be 4 : The address is same for all the
in asecending order. This indicates that members of a union. This indicates that
107

memory for each member will start at every member begins at offset values.
different offset values.
6 : Individual members can be 6 : Only one member can be accessed
accessed at a time. at a time.
7 : Several members of a structure can 7 : Only the first member of a union
be initialized at once. can be initialized.
4.7 Command Line Argument
Command line argument is a parameter supplied to the program when it is invoked.
Command line argument is an important concept in C programming. It is mostly used
when you need to control your program from outside. command line arguments are
passed to main() method.
Syntax :
int main( int argc, char *argv[])
argc    – Number of arguments in the command line including program name
argv[]   – This is carrying all the arguments
argc (ARGument Count) is int and stores number of command-line arguments passed
by the user including the name of the program. So if we pass a value to a program, value
of argc would be 2 (one for argument and one for program name)
The value of argc should be non negative.

argv(ARGument Vector) is array of character pointers listing all the arguments.


If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.

FILE MANAGEMENT IN C
4.8 FILES:

File Handling concept in C language is used for store a data permanently in computer.


Using this concept we can store our data in Secondary memory (Hard disk). All files
related function are available in stdio.h header file.

DRAWBACKS OF TRADITIONAL I/O SYSTEM


 Main drawback of using Traditional I/O (consoe) :- data is temporary
 New way of dealing with data is file handling.
108

 Data is stored onto the disk and can be retrieve whenever require.

4.8.1 TYPES OF FILES


When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files

1. TEXT FILES
 Text files are the normal .txt files. You can easily create text files using any simple
text editors such as Notepad.
 When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.
 Text File is Also Called as “Flat File“.
 Text File Format is Basic File Format in C Programming.
 Text File is simple Sequence of ASCII Characters.
 Text File have .txt Extension.
 Files with the .txt extension can easily be read or opened by any program that reads
text and, for that reason, are considered universal (or platform independent).
 Text Format Contain Mostly English Characters

Examples of the text files


Notepad.
C editor

2. BINARY FILES
 Binary files are mostly the .bin files in your computer.
 Instead of storing data in plain text, they store it in the binary form (0's and 1's).
 Binary Files Contain Information Coded Mostly in Binary Format.
 Binary Files are difficult to read for human.
 Binary Files can be processed by certain applications or processors.
 Humans can read binary files only after processing.
 All Executable Files are Binary Files.
Some Examples of the Binary files :
Executable Files
Database files
109

4.8.2 Why use File Handling in C ( uses of files)

 For permanet storage.


 The transfer of input - data or output - data from one computer to another can be
easily done by using files.
 When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter
them all.
 However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
 You can easily move your data from one computer to another without any
changes.

4.8.3 How to achieve File Handling

The following operations can be performed on a file.

The basic file operation in ‘C’


1. Naming a file
2. Opening a file
3. Reading data from a file
4. Writing data to a file
5. Closing file

4.8.4 Working with files

When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and the program.

Declaration or syntax of file

FILE *fp; // FILE is data type and *fp pointer variable


110

Opening a file - for creation and editOpening a file is performed using


the fopen() function defined in the stdio.h header file.

The syntax for opening a file in standard I/O is:

1. fp = fopen("path and filename and type","mode");

File can be opened in basic 3 modes : Reading Mode, Writing Mode, Appending Mode

File modes

mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
4.8.5 Closing a File

The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.


1. fclose(fp);

Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is
that fprint() and fscanf() expects a pointer to the structure FILE.
111

4.9 File I/O functions :-


Sometimes it is necessary to store the data in a manner that can be later retrieved and
displayed either in a part or in whole. This medium is usually a “file” on the disk.
File I/O can be handled by using different functions.

a) Formatted functions:-
The file input function fscanf( ) and the file output function fprintf( ) are called formatted
file I/O functions.
Syntaxes:
fprintf (fp, "control string", list_of_var);

fscanf (fp, “control string”, list_of_var);

b)Unformatted functions:-
The input functions like getc( ), getw( ), and fread( ) are called unformatted file input
functions and putc( ), putw( ), and fwrite( ) functions are unformatted file output
functions. Each and every function is having its own syntax and meaning.

4.10 File handling functions in ‘C’ library / file management or


manipulation functions in C

fopen( ) → creates a new life for use/open existing file


fclose( ) → closes file
fgetc( ) → read a char from file
fputc( ) →writes a char to file
fprintf →writes a set of data values to a file
fscanf → reads a se of data values from a file
getw( ) → reads an integer from a file
putw( ) → writes an integer to a file
fseek( ) → sets the position to a designed point in file
ftell( ) → sets the position to the beginning of file

Explanation of above functions :

Fopen function:  
The general format for declaring and opening la file is
112

FILE  *fp;
Fp = fopen ( “file name”, “mode” );

 Where the variable fp has a pointer to the data type File opens the  File name a
and pointer assigns an identifier to the File type pointer  fp.  This pointer which contains
all the information about the File subsequently used as a communication link between the
system used as a communication between the system and the program.

“Mode” can be one the following

r  - open the file for  reading only.


w - open the file writing only.
a  - open the file for appending  (adding) data  to each.

Both ‘file name’ and ‘mode’ are specified as string they should be enclosed in ‘’  ‘’.

Ex :                 FILE  * fp1, *fp2;


Fp1 = fopen (“data’’, “r”);
Fp2= fopen (“result”, “w”);

 Where fp1,fp2 are pointer the ‘fp1’ is opens the File named as data for reading
mode only then fp2 opens the file named as ‘result for writing made only

Fclose function :  


A  File must be closed after all operations have been completed. The general form of
fclose function is

Fclose (file pointer);

The getw function :  


The simplest integer oriented file I/o function is get w  that has been opened in read
mode  the general from of statement is

Num =getw (fp);

The Putw function :  


The simplest I/O integer oriented function is putw. ‘putw’ is used to create an integer
value to a file that has been opened in write mode. The general form statement is
113

Putw(num,fp);

The fprintf function : 


The fprintf statement is used to write data items to the file whose file pointer is opened in
the writing mode. ‘fprintf’ perform I/O operations an files the   general form of fprintf  is

Fprintf (fp, "control string", list);

 Where ‘fp’ is a file pointer associated with a file that has been opened for writing.
The control string contains output specifications for the items in the list. The list may be
including variable constants and strings.
Ex :                 fprintf (fp1, "%s %d %f”, name age,7.5);

Where ‘name is an array variable of type and age is an int variable.

The fscanf function : The  fscanf function is used to read data items to the file whose
pointer is opened in the reading mode. fscanf function performs I/O operations on files.
The general form of fscanf is 

fscanf (fp, “control string”, list);

This statement reading of the items in the list from the file specified by fp. The
control string contains input specifications for the items in the list.

Ex :                   fscanf (fp1, “%s %d”, item & quantity

Where “item “ is an array variable of type and  quanity is an int variable. Fscanf


returns the no.of items when the end of file is reached 'i' returns the value Eof

The ftell function : 


This function is useful in saving the current position of a file, which can be used later in
the program . It takes the following form

                                    N = ftell ( fp);

Where ‘n’ gives the relative offset (in bytes) of the current position. This means
that ‘n’ bytes have already read.
114

The Rewind  function : 
It takes a file pointer and resets the position to the start of the (in bytes).  The statement is

Rewind (fp);
N = ftell(fp);

It will assign ‘o’ to n’ because the file position has been set to the start of the file
by rewinded.  i.e.., The first byte in the file is numbered as ‘o’ second as ‘1’ and a so on.

Fseek function : 
It is used to move  the file   position to a desired location within the file It takes the
following form

Fseek (file pointer, offset, position);

Here ‘file pointer’ is a pointer to the file, ‘offset’ is a number or variable of type
‘long’, and position is an integer variable. The offset specifies the positions (bytes) to be
moved from the location specified by position.

Writing File : fputc() function


The fputc() function is used to write a single character into file. It outputs a character to a
stream.

Syntax:
fputc(ch,fp)
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the
stream. It returns EOF at the end of file.

Syntax:
fgetc(fp)

4.11 File of records:


Write a C program to store record of student (stud_no, stud_name, stud_addr,
stud_Percentage) in a file using structure.
To store a record of data into a file we can achieve by using structures.
115

      printf("\nEnter percentage of
student : ");
#include<stdio.h>
struct stud
{       scanf("%f",&s.per);
      int rno;       fprintf(fp,"%d\n%s\n%s\n
      float per; %f",s.rno,s.name,s.add,s.per);
      char name[20],add[20];       printf("\nRecord stored in file...");
}s;       fclose(fp);
void main()       }
{
      FILE *fp;
      fp=fopen("student.txt","w");

printf("Enter record of student:\n\n");


      printf("\nEnter student number : ");
      scanf("%d",&s.rno);
      printf("\nEnter name of student: "); Output:
      scanf("%s",s.name);
      printf("\nEnter student address : ");
      scanf("%s",s.add);

4.12 Random Access to Files (or) Positioning functions in C:-


Files can be accessed either sequentially or randomly. Random accessing of files can be
achieved by using some predefined C library functions:
fseek( ),
116

ftell( ),
and rewind( ).

ftell( ) function:- If we wish to know where the file pointer is positioned right now, we
can use the function ftell. ftell takes a file pointer as an argument, and it returns the
position as long int which is an offset from the beginning of the file. It takes the
following form:
syntax: n = ftell(fp);

Example on Random Access to Files


#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("test.txt", "r");
fseek(fp,5L,2);
printf("%ld", ftell(fp));
}

Example program on files : To check whether the file is present or not


#include <stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int ch; clrscr();
filePointer = fopen("student.txt", "r"); // read mode
if (fp == NULL)
printf("File is not present");
else
printf("file is present");
fclose(fp);
getch();
}

Note : refer class notes/ lab notes for following programs:

 How to create a file using w mode


 Program using fprintf and fgetc and fputc
117

 Program to count no of characters in a file


 Program to copy one file to another file

Note : for binary file programs save file as .bin and change mode to rb/wb/ab

You might also like