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

17UCA02-Programming in 'C' (T.vijayakumar)

Uploaded by

srlohitkriishnaa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

17UCA02-Programming in 'C' (T.vijayakumar)

Uploaded by

srlohitkriishnaa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

VYSYA COLLEGE, SALEM-103.

SUBJECT: PROGRAMMING IN C CLASS: I B.C.A.,


SUBJECT CODE:17UCA02 UNITS: 5
DECEMBER JANUARY FEBUARY MARCH APRIL

UNIT-I UNIT-II UNIT-III UNIT-IV (Contd…) UNIT-V


From : 04.12.2017 From :02.01.2018 From: 01.02.2018 (Contd…)
To : 29.12.2017 To :31.01.2018 To : 24.02.2018 01.03.18 TO 02.03.18 (2)
Arrays of structures - 02.04.18 TO
04.12.17 TO 09.12.17 (6) 02.01.18 TO 06.01.18 (5) 01.02.18 TO 02.02.18 (2) Arrays within structures- 07.04.18 (6)
Overview of C: History of C- Decision Making and Character Arrays and Structures within Random access
Importance of C-Basic Branching: Decision Strings: Introduction- structures- Structures and files-Command
Structure of C programs- making with if statement Declaring and initializing functions-Unions-Size of line arguments.
Executing C programs . Simple IF,IF-ELSE, string variables-Reading structures-Bit fields
Nesting of IF-ELSE ELSE- string from terminal-Writing Total No. of
11.12.17 TO 15.12.17 (5) IF Ladder -Switch strings to screen. 05.03.18 TO 10.03.18 (6) Working Days:
(ELTP) statements-The ?: operator. 05.02.18 TO 10.02.18 (6) Pointers : Introduction- 18
(11.12.17 TO 29.12.17) GOTO statements. Arithmetic Operations on Understanding Pointers- Total Hours: 17
Constants ,Variables and Characters-Putting Strings Accessing the address of a
Data Types : Character set - 08.01.18 TO 12.01.18 (5) Together- Comparison of two variable- Declaring
C Tokens-Keywords and Decision Making and Strings- String handling pointer Variables-
identifiers - Constants- Looping: WHILE functions-Table of strings. Initializing of pointer
Variables. Data Types- statement - DO statement 12.02.18 TO 16.02.18 (5) variables-Accessing a
Declaration of storage classes FOR statement-Jump in User-defined Functions: variable through its
-Assigning values to LOOPS. Introduction-Need for user- pointer. Chain of pointers-
variables- Defining symbolic Defined function- A multi- Pointer Expressions-
constants-Declaring variable 17.01.18 TO 20.01.18 (4) function program- Elements Pointers and arrays-
as Constant - Declaring a Arrays: Definition & of user-defined functions - Pointer and character
variable as volatile. Declaration. One Definition of functions- strings-Arrays of pointers-
(ELTP:1 Hour) Dimensional-Declaration Return values and their types- pointers as function
of one dimensional array Function Calls arguments
18.12.17 TO 23.12.17 (6) 19.02.18 TO 24.02.18 (6)
Operators & Expressions - Function declaration-All
Arithmetic Operators- 22.01.18 TO 25.01.18 (4) category of functions- 12.03.18 TO 16.03.18 (5)
Relational operators-Logical Two Dimensional- Functions with no arguments Functions returning
operators-Assignment Initializing two dimensional and No Return values- pointers- pointer to
operators-Increment and arrays- Function with Arguments and functions-pointer and
decrement operators. No return values- Functions structures.
Conditional operators- Bitwise 29.01.18 TO 31.01.18 (3) with no arguments But return
Operators- Special Operators- Multi dimensional arrays- a value- Functions with Total No. of Working
Special Operators-Evaluation Dynamic Arrays. arguments and one return Days: 16
of expressions. Precedence of value- Functions that return Total Hours: 16
arithmetic operators -Type Total No. of Working Multiple values. Nesting of
conversions in expressions - Days: 21 functions- Recursion-Passing UNIT-V
operator precedence and Total Hours: 21 arrays to Function- Passing From:19.03.2018
associatively-Mathematical strings to function To :07.04.2018
functions Total No. of Working Days:
(ELTP:1 Hour) 19 19.03.18 TO 24.03.18 (6)
Total Hours: 16 File Management:
26.12.17 TO 29.12.17 (4) UNIT-IV Introduction-Defining and
Managing Input and output From : 26.02.2018 opening a file-Closing a
operations: Reading and To : 16.03.2018 file
writing a character-Formatted
input and Output. 26.02.18 TO 28.02.18 (3) 26.03.18 TO 31.03.18 (6)
(ELTP:1 Hour) Structures and Input /Output operation on
Unions :Introduction- files - Error handling
Total No. of Working Days: Defining a Structure- during I/O operations
21 Declaring structure variables-
Total Hours: 18 Accessing structure members- UNIT TEST –II
Structure initialization- (26.03.2018 TO
Copying and comparing 03.04.2018)
structure variables-
Operations on Individual
Members.
UNIT TEST –I
(05.02.2018 TO 13.02.2018)

1
UNIT-I
1. OVERVIEW OF C
GIVE SHORT INTRODUCTION ABOUT C. (PART A)
 The C is a general-purpose, procedural, imperative computer programming language developed in
1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating
system.
 The C is the most widely used computer language, it keeps fluctuating at number one scale of
popularity along with Java programming language, which is also equally popular and most widely
used among modern software programmers.
 C was initially used for system development work, in particular the programs that make up the
operating system. C was adopted as a system development language because it produces code that
runs nearly as fast as code written in assembly language. Some examples of the use of C might be:
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Network Drivers
 Modern Programs
 Databases , Language Interpreters
 Utilities
i.) HISTORY OF C
EXPLAIN THE HISTORY OF C (PART B)
 C has often been termed as a "Pseudo high level
language" or a "Middle level language" by many
programmers. This is not because of its lack of
programming power but because of its capability
to access the system's low level functions.
 In fact C was invented specifically to implement
UNIX. C instructions are compiled to assembly
code, therefore, depending on the complexity of
the code and on the compiler optimization
capabilities, C code may run as fast as assembly.
 Ken Thompson created the B language in 1969
from Martin Richard's BCPL (Basic Combined
Programming Language). He used assembly language and B to produce the initial versions of the
UNIX operating system.
 BCPL and B were typeless languages in which variables were simply words in memory. Dennis
Ritchie of Bell Laboratories later converted B into C by retaining most of B's syntax in 1972 and
wrote the first compiler.
 in 1983, the ANSI X3J11 committee was asked to standardize the C language. The result was ANSI
C, a standard which was adopted in 1988. It is not forced upon any programmer, but since it is so
widely accepted, it would be economically unwise for any systems programmer or compiler writer
not to conform to the standard.
ii.) IMPORTANCE OF ‘C’ LANGUAGE
WRITE ABOUT IMPORTANCE OF C LANGUAGE (PART B)
 It is robust language whose rich setup of built in functions and operator can be used to write any
complex program.
 Program written in c are efficient due to several variety of data types and powerful operators. The c
complier combines the capabilities of an assembly language with the feature of high level language.
 Therefore it is well suited for writing both system software and business package. There are only 32
keywords; several standard functions are available which can be used for developing program.
 C is portable language; this means that c programs written for one computer system can be run on
another system, with little or no modification. C language is well suited for structured programming,
this requires user to think of a problems in terms of function or modules or block. A collection of
these modules make a program debugging and testing easier.
2
 C language has its ability to extend itself. A c program is basically a collection of functions that are
supported by the c library. We can continuously add our own functions to the library with the
availability of the large number of functions.
 The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
 Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are also enumeration constants as well.The constants are
treated just like regular variables except that their values cannot be modified after their definition.
iii.) FEATURES OF C LANGUAGE
WHAT ARE ALL THE FEATURES OF C LANGUAGE (PART B)
 C is a procedure-based programming language. This means the program is viewed as a means to
solve a problem. Various functions modules or code blocks are thus, written to solve this problem.
 C functions can accept parameters and return values and perform variety of tasks like input from the
user, displaying the information, etc.
 C is simple and easy to learn and use. The main components like built-in functions, operators,
keywords are small in number.
 In C, errors are checked only at compile time. The compiled code though have no safety checks for
bad type casts, bad array indices, or bad pointers.
 C works best for small projects where performance is important.
 C contains the capability of assembly language with the features of high level language.
iv.) BASIC STRUCTURE OF C
EXPLAIN ABOUT BASIC STRUCTURE OF C PROGRAM(PART B)
 C program can be viewed as a group of building blocks called Functions.
 A function is a subroutine that may include one or more statements designed to perform a specific
task. To write a C program, we first create functions
and then put them together.
 A C program may contain one or more sections.
Documentation Section
 This section contains a set of comment lines giving
the name of the program, author, date created, and
other details.
Link Section
 This section provides instructions to compilers to link
functions from the system library.
Definition Section
 This section defines all symbolic constants.
Global declaration Section
 contains a variable that is used outside of all the
functions. These variables are Global variables.
Main ( ) function Section
 Every C program must have one main ( ) function section. C permits different forms of main() as,
1) main ( ) 4) main (void)
2) int main ( ) 5) void main(void)
3) void main ( ) 6) int main(void)
 The empty pair of parentheses indicates that the function has no arguments.
 This may be explicitly indicated by using the keyword ‘void’ inside the parentheses.
 We may also specify the keyword ‘int’ or ‘void’ before the word ‘main’.
 Main() has two parts,
 Declaration part  declares all variables.
 Executable part  statements to be executed to get output
 These two parts must appear between the opening and closing braces.
Subprogram section
 This section contains all the user-defined functions that are called in the main function.
 User-defined functions are generally placed immediately after the main function.
The # include Directive
3
 C programs are divided into modules or functions.
 Some functions are written by users and many others are stored in the C Library.
 Library functions are grouped category-wise and stored in different files known as Header Files.
 If we want to access the functions stored in the library, it is necessary to tell the compiler about the
files to be accessed by using the preprocessor directive, # include <filename> where filename 
name of the library file. Preprocessor directives are placed at the beginning of a program.
v.) EXECUTING C PROGRAMS
1. This is First Step i.e Creating and Editing Program.
2. First Write C Program using Text Editor , such as [ Borland C/C++ 3.0 , Notpad++,Notpad ]
3. Save Program by using [.C] Extension.
4. Compiling C Program: C Source code with [.C] Extension is given as input to compiler and compiler
converts it into Equivalent Machine Instruction.
5. Program is linked with included header files.
6. If run time error occurs then “Run-time” errors are reported to user.
7. Again programmers have to review code and check for the solution.
2. CONSTANTS ,VARIABLES AND DATA TYPES
i.) CHARACTER SET
C characters are grouped into the following categories.
a) Letters, b) Digits, c) Special Characters, d) White Spaces
a) Letters
Uppercase A….Z
Lowercase a…..z
b) Digits
All decimal digits 0…..9
c) Special characters
, Comma & Ampersand ‘ Apostrophe / Slash + Plus Sign
. Period ^ Caret “ Quotation mark \ Backslash ( Left Parenthesis
; Semicolon * Asterisk ! Exclamation mark ~ Tilde ) Right Parenthesis
: Colon - Minus Sign | Vertical Bar _ Underscore [ Left Bracket
$ Dollar Sign % Percent Sign# number sign ] right Bracket { Left Brace } Right Brace
< Opening angle bracket (or Less than sign) > Closing angle bracket (or Greater than sign)
d) White Spaces
Blank Space, Horizontal tab Carriage return New Line Form Feed.
ii.) C TOKENS
In C programs, the smallest individual units are known as tokens.
C TOKENS

Keywords Constants Strings Operators

float -15.5 “ABC” +-


while 100 “year” *,

Identifiers Special symbols

Main []
amount {}

iii.) KEYWORDS
Every C word is classified as either a keyword or an identifier. All keywords have fixed meanings
and these meanings cannot be changed.

4
auto else Long switch
break Enum register typedef
case extern return union
char float short unsigned
const for signed void
continue Goto sizeof volatile
default if static while
do Int struct _packed
iv.) IDENTIFIERS
DEFINE IDENTIFIER (PART A)
 Identifiers refer to the names of variables, functions and arrays.
 They are user-defined names and consist of a sequence of letters and digits, with a letter as a first
character. Both uppercase and lowercase letters are permitted.
 The underscore character is also permitted in identifiers.
 Identifiers should not be a keyword.
 Should not start with Digit.
v.) CONSTANTS
DEFINE CONSTANTS (PART A)
 The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
 Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are also enumeration constants as well.
 The constants are treated just like regular variables except that their values cannot be modified after
their definition.
 Constants in C refer to fixed values that do not change during the execution of a program.
CONSTANTS

Numeric Constants Character Constants

Integer Real Single character String


constants constants constants constants
a.) Integer Constants
 An integer constant refers to a sequence of digits, There are three types integers,namely, decimal,
octal, and hexa decimal.
Decimal Constant
 Eg:123,-321 etc.,
 Note: Embedded spaces, commas and non-digit characters are not permittedbetween digits.
 Eg: 1) 15 750 2)$1000
Octal Constant
 An octal integer constant consists of any combination of digits from the set 0 through7, with a
leading 0.
 Eg: 1) 037 2) 0435
Hexadecimal Constant
 A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer.
 They may also include alphabets A through F or a through f.
 Eg: 1) 0X2 2) 0x9F 3) 0Xbcd
b.) Real Constants
 Certain quantities that vary continuously, such as distances, heights etc., are represented by numbers
containing fractional parts like 17.548.Such numbers are called real(or floating point)constants.
 Eg:0.0083,-0.75 etc.,
5
 A real number may also be expressed in exponential or scientific notation.
 Eg:215.65 may be written as 2.1565e2
c.) Single Character Constants
 A single character constants contains a single character enclosed within a pair of single quote marks.
 Eg: ’5’, ‘X’, ‘;’
d.) String Constants
 A string constant is a sequence of characters enclosed in double quotes. The characters may be
letters, numbers, special characters and blank space.
 Eg:”Hello!”, “1987”, “?….!”
e.) Backslash Character Constants
 C supports special backslash character constants that are used in output functions.
 These character combinations are known as escape sequences.
Constant Meaning
‘\a’ audible alert
‘\b’ backspace
‘\f’ form feed
‘\n’ new line
‘\0’ null
‘\v’ vertical tab
‘\t’ horizontal tab
‘\r’ carriage return
vi.) VARIABLES
DEFINE VARIABLE (PART A)
WHAT ARE ALL THE RULES FOR DECLARING VARIABLE (PART A)
Definition:
 A variable is a data name that may be used to store a data value. A variable may take different values
at different times of execution and may be chosen by the programmer in a meaningful way. It may
consist of letters, digits and underscore character.
 Eg: 1) Average 3) student_name
2) Height 4) address1
Rules for defining variables
 They must begin with a letter. Some systems permit underscore as the first character.
 ANSI standard recognizes a length of 31 characters. However, the length should no tbe normally
more than eight characters.
 Uppercase and lowercase are significant.
 The variable name should not be a keyword.
 White space is not allowed.
Declaration of Variables
The syntax is
Eg: int count; Data-type v1,v2…..vn;
Double ratio, total;
User-defined type declaration
 C allows user to define an identifier that would represent an existing int data type. The general form is
Eg: 1) typedef int units;
Typedef type identifier;
2) typedef float marks;
 Another user defined data types is enumerated data type which can be used to declarevariables that can
have one of the values enclosed within the braces. enum identifier {value1,value2,……valuen};
vii.) DATA TYPES
EXPLAIN ABOUT PRIMARY DATA TYPE IN C (10 MARKS)
ANSI C supports Three classes of data types.
1. Primary (or Fundamental) data types.
2. User-defined data types.
3. Derived data types.

6
Primary Data Types
PRIMARY DATA TYPES
Integral Type

Integer Character
signed type unsigned type signed char
int unsigned int unsigned
short int unsigned short int char
long int unsigned long int

Floating Point Type


float double long double void

Integer Types
Type Size (bits) Range
int or signed int 16 -32,768 to 32767
unsigned int 16 0 to 65535
short int 8 -128 to 127
unsigned short int 8 0 to 255
long int 32 -2,147,483,648 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
Floating Point Types
Type Size (bits) Range
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932to 1.1E+4932
Character Types
Type Size (bits) Range
char 8 unsigned char
unsigned char 8 0 to 255

viii.) DECLARATION OF STORAGE CLASSES


 Variables in C can have not only data type but also storage class that provides information about
their locality and visibility.
/*Example of storage class*/
int m;
main()
{
int i;
float bal;
……
……
function1();
}
function1()
{
int i;
float sum;
……
……

7
}
 Here the variable m is called the global variable. It can be used in all the functions in the program.
 The variables bal, sum and i are called local variables. Local variables are visible and meaningful
only inside the function in which they are declared.
 There are four storage class specifiers, namely,
o auto,
o static,
o register and
o extern.
 Static and extern variables are automatically initialized to zero. Auto variable contain undefined
value(garbage value) until they are initialized explicitly.
Auto : Local variables known only to the function in which it is declared.
Register : Local variables which is stored in he registers.
Static : Local variables which exist and retain its value even after the control is transferred to the calling
function.
Extern : Global variables known to all functions in the file.
ix.) ASSIGNING VALUES TO VARIABLES
Assigning Statement:
 The syntax is
Variable_name=constant;
Eg: 1) a=20;
2) bal=75.84;
3) yes=’x’;
 C permits multiple assignments in one line.
Example:
initial_value=0; final_value=100;
 In C declaration and assignment can be done simultaneously, as follows.
The syntax is
data-type variable_name = constant;

Eg: 1) int final_value=100;


2) char yes=’x’;
Reading Data from keyboard:
Another way to giving values to variable is to input data through keyboard using the scanf function.
The general format of the scanf is,
Scanf(“Control String”, & Variable 1, & variable 2, ….);
Eg: scanf (“%d”, & number);
x.) DEFINING SYMBOLIC CONSTANTS
EXPLAIN ABOUT SYMBOLIC CONSTANT IN C LANGUAGE (PART B)
 We often use certain unique constants in a program. These constants may appear repeatedly in a
number of places in the program. One example of such a constant is 3.142, representing the value of
the mathematical constant “pi”. We face two problems in the subsequent use of such programs.
1. Problem in modification of the programs.
2. Problem in understanding the program.
A constant is defined as follows:
#define symbolic-name value of constant
Eg: 1) #define pi 3.1415
2) #define pass_mark 50
The following rules apply to a #define statement which define a symbolic constant.
1. Symbolic names have the same form as variable names.

8
2. No blank space between the sign ‘#’ and the word define is permitted
3. ‘#’ must be the first character in the line.
4. A blank space is required between #define and symbolic name and between the symbolic name and
the constant.
5. #define statements must not end with the semicolon.
6. After definition, the symbolic name should not be assigned any other value within the program by
using an assignment statement.
7. Symbolic names are NOT declared for data types. Their data types depend onthe type of constant.
8. #define statements may appear anywhere in the program but before it is referenced in the program.
xi.) DECLARING A VARIABLE AS CONSTANT
 Eg: 1) const int class_size=40;
 This tells the compiler that the value of the int variable class_size must not be modified by the
program.
xii.) DECLARING A VARIABLE AS VOLATILE
 By declaring a variable as volatile, its value may be changed at any time by some external source.
 Eg:1) volatile int date;
3. OPERATORS AND EXPRESSIONS
I. OPERATORS
INTRODUCTION TO OPERATORS
EXPLAIN ABOUT OPERATOR CONCEPT IN C (10 MARKS)
 C supports a rich set of operators. Operators are used in programs to manipulate data and variables.
They usually form a part of the mathematical or logical expressions.
 C operators are classified into a number of categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
i.) ARITHMETIC OPERATORS
The operators are
 + (Addition)
 - (Subtraction)
 * (Multiplication)
 / (Division)
 % (Modulo division)
 Eg: 1) a-b 2) a+b 3) a*b 4) p%q
 The modulo division produces the remainder of an integer division.
 The modulo division operator cannot be used on floating point data.
 Note: C does not have any operator for exponentiation.
a.) Integer Arithmetic
 When both the operands in a single arithmetic expression are integers, the expression is called an
integer expression ,and the operation is called integer arithmetic.
 During modulo division the sign of the result is always the sign of the first operand.
 That is -14 % 3 = -2 , -14 % -3 = -2 , 14 % -3 = 2
b.) Real Arithmetic
 An arithmetic operation involving only real operands is called real arithmetic. If x and yare floats
then we will have:
1) x = 6.0 / 7.0 = 0.857143 2) y = 1.0 / 3.0 = 0.333333
 The operator % cannot be used with real operands.

c.) Mixed-mode Arithmetic

9
 When one of the operands is real and the other is integer, the expression is called a mixed-mode
arithmetic expression and its result is always a real number.
Eg: 1) 15 / 10.0 = 1.5
ii.) RELATIONAL OPERATORS
 Comparisons can be done with the help of relational operators. The expression containing a
relational operator is termed as a relational expression. The value of a relational expression is either
one or zero.
Operator Meaning Examples
< Less than a<b
<= Less than or equal to a < =b
> Greater than a >b
>= Greater than or equal to a > =b
== Equal to a = =b
!= Not equal to a!=b

Example program for Relational Operators


#include<stdio.h>
main()
{ int a=16; Output:
int b=973;
if (a > b) b is big
printf(“a is big”);
else
printf(“b is big”);
}

iii.) LOGICAL OPERATORS


 C has the following 3 logical operators:Truth table for Logical AND
 OPERATOR  MEANING
 &&  Logical AND
 ||  Logical OR
 !  Logical NOT
Truth table for Logical AND
Truth table for Logical OR
1 1 =1 1 1 =1
1 0 =0 1 0 =1
0 1 =0 0 1 =1
0 0 =0 0 0 =0
 The logical operators && and || are used to test more than one condition and make decisions.
o Example: a>b&& x==10
 An expression of this kind, which combines two or more relational expressions, is termed as a logical
expression or a compound relational expression.
 The logical expression given above is true only if a>b is true and x==10 is true. If either (or both) of
them are false, the expression is false.

# include <stdio.h>
main() Output:
{ int a,b,c;
a=70;b=50;c=30; A is Largest
if ((a>b) && (a>c))
printf("\n\ n\t\t\t A is Largest ");
else if (b>c)
printf("\n\n \t\t B is Largest ");
else
printf("\n\n \t\t C is Largest ");
getch();
} 10
iv.) ASSIGNMENT OPERATORS
 The usual assignment operator is ‘=’.In addition, C has a set of ‘shorthand’ assignment operators of
the form, v op = exp;
Eg: 1.x += y+1; This is same as the statement x=x+(y+1);
Shorthand Assignment Operators
Statement with shorthand operator Statement with simple assignment operator
a + =1 a=a+1
a-=1 a=a–1
a *= n + 1 a = a * (n+1)
a /= n + 1 a = a / (n+1)
a %= b a=a%b
v.) INCREMENT AND DECREMENT OPERATORS
 C has two very useful operators that are not generally found in other languages. These are the,
o increment operator : ++
o decrement operator: --
 C allows two very useful operators. These are the increment and decrement operators: ++ and - - .
 The operators ++ adds 1 to the operand, and - - subtracts 1.
 Both are unary operators and takes the following form:

 ++m ; (or) m ++;  ++m; is equivalent  toConsider the following


m = m+1;(or m+= 1;) example: m = 5; y = m++;
Consider
--m ; (or) m--;  --m; is equivalent to m = m-1;(or m-=1;) the
 In this case, the value of y would be 5 and m
would be 6. following
example:
m = 5; y = ++m;
 In this case, the value of m and y would be 6.
#include<stdio.h>
#include<stdio.h>
main()
main()
{
{
int e,f,g,h;
int a,b,c,d;
e=10; g=- -e;
a=10; c=++a;
f=13; h=f- - ;
b=13; d=b++;
printf(" \n E = %d \t G= %d ",e,g);
printf(" \n A = %d \t C= %d ",a,c);
printf("\n F= %d \t H= %d",f,h);
printf("\n B= %d \t D= %d",a,d);
getch();
getch();
}
}

vi.) CONDITIONAL OPERATOR


 A ternary operator pair “?:” is available in C to construct conditional expression of the form:
 Here exp1 is evaluated first. If it is true then the expression exp2 is evaluated and becomes the value
of the expression. If exp1 is false then exp3 is evaluated and its value becomes the value of the
expression.
Syntax: exp1 ? exp2 : exp3
Eg:1) if(a>b)
x = a;
else Example Program: Output:
x = b; #include<stdio.h>
main()
{ C = 100
int a,b,c;
a=100;
b=50;
c= (a>b) ? a : b;
printf ( " C= %d " , c);
getch();
}
vii.) BITWISE OPERATORS
11
 C has a distinction of supporting special operators known as bitwise operators for manipulation of data
at bit level.

 Bitwise operator works on bits and performs bit by bit operation.

 These operators are used for testing the bits, or shifting them right or left. Bitwise operators may not be
applied to float or double.
Example  Assume if A = 60; and B = 13; Now in binary Operator Meaning
format they will be as follows: & Bitwise AND
A = 0011 1100
B = 0000 1101 | Bitwise OR
-------------------- ^ Bitwise exclusive
A&B = 0000 1100 OR
A|B = 0011 1101 << Shift left
A^B = 0011 0001
~A = 1100 0011 >> Shift right
viii.) SPECIAL OPERATORS
Define Sizeof operator(PART A)
 C supports some special operators such as
Comma operator
Size of operator
Pointer operators(& and *) and
Member selection operators(. and ->)
The Comma Operator
 The comma operator can be used to link the related expressions together. A comma linked list of
expressions are evaluated left to right and the value of right-most expression is the value of the
combined expression.
Eg: value = (x = 10, y = 5, x + y);
 This statement first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15 (i.e, 10+5) to
value.
The Size of Operator
 The size of is a compiler time operator and, when used with an operand, it returns the number of
bytes the operand occupies.
Eg: 1) m = sizeof(sum); Example Program:
2) n = sizeof(long int) #include <stdio.h>
3) k = sizeof(235L) int main(){
int a;
float b;
Output: double c;
Size of int = 2 bytes char d;
Size of float = 4 bytes printf("Size of int=%d bytes\n",sizeof(a));
Size of double = 8 bytes printf("Size of float=%d bytes\n",sizeof(b));
Size of byte = 1 byte printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
}

II.EXPRESSION
i.) ARITHMETIC EXPRESSIONS
DEFINE EXPRESSION (OR)ARITHMETIC EXPRESSION(PART A)
Expressions
 The combination of operators and operands is said to be an expression. An arithmetic expression is a
combination of variables, constants, and operators arranged as per the syntax of the language.
Eg 1) a = x + y;
ii.) EVALUATION OF EXPRESSIONS
12
 Expressions are evaluated using an assignment statement of the form,
variable = expression;
 An arithmetic expression without parentheses will be evaluated from left to right using the rules of
precedence of operators.
 The basic evaluation procedure includes ‘two’ left-to-right passes through the expression.
 During the first pass, the high priority operators (if any) are applied as they are encountered.
 During the second pass, the low priority operators (if any) are applied as they are encountered.
 Consider the following evaluation statements that has been used in the program
x = a-b/3 + c*2-1
When a =9, b =12, and c = 3, the statement becomes Ex:- x= 12-4*6/3+2
x = 9-12/3 + 3*2-1 x= 12-4*2+2
and is evaluated as follows: Second pass x= 12-8+2
First pass : x = 9-12/3 + 3*2-1 Step3: x = 5+6-1 x= 12-10
Step1: x = 9-4+3*2-1 Step4: x = 11-1 x= 2
Step2: x = 9-4+6-1 Step5: x = 10
 The order of evaluation can be changed by introducing parentheses into an expression.
Example:
main()
{
float a, b, c, y, x, z;
a = 9; b = 12; c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – (b / (3 + c) * 2) – 1;
printf(“x = %f ”,x);
printf(“y = %f ”,y);
printf(“z = %f ”,z);
}
OUTPUT
x = 10.000000 y = 7.000000 z = 4.000000
iii.) PRECEDENCE OF ARITHMETIC OPERATORS
EXPLAIN ABOUT PRECEDENCE OF ARITHMETIC OPERATORS IN C (PART B)
 An arithmetic expression without parenthesis will be evaluated from left to right using the rule of
precedence of operators. There are two distinct priority levels of arithmetic operators in C.
High priority * / % Low priority + -
 Consider the above program and if the a=9, b=12 and c=3, the statement becomes.
X=9-12/3+3*2-1
 The above expression is evaluated as follows.
First Pass
o Step 1: x=9-4+3*2-1
o Step 2: x=9-4+6-1
Second Pass
o Step 3: x=5+6-1
o Step 4: x=11-1
o x=10
iv.) TYPE CONVERSION IN EXPRESSIONS
DEFINE AUTOMATIC TYPE CONVERSION(PART A)
 If the operands are of different types, the lower type is automatically converter to the higher type
before the operation proceeds. This is called Type conversion.
 There are two types of type conversions,
a) Implicit Type conversion
b) Explicit Type conversion
a.) Implicit or Automatic Type Conversion

13
 C permits the mixing of constants and variables of different types in an expression. If the operands
are of different types, the lower type is automatically converted to higher type before the operation
proceeds. The result is of the higher type.
 Given below are the sequence of rules that are applied while evaluating expressions. All short and
char are automatically converted to int; then
 If one of the operands is long double, the other will be converted to long double and the result
will be in long double.
 Else, If one of the operands is double, the other will be converted to double and the result will
be in double.
Rules while evaluating expressions
1. If the operands are of different types, the long double
‘lower’ type is automatically converted to the
‘higher’ type before the operation proceeds. double
The result is of the higher type. Conversion
float
2. All short and char are automatically converted Hierarchy
to int; then unsigned long
3. If one of the operands is long double, the other int
long int
will be converted to long double and the result
will be long double; unsigned
4. Else, if one of the operands is double, the other int
will be converted to double and the result will int
be double; short char
5. Else, if one of operands is float, the other will
be converted to float and the result will be float;
6. Else, if one operand is unsigned long int, the other will be converted to unsigned long int and the result
will be unsigned long int;
7. Else, if one of the operands is long int and the other is unsigned int, then
a .If unsigned int can be converted to long int, the unsigned int operand will be converted as such and
the result will be long int;
b. Else, both operands will be converted to unsigned long int and the result will be unsigned long int;
8. Else, if one of the operands is long int, the other will be converted to long int and the result will be long
int;
9. Else, if one of the operands is unsigned int, the other will be converted to unsigned int and the result
will be unsigned int.
 The following changes are introduced during the final assignment.
1. Float to int causes truncation of the fractional part.
2. Double to float causes rounding of digits.
3. Long int to int causes dropping of the excess higher order bits.
b.) Explicit or Casting a Value
 C performs type conversion automatically. However, there are instances when we want to force a
type conversion in a way that is different from the automatic conversion.

Syntax: (type_name)

EXAMPLE ACTION
x=(int)7.5 7.5 is converted to integer by truncation
a=(int)21.3/(int)4.5 Evaluated as 21/4 and the result would be 5.
b=(double)sum/n Division is done in floating point mode
y=(int)(a+b) The result of a+b is converted to integer
z=(int)a+b A is converted to integer and then added to b
p=cos((double)x) Converts x to double before using it

14
v.) OPERATORS PRECEDENCE AND ASSOCIATIVELY IN C
 Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
 For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
 Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

OPERATOR DESCRIPTION ASSOCIATIVITY RANK


() Function call Left to right
[] Array element reference 1
+ Unary plus
- Unary minus Right to left 2
++ Increment
-- Decrement
! Logical negation
~ Ones complement
* Pointer reference
& (indirection)
Sizeof(type) Address 2
Size of an object/Type cast
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
- Subtraction
<< Left shift Left to right 5
>> Right shift
< Less than Left to right 6
<= Less than are equal to
> Greater than
>= Greater than or equal to
== Equality Left to right 7
|= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional expression Right to left 13
=, * =. / =. %=. Right to left 14
Assignment operators
+=.
- =, &=,^=, | =,
<< =, >> =
, Comma operator Left to right 15
WRITE C PROGRAM FOR OPERATOR PRECEDENCE IN C (5MARKS)
Void main()
{
int a = 20; b = 10; c = 15; d = 5; e;
When you compile and execute the
e = (a + b) * c / d; // 30 * 15 / 5
above program, it produces the
printf("Value of (a + b) * c / d is : %d\n", e );
following result:
e = ((a + b) * c) / d; // (30 * 15 ) / 5
Value of (a + b) * c / d is : 90
printf("Value of ((a + b) * c) / d is : %d\n" , e );
Value of ((a + b) * c) / d is : 90
e = (a + b) * (c / d); // (30) * (15/5)
Value of (a + b) * (c / d) is : 90
printf("Value of (a + b) * (c / d) is : %d\n", e );
Value of a + (b * c) / d is : 50
15
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
}
vi.) MATHEMATICAL FUNCTIONS
 Mathematical functions such as sqrt, cos, log etc., are the most frequently used ones. To use the
mathematical functions in a C program, we should include the line #include<math.h> in the
beginning of the program.
Trignometric
acos(x) Arc cosine of x
asin(x) Arc sine of x
Hyperbolic
cosh(x) Hyperbolic cosine of x
sinh(x) Hyperbolic sine of x
Other functions
ceil(x) x rounded up to the nearest integer
log(x) base 10 log of x.x>0
pow(x,y) square root of x,x>=0

4. MANAGING INPUT AND OUTPUT OPERATIONS


 All input/output operations are carried out through functions called as printf and scanf. There exist
several functions that have become standard for input and output operations in C. These functions are
collectively known as standard i/o library. Each program that uses standard I/O function must
contain the statement #include<stdio.h>
 The file name stdio.h is an abbreviation of standard input-output header file.
i.) READING A CHARACTER
WRITE A C PROGRAM BY USING getchar() function(PART B)
 Reading a single character can be done by using the function getchar. The getchar takes the
following form:
variable_name = getchar();
Eg: char name;
name=getchar();
OUTPUT
Program
Would you like to know my
/*Reading a character from terminal*/
name?
#include<stdio.h>
Type Y for yes and N for no:Y
main()
My name is India
{
Would you like to know my
Char ans;
name?
printf(“Would you like to know my name? \n”);
Type Y for yes and N for no:n
printf(“Type Y for yes and N for no”);
You are good for nothing
ans=getchar();
if(ans ==’Y’ || ans = =’y’)
printf(“\n\n My name is India \n”);
else
printf(“\n\n You are good for nothing \n”);
}
ii.) WRITING A CHARACTER
 Like getchar, there is an analogous function putchar for writing characters one at a time to the
terminal. It takes the form as shown below:
putchar(variable_name);
 Eg: 1) answer=’y’;
putchar(answer);
 Will display the character y on the screen.
The statement putchar(‘\n’);
 Would cause the cursor on the screen to move to the beginning of the next line.
Program
16
/*A program to read a character from keyboard and then prints it in reverse case*/
/*This program uses three new functions: islower, toupper, and tolower.
#include<stdio.h>
#include<ctype.h> OUTPUT
main() Enter An alphabet
{ a
char alphabet; A
printf(“Enter an alphabet”); Enter An alphabet
putchar(‘\n’); Q
alphabet = ghetchar(); q
if(islower(alphabet)) Enter An alphabet
putchar(toupper(alphabet)); z
else Z
putchar(tolower(alphabet));
}
iii.) FORMATTED INPUT
EXPLAIN ABOUT I/O OPERATIONS IN C(10 MARKS)
 Formatted input refers to an input data that has been arranged in a particular format.
 The formatted data can be read with the help of scanf function. The general form of scanf is

scanf (“control string”, arg1,arg2,

 The control string specifies the field format in which the data is to be entered and the arguments
arg1,arg2...argn specifies the address of locations where the data are stored. Control strings and
arguments are separated by commas.
 Control string contains field specification which direct the interpretation of input data.
 It may include
 Field(or format)specifications, consisting of conversion character %, a datatype character,
and an optional number, specifying the field width.
 Blanks, tabs, or newlines.
Inputting integer numbers
 The field specification for reading an integer number is %wd
Eg: scanf(“%2d %5d”,&num1, &num2);
 An input field may be skipped by specifying * in the place of field width.
For eg, scanf(“%d %*d %d”,&a, &b);
Inputting Real numbers
 The scanf reads real numbers using the simple specification %f for both the notations, namely
decimal point and exponential notation.
 If the number to be read is of double type, then the specification should be %lf.
Scanf(“%f%f%f”, &x,&y,&z); OUTPUT
Enter three integer numbers
Inputing a Character String 123
Scanf(“%c%s”, name1, name2); 1 3 –3577
Program Enter two 4-digit numbers
/*Reading integer numbers*/ 6789 4321
main() 67 89
{ Enter two integer numbers
int a, ,b, c, x, y, z; 44 66
int p, q, r; 4321 44
printf(“Enter three integer numbers \n”); Enter a nine digit numbers
scanf(“%d %*d %d”,&a, &b, &c); 123456789
printf(“%d %d %d \n \n”,a, b, c); 66 1234 567
printf(“Enter two 4-digit numbers \n”); Enter two three digit numbers
123 456
17 89 123
scanf(“%2d %4d ”,&x, &y);
printf(“%d %d \n \n”,x, y);
printf(“Enter two integer numbers \n”);
scanf(“%d %d”,&a, &x);
printf(“%d %d \n \n”,a, x);
printf(“Enter a nine digit numbers \n”);
scanf(“%3d %4d %3d”,&p, &q, &r);
printf(“%d %d %d \n \n”,p, q, r);
printf(“Enter two three digit numbers \n”);
scanf(“%d %d”,&x, &y);
printf(“%d %d \n \n”,x, y);
}
Reading Mixed Data Types
 It is possible to use one scanf statement to input a data line containing mixed mode data. In such
cases, it should be ensured that the input data items match the control specifications in order and
type.
Eg: scanf(“%d %c %f %s”,&count, &code, &ratio, &name);
Scanf Format Codes ( Code Meaning )
%c Read a single character %i Read a decimal, hexadecimal, or octal integer
%d Read a decimal integer %o Read an octal integer
%e Read a floating point value %s Read a string
%f Read a floating point value %u Read an unsigned decimal integer
%g Read a floating point value %x Read a hexa decimal integer
%h Read a short integer %[..] Read a string of word(s)
iv. ) FORMATTED OUTPUT
 The printf statement provides certain features that can be effectively exploited to control the
alignment and spacing of print-outs on the terminals. The general form of printf statement is
printf(“control string”,arg1, arg2…argn)
 Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b
Output of Integer Numbers
 The format specification for printing an integer number is %wd Output of Real Numbers
 The output of real numbers may be displayed in decimal notation using the following format
specification:
%w.p f
 The integer w indicates the minimum number of positions that are to be used for the display of the
value and the integer p indicates the number of digits to be displayed after the decimal point.
 We can also display real numbers in exponential notation by using the specification
%w.p e
Printing of Single Character
 A single character can be displayed in a desired position using this format The character will be
displayed right-justified in the field of w columns.
 We can make the display left-justified by placing a minus sign before the integer w.
 The default value for w is 1.
Printing of Strings
 The format specification for outputting strings is of the form
%wc %w.ps

UNIT – I COMPLETED
References: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy,

18
UNIT-II
DECISION MAKING AND BRANCHING
EXPLAIN ABOUT DECISION MAKING CONCEPTS (10 MARKS)
i.) INTRODUCTION:
 Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
 Following is the general form of a typical decision making structure found in most of the
programming languages:
i. if statement
ii. switch statement
iii. Conditional operator statement
iv. Goto statement.
i.) DECISION MAKING WITH IF STATEMENT
If statement can be implemented in many forms.
a) Simple if statement
b) IF…. ELSE statement
c) Nested IF…ELSE Statement
d) ELSE IF Ladder.
a.) Simple IF statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
if(Test_Expression)
{
/* statement(s) will execute if the boolean expression is true */
}
Example program
#include <stdio.h>
int main ()
{
int a = 10; /* local variable definition */
if( a < 20 ) /* check the boolean condition using if statement */
{
printf("a is less than 20\n" ); /* if condition is true then print the following */
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is less than 20;
value of a is : 10
b.) IF...ELSE statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
Example Program:
19
#include <stdio.h>
int main ()
{
int a = 100; /* local variable definition */
if( a < 20 ) /* check the boolean condition */
{
/* if condition is true then print the following */ When the above code is compiled and
printf("a is less than 20\n" ); executed, it produces the following result:
} a is not less than 20;
else value of a is : 100
{
printf("a is not less than 20\n" ); /* if condition is false then print the following */
}
printf("value of a is : %d\n", a);
return 0;
}
c.) Nesting of IF...ELSE IF...ELSE Ladder
 An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.
 When using if , else if , else statements there are few points to keep in mind:
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
 The syntax of an if...else if...else statement in C programming language is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}

20
Example Program
#include <stdio.h>
int main ()
{
int a = 100; /* local variable definition */
if( a == 10 ) /* check the boolean condition */
{
printf("Value of a is 10\n" ); /* if condition is true then print the following */
}
else if( a == 20 )
{
printf("Value of a is 20\n" ); /* if, else if condition is true */
}
else if( a == 30 )
{
printf("Value of a is 30\n" ); /* if else if condition is true */
}
else
{
printf("None of the values is matching\n" ); /* if none of the conditions is true */
}
printf("Exact value of a is: %d\n", a );
return 0;
}
When the above code is compiled and executed, it produces the following result:
None of the values is matching
Exact value of a is: 100

d.) Nested if statements


 It is always legal in C programming to nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).
Syntax
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
21
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example Program
#include <stdio.h>
int main ()
{
int a = 100; /* local variable definition */
int b = 200;
if( a == 100 ) /* check the boolean condition */
{
if( b == 200 ) /* if condition is true then check the following */
{
printf("Value of a is 100 and b is 200\n" ); /* if condition is true then print the following */
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
ii.) SWIITCH STATEMENT
EXPLAIN ABOUT SWIITCH STATEMENT WITH AN EXAMPLE (PART B)
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.
Syntax
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
Example Program
#include <stdio.h>
int main ()
{
char grade = 'B'; /* local variable definition */
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
22
case 'C' :
printf("Well done\n" );
break;
When the above code is compiled and
case 'D' :
executed, it produces the following result:
printf("You passed\n" );
break;
Well done
default :
Your grade is B
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
iii.) THE ?: OPERATOR (TERNARY OPERATOR)
DEFINE TERNARY OPERATOR(PART A)
This is also known as ‘Conditional Operator’. Since this operator operates on three operands, this is
called a ternary operator.
This operator Simplifies the if…else construct.
The general form of this operator is:
(test-expression)?true-expression:false expression;
 The Test expression is executed first and if it is true, then the true expression will be executed.
 If the test-expression is false, then the false-expression will be evaluated and assigned to the
conditional expression.
 The C language has an unusual operator, useful for making two-way decisions. This operator is a
combination of ? and : and takes three operands.
 It is of the form
 exp1?exp2:exp 3
o Here exp1 is evaluated first. If it is true then the expression exp2 is evaluated and becomes
the value of the expression. If exp1 is false then exp3 is evaluated and its value becomes the
value of the expression.
Eg:
if(x < 0)
flag = 0;
else
flag = 1;
can be written as flag = (x < 0)? 0 : 1;
iv.) THE GOTO STATEMENT
Define Goto Statemet(PART A)
 C supports the goto statement to branch unconditionally from one point of the program to another.
The goto requires a label in order to identify the place where the branch is to be made. A label is any
valid variable name and must be followed by a colon.
 The general from is

23
DECISION MAKING AND LOOPING
EXPLAIN ABOUT DECISION MAKING AND LOOPING (PART C)
 In looping, a sequence of statements are executed until some conditions for termination of the loop
are satisfied. A program loop therefore consists of two segments, one known as the body of the loop
and the other known as the control statements.
Eg:
main()
{
double x, y;
read:
scanf(“%f”,&x);
if(x < 0) goto read;
y = sqrt(x);
printf(“%f %f \n”,x, y);
goto read;
}
 The C language provides for three loop constructs for performing loop operations. They are
i. The while statement
ii. The do statement
iii. The for statement
i.) THE WHILE STATEMENT
 The basic format of the while statement is
 The while is an entry–controlled loop statement. The test-condition is
evaluated and if the condition is true, then the body of the loop is
executed. After execution of the body, the test-condition is once again
evaluated and if it is true, the body is executed once again. This process of repeated execution of the
body continues until the test-condition finally becomes false and the control is transferred out of the
loop.
Eg:
sum = 0;
n = 1;
while(n <= 10)
{
sum = sum + n* n;
n = n + 1;
}
printf(“sum = %d \n”,sum);
ii.) THE DO STATEMENT
 In while loop the body of the loop may not be executed at all if the condition is not satisfied at the
very first attempt. Such situations can be handled with the help of the do statement.

 Since the test-condition is evaluated at the bottom of the


loop, the do…..while construct provides an exit-controlled
loop and therefore the body of the loop is always executed
at least once.
Eg:
do
{
printf(“Input a number\n”);
number = getnum();
}
while(number > 0);
24
iii.) FOR STATEMENT
 for-loops are counter-controlled, meaning that they are normally used whenever the number of
iterations is known in advance.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Details:
 The initialization step occurs one time only, before the loop begins.
 The condition is tested at the beginning of each iteration of the loop.
o If the condition is true ( non-zero ), then the body of the loop is executed next.
o If the condition is false ( zero ), then the body is not executed, and execution continues with
the code following the loop.
 The incrementation happens AFTER the execution of the body, and only when the body is executed.
iv.) JUMP IN LOOPS
EXPLAIN ABOUT BREAK AND CONTINUE WITH AN EXAMPLE(PART B)
Break and continue
 To exit a loop you can use the break statement at any time. This can be very useful if you want to
stop running a loop because a condition has been met other than the loop end condition. Take a look
at the following example:
#include<stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
if ( i == 10)
break;
}
return 0;
}

 In the example above, the while loop will run, as long i is smaller then twenty. In the while loop
there is an if statement that states that if i equals ten the while loop must stop (break).
 With “continue;” it is possible to skip the rest of the commands in the current loop and start from
the top again. (the loop variable must still be incremented). Take a look at the example below:
#include<stdio.h>
int main()
{
int i = 0;
while ( i < 20 )
{
i++;
continue;
printf("Nothing to see\n");
}
return 0;
}
 In the example above, the printf function is never called because of the “continue;”.

25
ARRAYS : DEFINITION AND DECLARATION
DEFINE ARRAY (PART A)
 Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
 Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an array is accessed by an index.
 All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.

Declaring Arrays
 To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows −
type arrayName [ arraySize ];
 This is called a single-dimensional array. The arraySize must be an integer constant greater than
 zero and type can be any valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement −
double balance[10];
 Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
 The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ].
 If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
 You will create exactly the same array as you did in the previous example. Following is an example
to assign a single element of the array −
balance[4] = 50.0;
th
 The above statement assigns the 5 element in the array with a value of 50.0. All arrays have 0 as
the index of their first element which is also called the base index and the last index of an array will
be total size of the array minus 1. Shown below is the pictorial representation of the array we
discussed above −

#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
for ( i = 0; i < 10; i++ ) /* initialize elements of array n to 0 */
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
for (j = 0; j < 10; j++ ) /* output each array element's value */
{
26
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
ONE DIMENSIONAL ARRAY
EXPLAIN IN DETAIL ABOUT ONE DIMENSIONAL ARRAY (5 marks)
i.) INTRODUCTION:
 An array with a single subscript is known as one dimensional array.
Eg: 1) int number[5];
 The values to array elements can be assigned as follows.
Eg: 1) number[0] = 35;
number[1] = 40;
number[2] = 20;
ii.) DECLARATION OF ARRAYS
 The general form of array declaration is
type variable-name[size];
Eg: 1) float height[50];
2) int group[10];
3)char name[10];
Program
/*Program showing one-dimensional array*/
main() OUTPUT
{ Enter 10 real numbers:
int i; 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10
float x[10],value,total; x[1] = 1.10
printf(“Enter 10 real numbers:\n”); x[2] = 2.20
for(i =0; i < 10; i++) x[3] = 3.30
{ x[4] = 4.40
scanf(“%f”,&value); x[5] = 5.50
x[i] = value; x[6] = 6.60
} x[7] = 7.70
total = 0.0; x[8] = 8.80
for(i = 0; i < 10; i++) x[9] = 9.90
total = total + x[i] * x[i]; x[10] = 10.10
printf(“\n”); Total = 446.86
for(i = 0; i < 10; i++)
printf(“x[%2d] = %5.2f \n”,i+1,x[i]);
printf(“\nTotal = %.2f\n”,total);
}
TWO-DIMENSIONAL ARRAYS
 Two-dimensional arrays are declared as follows
Eg: product[i][j] = row * column;

type array-name[row_size][column_size];
27
 For example consider a two array v[4][3]
Col 0 Col 1 Col 3

Row0

Row1

Row2

Row3

Example Program:
include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}

MULTIDIMENSIONAL ARRAY
 C allows arrays of three or more dimensions. The exact limit is determined by the compiler. The
general form of a multidimensional array is

type array_name[s1][s2][s3]…s[m];

Eg: 1. int survey[3][5][12];


2. float table[5][4][5][3];

Example Program:
include<conio.h>
void main()
{
int i, j, k;
int arr[3][3][3]=
{
{
{11, 12, 13},
28
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
clrscr();
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
getch();
}
DYNAMIC ARRAYS

 Dynamic memory allocation allows a program to obtain more memory space, while running or to
release space when no space is required.
 Although, C language inherently does not has any technique to allocated memory dynamically, there
are 4 library functions under "stdlib.h" for dynamic memory allocation.

Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory
free() dellocate the previously allocated space

realloc() Change the size of previously allocated space

malloc()
 The name malloc stands for "memory allocation". The function malloc() reserves a block of memory
of specified size and return a pointer of type void which can be casted into pointer of any form.

 Syntax of malloc() :
o ptr=(cast-type*)malloc(byte-size)
 Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with
size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
o ptr=(int*)malloc(100*sizeof(int));

29
 This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and
the pointer points to the address of first byte of memory.
calloc()
 The name calloc stands for "contiguous allocation". The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks
of memory each of same size and sets all bytes to zero.
 Syntax of calloc() :
o ptr=(cast-type*)calloc(n,element-size);
 This statement will allocate contiguous space in memory for an array of n elements. For
example:ptr=(float*)calloc(25,sizeof(float));This statement allocates contiguous space in memory for
an array of 25 elements each of size of float, i.e, 4 bytes.
free()
 Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The
programmer must use free() explicitly to release space.
o syntax of free() : free(ptr);
 This statement cause the space in memory pointer by ptr to be deallocated.
 Examples of calloc() and malloc()
UNIT –II COMPLETED
Reference Book: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy.

UNIT-III
CHARACTER ARRAYS AND STRINGS
i.) INTRODUCTION
 A string is a array of characters. Any group of characters (except the double quote sign) defined
between double quotation marks is a constant string. Eg: “Man is obviously made to think”
 If we want to include a double quote in a string, then we may use it with the back slash.
Eg: printf(“\”well done!\””);
Output : “well done!”
 The operations that are performed on character strings are
 Reading and writing strings.
 Combining strings together.
 Copying one string to another.
 Comparing strings for equality.
 Extracting a portion of a string.
ii.) DECLARING AND INITIALIZING STRING VARIABLES
 A string variable is any valid C variable name and is always declared as an array.
 The general form of declaration of a string variable is
char string_name[size];
Eg: char city[10]; char name[30];
 When the compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of the string. Therefore, the size should be equal to the maximum number
of characters in the string plus one. C permits a character array to be initialized in either of the
following two forms
static char city[9] = “NEW YORK”;
static char city[9] = {‘N’, ‘E’, ‘W’, ‘ ‘, ‘Y’, ‘O’, ‘R’, ‘K’, ‘\0’};
iii.) READING STRING FROM TERMINAL
 The familiar input function scanf can be used with %s format specification to read in a string of
characters.
 Eg: char address[15];
scanf(“%s”,address);
Program
/*Reading a series of words using scanf function*/
main()
{
30
char word1[40],word2[40],word3[40],word4[40];
printf(“Enter text:\n”);
scanf(“%s %s”,word1, word2);
scanf(“%s”, word3);
scanf(“%s”,word4);
printf(“\n”);
printf(“word1 = %s \n word2 = %s \n”,word1, word2);
printf(“word3 = %s \n word4 = %s \n”,word3, word4);
}
Reading a Line of Text
 It is not possible to use scanf function to read a line containing more than one word. This is because
the scanf terminates reading as soon as a space is encountered in the input. We can use the getchar
function repeatedly to read single character from the terminal, using the function getchar. Thus an
entire line of text can be read and stored in an array.
Program
/*Program to read a line of text from terminal*/
#include<stdio.h>
main()
{
char line[81],character;
int c;
c = 0;
printf(“Enter text. Press<Return>at end \n”);
do
{
character = getchar();
line[c] = character;
c++;
}
while(character != ‘\n’);
c = c-1;
line[c] = ‘\0’;
printf(“\n %s \n”,line);
}
iii.) WRITING STRINGS TO SCREEN
 We have used extensively the printf function with %s format to print strings to the screen. The
format %s can be used to display an array of characters that is terminated by the null character.
 For eg, the statement printf(“%s”, name); can be used to display the entire contents of the array
name.
iv.) ARITHMETIC OPERATIONS ON CHARACTERS
 C allows us to manipulate characters the same way we do with numbers. Whenever a character
constant or character variable is used in an expression, it is automatically converted into integer
value by the system.
 For eg, if the machine uses the ASCII representation, then,
x = ‘a’;
printf(“%d \n”,x);
will display the number 97 on the screen.
 The C library supports a function that converts a string of digits into their integer values. The
function takes the form x = atoi(string)
v.) PUTTING STRINGS TOGETHER
 Just as we cannot assign one string to another directly, we cannot join two strings together by the
simple arithmetic addition. That is, the statements such as
string3 = string1 + string2;
string2 = string1 + “hello”;
are not valid.
31
 The characters from string1 and string2 should be copied into string3 one after the other. The process
of combining two strings together is called concatenation.
x = atoi(string)
vi.) COMPARISON OF TWO STRINGS
 C does not permit the comparison of two strings directly. That is, the statements such as
if(name1 == name2)
if(name == “ABC”);
are not permitted.
 It is therefore necessary to compare the two strings to be tested, character by character. The
comparison is done until there is a mismatch or one of the strings terminate into a null character,
whichever occurs first.
vii.) STRING - HANDLING FUNCTIONS
C library supports a large number of string-handling functions that can be used to carry out many of
the string manipulation activities. Following are the most commonly used string handling functions.
Function Action
a) strcat( ) Concatenates two strings
b) strcmp( ) Compares two strings
c) strcpy( ) Copies one string over another
d) strlen( ) Finds the length of the string
a) strcat( ) Function
 The strcat function joins two strings together. It takes the following form
strcat( string1,string2);
 Eg: strcat(part1, “GOOD”);
b) strcmp( ) Function
 It is used to compare two strings identified by the arguments and has a value 0 if they are equal. It
takes the form: strcmp(string1,string2);
 Eg: 1) strcmp(name1,name2);
2) strcmp(name1,”john”);
3) strcmp(“ram”, “rom”);
c) strcpy( ) Function
 This function works almost like a string assignment operator. It takes the form
strcpy(string1,string2)
 This assigns the content of string2 to string1.
 Eg: 1) strcpy(city, “DELHI”);
2) strcpy(city1,city2);
d) strlen( ) Function
 This function counts and returns the number of characters in a string.
n = strlen(string);
Example Program
/*Illustration of string-handling functions*/
#include<string.h>
main()
{
char s1[20],s2[20],s3[20];
int x, l1, l2, l3;
printf(“Enter two string constants \n”);
printf(“?”);
scanf(“%s %s”, s1, s2); OUTPUT
x = strcmp(s1, s2); Enter two string constants
if(x != 0) ? New York
printf(“Strings are not equal \n”); Strings are not equal
strcat(s1, s2); s1 = New York length = 7 characters
else s2 = York length = 4 characters
printf(“Strings are equal \n”);
strcpy(s3,s1);
32
l1 = strlen(s1);
l2 = strlen(s2);
l3 = strlen(s3);
printf(“\ns1 = %s \t length = %d characters \n”,s1, l1);
printf(“\ns2= %s \t length = %d characters \n”,s2, l2);
printf(“\ns3 = %s \t length = %d characters \n”,s3, l3);
}
viii.) OTHER STRING FUNCTIONS
Strncpy Function
 In addition to the function strcpy that copies one string to another; we have another function strncpy
that copies only the left-most n characters of the source string to the target string variable.
 This is a three-parameter function and is invoked as follows: strncpy(s1, s2, 5);
 This statement copies the first 5 character of the source string s2 into the target string s1.
 Since the 5 characters may not include the terminating null character, we have to place it explicitly in
the 6th position of s2 as: s1[6] =’\0’; Now, the string s1 contains a proper string.
Strncmp Function
 A variation of the function strcmp is the function strncmp. This function also has three parameters
as: strncmp (s1, s2, n);
 This compares the left-most n character of s1 to s2 and returns
1. 0 if they are equal;
2. Negative number, if s1 sub-string is less than s2; and
3. Positive number, otherwise.
Strncat Function
 This is another concatenation function that takes three parameters: strncat(s1,s2,n);
This call will concatenate the left-most n characters of s2 to the end of s1.
Strstr Function
 It is a two-parameter function used to locate a sub-string in a string and takes the form: strstr (s1,
s2);
 Example  strstr (s1, “ABC”);
 The function strstr searches the string s1 to see whether the string s2 is contained in s1. If yes, the
function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL
pointer.
 We also have functions to determine the existence of a character in a string.
 The function call strchr(s1, ‘m’); will locate the first occurrence of the character ‘m’
 A list of names can be treated as a table of strings and a two dimensional character array can be used
to store the entire list.
Example:
printf("%d", strlen ("cord") )'; 4
printf("%s", strcpy(sl, "string")); string
printf("%s", strncpy(s2, "endomorph", 4)); endo
printf("%s", strcat(s1, s2)); stringendo
printf("%d", strcmp (s1, s2)); 1
printf("%d". strncmp(sl+6, s2, 4)); 0
printf("%s", strchr (si, 'n')); ngendo
printf ("%s". strrchr (si, 'n' ) ) ; ndo

USER-DEFINED FUNCTIONS
 User-defined functions are those functions which are defined by the user at the time of writing
program. Functions are made for code reusability and for saving time and space.
i.) INTRODUCTION
 Functions can be classified into two categories, namely, library functions and user defined functions.
 Main is an example of user-defined functions, printf and scanf belong to the category of library
functions.

33
 The main difference between these two categories is that library functions are not required to be
written by us whereas a user-defined function has to be developed by the user at the time of writing
the program.
Function declaration
 General syntax of function declaration is, return-type function-name (parameter-list) ;
Function definition Syntax
 General syntax of function definition is,
return-type function-name (parameter-list)
{
function-body ;
}
 The first line return-type function-name(parameter) is known as function header and the
statement within curly braces is called function body.
ii.) NEED FOR USER-DEFINED FUNCTIONS
 It facilitates top-down modular programming.
 The length of the source program can be reduced by using functions at appropriate places.
 It is easy to locate and isolate a faulty function for further investigations.
 A function can be used by many other programs
iii.) A MULTIFUNCTION PROGRAM
 A function is a self-contained block of code that performs a particular task. Once a function has been
designed and packed, it can be treated as a ‘black box’ that takes some data from the main program
and returns a value. Thus a program, which has been written using a number of functions, is treated
as a multi-function program.
iv.) ELEMENTS OF USER DEFINED FUNCTIONS
 In order to make use of a user-defined function, we need to establish three elements that are related
to functions.
1. Function definition
2. Function call
3. Function declaration
v.) DEFINITION OF FUNCTIONS
 The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
body of the function
}
 A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function:
 Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
 Function Body: The function body contains a collection of statements that define what the function
does.
vi.) RETURN VALUES AND THEIR TYPES
All C functions can be called either with arguments or without arguments in a C program.
 C function with arguments (parameters) and with return value
 C function with arguments (parameters) and without return value
 C function without arguments (parameters) and without return value
 C function without arguments (parameters) and with return value

34
S.no C function syntax
1 with arguments and with int function ( int ); // function declaration
return values function ( a ); // function call
int function( int a ) // function definition
{statements; return a;}
2 with arguments and without void function ( int ); // function declaration
return values function( a ); // function call
void function( int a ) // function definition
{statements;}
3 without arguments and without void function(); // function declaration
return values function(); // function call
void function() // function definition
{statements;}
4 without arguments and with int function ( ); // function declaration
return values function ( ); // function call
int function( ) // function definition
{statements; return a;}
vii.) FUNCTION CALLS
 While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
 When a program calls a function, program control is transferred to the called function. A called
function performs defined task, and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.
 To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:
#include <stdio.h>
int max(int num1, int num2);
int main ()
{
int a = 100,b = 200, ret;
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
FUNCTION DECLARATION
 Function declaration is the first line of function definition. When a
function is called, control of the program is transferred to function
declaration.
Syntax of function declaration
return_type function_name(type(1) argument(1),....,type(n) argument(n))
Function body
 Function declaration is followed by body of function inside braces.
Passing arguments to functions
 In programming, argument(parameter) refers to data this is passed to function(function
definition) while calling function.
 In above example two variable, num1 and num2 are passed to function during function call
and these arguments are accepted by arguments a and b in function definition.

CATEGORY OF FUNCTIONS
 A function may belong to one of the following categories.
1) Functions with no arguments and no return values.
2) Functions with arguments and no return values.
3) Functions with arguments and return values
4) Function with no arguments return value

35
i.) FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUE
#include<stdio.h>
void area(); // Prototype Declaration
void main()
{
area(); Output :
} Enter the radius : 3
void area() Area of Circle = 28.260000
{
float area_circle;
float rad;
printf("\nEnter the radius : ");
scanf("%f",&rad);
area_circle = 3.14 * rad * rad ;
printf("Area of Circle = %f",area_circle);
}
ii.) FUNCTION WITH ARGUMENTS AND NO RETURN VALUES
#include<stdio.h>
#include<conio.h>
void area(float rad); // Prototype Declaration
void main()
{
float rad;
printf("nEnter the radius : "); Output :
scanf("%f",&rad); Enter the radius : 3
area(rad); Area of Circle = 28.260000
getch();
}
void area(float rad)
{
float ar;
ar = 3.14 * rad * rad ;
printf("Area of Circle = %f",ar);
}

iii.) FNCTION WITH NO ARGUMENTS BUT RETURN VALUE


#include <stdio.h>
int input();
int main()
{
int num,i,flag = 0;
num=input(); /* No argument is passed to input() */
for(i=2; i<=num/2; ++i)
{
if(num%i==0)
{
flag = 1; break;
}
}
if(flag == 1)
printf("%d is not prime",num);
else
printf("%d is prime", num);
return 0;
}
36
int input()
{ /* Integer value is returned from input() to calling function */
int n;
printf("Enter positive integer to check:\n");
scanf("%d",&n);
return n;
}
iv.) FUNCTION WITH ARGUMENT AND ONE RETURN VALUE
#include<stdio.h>
float calculate_area(int);
int main()
{
int radius;
float area;
printf("\nEnter the radius of the circle : ");
scanf("%d",&radius);
Output :
area = calculate_area(radius);
printf("\nArea of Circle : %f ",area); Enter the radius of the circle : 2
return(0); Area of Circle : 12.56
}
float calculate_area(int radius)
{
float areaOfCircle;
areaOfCircle = 3.14 * radius * radius;
return(areaOfCircle);
}
FUNCTION THAT RETURN MULTIPLE VALUE
Syntax:
return type function_name (arg1, arg2, arg3….argn)
{
executable statement;
}
NESTING OF FUNCTIONS
 C permits nesting of functions freely. main can call function1,which calls function2,which calls
function3,…..and so on.

Syntax:
Void Main( ) Void Function1( ) Void function3( )
{ { {
Function1( ); Function2( ) Function3( )
} } }

RECURSION
i.) INTRODUCTION
 A function that calls itself is known as recursive function and this technique is known as
recursion in C programming.
Output:
Example of recursion in C programming
This is example of recursion
Main( )
This is example of recursion
{
This is example of recursion
Printf(“This is example of recursion\n”);
:
Main( );
:
}
 It will run indefinitely.
37
PASSING ARRAYS TO FUNCTION
Example program for passing arrays to function
#include <stdio.h>
disp( char ch)
{
printf("%c ", ch); Output:
} abcdefghij
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'j'};
for (int x=0; x<=10; x++)
{
disp (arr[x]);
}
return 0;
}
PASSING STRING TO FUNCTION
 String can be passed to function in similar manner as arrays as, string is also an array
#include <stdio.h>
void Reverse();
int main()
{
printf("Enter a sentence: ");
Reverse();
return 0;
}
void Reverse()
{
char c; Output
scanf("%c",&c); Enter a sentence: margorp emosewa
if( c != '\n') awesome program
{
Reverse();
printf("%c",c);
}
}

SCOPE, VISIBILITY AND LIFETIME OF VARIABLES


 In C not only do all the variables have a data type, they also have a storage class.
 The variable storage classes relevant to functions are
1. Automatic variables,
2. External variables,
3. Static variables,
4. Register variables.
 The variables may also be broadly categorized depending on the place of their declaration as:
 Internal (local)  declared within a particular function.
 External (global)  declared outside of any function.
Automatic variables
 They are declared inside a function in which they are to be utilized.
 They are created when the function is called and destroyed automatically when the function is exited.
Hence the name automatic and they are private.
 We may use the keyword auto to declare automatic variables explicitly.
Eg: main()
{ auto int number;
38
---- }
External variables
 Variables that are both alive and active throughout the entire program are known as external variables.
 They are also called as global variables.
 Global variables can be accessed by any function in the program and are declared outside a function.
External declaration
Eg: extern float height[ ];
main()
{ extern int y; /* external declaration */
------ }
function 1
{ extern int y;
-----
int y; /* external declaration*/ }
Static variables
 The value of any static variables persists until the end of the program.
 A variable can be declared static using the keyword static like:
static int x;
static float y;
 It can be either an internal type or external type depending on the place of declaration.
Program
#include<stdio.h>
void stat(void);
main()
{ int i;
for(i=1;i<=3;i++)
stat(); }
void stat(void)
{
static int x=0;
x=x+1;
printf("x=%d\n",x);}
Register variables
 A variable should be kept in one of the machine’s register, instead keeping in the memory.
 Since a register access is much faster than a memory access, keeping the frequently accessed variables in
the register will lead to faster execution of programs.
register int count;
Scope and lifetime of variables
Storage class Where declared Visibility(active) Lifetime(alive)
Extern Before all the functions Entire files and other files where the Global
(cannot be initialized) variable is declared ‘extern’.
Static Before all functions Only in that file Global
None or auto Inside a function (or Only in that function or block Until end of the
block) function or block
Register Inside a function Only in that function or block Until the end of the
function or block
Static Inside a function Only in that function Global

Nested blocks
 A set of statements enclosed in a set of braces is known a block or compound statement.
 A block can have its own declaration and other statements.
 It is also possible to have a block of such statements inside the body of a function or another block
known as nested blocks.
39

Ex: main()
{ int a =20;
int b=10;
-------- outer block The result C
{ int a=0; will be 10,
int c=a+b; inner block not 30
}
b=a;
}
UNIT –III COMPLETED
Reference Book: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy.

UNIT-IV
STRUCTURES AND UNION
i.) INTRODUCTION
 C supports a constructed data type known as structures, a mechanism for packing data of different
types. A structure is a convenient tool for handling a group of logically related data items. For
example, it can be used to represent a set of attributes, such as student _ name, roll _ number and
marks. The concept of a structure is analogous to that of a ‘record’ in many other languages. More
examples of such structures are:
 time : seconds, minutes, hours
 data : day, month, year
 book : author, title, price, year
 city : name, country, population
ii.) DEFINING A STRUCTURE
 Unlike arrays, structure must be defined first for their format that may be used later to declare
structure variables
 We can define a structure to hold this information as follows:
struct book _bank
{
char title[20];
char author[15];
int pages;
float price;
};
 The keyword struct declares a structure to hold the details of four data fields, namely title, author,
pages, and price. These fields are called structure elements or members. Each member may belong to
different type of data. book _ bank is the name of the structure and is called the structure tag. The tag
name may be used subsequently to declare variables that have the tag’s structure.
 The general format of a structure definition is as follows:
struct tag _ name
{
data _ type member1;
data _ type member2;
--------- -----
--------- -----
};
iii.) DECLARING STRUCTURE VARIABLE
Let us see how to declare structure in c programming language.
struct tag
{
data_type1 member1;
data_type2 member2;
40
data_type3 member3;
};
Example
struct date
{
int date;
char month[20];
int year;
}today;

// 'today' is name of Structure variable


iv.) ACCESSING STRUCTURE MEMBERS
1. Array elements are accessed using the Subscript variable , Similarly Structure members are accessed
using dot [.] operator.
2. (.) is called as “Structure member Operator”.
3. Use this Operator in between “Structure name” & “member name”
#include<stdio.h>
struct Vehicle
{
int wheels;
char vname[20];
char color[10];
}v1 = {4,"Nano","Red"};

int main()
{
printf("Vehicle No of Wheels : %d",v1.wheels);
printf("Vehicle Name : %s",v1.vname);
printf("Vehicle Color : %s",v1.color);
return(0);
}

Output :
Vehicle No of Wheels : 4
Vehicle Name : Nano
Vehicle Color : Red

v.) C STRUCTURE INITIALIZATION


1. When we declare a structure, memory is not allocated for un-initialized variable.
2. Let us discuss very familiar example of structure student , we can initialize structure variable in
different ways –
struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };
 In the above code snippet, we have seen that structure is declared and as soon as after declaration we
have initialized the structure variable.
std1 = { "Pritesh",67,78.3 }
 code for copying and comparing structure variable

vi.) COPYING AND COMPARING STRUCTURE VARIABLES


structclass
{
41
int number;
char name[20];
float marks;
};
main()
{
int x;
structclass student1 = {111,"Rao",72.50};
structclass student2 = {222,"Reddy", 67.00};
structclass student3;
student3 = student2;
x = ((student3.number == student2.number) & (student3.marks == student2.marks)) ? 1 : 0;
if(x == 1)
{
printf("\nstudent2 and student3 are same\n\n");
printf("%d %s %f\n", student3.number,
student3.name,
student3.marks);
}
else
printf("\nstudent2 and student3 are different\n\n");
}
Output
student2 and student3 are same
222 Reddy 67.000000
vii.) OPERATIONAL ON INDIVIDUAL MEMBERS
 A member with the dot operator along with its structure variable can be treated like any other
variable name and therefore can be manipulated using expressions and operators.
if(student.number==111)
student1.marks +=10.00;
float sum=studen1.marks+student2.marks;
stuent2.marks *=0.5;
 We can also apply increment and decrement operators to numeric type members. For example, the
following statements are valid.
student.number++;
++ student1.number;
 The precedence of the operator is higher than all arithmetic and relational operators and therefore no
parentheses are required.
ARRAY OF STRUCTURE
 Structure is used to store the information of One particular object but if we need to store such 100
objects then Array of Structure is used.
Example :
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}Book[100];
Explanation :
1. Here Book structure is used to Store the information of one Book.
2. In case if we need to store the Information of 100 books then Array of Structure is used.
3. b1[0] stores the Information of 1st Book , b1[1] stores the information of 2 2nd Book and So on We
can store the information of 100 books.
#include<stdio.h>
struct Employee
42
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{
int i;
struct Employee Emp[ 3 ]; //Statement 1
for(i=0;i<3;i++)
{
printf("\nEnter details of %d Employee",i+1);

printf("\n\tEnter Employee Id : ");


scanf("%d",&Emp[i].Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&Emp[i].Name);

printf("\n\tEnter Employee Age : ");


scanf("%d",&Emp[i].Age);

printf("\n\tEnter Employee Salary : ");


scanf("%ld",&Emp[i].Salary);
}
printf("\nDetails of Employees");
for(i=0;i<3;i++)
printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);

}
Output :

Enter details of 1 Employee


Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000

Enter details of 2 Employee


Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
i.) ARRAY WITHIN STRUCTURE
 Structure is used to store the information of One particular object but if we need to store such 100
objects then Array of Structure is used.
Example :
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}Book[100];
43
Explanation :
1. Here Book structure is used to Store the information of one Book.
2. In case if we need to store the Information of 100 books then Array of Structure is used.
3. b1[0] stores the Information of 1st Book , b1[1] stores the information of 2 2nd Book and So on We
can store the information of 100 books.
ii.) STRUCTURE WITHIN STRUCTURE
EXPLAIN ABOUT STRUCTURE WITHIN STRUCTURE (10 MARKS)
 Structure written inside another structure is called as nesting of two structures.
 Nested Structures are allowed in C Programming Language.
 We can write one Structure inside another structure as member of another structure.
struct date
{
int date;
int month;
int year;
};

struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;

#include <stdio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;

struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};

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


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

return 0;
}
Output :
Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990
44
iii.) STRUCTURE AND FUNCTIONS:
EXPLAIN ABOUT STRUCTURE AND FUNCTIONS.(PART B)
C supports the passing of structure values as arguments to functions. There are 3 arguments by which the
values of a structure can be transferred from one function to another.
1. The first method is to pass each member of the structure as an actual argument of the function call.
2. The second method involves passing of a copy of the entire structure to the called function.
3. The third approach employs a concept called pointers i.e., the address location of the structure is
passed to the called function. This method is more efficient as compared to the second one.
Syntax:

function-name (structure_variable_name);

The called function takes the following form:

data-typefn-name (struct_typest_name)
{
----
----
return (expression);
Description: }
1. The called function must be declared for its type, appropriate to the data type it is expected to return.
2. The structure variable used as the actual argument and the corresponding formal argument in the
called function must be of the same struct type.
3. The return statement is necessary only when the function is returning some data.
4. When a function returns a structure, it must be assigned to a structure of identical type in the calling
function.
5. The called function must be declared in the calling function for its type, if it is placed after the
calling function.

UNION
DEFINE UNION(PART A)
 A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose.
Defining a Union
 To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];

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

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
i.) SIZE OF STRUCTURE
WHAT ARE ALL DIFFERENT WAYS OF CALCULATING SIZE OF STRUCTURE(PART B)
Different ways of calculating size of structure
1. By observation
2. By Using sizeof Operator
3. Without using Sizeof Operator
Way 1 : Calculate by adding Individual Sizes
struct Book
{
int pages;
char name[10];
char author[10];
float price;
}b1;
Calculating Size of Structure :
Size = size of 'Pages' + size of 'Name' +
size of 'Author' + size of 'Price'
= 2 + 10 * 1 + 10 * 1 + 4
= 2 + 10 + 10 + 4
= 26
 Sizeof Operator is used to Calculate size of data type,variable,expression result.Syntax of sizeof is
much like function, but sizeof is not a library function. Sizeof is C Operator.
#include<stdio.h>
typedef struct b1 {
char bname[30];
int ssn;
int pages;
}book;
book b1 = {"Let Us C","1000",90};
int main()
{
printf("\nSize of Structure : %d",sizeof(b1));
return(0);
}
Output :
Size of Structure : 26

ii.) BIT FIELD DECLARATION


WHAT IS BIT FIELD DECLARATION(PART A)
The declaration of a bit-field has the following form inside a structure
struct {
type [member_name] : width ;
};
The following table describes the variable elements of a bit field −
Elements Description
An integer type that determines how a bit-field's value is interpreted. The type may be
Type
int, signed int, or unsigned int.
46
member_name The name of the bit-field.
The number of bits in the bit-field. The width must be less than or equal to the bit
Width
width of the specified type.
 The variables defined with a predefined width are called bit fields. A bit field can hold more than a
single bit; for example, if you need a variable to store a value from 0 to 7, then you can define a bit
field with a width of 3 bits as follows −
struct {
unsigned int age : 3;
} Age;

POINTERS
i.) INTRODUCTION
DEFINE POINTER(PART A)
 Pointers are variables that hold address of another variable of same data type.
 Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language. Although pointer may appear little confusing and complicated in the
beginning, but trust me its a powerful tool and handy to use once its mastered.
Benefit of using pointers
 Pointers are more efficient in handling Array and Structure.
 Pointer allows references to function and thereby helps in passing of function as arguments to other
function.
 It reduces length and the program execution time.
 It allows C to support dynamic memory management.
ii.) UNDERSTANDING POINTER
 Whenever a variable is declared, system will allocate a
location to that variable in the memory, to hold value. This
location will have its own address number.
 Let us assume that system has allocated memory location 80F
for a variable a. int a = 10 ;
 We can access the value 10 by either using the variable name a or the address 80F. Since the
memory addresses are simply numbers they can be assigned to some other variable.
 The variable that holds memory address are called pointer variables. A pointer variable is therefore
nothing but a variable that contains an address, which is a location of another variable. Value of
pointer variable will be stored in another memory location.

iii.) ACCESSING THE ADDRESS OF A VARIABLE


HOW WILL YOU ACCESS THE ADDRESS OF A VARIABLE?
 The address of variable’s memory location can be determined by the
& variable-name;
 Where & is a unary operator, called the address operator, which evaluates the address of its operand.
Example: p=&quantity;
 Here the address of quantity can be assigned to another variable P; this new variable is called a
pointer to quantity, since it “points” to the location where quantity is stored.
 Thus, P is referred to as a pointer variable.
 The data item represented by quantity can be accessed by the expression * P, where * is a unary
operator called the indirection operator, that operates only on a pointer variable.
 Therefore, * P and quantity both are represent the same data item.
iv.) DECLARING POINTER VARIABLES
HOW CAN YOU DECLARE A POINTER VARIABLE?
47
 When a pointer variable is declared, the variable must be preceded by an asterisk (*). This identifies
the fact that the variable is a pointer.
Syntax: data-type * pointer variable;
 Where pointer variable is the name of the pointer variable & data-type refer to the data-type of the
pointer’s object. Note that an asterisk must precede pointer variable.
Example: int *p;
 The above declares the variable p as a pointer variable that points to an int data type. Once a pointer
variable has been declared, the compiler allocates memory locations for that variable. Since the
memory location have not been assigned any values, these locations may contain some unknown
values in them and therefore they point to unknown locations.
Example:
int *p;

p ----------> ?

containsgarpage points to unknown location


v.) INITIALIZATION OF POINTER VARIABLE
 Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer
variable contains address of variable of same data type. In C language address operator & is used to
determine the address of a variable. The & (immediately preceding a variable name) returns the
address of the variable associated with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ;

vi.) ACCESSING A VARIABLE THROUGH ITS POINTER


 The indirection operator (*) is used to access the value of a variable by its ptr
 * can be remembered as value at address
 int n = *p // int *p = &quantity is done
 int n = *&quantity // is = quantity
 *5445 where 5445 is a valid location does not yield the content at that address
Syntax:
*pointer variable;
 where * - indirection operator & pointer variable - declared pointer variable
Program:
#include<stdio.h>
main()
{
int a;
int *b;
a=100;
b=&a;
printf("The content of the pointer b=%d\n", *b);
}
Output:
1. The content of the pointer b=100

vii.) CHAIN OF POINTERS


WRITE A NOTE ON CHAIN OF POINTERS.
 It is possible to make a pointer to point to another pointer, thus creating a chain of pointers as shown
below:
P2 p1 variable

Address 2 Address 1 Value


48
 The pointer variable p2 contains the address of the pointer variable p1, which points to the location
that contains the desired value. This is known as multiple indirections.
Example: void main()
{
int x, *p1,**p2;
x=100;
p1= &x;
p2=&p1;
printf(“%d”,**p2);
}
viii.) POINTER EXPRESSIONS
 Pointer expression is a linear combination of pointer variables, variables and operators (+, -, ++, __).
The pointer expression gives either numerical output or address output.
Pointer Assignment:
 The general form of pointer assignment is variable = pointer expression
Example:
 int x=5,y;
 int *p, *q;
 p = &x;
 q = &y;
 *q = *p +10 => pointer assignment.
Example:
1. y = *p1 * *p2;
2. sum = sum + *p1;
3. z = 5* - *p2/p1;
4. *p2 = *p2 + 10;

ix.) POINTERS AND ARRAYS


EXPLAIN ABOUT POINTERS AND ARRAYS.
 When an array is declared, the compiler allocates a base address and sufficient amount of storage to
contain all the elements of the array in contiguous memory allocations.
 The base address is the location of the first element i.e., index 0 of the array.
 The compiler also defines the array name as a constant pointer to the first element.
 Suppose we declare an array x as follows:
int x[5] = {1, 2, 3, 4, 5};

 Suppose the base address of x is 1000 and assuming that each integer requires 2 bytes then the 5
elements will be stored as follows:
Elements  x [0] x [0] x [0] x [0] x [0]

Value  1 2 3 4 5

Address  1000 1002 1004 1006 1008

Base address
 The name x is defined as a constant pointer pointing to the first element, x [0] and therefore the value
of x is 1000, the location where x [0] is stored. That is,
X = & x [0] = 1000
 If we declare p as an integer pointer, then we can make the pointer p to point to the array and x by
the following assignment.
p = x;
This is equivalent to p = & x [0];

49
 Now, we can access every value of x using p++ to move from one element to another. It contains the
two concepts,
1. pointers and one-dimensional arrays
2. pointers and two-dimensional arrays
Pointers and one-dimensional arrays:
It includes only one subscript (or) one index value
int a[10];

*a= *(a+0)=a[0]
*(a+1)=a[1]
*(a+2)=a[2]
*(a+3)=a[3]
*(a+4)=a[4]
……………
……………
*(a+i)=a[i]
In general,(a+i) gives the address of ith element in the array a and *(a+i) is the element stored in the
ith location of the array.
x.) POINTER AND CHARACTER STRINGS
 Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
 This creates a string and stores its address in the pointer variable str. The pointer str now points to
the first character of the string "Hello". Another important thing to note that string created using
char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //thi is Legal
 The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
 Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to use
indirection operator *.
xi.) ARRAY OF POINTERS
 We can also have array of pointers. Pointers are very helpful in handling character array with rows of
varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};

50
xii.) POINTERS AS FUNCTION ARGUMENTS
WRITE A NOTE ON POINTERS AND FUNCTIONS.
 When we pass addresses to a function, the parameters receiving the addresses should be a pointer.
The process of calling the function using pointers to pass the addresses of variable is known as call
by reference.
Example
#include<stdio.h>
void swap (int *a, int *b )
{
int temp;
temp= *a;
Output:
a=*b;
20 10 ( the values are changed)
*b=temp;
}
void main ( )
{
int a = 10,= 20
swap (&a, &b);
printf( “%d %d”,a ,b);
}

It includes
1. Passing pointers as arguments to functions.
2. Returning a pointer from a function.
3. Pointer to a function.

Passing pointers as arguments to functions:


Syntax: Function-name(type *ptr);
Types:
1. Call by value
2. Call by reference
Call by value: The mechanism of calling a function by passing values is called call by value.
Call by reference: The mechanism of calling a function by passing pointers is called call by value.
xiii.) FUNCTION RETURNING POINTERS:
DISCUSS ABOUT FUNCTION RETURNING POINTERS.
 The function returns a pointer to data-type
Syntax: Data-type *function-name(arguments);
Example: int *sum(int,int);
xiv.) POINTERS TO FUNCTIONS:
DISCUSS ABOUT POINTERS TO FUNCTIONS.
 A pointer invokes a function before which the pointer has to be declared appropriately and assigned
the address of the function
Syntax: Data-type (*variable-name)(argument-types);
Example: Int (*fnp)(int,int);
xv.) POINTERS AND STRUCTURES:
WRITE A NOTE ON POINTERS AND STRUCTURES.
 Thestructure used by pointer otherwise called as variable points to structure.
Example:-
structstu
{ int number(10);
char name(10);
int mark(4) ;
} stu1, * s;
 Here stu1 is the object of the stu. *s also points to the stu structure.
stu1 number;
51
stu1  name;
stu1  mark;
The symbol  is called the arrow operator and is made up of a minus sign and a greater than sign.
 In structure pointer could also use the notation (*s).number; to access the member number.
 The parenthesis around *s are necessary therefore the member operator “.” has a higher precedence
than the operator *;
Program:
struct temp
{
inti;
int *ip;
};
void main( )
{
struct temp t;
int a=10;
clrscr();
t.i=a;
t.ip=&a;
printf(“Value of a =%d \n”,t.i);
printf(“Address of a =%u \n”,t.ip);
getch();
}
UNIT –IV COMPLETED
Reference Book: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy.
UNIT-V
FILE MANAGEMENT
i.) INTRODUCTION
EXPLAIN ABOUT FILE MANAGEMENT.
 A file is a collection of records.
 Many real-life problems involve large volumes of data and in such situations; the console oriented
I/O operations pose 2 major problems:
1. It becomes cumbersome and time consuming to handle large volumes of data through
terminals.
2. The entire data is lost when either the program is terminated or the computer is turned off.
 Using file we can overcome these kinds of problems. A file is a place on the disk where a group of
related data is stored. C supports the basic file operations such as
1. naming a file
2. opening a file
3. reading data from a file
4. writing data from a file
5. Closing a file.
 There are two distinct ways to perform file operations in C. They are
1. Low – level I/O and
2. High – level I/O
The high level I/O functions are:
Function name Operation
fopen() Creates a new file for use & Opens an existing file for use
fclose() Closes a file which has been operand for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values to a file
52
getw() Reads an integer from a file
putw() writes an integer from a file
fseek() Sets the position to a desired point in the file
ftells() Gives the current position in the file. (i.e., in terms of bytes from the start )
rewind() Sets the position to the beginning of the file.
ii.) DEFINING AND OPENING A FILE:
HOW WILL YOU OPEN AND CLOSE A FILE?
 To store data in a file in the secondary memory, then certain things about the file should be specified
to the operating system. They include
1. Filename
2. Data structure
3. Purpose
 File name is a string of characters that make up a valid file name for the operating system.it may
contain two parts, a primary name and an optional period with the extension. Ex: input.data,text.out.
General format:
FILE * fp;
fp= fopen(“filename”, ”mode”);
 The first statement declares the variable fp as a “pointer to the data type FILE”.
 FILE is a Data structure defined in the I/O library.
Mode can be any one of the following,
1. r Opens the file for reading only
2. w Opens the file for writing only.
3. a Opens the file for adding data to it.

Example
FILE *p1,*p2;
P1=fopen(“data”,”r”);
P2=fopen(“result”,”w”);
Mode of opening Purpose
r Open for reading
w Open for writing (file need not exist)
a Open for appending (file need not exist)
r+ Open for reading and writing, start at beginning
w+ Open for reading and writing (overwrite file)
a+ Open for reading and writing (append if file exists)
Many recent compilers include additional modes of operation. They include
r+  The existing file is opened to the beginning for both reading and wring
w+ Same as w except both for reading and writing
a+  Same as a except both for reading and writing
iii.) CLOSING A FILE:
 A file must be closed as soon as all operations on it have been completed.
Syntax: fclose(file_pointer);
 Here file pointer indicates the pointer of the file
Example:
FILE *p1, *p2;
P1=fopen(“input”, “w”);
P2=fopen(“output”, “r”);
……
fclose(p1);
fclose(p2);
INPUT AND OUTPUT OPERATIONS ON FILES
WHAT ARE THE INPUT AND OUTPUT OPERATIONS USED IN FILES?
i.) getc( ):
53
 It is used to read a character from a file associated with FILE pointer fp1. Similarly getc is used to
read the data from file that has been opened in read mode.
Syntax: c=getc(fp);
 Where c represents a variable of character and fp represents a pointer to file.
Program: To count the number of lines, words, and characters in a file.
#include<stdio.h> if(ch==' ')
#include<conio.h> w++;
void main() else if(ch=='\n' || ch=='\0')
{ {
FILE *fp; l++;
char name[100],ch; w++;
int c=0,w=0,l=0; }
clrscr(); else
printf("enter line of text : \n"); c++;
fp=fopen("sample5.txt","w"); }
scanf("%[^EOF]",name); fclose(fp);
fprintf(fp,"%s",name); printf("no of character: %d\n no of words: %d \n no of lines:
fclose(fp); %d \n",c,w,l);
fp=fopen("sample5.txt","r"); getch();
while((ch=getc(fp))!=EOF) }
{
putc( ):
 It is used to write a character to the file. Syntax: putc(c,fp);
 Where c represents a character and fp represents a pointer to file.
 The file pointer moves by one character position for every operation of getc or putc.
The getw() and putw() functions:
 The getw and putw are integer oriented functions. They are used to read and write integer values.
Syntax:
1. getw(fp);
2. putw(integer, fp);
 Program to separate odd and even numbers using file.
#include<stdio.h> if(temp%2==0)
#include<conio.h> putw(temp,f3);
void main() else
{ putw(temp,f2);
FILE *f1,*f2,*f3; }
inttemp,i; fclose(f1);
clrscr(); fclose(f2);
printf("enter number:\n "); fclose(f3);
f1=fopen("input.txt","w"); f2=fopen("odd.txt","r");
for(i=0;i<=50;i++) f3=fopen("even.txt","r");
{ printf("\n Odd numbers are \n");
scanf("%d",&temp); while((temp=getw(f2)) !=EOF)
if(temp == -1) break; printf("%d ",temp);
putw(temp,f1); printf("\n Even numbers are \n");
} while((temp=getw(f3)) !=EOF)
fclose(f1); printf("%d ",temp);
f1=fopen("input.txt","r"); fclose(f2);
f2=fopen("odd.txt","w"); fclose(f3);
f3=fopen("even.txt","w"); getch();
while((temp=getw(f1)) !=EOF) }
{
fscanf ():

54
 fscanf allows to read multiple data items which may (or not) be of different types to a file. fscanf() is
similar to scanf().
Syntax: fscanf(fp,”control string”,arguments-list);
fprintf():
 fprintf is to write multiple data items which may (or not) be of different types to a file. fprintf() is
similar to printf()
Syntax: fprintf(fp,”control string”,arguments-list);
ERROR HANDLING DURING I/O OPERATIONS
EXPLAIN ABOUTERROR HANDLING DURING I/O OPERATIONS?
 It is possible that an error may occur during I/O operations on a file.
1. Trying to read beyond the end-of file mark
2. Device overflow
3. File has not been opened
4. Opening a file with an invalid file \name
 They are two status-inquiry library functions: feof and ferror that can help us detect I/O errors in the
files.
Example1:
if (feof(fp))
printf(“End of data]n”);
Example2:
if(ferror(fp)!=0)
printf(“An error has occurred”);

RANDOM ACCESS TO FILES


DESCRIBE ABOUT RANDOM ACCESS TO FILES WITH EXAMPLE.
 We can access the file in randomly by using the following function.
fseek():
 It takes a file pointer and return a number of type long that corresponding to the current position.
Syntax:
fseek ( fp, offset, position);
1. fppointer to FILE type
2. Offsetnumber of bytes
3. Positionit takes 3 values 0,1,2
operation of fseek function:

Statement Meaning
fseek(fp,0l,0); Go to the beginning.
fseek(fp,0l,1); Stay at the current position.
fseek(fp,0l,2); Go to the end of the file, past the last character of the file.
fseek(fp,m,0); Move to (m+1)th byte in the file
fseek(fp,m,1); Go forward by m bytes
fseek(fp,-m,1); Go backward by m bytes from the current position
fseek(fp,-m,2); Go backward by m bytes from the end.

ftell():
 The function ftell() returns the current position of the file pointer
Syntax:
position=ftell(fp);
 Here fp is a pointer to FILE type representing a file,the current position of the file pointer of the file
is returned by the function
rewind():

55
 The rewind() repositions the file pointer to the beginning of a file
Syntax:
rewind(fp);
COMMAND LINE ARGUMENTS
EXPLAIN ABOUT COMMAND LINE ARGUMENT WITH EXAMPLE.
 Itis a parameter supplied to a program when the program is invoked.
 This parameter may represent a filename the program should process.
Example:
C>PROGRAM X_FILE
 Consider the first line of the main function, i.e., main (). These parentheses may contain special
arguments that allow parameters to be passed to main from the Operating System. Two such
arguments are argc and argv, respectively.
 The first of these, argc, must be an integer variable, while the second, argv, is an array of pointer to
characters, i.e., an array of strings. Each string in this array will represent a parameter that is passed
to main.
 The value of argcwill indicate the number of parameters passed. The variable argc is an argument
counter that counts thye number of arguments on the command line.
 The argv is an argument vector and represents an array of character pointers that points to the
command line arguments.
argv[0]->PROGRAM
argv[1]->X_FILE
argv[2]->Y_FILE

Program:
#include<stdio.h>
#include<process.h>
void main(intargc,char *argv[]);
{
FILE *fin,*fout;
Char c;
If(argc!=3) Output:
{ C:\>copy om.dat om1.dat
printf(“Invalid number of arguments”); As a result the contents of om.dat are
exit(1); copied to om1.dat
}
fin=fopen(argv[1],”r”);
fout=fopen(argv[2],”w”);
while(!feof(fin))
{
c=getc(fin);
putc(c,fout);
}
fclose(fin);
fclose(fout);
}
Example Program:
#include <stdio.h>
main()
{ When the above code is compiled and
FILE *fp; executed, it reads the file created in previous
char buff[100]; section and produces the following result:
fp = fopen("/tmp/test.txt", "r"); 1 : This
fscanf(fp, "%s", buff); 2: is testing for fprintf...
printf("1 : %s\n", buff );

56
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
}
Example Program
#include <stdio.h> When the above code is compiled and executed, it waits
int main( ) for you to input some text when you enter a text and
{ press enter then program proceeds and reads the input
char str[100]; and displays it as follows:
int i;
printf( "Enter a value :"); $./a.out
scanf("%s %d", str, &i); Enter a value : seven 7
printf( "\nYou entered: %s, %d ", str, i); You entered: seven 7
return 0;
}

UNIT –V COMPLETED
Reference Book: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy.

57

You might also like