0% found this document useful (0 votes)
63 views131 pages

Cnotes - 2019

Uploaded by

tamilselvan50629
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views131 pages

Cnotes - 2019

Uploaded by

tamilselvan50629
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.

19UCA02 – PROGRAMMING IN C

Unit – I
Overview of C: History of C – Importance of C – Basic structure of C programs. Constants,
variables and data types: Character set – Keywords and identifiers – Constants – Variables –
Declaration of storage classes. Operators and expression – Evaluation of expressions – Type
conversions in expressions – Operator precedence and associatively – Mathematical functions.
Managing input and output operations: Reading and writing a character – Formatted input and
output.
Unit – II
Decision making and branching: Simple IF, IF-ELSE, Nesting of IF-ELSE, ELSE-IF ladder,
Switch statements – GOTO statements. Decision making and looping: WHILE statement – DO
statement – FOR statement – Jumps in loops. Arrays: Definition & Declaration – One dimensional –
Two dimensional – Multi dimensional arrays – Dynamic arrays.
Unit – III
Character arrays and strings: Introduction – Declaring and initializing string variables –
Reading strings from terminal – Writing strings to screen – String handling functions – Table of
Strings. User – Defined functions: Introduction – Need for user – Defined function – A Multi –
function program – elements of user – Definition of functions – definitions of Functions - Return
values and their types – Function calls – Function declaration – All category of functions – Nesting
of functions – Recursion – Passing arrays to functions – Passing strings to function.
Unit – IV
Structures and Unions: Introduction – Definition a structure – Declaring structure variables –
Accessing structure members – Structure initialization – Copying and comparing structure variables
– Arrays of structures – Arrays within structures – Structures within structures – Structures and
functions – Unions – Size of structures – Bit fields. Pointers: Introduction – Understanding pointers –
Accessing the address of variables – Initializing of pointer variables. Chain of pointers – Pointers –
Pointers expressions – Pointers and arrays – Pointers and character strings- Arrays of pointers –
Pointers as function arguments – Functions returning pointers – Pointers to functions- Pointer and
structures.
UNIT – V
File Management: Introduction – Defining and opening a file – Closing a file – Input/Output
operation on files – Error handling during I/O operations – Random access files- Command line
arguments. The Preprocessor: Introduction – Macro substitution – File inclusion – Compiler control
directives.
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 1
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

UNIT-I

OVERVIEW OF C
History of C:
 C is one of the most popular computer languages.
 It is structured, high level, machine independent language.
 It is platform independent
 ALGOL is the first structured programming language used in Europe.
 In 1967, Martin Richards developed a language called BCPL (Basic Combined programming
Language)
 In 1970, ken Thompson created a language using BCPL features called B.
 C was evolved from ALGOL, BCPL and B by Dennis Ritchie at Bell Laboratories in 1972.
 Unix Operating system, which was developed at Bell Laboratories, was coded almost entirely
in C
 C is running under a variety of operating system and hardware platform.
 C proved to be an excellent programming language for writing system programs.
 “The C programming language” by Kernighan and Ritchie, 1977 is known as “K&RC”
 ANSI, in 1983 standard for C was introduced it is called an ANSI C.

1960 - ALGOL - International Group


1967 - BCPL - Martin Richards
1970 - B - Ken Thompson
1972 - Tradional C - Dennis Ritchie
1978 - K & RC - Kernighan and Ritchie
1989 - ANSI C - ANSI Committee
1990 - ANSI/ISOC - ISO
1999 - C99 - Standardization Committee
Features of C:
C is attractive and popular because
1. General-purpose language
2. Structured Language
3. Flexible and powerful language
4. System programming Language
5. Fast running and efficient Language
6. Supports limited data types.
7. Commands may be inserted anywhere in a program
8. Programs are made up of functions
9. More built-in functions
10. Permits recursion.
Importance of C:
 It is a robust language
 It is well suited for writing both system software and business packages.
 Programs written in C are efficient and fast
 It is many times faster than BASIC
 Several standard functions are available
 It is highly portable
 C language is structured and it makes program debugging, testing and maintenance easier.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 2


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
 It is a collection of functions that are supported by C library.
 We can add own functions
 The programming task becomes simple using functions

Advantages
– C is a real world language, widely available and popular with professional
– C is a small, efficient, powerful and flexible language
– C has been standardized, making it more portable than some other languages
– C is close to the computer hardware revealing the underlying architecture
– C provides enough low level access to be suitable for embedded systems
– C is a high level language allowing complex systems to be constructed with minimum effort
– C‟s modular approach suits large, multi-programmer projects
– C‟s use of libraries makes it adaptable to many different application areas
– The Unix operating system was written in C and supports C
– C gave birth to C++, widely used for applications programming and more recently Java which was
based upon C++
– Many other languages borrow from C‟s syntax: e.q. Java,JavaScript, Perl etc

Disadvantages
– C is not really a language for novices; it was designed for professional users
– There are many things that can go wrong if you‟re not careful
– C lacks much of he automatic checking found in other high level languages
– Small typing errors can cause unwanted effect
– Does not support modern concepts such as object orientation and multi threading.

BASIC STRUCTURE OF C PROGRAM:

Documentation Section
Link Section
Definition Section
Global Declaration Section
Main( ) Function Section
{
Declaration Part
Executable Part
}
Subprogram Section
Function 1
Function 2

Function N

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 3


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Documentation Section:
This section consists of a set of comment lines useful for documentation. A comment is one
in C, When it is used in the program should be ignored by the compiler in C. “/*” is used to mark the
start of comment and it teminate with “*/”.

Example :
/* Programmer name : WELCOME
Programmer : Nareshkumar */
(or)

// This is the standard deviation program

Link Section:
It provides instruction to the compiler to link function from the system library. They are also
known as preprocessor directive used to include header files in C program.

Example :
#include<stdio.h>
#include<conio.h>
#include<math.h>

Definition Section:
The definition section defines all the symbolic constants to define any symbolic constant to
our program. We should use # define instructions.
 Define all symbolic constant.
 It must be in uppercase.

Example:
#define PI 3.14.
#define MONTHS 12

Global Declaration Section:


The global Declaration section contains variables that are used in more than one functions.
Such variables are called global variables and they are declared in the global declaration section that
is outside at all the functions.

Example:
#include<stdio.h>
int a=10;
float b=3.14;
void main( )
{
---------
---------
}

Main Function Section:


All the c programs consists one or more functions but there must be always be a function called
main( )
It contain is 2 part :

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 4


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
1. Declaration part.
2. Executable part.

Declaration Part:
In the part, declare all variables used in the executable part.

Executable Part:
 There is at least one statement in the executable part.
 These two parts appear between the opening and closing braces &all statements end with a
semicolon.

Subprogram Section:
The subprogram section contains all the user-defined function that are called in the main
function.
Example :
Myfunction( )
{
Printf(“Hello”);
}

Example program:
/* Program For Example */
#include<stdio.h>
int a = 10, b=20;
void main( )
{
int x = 30, y;
y = x;
printf(“%d”,y);
}

EXCUTING A C PROGRAM:-
The different steps involved in executing (or) running a program.

1. Writing the program


2. Compiling the Source program
3. Linking the program
4. Executing the program
An operating system is a program that controls the entire operating of a computer system.
1. Writing the program:
C programs can be written using Turbo C, Microsoft C etc. The written program is called the
source code (or) source program.

2. Compiling the Source program:


When the C program is compiler checks for syntax errors, if any errors exist, the user must
edit the program and compile it once again to generate the object code.

3. Linking the program:


In most of the compilers linking of function in the program, with the c library is done
automatically.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 5


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
4. Executing the program:
The C program is executed by the comment relevant to the compiler. The executable code
generated has an extension .exe

CONSTANTS, VARIABLES & DATA TYPES


Program:

A sequence of instruction is used to perform a particular task. The instructions are formed
using the character set.
Character Set:
The character sets are grouped into the following categories.

1. Letter (A….Z)&(a….z).
2. Digits (1…9).
3. Special characters
4. White spaces.
Special Characters:
SYMBOL NAME SYMBOL NAME

, comma \ back slash


. period - under score
; semicolon $ dollar sign
: colon % percentage sign
? question mark & ampersand
„ apostrophe ^ caret
“ quotation mark * asterisk
! exclamation mark - minus sign
| vertical bar + plus sign
/ slash < less sign
\ greater than sign ] right bracket
> left parenthesis { left brace
( right parenthesis } right brace
) right parenthesis # number sign
[ left bracket

White Space:

Black space.
Horizontal tab(„\t‟)
Carriage return(„\r‟).
New line(„\n‟)
Form Feed.(„\f‟)

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 6


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

C Tokens:
The smallest individual units are known as c Tokens. It consist Individual words, punctuation
mark, text are called tokens.

Keywords

Identifiers

constants
C Tokens -

Strings

Operators

Special Symbols

Keyword:

 All keywords have fixed meaning & these meanings cannot be changed. It must be written in
lower case.
 „C„support 32 keywords only.

EX:
Auto double int struct
Break else long switch
Case enum register typedef
Char extern return union
Const float short unsigned
Continue for signed void
Default goto sizeof volatile
Do if static while

Identifiers:
It refer to the name of variables, functions & arrays. Both lowercase & uppercase are
permitted. It cannot use a keyword.
 Identifiers are user-defined names and consist of a sequence of letters and digits with a
letter as a first character..
 Both upper case and lower case letters are permitted lower case letters are commonly
used.
 Identifiers are permits by using underscore.

Rules of Identifiers:
 First character must be an alphabet or underscore.
 Must consists of only letters, digits or underscore.
 Only first 31 characters are significant
 Cannot use a keyword.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 7


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
 Must not contain white space.

EX:
Valid Identifiers Invalid Identifiers
ADD, Add, - Add 3add . add+123 , for
Constants:
It refers to fixed data value that does not change during the execution of a program.

Constants

Primary constants Secondary constants


Array
Structure
Numeric Constant Character Constant Pointer
Union
Integer Real Single String Enum etc..
Constant Constant Character Constant
Constant
Integer Constant:
 It refer to a sequence of digit.
Rules:
 Comma and blank spaces cannot be included within integer constants.
 It must not have a decimal point.
 It Can be either positive or negative.
 If no sign precedes an integer constant it is assumed to be positive.

Three types of integers


1. Decimal
2. Hexadecimal
3. Octal
Decimal Integer:
Decimal integers consists of a set of digits 0 through 9, preceded by an optional – or +
sign.
Valid Invalid
0 1 +1 -1 345,123
-4236 34 51 23
94838639L 75.
600000u 34-51-23
L or l representing long integer.
U or u representing unsigned integer
UL or ul representing unsigned long integer.

Hexadecimal :
 It is formed from the hexadecimal number 0 through 9 and A through F (either upper
or lowercase), leading with 0X, or 0x
Valid Invalid
0x0 626
0x9A 0626
-0X9Aff 0Xapq

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 8


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Octal Integer Constant:


 Octal Integer constant is formed form the octal number system 0 through 7, with a
leading 0 (Zero)
Valid Invalid
00 01 627
0627 0628
-07757 06.27

Floating Point Constant:


 Any number with a decimal point is called a floating point or real or single precision
constant.
 The real number may also be expressed in exponential or scientific notation.
General Form:
Mantissa e exponent
e or E is used to represent exponent followed by a positive or negative integer.
Rules :-
1) Both the integer and fractional parts consists of a sequence of digits
2) Special character‟s except +,- and . are not allowed.
3) Floating constants may end with f or F
Example:
The value 215.65 may be written as 2.1565e2 in exponential notation
e2 means multiply by 102.

Double precision floating constants:


 A double precision floating constant is similar to a single precision floating constant,
but with higher range of values and greater precision.
 L or l is used for extend double precision numbers.
Valid Invalid
698354L 1.5E +2.5
+5.0E3 -4.5e-2
3.5e-5 $255

Single Character Constants:


A character written within single quotes is called a character constant.
Valid Invalid
„x‟ „z‟ „8‟ “ „y
„?‟ „!‟ „;‟ „+‟ “k”
For example,
The statement
printf(“%d”,‟a‟);
Would print the number 97, the ASCII value of the letter a.
printf(“%c”,‟97‟);
Would output the letter „a‟

String Constant:
 A string constant is a sequence of characters enclosed in double quotes.
 The characters may be letters, numbers, special characters and blank spaces.
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 9
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Valid Invalid
“Hello!” Program
“987” „Area‟
“Good” Maths”
“5+3”
„K‟ gives the integer value
“K” It is a string constant that contains the character K.

Backslash Character Constants:


 It is used in output functions.
 It is also called as escape sequence characters.
„\a‟ audible alert
„\b‟ back space
„\f‟ form feed
„\n‟ new line
„\r‟ carriage return
„\t‟ horizontal tab
„\v‟ vertical tab
„\‟‟ single quote
„\”‟ double quote
„\?‟ question mark
„\\‟ backslash
„\0‟ null

DEFINING SYMBOLIC CONSTANTS:


The Constants may appear repeatedly in a number of places in the program. It defined
some symbolic names are sometimes called identifiers.
The symbolic names are constant they do not appear in declarations. It defined by
using #define keyword.

Syntax :
#define symbolic name value of constant
Ex:
#define Max 200

Rules:
 Symbolic names have the same form as variable names It Should declare as a capital letters.
 No blank space between # and define.
 A blank space is required between the symbolic name and the constant.
 # define statement is declared in definition section in the c programme and it end with
semicolon.
 Symbolic names are NOT declared for data types. Its depend on type of constant.
 #define statement may appear anywhere in the program but before it is referees in the
program.
 #define statement is called a pre-processor compiler.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 10


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Variables:
 A variable is a data name that may be used to store a data value.
 Variable may take different values at different times during execution.
 Variable names may consist of letters, digits and underscore (_) character.
Rules:
 They must begin with a letter or underscore.
 ANSI standard recognizes a length of 31 characters but normally should not be exceed
more than eight characters.
 It should not be a keyword.
 White space is not allowed.
Valid Invalid
John 123
X1 (area)
Mark 25th
T-raise Char
int-type group one

Declaration Of Variables:
The declaration statement tells the complier 2 things.
1) It tells the complier what the variable name is.
2) It specify what type of data variable name is.

1. Primary type declaration:


A variable can be used to store value of any data type.
Syntax:
Data-type v1,v2,…..,vn;
 V1,v2,…,vn are the names of variables.
 Variables are separated by commas.
Example:
int count;
int number,total;
double ratio;

2. User-Defined Type Declaration:


“Type Definition” that allows users to define an identifier that would represent an
existing data type.
Syntax:
typedef type identifier;
 Type refers to an existing data type and “identifier” refers to the “new” name given
to the data type.
 Typedef cannot create a new type
typedef int units;
typedef float marks;
unit symbolizes int and marks symbolizes float.
units batch1,batch2;
marks name, class;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 11


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
 Advantage of typedef is that we can create meaningful data type names for
increasing the readability of the program.

3. Enumerated Data type:


 An enumeration is a special integer data type.
 This data type associated integer constants to identifiers.
 Enumerated data type is also user defined data type.
Syntax:
enum identifier {value1, value2,…..,valuen);
It can be used to declare variables that can have one of the values enclosed within the
braces (known as enumeration constants).
enum identifier v1,v2,….,vn;
enum tag
{
enumerator-1;
enumerator-2;


enumerator-n;
}
where
enum is a keyword indicating enumerated data type.
Tag is a name used to identify the specific enumeration. It is optional.
Enumerator-1,enumerator-2,…,enumerator-n are list of identifiers.
The list of identifiers enclosed within braces.

The enumerators may have


Default integer constant settings (or)
Explicit assignment given by programmer.
Syntax for declaring enumeration data type is
enum tag var1, var2, ….., varn;

Example:
enum flowers { ROSE,JASMINE, LOTUS};
enum vehicles {BUS,TRAIN,SCOOTER,CAR};
enum currency {rupee=1,dollar=50,pound=60,euro=40};
 If there is no value the identifier represent the values 0,1,2,3 and so on, from left to
right.
 During explicit assignment, the value may be in any order.

main()
{
int i;
enum swtch
{ OFF,ON
}
enum swtch flag;
i = setflag(flag);

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 12


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
printf(“Flag value : %d \n”,i);
}
setflag(flag)
{
printf(“Enter the flag value \n”);
printf(“0 for OFF and 1 for ON \n”);
scanf(“%d”,&flag);
return flag;
}

ASSIGNING VALUES TO THE VARIABLES:

 Variables are created for use in program statement.


value = amount + inrate * amount;
while (year <= PERIOD)
{


year = year + 1;
}
 the numeric value stored in the variable inrate is multiplied by the value stored in
amount and the product is added to amount. The result is stored in the variable value.
 The variable value is called the target variable.

Assignment statement:
Syntax:
variable-name = constant/ variable/expression;
Ex:
Initial-value = 0;
Balance = 75.84;
Final-value = balance * 1000;
C permits multiple assignments in one line.
Initial-value = 0; final-value = 100;
Assign a value to a variable at the time the variable is declared.
Ex:
int final-value = 100;
int yes = 1;
float balance = 756.56;
char yellow = „y‟;

 The process of giving initial values to variables is called initialization.


 Initialization of more than one variable in one statement using multiple assignment
operators.
p =q=s=0;
x=y=z=100;
Qualifiers :
 short,long,signed or unsigned identifiers may precede some of the scalar data types to
specify the nuber of bits used for reprinting the respective type of data in memory they
are known as qualifiers or modifiers
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 13
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
1. short and int are atlest 16 bits
2. long is atleast 32 bits
3. short is not longer than int
4. int is not longer than long
 signed or unsigned qualifiers may precede int to represent a signed integer or
an unsigned integer
 suppose 16 bits used to represent an integer.
 The most significant bit is used as sign bit and other 15 bit are for representing
the magnitude. otherwise all 16 bits are used for magnitude.
15 14 2 1 0 15 14 2 1 0

sign 15 bits 16 bits


bit Magnitude Magnitude
 Long and short qualifiers may precede int or signed int or unsigned int
 Float uses 32 bits and double uses 64 bits long double may be used for a very large
double precision data.

Reading Data from keyword:


 The way of giving values to variables is to input data through keyboard using the
scanf function
Syntax :
scanf(“control string “,&variable 1,&variable 2,…………….”);
 The control string contains the format of data being received.
 The ampersand symbol & before each variable name is an operator that specifies the
variable name‟s address.
scanf(“%d”,&number);
 This statement is encountered by the computer, the execution stops and waits for the
value of the variable number.
 The control string %d specifies that an integer value is to be read from the terminal.

Ex:
main()
{
int number;
printf(“enter an integer number”);
scanf(“%d”,&number);
printf(“print the number value \n”);
printf(“%d”,number);
}

Declaring a variable as constant :


The value of certain variable to remain constant during the execution of a program. so
we declaring the variable with the qualifier Const at the time of initialization
const int class,size =40 ;
const is a new data type this tells the compiler that the value of the int variable class size
must not be modified by the program.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 14


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Declaration of Storage class:


 Storage class that provides information about the variable location and visibility.
 The storage class decides the portion of the program within which the variables are
recognized.
Storage class Meaning
Auto Local variable known only to the function in which
it is declare. Default is auto.
Static Local variable which exists and retains its value even
after the control is transferred to the calling function.
Extern global variable known to all functions in the file.
Register Local variable which is stored in the register.
Storage class is another qualifier (like long or unsigned) that can be added to a variable
declaration.
Auto int count;
Register char ch;
Static int x;
Extern long total;
 Static and extern variables are automatically initialized to zero.
 Auto variables contain undefined values known as „garbage‟ unless they are initialized
explicitly.
Example:
int m;
main()
{
int i;
float balance;


function1();
}
function1()
{
int i;
float sum;


}
 m variable is declared before main is called global variable. It can be used in all the
functions.
 Global variable is also known as an external variable.
 I,balance,sum are called local variables.
 Local variables are visible and meaningful only inside the functions.
 Note the variable i has been declared in both the functions.
 Any change in the value of i in one function does not affect its value in the other.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 15


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
It provides the information about their location and visibility. The storage classes are
 auto
 register
 static
 extern
1. Automatic Storage class (auto):
 Automatic variables are declared inside a function. It also referred to as local or internal
variables.
 We may declare and use the same variable name in different function in the same program
without causing any confusion the complier.
Eg:1
main()
{
auto int i , j;
pintf(“\n %d%d”,i, j);
}

Output:
i = 1211 j= 211
Eg:2
Main()
{
Auto int i=1;
{
{
Printf(“\n %d”,i);
}
Printf(“%d”,i);
}
}
Output:
1
1

2. External Storage class (extern):


 It is also known as global variables.
 It is declared as outside a function.
 Once a variable has been declared as global any function can use it and also change its value.
 The keyword is extern.
Ex:
int i;
main( )
{
printf(“\n i=%d”,i);
increment( );
increment( );
decrement( );
decrement( );
}
increment()
{
i = i+1;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 16


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
printf(“\n i=%d”,i);
}
decrement( )
{
i= i-1;
printf(“\n i=%d”,i);
}

Output:
i =0
i=1
i=2
i=1
i=0

3. Static storage class (static):


It is a local variable which exists and retains its value even after the control is transferred to
the calling function.
Default initial value is 0(zero)

Ex:
main()
{
increment();
increment();
}
increment()
{
static int i=1;
printf(“%d\n”, i);
i=i+1;
}

4. Register Storage class (register):


Local variables which is stored in the register. Default initial value is garbage value.
Ex:
main()
{
register int i;
for( i=1; i<=10;i++)
printf(“\n%d”,i);
}
Advantage:
A value stored in CPU register can always be accessed faster than the one that is stored in
memory.

DATA TYPES:
 Data type is a term that refers to the kind of data used in a program.
Two major categories of data types are
(i) Scalar data types or Fundamental data types.
(ii) Derived data types or Structured data types.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 17


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
 The data items of scalar data-types are numbers and hence they are known as
Arithmetic data types.
 Arithmetic data-types are classified as integral and floating types.
 The enum, int and char types are known as integral types.
 Float and double are known as floating types.
 Also known as primitive or primary or fundamental or basic data types.
 Derived data types are derived from the collections of scalar data types. They are also
known as structured data types.
 Arrays
 Functions
 Pointers
 Structures
 Union
Data types

Scalar Derived

Arithmetic Pointer aggregate union function pointer

Integral Floating

Float double long double

Enum int short long signed unsigned signed unsigned


Int int short int short int long int long int

Char signed unsigned


Char char
Type Memory range
Char 8 -128 to 127
Unsigned char 8 0 to 255
Int 16 -32,768 to 32,767
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
Float 32 3.4E-38 TO 3.4E +38
Double 64 1.7E-38 TO 1.7E + 308
Long double 80 3.4E-4932 TO 1.1E+4932

Void types:
 The void types has no values.
 This is usually used to specify the type of functions.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 18


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
User Defined Data Declaration:
This allows the user to define an identifier that would represent an existing data type.
General format:
Typedef type identifier

Type refer to an existing data type.


identifier refer to the new name given to the data type.

Ex Program:

#include<stdio.h>
#include<conio.h>
void main()
{
typedef int marks;
marks m1,m2,m3,tot;
char name;
scanf(“%d%d%d%s”,&m1,&m2,&m3,&name);
tot=m1+m2+m3;
printf(“%d”,tot);
getch();
}

Enumerated Data Type:

General format:
enum identifier {value1,value2……valuen}

identifier is a user defined data type.


Eg: enum day{Monday,Tuesday……………Sunday};
 The complier automatically assign integer digits beginning with 0 to all the enumeration
constants.
 ie) the enumeration constant value1 is assigned 0,value2 Is assigned 1 and so on.
 The automatic assignments can be overridden by assigning values.
 Eg enum day{Monday=1,Tuesday=2……..Sunday=n}

OPERATORS:
It is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
o Arithmetic operators
o Relational operators
o Logical operators
o Assignment operators
o Increment & decrement operators
o Conditional operators
o Bitwise operators
o Special operators

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 19


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
1.Arithmetic Operators:

The operators that works on numbers are called arithmetic operators.

+ addition
- subraction
* multiplication
/ division
% modulo(It is used to give the reminder value )

Integer Arithmetic:
We use integer values in the arithmetic expression is called integer arithmetic.
Eg:
A=5,b=3

Expression value
a+b 8
a-b 2
a*b 15
a/b 1 (decimal point truncated)
a%b 2

Example program
/*calculate months &days*/
void main()
{
int months, days;
printf(“enter the days”);
scanf(“%d”,&days);
months=days/30;
days=days%30;
printf(“months=%d days=%d”,months,days);
}

Real Arithmetic:
The arithmetic operation involves only real numbers is called real arithmetic.
A=5.5,b=2.0
Expression value
a+b 7.0
a-b 3.0
a*b 10.0
a/b 2.75

Mixed mode Arithmetic:


When one of the operands is real & other is integer .
Eg 15/10.0=1.5

2. Relational Operators:

These operators are used to compare two or more quantities. the result is either true or false.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 20


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Operators Meaning
< is less than
<= is less than or equal to
< is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

General format:

Operand1 relational operator operand2

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“ the largest value is %d”,a);
else
printf(“ the largest value is%d”,b);
getch();
}

3. Logical Operator:

The logical operator is used to test more than one condition.

Logical Operator Meaning


&& logical AND
|| logical OR
! logical NOT

Working of AND,OR:

Op1 op2 op&&op2 op1||op2

0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

Working of NOT:
Op1 !op1
0 1
1 0

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 21


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
4. Assignment Operator:

The assignment operator is used to assign the values to the operand.


General format:

Variable operand = expression

Shorthand Assignment:
The shorthand assignment operator is op=.
Op->operator.
Statement with simple statement with shorthand
Assignment operator operator
a=a+1 a+=1;
a=a-1 a-+1;
a=a*(n+1) a*=n+1;

Advantages:
 The statement more concise and easier to read.
 The left-hand side variable need not to repeat on the right-hand side.
 The statement is more efficient.

5. Increment And Decrement Operator:

 The increment is operator (++) add one and decrement operator(--) is subtract one.
Eg.
++m =>m=m+1=>m+=1.
M++=>m=m+1=>m+=1.
 In general m++,++m are same but when they are used in assignment statement they have
different meanings.
 If the operator placed before the operand it is known as preincrement operator. if the operator
placed following the operand it is known as post increment operator.
For eg.
M=5 m=5;
Y=++m; y=m++;
Y=6,m=6. y=5,m=6.
 A prefix operator first adds 1 to the operand and then the result is assigned to the variable on
left.
 Postfix operators first assigns the value to the variable on left and then increment the operand.

6. Conditional Operator (or) Ternary operator:

It is a ternary operator and takes three operands. The “?:” is jointly known as conditional
operator.
General format:

Exp1?Exp2:Exp3

Exp -> expressions.

 Exp1 is evaluated and if it is true,exp2 is evaluated and the value is assign to variable.
 Exp1 is false exp3 is evaluated and the value is assign to variable.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 22


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Ex:
a = 10 b=5
z = (a>b) ? a: b;
Hear a > b is true then a is printed otherwise b is printed.

7. Bitwise Operator:

- Bitwise operator are used for manipulation of data at bit level.


- Direct manipulation of the bits stored in the memory.
- Bitwise operator are applied only to integer types such as char, short, int, signed,
unsigned and long ,not applied for float and double.
Bitwise operators
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR(XOR)
<< left shift
>> right shift
~ one‟s compliment (unary)

Compared bits Result


0&0 0
0&1 0
1&0 0
1&1 1

Ex:
a&b 00000101
& 00000011

00000001 result =1
Bitwise or (|) inclusive:
- The | operator performs a bitwise OR between two operators.
Compared bits result
0|0 0
0|1 1
1|0 1
1|1 1

Ex:
a|b 00000101
00000011

00000111
given number 187 Binary Representation: 10111011
15 00001111

91 10111111

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 23


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Bitwise exclusive or(^):
The operator ^ performs a bitwise exclusive OR between two operands.
COMPARED BITS RESULT
0^0 0
0^1 1
1^0 1
1^1 0

Ex:
a^b 00000101
00000011 result(decimal)
00000110 6
given number 214 11010110
selected second operand 31 ^ 00011111
201 11001001
Shift operators:
- The right shift operator >> and the left shift operator << more the bit patterns
To the right or less respectively,
Syntax: constant shift operator n
Variable or shift operator n
- Where shift operator is any one of the shift operator >>. And << n is the number
of bit positions to be shifted.
Ex:
Bit pattern 10101101 is to be shifted by 3 bit position
1 0 1 0 1 1 0 1
The bit paten after the right shift operation is given below
0 0 0 1 0 1 0 1
Left shift operator
0 1 1 0 1 0 0 0
Example:
+20 >> 2 00010100 >> 2 100 >> 1 01100100 >> 1
00000101 5 Decimal 00110010 50 Decimal
+20<<2 00010100 <<2
01010000 ->80 (decimal)
100<< 1 01100100 <<1
11001000 -> 200(decimal)
One’s compliment operator:
- this operator converts all 1 bits to 0 and all 0 bit to 1
illustration of ~operator
Expression Binary representation one‟s compliment
Binary decimal
~17 ~00010001 11101110 238

8 .Special Operators:
- Special operators such as comma operator, size of operator, pointer operators
(& and *)
- And member selection operator (. And ->)

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 24


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
The comma operator:
- The comma operator can be used to link the related expression together.
- It is evaluated from left to right and the value of right most expression is the value
of combined expression
- Value=(x=10,y=5,x+y)
- First assigns the value 10 to x then assigns 5 tpo y and finally assigns 15 to value.

The size of operator:


- sizeof is a compile time operator and when used with an operand it returns the
number of bytes the operand occupies.
- The operand may be a variable ,a constant or a data type qualifier
M = sizeof(sum);
N = sizeof(long int);
K = sizeof(235l);

EXPRESSION:
1. Arithmetic expression:
 An arithmetic expression is a combination of variable, constant, and operator arranged
as per the a syntax of the language.
Algebraic expression ‘C’ Expression
axb-c a*b-c
(m+n)(x+y) (m+n) * (x+y)
(ab/c) a*b/c
3x^2 +2x+1 3*X*X+2*X+1

EVALUATION OF EXPRESSIONS:
Expressions are evaluated using an assignment statement
variable =expression
X=a*b-c;
Y=b/c*a;
PRECEDENCE OF ARITHMETIC OPERATORS:
An arithmetic expression without parentheses will be evaluated from left to right using the
rules of precedence of operators
Arithmetic operator:
+,-,*,/,%
high priority * /%
low priority + -
First the high priority operators are evaluated and then the low priority operators
x=a-b/3+c*2-1
when a=9,b=12 and c=3
x=9-12 /3+3*2-1
it is evaluated as
step:
x=9-4+3*2-1
x=9-4+6-1
x=5+6-1
x=11-1
x=10

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 25


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
First Priority:()
The quantity inside the parenthesis have highest priority.
Second Priority:*/%
The * and / have equal priority and are evaluated from left to right in the order of occurrence.
Third Priority:+-
The + and - have equal priority and are evaluated from left to right in the order of
occurrence.

Arithmetic Expression Are Of Three Types :


1. Integer expression
2. Real expression
3. Mixed mode expression

Integer Expression:
An arithmetic expression involving only integer operands is known as an integer expression.
Let a=2,b=3,c=4,d=5,e=6

Eg 1:
(a+c)/c*d
Step 1). (2+4)/4*5
Step 2). 6/4*5
Step 3).1*5
Step 4). 5

Eg 2:
(a+c)/(c*d)
Step 1). (2+4)/(4*5)
Step 2). (6)/(4*5)
Step 3). (6)/(20)
Step 4). 0

Real Expression:
If all the operands in an expression are of real type the expression is known as real
expression. where a,b, c, d, are real variables
Eg :
Let a=.0 ; b=15.0;c=2.5
=10.0+15.0*2.5
=10.0+37.5
=47.5

Mixed Mode Expression:


If the operands in an expression are of different types, the expression is known as mixed
mode expression for evaluating a mixed mode expression, the lowest type operands is converted to
highest type and the result is of highest type.
Eg:
a+b*c
let a=10,b=15,c=2.5
=10+15*2.5
=10+37.5
=47.5

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 26


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Relational Expression:
 An expression containing relational operators is known as the relational expression.
 It is also used to combine two arithmetic expression.
 The result of a relational expression is either true or false. True is taken as one and false is
taken as zero.
The general form is
Exp1 relational operator Exp2

E.g.: a=5,b=6
a>b = false (0)
a!=b = True (1)
Logical Expressions:
 An expression containing logical operators is known as the logical expression.
 It is used to combine two or more relative expression.
 The result of a logical expression is either true or false.

The general form is


Exp1 logical operator Exp2

E.g. 1:
(test 1 > 40)||(test 2 > 40)
Mark = 5

E.g. 2:
Mark 1 > 40)&& (mark 2 >40) && (mark 3 > 40)
R = „p‟

l NOT (!)
Second priority: logical AND (&&)
Third priority: logical OR (||)

OPERATOR PRECEDENCE AND ASSOCIATIVELY:


OPERATOR DESCRIPTION ASSOCIATIVITY
1.( ) function call left to right
[] array element reference “
2. ! Logical Not Right to left
~ one‟s complement “
- Unary Minus “
++ Increment “
-- Decrement “
& Address of “
* Indirection “
(data_type) Cast Operator “
sizeof size of “
3. * Multiplication Left to Right
/ Division “
% Modulus “
4. + Addition “
- Subtraction “
5. << Left shift “
>> Right shift “
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 27
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
6. < Less than “
> Greater than “
<= Less than or Equal “
>= Greater than or Equal “
7. == Equal to “
!= Not equal to “

8. & Bitwise AND “


^ Bitwise XOR “
| Bitwise OR “
9. && Logical AND “
|| Logical OR “
10. ?: Conditional Right to Left
= += -= *= Simple and Compound “
/= %= >>= Assignment
<<= &= ^= /=
11. , Comma Left to Right

Rules:
1. First, parenthesized sub expression from left to right are evaluated
2. If parentheses are nested, the evaluation begins with the
3. Arithmetic expression are evaluated from left to right using the rules of precedence.
4. When parentheses are used ,the expressions with in parentheses assume highest priority.

TYPE CONVERSIONS IN EXPRESSIONS:


C converts one or both the operands to the appropriate data types by type conversions.
Type conversion can be
1.Implicit type conversion
2.Explicit type conversion

1.Implicit Type Conversion:


Expression combines of constant and variables of different types.
 C automatically converts any intermediate values to the proper type. This automatic
conversion is known as implicit type conversion
 If the operands are of different types the lower type is automatically converted to the
highest type before the operation proceeds.
Data type Rank
long double 1 (higher rank)
double 2
float 3
int 4
short int 5
char 6(lower rank)
Rules:
1. If one of the operand is long double, double, float & unsigned long int, the other will be
converted to long double, double, float &unsigned long int and the result will be the same.
2. if either operand is long, the other operand is converted to long.
3. if either operand is unsigned, the other operand is converted to unsigned.
4. char and short are converted to int
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 28
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Assignment type conversion:
1. float to int cause truncation of the fractional part.
2. double to float cause rounding of digits.
3. long int to int cause dropping of the excess higher order bits.
If the two operands in an assignment operation are of different data type, the right side
operand is automatically converted to the data type of the left side.

2. Explicit type conversion:


Scalar data types can be explicitly converted into desired data types.
It is accomplished by using cast operator.
Syntax:
(data_type) expression
where expression is converted to the target data type enclosed within the parentheses.
ratio=female/male
Female and male are declared as integers the decimal part of the result of the division would
be lost and ration would represent a wrong figure.
ratio =(float)female/male
(float)converts the female to floating point for the purpose of evaluate of the expression
Ex:
x=(int)%5 result is x=7
a=(int)21.3/(int)4.5 result is 21/4=5
y=(int)(a+b) the result of a+b is converted to integer.

OPERATOR PRECEDENCE AND ASSOCIATIVITY:


 The operator at the higher level of precedence are evaluated first.
 The operator of the same precedence are evaluated from left to right

Operator Description Associativity Rank


() Function call
Left to right 1
[] Array element refer
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
~ One‟s complement
* Pointer reference
Address Right to left 2
Size of Size of object
(type) Type cast
*
Multiplication
/
Division Left to right 3
%
modulos
+ Plus
Left to right 4
- minus
<< Shift left
Left to right 5
>> Shift right
< Less than
Left to right 6
<= Less that or equal to

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 29


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
> 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

BUILT IN FUNCTIONS (OR) LIBRARY FUNCTIONS


 In general most of the programmers require mathematical.
E.g. sin(x),cos(x), tan(x),………….
 These functions are known as built in functions or library functions. Functions, it is
necessary to include the header file math.h
 C, provides, the below library functions for performing mathematical computations.

TRIGNOMETRIC FUNCTIONS;
 sin(x) – used to find the sine valve of x . x in radians
 cos(x)- used to find the cosine value of x.
 tan (x)- used to find the tangent value of s.
a sin (x) = sin -1 (x)
a cos (x)= cos-1 (x)
a tan (x)= tan-1 (x)
Other functions:
 Ceil (x)- >If rounds the number to the next highest integer ceil (10.6)=1, ceil (10.3)=11
 Floor(x)-> it rounds the number to the next lowest integer floor (10.6)= 11, floor (10.3)= 10
 Exp(x)->e to the power.
 abs(x)-absolute value of x.
 Sqrt(x)->square root of x.
 Log(x)->natural log of x.
Ex:
#include<stdio.h>
#include<math.h>
void main()
{
int a,c;
scanf(“%d”,&a);
c= sin(a);
printf(“%d”,c);
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 30


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
MANAGING INPUT AND OUTPUT OPERATIONS:
Input operation involves data transfer from the input device to the computer memory and in
output operation data transfer is from the computer memory to the output device.
I/O Header File:
Each program that uses a standard input/output function must contain the statement.
# include <stdio.h>
The file name stdio.h is an abbreviation for standard input-output header file.

Reading a character:
I/O Functions:
1) Character-Oriented I/O functions:
i. getchar()
ii. putchar()
2) Formatted I/O Functions
i. Scanf()
ii. Printf()
i. getchar()
getchar() is used to read a single character from the keyboard.
Syntax:
variable_name = getchar();
variable_name is a valid C name.
It is declared as char type.
char name;
name = getchar();
getchar is used on the right-hand side of an assignment statement, the character value
of getchar is turn assigned to the variable name on the left.

# include <stdio.h>
main()
{
char answer;
printf(“ Would u like to know my name ? \n”);
printf(“Type Y for Yes and N for No :”);
answer = getchar();
if(answer == „Y‟ || answer == „y‟)
printf(“\n\n My name is Busy Bee\n”);
else
printf(“\n\n You are good for nothing\n”);
}
The Character functions are contained in the file ctype.h. # include <ctype.h>

CHARACTER SET FUNCTIONS:


isalnum(c) isprint(c)
isalpha(c) ispunct(c)
isdigit(c) isspace(c)
islower(c) isupper(c)

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 31


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Writing a character:
Syntax:
putchar(variable_name);
putchar for writing characters one at a time to the terminal.
variable_name is a type char variable containing a character.
answer = „Y‟;
putchar(answer);
toupper and tolower functions are used to converts the lowercase arguments into an
uppercase alphabet which the function tolower does the reverse.
# include <stdio.h>
# include <ctype.h>
main()
{
char alphabet;
printf(“Enter an alphabet”);
putchar(„\n‟);
alphabet = getchar();
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}

Formatted I/O Functions:


scanf()
The function scanf() is used to read input values.
Syntax:
scanf(“format_string”, address_list);
format_string contains the required formatting specifications
enclosed within double quotes.
address_list contains the address of the memory locations where
the input data is stored. The addresses are separated by commas.
The format_string includes conversion specifications directing the conversion of the
next input data.
Conversion specification is written as % followed by a conversion character.
Conversion specification for scanf()
Conversion specification Input
%c Single character
%d Reads integer data type.
%f or %e %g Reads float data type.
%s Reads a sequence of characters
NULL is added at the end.
%u Reads unsigned integer.

Inclusion of whitespace Character:


Scanf(“%d %d”, &a,&b);
If the input data entered for this scanf() are 25 387

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 32


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Inclusion of Non-Whitespace Character:


1.scanf(“%d.%d.%d”, &date,&month,&year);
If the data are entered as 4.5.93

2. scanf(“Rs.%f %d %%”,&amount,&interest);
If the data are entered as Rs.2200.75 11%

3. scanf(“%d,%f,%c”,&x,&y,&z);
If the inputs are entered as 15,34.32,

Inclusion of Field width:


A positive number between the percent sign (%) and the conversion character in a
conversion specification may appear to specify the field width of the input data.
The field width specifies the maximum number of characters to be read.
The number of character read from the input field never exceeds the specified field
width.

Syntax:
%[Field width] conversion Character
Where the optional item is enclosed within square brackets.
scanf(“%2d %2d”,&p,&q);
If the inputs are given as
7 56
7 is assigned to p and 56 is assigned to q.
If the inputs are given as 50 356
50 is assigned to p and 35 is assigned to q, 6 is read by the next scanf if any, else the
data 6 is ignored.
If the inputs are 356 47 3
356 is assigned to p and 6 is assigned to q and the remaining data are ignored.

scanf(“%6f%4f”,&x,&y);
If the inputs are given as 425.35 1.3
425.35 is assigned to x and 1.3 is assigned to y.

Inclusion of placeholder:
scanf function can input strings containing more than one character.
%ws or %wc
main()
{
int no;
char name1[15], name2[15];
printf(“Enter serial number and name one\n”);
scanf(“%d%15c”,&no,&name1);
printf(“%d%15s\n\n”,no,name1);
printf(“Enter serial number and name two\n”);
scanf(“%d%s”,&no,name2);
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 33


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Enter serial number and name one:


1 123456789012345
1 123456789012345r
Enter serial number and name two:
2 New york
2 New
scanf support the following conversion specification for strings.
%[characters]
%[^characters]
The specification %[characters] means that only the characters specified within the
brackets are permissible in the input string.
The specification %[^characters] does exactly the reverse.
main()
{
char address[80];
printf(“Enter address \n”);
scanf(“%[a-z]”,address);
printf(“%-80s\n\n”,address);
scanf(“%[^\n]”,address);
printf(“%-80s”,address);
}

output:
Enter Address:
New delhi 110002
Newdelhi
New delhi 110 002
New delhi 110 002

Formatted output:
printf function for printing captions and numerical results.
Syntax:
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.
Format output
Printf(“%d”,9876); 9876
Printf(“%6d”,9876) 9876
printf(“%06d”,9876) 009876

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 34


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

UNIT-II
DECISION MAKING AND BRANCHING
DECISION MAKING STATEMENT (OR) CONTROL STATEMENT:
The control statements are used to make a decision several control statement available in c.
1. If statement.
2. If else statement.
3. Nested if statement.
4. Else if ladder.
5. Switch statement.
6. Goto statement.
1. Simple if statement:
Simple if is a one-way branching statement .when the condition of if is true, the
statement present within the if block are executed, otherwise the if block is skipped by
transferring the control directly to the first statement after the if block
Syntax:
if(condition)
{
statement;
}
Flowchart:

If
condition true

statement

False

exit
Example:
# include<stdio.h>
void main()
{
int a;
scanf(“%d”,&a);
if(a>20)
printf(“Greater than 20”);
}
Output:
30
Greater than 20

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 35


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Description:
The above program as illustrated for using simple if statement. If the user
enter the a value is greater than 20. Then the “greater than 20” statement will be
printed otherwise if block is skipped by transferring the control directly to the first
statement after if block.

2. If ..else statement
 If …else statement is two way branching statement.
 If the condition is true ,then the statement present within the if block are
executed, otherwise the else block are executed.

Syntax:
if(condition)
{
true_block statement
}
else
{
false_block statement
}

Flow chart:
Entry

True If false
condition

True block statement False block statement

Next statement

Example:
if(marks>=40)
printf(“passed”);
else
printf(“failed”);

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 36


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example program:
#include<stdio.h>
void main()
{
int n;
scanf(“%d”,&n);
if(n%2= =0)
printf(“even number”);
else
printf(“odd number”);
}

Output:
8
Even number

Description:
The above program is illustrated for the use of if else statement, if(n%2= =0) the
condition is true the given number is even otherwise false the given number is odd should be
printed.

3. Nested –if statement


 A structure consisting of an if statement within another if statement is called
nested if statement.
 If the condition-1 false the statement-3 will be executed, otherwise it contains
to perform the second text.
 If condition 2 is true statement-1 is will be evaluated, otherwise the statement-
2 will be evaluated.

Syntax:
if (condition)
{
if(condition-2)
{
Statement-1
}
else
{
Statement-2
}
}
else
{
Statement-3
}
Statement-x;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 37


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Flowchart:
entry

False true
Con
-1

False Co true
n-2

statement-3
Statement-2 Statement-1

Statement-x

Example:
if (a>b)
{
if(a>c)
{
printf(“largest a”);
}
else
{
printf(“largest b”);
}
}

Example program:
#include<stdio.h>
void main()
{
inta,b,c;
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“%d largest”,a);
}
else
{
printf(“%d largest”,c);
}
}
else

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 38


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

{
if(c>b)
{
printf(“%d largest”,c);
}
else
{
prinf(“%d largest”,b);
}
}
}

Output:
10 20 5
20 largest

Description:
The above program as illustrated the use of nested if statement. hear the first
condition (a>b) is true then it will enter to the second condition (a>c) otherwise it will entered
for the third condition(c>b). if the second condition is true the a is largest will be printed
otherwise false c largest will be printed , if the third condition is true c largest will be printed
otherwise false means b largest will be printed.

4. Else…if Ladder
The else-if ladder is a multiday decision maker which contains two or more else if
,from any one block is executed.

Syntax:
if(condition-1)
Statement-1
elseif (condition-2)
Statement-2;
elseif (condition-3)
Statement-3;
------------------

--------------------
elseif (condition-n)
Statement-n;
else
Default statement
Statement-x;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 39


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Flowchart:
Entry

True Con false


-1

True false
Statement-1
Con
Statement-2 -2

True false
Con
-3
Statement-3
True Con
false
-n
Statement-n Default statement

Statement-x

Example program:
#include<stdio.h>
void main()
{
float per;
scanf(“%f”,&per);
if(per>=75)
printf(“distinction”);
elseif (per>=60)
printf(“first class”);
elseif(per>=50)
printf(“second class”);
elseif(per>=40)
printf(“third class”);
else
printf(“fail”);
}
Output:
56
First class
Description:
The above program is illustrated the use of else if ladder structure. If the first
condition (per>=75) is true then distinction will be printed otherwise false means the second
condition (per>=60) will be checked if its true first class will be printed otherwise it will enter to
third condition (per>=50) if its true second class will be printed, otherwise false means it will

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 40


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
entered the last condition (per>=40) if its true means third class will be printed otherwise false
means fail will be printed.

5. Switch case statement


 The switch statement provides multi-way branching.
 The switch allows the user to select any one of the alternatives depending on
the value of an expression.
 The expression present within a parenthesis of switch statement must be of the
type int (or) char
Syntax:
switch(expression)
{
case label 1: statement 1;
break;
case label 2: statement 2;
break:
--------------------------------
--------------------------------
case label n: statement n;
break;
default : default statement;
}
statement x
 If the expression value is same as case label, then the statement corresponding
to that particulars case is executed.
 In case the expression value does not match with any case label, the statement
in the default block will be executed.

Flowchart:

Switch
expression

Statement 1 Statement 2 statementn

Next statement

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 41


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Example program:
#include<stdio.h>
void main()
{
int ch;
scanf(“%d”,&ch);
switch(ch)
{
case 1: printf(“Sunday”);
break;
case 2: printf(“monday”);
break;
case 3: printf(“tuesday”);
break;
case 4: printf(“wednesday”);
break;
case 5: printf(“thursday”);
break;
case 6: printf(“friday”);
break;
case 7: printf(“Saturday”);
break;
default: printf(“invalid”);
}
}
Output:
4
Wednesday
Description:
The above program is illustrated for using switch case statement. If the user enter the
choice through the variable „ch‟. If it match the case1 to case 7 the required statement will be
printed otherwise default statement invalid is printed at run time.

6. Goto statement
Go to statement transfer control unconditionally to another part of the program which
is marked by a label.

Syntax:
Goto label;
A lable is a valid name of variable.
Goto label;
-------------
-------------
label: statement;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 42


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
#include<stdio.h>
void main()
{
int x;
scanf(“%d”,&x);
if(x%2==0)
Goto even;
else
goto odd;
even : printf(“even number”);
odd : printf(“odd number”);
}

Output:
5
Odd number

Description
The above program is illustrated the use of goto statement. When if the condition
(x%2== 0) if matchs to true the label even statement will be printed otherwise false means
label odd statement will be printed.

DECISION MAKING AND LOOPING

Looping:
A sequence of statement is executed until some condition for termination of the loop are
satisfied. It consists of two segments.
1. Body of the loop
2. Control statement
Classification of control structure
1. Entry controlled loop/pre test
2. Exit controlled loop/post test
1. Entry controlled loop:
The control condition is tested before the start of the loop execution. If the condition
are not satisfied, then the body of the loop will not be executed.
2. Exit controlled loop:
The test is performed at the end of the body of the loop and the body of the loop is
executed unconditionally for the first time.
1. While statement:
While is an entry controlled loop statement. If is used to execute the statements repeated as
long as the condition is true.

Syntax:
while (condition)
{
Body of the loop;
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 43


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Flowchart:

 The test condition is evaluated and if the condition is true, then the body of loop is executed.
 After execution of the body, the test condition is once again evaluated and if it is true, the boy
is executed once again.
 If the condition is false then the control is transferred out of the loop.

Example:
#include<stdio.h>
void main()
{
int n,i=0;
int s=0;
scanf(“%d”,&n);
while (i<=n)
{
s =s+i:
i =i+1;
}
printf(“%d”,s);
}

Output:
5
15

Description:
The above program is the use of wile statement when for user may entered n value is 5, then
the condition (i<=n) must be checked repeat up to that the s value will be calculated s=s+i and I
value also increase for the body of the loop when the condition is false immediately the final
calculation value of s will be printed in the screen.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 44


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
2. Do-while statement:
 Do-while is an enit controlled loop it is used to test the condition after executing the body of
the loop for first time.
 if is condition is true ,again the body of the loop will be executed .
 if the condition is false , then the control transferred out of the do-while .

Syntax:
do
{
Body of the loop;
}
while(test –condition);

Flowchart:

The test condition is evaluated at the bottom of the loop is called exit controlled loop.

Example:
#include<stdio.h>
void main()
{
int i=0,s=0,n;
scanf(“%d”,&n);
do
{
s=s*I;
i=i+1;
}
while(i<=n);
printf(“%d”,s);
}
printf(“%d”,s);
}

Output:
5
120
Description:
The above program is illustrated the use of do-while statement .when the user entered the n
value is 5,it will calculated s=s+I and i=i+1 upto the condition (i<=n) false onwards , if reached false
then the process will be stopped , then the output s value 120 will be printed in the screen.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 45


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
3. For statement:
For statement is an entry controlled looping statement .it is used to execute the statement for
a certain number of times.

Syntax:
For (initialization; test condition; increment /decrement)
{
Body of the loop;
}

Flow chart:

1. Initialization of control variables is done first


2. The value of the control variable is tested using the test condition test condition relational
Expression .if the condition is the body of the loop is executed, otherwise loop is terminated
3. When the body of the loop is executed, he control is transferred back to the for statement
after evaluating the last statement in the control variable incremented .

Example :
• for (i=0;i<10;i++)
{
prinf(“%d”,i);
}

• for (i=0;i>=0;i--)
{
printf(“%d”,i)
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 46


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Example program:
#include<stdio.h>
void main()
{
int i,n,s=0;
scanf(“%d”,&n);
for (i=0; i<=n;i++)
{
s=s+i;
}
printf(“%d”,s);
}
Output:
5
15
Description :
The above program is illustrated the use of for statement, when the user enter the n value is 5,
then the condition checked first I<=n up to, if it‟s true the body loop statement s=s+i is calculated the
I value is increased simultaneously i++. Finally if the condition reaches false then output s value 15
will be printed.

Additional features:
1. More then one variable can be initialized at time using separator comma.
Ex.
for (p=1,n=0;n<10;++n)
2. The initialization section, increment /decrement section may also have more then one part .
Ex.
for (n=1,m=50;n<=m;n=n+i; m=m-1)
{
p=m/n;
printf(“%d%d%d”,n,m,p);
}
3. The test condition may have any compound relation the loop uses a compound test condition
Ex.
s=0;
for (i=1;i<20&&s<100;++i)
{
s=s+i;
printf(“%d%d”,i,s);
}
4. For loop is also permissible to use expressions in the assignment statement of initialization
and increment /decrement sections.
Ex.
for x=(m+n)/2;x>0;x=x/2)

5. for loop is that one or more section can be omitted .


m=5;
for (; m!=10 ; )
{
printf(“%d”, m);
m=m+5;
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 47


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Nesting of for loop:


One for statement within another for statement is called nested for loop.
Ex.
for (m=1;,m<=n;m++)
for (n=1;n<=n;n++)
{
j=m*n;
printf(“%d”,j);
}

JUMPS IN LOOP:

Unconditional Execution:
1. Break Statement
2. Continue statement
3. goto statement
 If the flow of execution is transferred from one part of a program to another part without
carrying out any conditional test, it is known as an unconditional execution.
1. Break statement:
Syntax:
break;
 When a break statement appears inside a loop or in a switch-case control structure is
terminates the execution at that point and transfer execution control to the statement
immediately following the loop or switch-case construct statement.

/* program to count the number of +ve, -ve and 0 values */


main()
{
char ch;
int n,pc=0,nc=0,zc=0;
while(1)
{
printf(“\n Enter a number \n”);
scanf(“%d”,&n);
if(n>0)
pc++;
else if(n<0) nc++;
else zc++;
printf(“Do you want to continue ? say (y/n)”);
ch=getchar();
if((ch = getchar())== „n‟)
break;
}
printf(“\n Number of positive values = %d”,pc);
printf(“\n Number of negative values = %d”,nc);
printf(“\n Number of zero values = %d”,zc);
}

Continue Statement:
The General format is
Continue;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 48


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

/* Program to sum the given series */


main()
{
int i,sum =0;
for(i=5;i<=20;i++)
{
if(i%5!=0) continue;
sum+=i*i;
}
printf(“Sum is = %d\n”,sum);
}

goto Construct:
 The goto construct causes an unconditional transfer of execution.
 Goto may be used for breaking more than one loop at a time.
Syntax:
label:
{
statement;
}
.
.
.
goto label;
 Where label is an identifier and not a number .
 Identifier is a statement label and it is not declared.
 Statement label can also be used as a variable name in the same program.
 The statements to be executed follow the label ending with a colon (:).
 If these statements appear before a goto statement, the flow is in backward direction and it is
known as backward goto.
 If the statements appear after a goto statement; this type of goto is known as forward goto.
 Same label cannot have in different places.

/* Program to read a string using GOTO */


main()
{
char ch;
printf(“Enter a string \n”);
read: ch=getchar();
if(ch!=‟\n‟)
{
putchar(ch);
goto read;
}
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 49


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

ARRAY
 An arrays is a fixed size sequenced collection of elements of the same data type.(or)
 An array is a sequential collection of related data items that‟s share a comma name

Types of Array :

1. One-dimensional arrays
2. Two-dimensional arrays
3. Multi dimensional arrays

1. ONE-DIMENSIONAL ARRAYS:
A list of items can be given one variable name using only one subscript and such as variables
is called a single subscripted or a one dimensional arrays.

Example:
int n[5];

Memory location
N[0]
N[1]
N[2]
N[3]
N[4]
• Declaration of one dimensional arrays:
An array must be declared before they one used the compiler can allocate space for them in
memory .

Syntax:
Data Type Array Name [SIZE];

• Data type specifies the basic data type


ie: int ,float ,char.
• Array name is name of the array
• Size indicates the minimum number of elements that can be stored .
Ex :
int a[5];

Example program:
#include<stdio.h>
#include<conio.h>
void main ()
{
intI,j,t,a[10];
printf(“\n enter the number of value \n”);
scanf(“%d”,&n);
for (i=0;I<n;i++)
scanf(“%d”,&a[i]);
for (i=0;I<n;i++)
for (j=0;j<n;j++)
if (a[i]>a[j])
{
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 50
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
temp =a[i];
a[i]=a[j];
a[j]=temp;
}
printf(“\n asendingoder \n”);
for (i=0;j<n;i++)
printf(“%d\t”,a[i]);
getch();
}

Output :
Enter the numbers
5
Enter the values
20 10 30 50 40
Ascending order
10 20 30 40 50

Description :
The above program is illustrated using single dimensional array the user entered the n number
of elements which can be stored in single dimensional array for using for loop the elements
locations are compared i and j for using temp variable finally the sorted elements are stored in
a[i] output location then the numbers are printed in the screen.

Initialization of one dimensional array:


After an array is declared ; its elements must be initialiazation otherwise they will contain “
garbage”.

Stages of array initialization

i. compile time initialization


Initialization the elements of array in the same way the ordinary variables when they are
declared.
data types arrayname [size]={list of values};
Values in the list separated by commas
inta[5]={10,20,30,40,50}
floatn[3]={10.5,20.5,30.5}
chara[5]={„a‟, „b‟ , „c‟, „d‟ , „e‟}

ii. Runtime initialization:


An array can be explicitly initialized at runtime
Ex.
for (i=0; i<100;i++)
{
if (i<50)
{
sum[i]=0;
else
sum[i]=20;
}
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 51


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
2. TWO-DIMENSIONAL ARRAY:
Two dimensional array consist of rows and columns. Each elements accessed by two subscripts.
• Declaration of each dimensional array:
• Data types array name [rowsize][columnsize];
Ex.
int a[4][3];

storage location coloumn1 coloumn2 coloumn3


ROW 0 [0][0] [0][1] [0][2]
ROW 1 [1][0] [1][1] [1][2]
ROW 2 [2] [0] [2][1] [2][2]

Example:
#include<stdio.h>
void main()
{
int a[0][10],b[10][10],c[10][10];
int i,j,k,n;
scanf(“d”,&n)
for(i=1;j<=n;i++)
{
for(j=1;j<=n;j+i)
{
scanf(“%d”,&a[i][j]);
printf(“%d”,a[i][j]);
}
}

Initializing Two Dimensional array:


Two dimensional array can be initialized by listing the values enclosed in braces .
Ex
int n[2] [2] ={10,20,30,40);
int n[[2][3]={{10,20,30},{40,50}};
• Commas are required after each brace closes off row except the last row
• Array is completely initialized with all values explicitly we need net specify size of first
dimension.
• If the values are missing in an initialized they are automatically set to zero .

MULTI DIMENSIONAL ARRAY:


Multidimensional array can have two or more subscripts

Syntax:
Datatypes arrayname [s][2]…….[sn];
• S1,s2………..sn is the size of the dimension
• Data type is any basic data type
• Array name is the variables name of the array
Ex.
int a[3][3][3];
float b[3][3][3];
• Initializing multi dimensional array:

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 52


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
The list of the initialization values assigned to array elements in order the last subscript
changing first.

Ex:
int n[2][3][5]={{1,2,3,4,5};
{6,7,8,9,10};
{2,3,4,5,6};}
{{7,8,9,10,1};
{1,2,4,5,6};
{8,7,9,1,2};}}

DYNAMIC ARRAYS:
 To allocate memory be an arrays at run time this is known as dynamic memory
allocation and
 The array created at runtime are called dynamic arrays.
 Dynamic arrays are created using what are known as pointer variable and memory
management functions malloc , calloc and realloc .
 These function are included in the head files <stdio.h>
 Dynamic array is used to creating and manipulating data structures.
Ie. Linked list, stack and queue. Now that we have firm grasp on pointers, how can
we allocate memory at run-time instead of compile time? ANSI C provides five
standard functions that helps you allocate memory on the heap.
Dynamic Memory Allocation :: sizeof()
We have already seen this function in the array section. To recap, sizeof() returns a size_t of the
item passed in. So on a typical 32-bit machine, sizeof(int) returns 4 bytes. size_t is just an unsigned
integer constant. sizeof() is helpful when using malloc or calloc calls. Note that sizeof() does not
always return what you may expect (see below).

Dynamic Memory Allocation :: malloc(3), calloc(3), bzero(3), memset(3)


 The prototype for malloc(3) is:
void *malloc(size_t size);
malloc takes in a size_t and returns a void pointer. Why does it return a void pointer?
Because it doesn't matter to malloc to what type this memory will be used for.
 Let's see an example of how malloc is used:
int *ip;
ip = malloc(5 * sizeof(int));
Pretty simple. sizeof(int) returns the sizeof an integer on the machine, multiply by 5 and
malloc that many bytes.
 Wait... we're forgetting something. AH! We didn't check for return values. Here's some
modified code:
#define INITIAL_ARRAY_SIZE 5
/* ... code ... */
int *ip;
if ((ip = malloc(INITIAL_ARRAY_SIZE * sizeof(int))) == NULL) {
(void)fprintf(stderr, "ERROR: Malloc failed");
(void)exit(EXIT_FAILURE); /* or return EXIT_FAILURE; */
}
Now our program properly prints an error message and exits gracefully if malloc fails.
 calloc(3) works like malloc, but initializes the memory to zero if possible. The prototype is:
void *calloc(size_t nmemb, size_t size);
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 53
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Refer to Weiss pg. 164 for more information on calloc.
 bzero(3) fills the first n bytes of the pointer to zero. Prototype:
void bzero(void *s, size_t n);
If you need to set the value to some other value (or just as a general alternative to bzero), you
can use memset:
void *memset(void *s, int c, size_t n);
where you can specify c as the value to fill for n bytes of pointer s.
Dynamic Memory Allocation :: realloc(3)
 What if we run out of allocated memory during the run-time of our program and need to give
our collection of items more memory?
 Enter realloc(3), it's prototype:
void *realloc(void *ptr, size_t size);
realloc takes in the pointer to the original area of memory to enlarge and how much
the total size should be.
 So let's give it a try:
ip = realloc(ip, sizeof(ip) + sizeof(int)*5);
Now we have some more space through adding the sizeof the complete array and an
additional 5 spaces for ints... STOP! This is NOT how you use realloc. Again. The above
example is wrong. Why?
 First, sizeof(ip) does not give the size of the allocated space originally allocated by malloc (or
a previous realloc). Using sizeof() on a pointer only returns the sizeof the pointer, which is
probably not what you intended.
 Also, what happens if the realloc on ip fails? ip gets set to NULL, and the previously
allocated memory to ip now has no pointer to it. Now we have allocated memory just floating
in the heap without a pointer. This is called a memory leak. This can happen from sloppy
realloc's and not using free on malloc'd space.
 So what is the correct way? Take this code for example:
int *tmp;
if ((tmp = realloc(ip, sizeof(int) * (INITIAL_ARRAY_SIZE + 5))) ==
NULL) {
/* Possible free on ip? Depends on what you want */
fprintf(stderr, "ERROR: realloc failed");
}
ip = tmp;
Now we are creating a temporary pointer to try a realloc. If it fails, then it isn't a big problem
as we keep our ip pointer on the original memory space. Also, note that we specified the real
size of our original array and now are adding 5 more ints (so 4bytes*(5+5) = 40bytes, on a
typical 32-bit machine).
Dynamic Memory Allocation :: free(3)
 Now that we can malloc, calloc, and realloc we need to be able to free the memory space if
we have no use for it anymore. Like we mentioned above, any memory space that loses its
pointer or isn't free'd is a memory leak.
 So what's the prototype for free(3)? Here it is:
void free(void *ptr);
free simply takes in a pointer to free. Not challenging at all. Note that free can take in NULL,
as specified by ANSI.
Dynamic Memory Allocation :: Multi-dimensional Structures
 It's nice that we can create a ``flat" structure, like an array of 100 doubles. But what if we
want to create a 2D array of doubles at runtime? This sounds like a difficult task, but it's
actually simple!
 As an example, lets say we are reading in a file of x, y, z coordinates from a file of unknown
length. The incorrect method to approach this task is to create an arbitrarily large 2D array

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 54


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
with hopefully enough rows or entries. Instead of leaving our data structure to chance, let's
just dynamically allocate, and re-allocate on the fly.
 First, let's define a few macros to keep our code looking clean:
#define oops(s) { perror((s)); exit(EXIT_FAILURE); }
#define MALLOC(s,t) if(((s) = malloc(t)) == NULL) { oops("error: malloc()
"); }
#define INCREMENT 10
MALLOC macro simply takes in the pointer (s) to the memory space to be allocated
(t). oops is called when malloc fails, returning the error code from malloc and exits the
program. INCREMENT is the default amount of memory to allocate when we run out of
allocated space.
 On to the dynamic memory allocation!
double **xyz;
int i;
MALLOC(xyz, sizeof(double *) * INCREMENT);
for (i = 0; i < INCREMENT; i++) {
MALLOC(xyz[i], sizeof(double) * 3);
}
What's going on here? Our double pointer, xyz is our actual storage 2D array. We must use a
double pointer, because we are pointing to multiple pointers of doubles! If this sounds
confusing, think of it this way. Instead of each array entry having a real double entry, each
array position contains a pointer to another array of doubles! Therefore, we have our desired
2D array structure.
 The first MALLOC call instructs malloc to create 10 double pointers in the xyz array. So
each of these 10 array positions now has an unitializied pointer to data of type pointer to a
double. The for loop goes through each array position and creates a new array at each
position to three doubles, because we want to read in x, y, z coordinates for each entry. The
total space we just allocated is 10 spaces of 3 doubles each. So we've just allocated 30 double
spaces.
 What if we run out of space? How do we reallocate?
double **tmp;
int current_size, n;
/* clip ... other code */
if (current_size >= n) {
if ((tmp = realloc(xyz, sizeof(double *) * (n + INCREMENT)) == NULL) {
oops("realloc() error! ");
}
for (i = n; i < n + INCREMENT; i++) {
MALLOC(tmp[i], sizeof(double) * 3);
}
n += INCREMENT;
xyz = tmp;
}
 What's going on here? Suppose our file of x, y, z coordinates is longer than 10 lines. On the
11th line, we'll invoke the realloc(). n is the current number of rows
allocated. current_sizeindicates the number of rows we are working on (in our case, the
expression would be 10 >= 10). We instruct realloc to reallocate space for xyz of (double *)
type, or double pointers of the current size (n) plus the INCREMENT. This will give us 10
additional entries. Remember NEVER reallocate to the same pointer!!
 If realloc() succeeds, then we need to allocate space for the double array of size 3 to hold the
x, y, z coordinates in the new xyz realloc'd array. Note the for loop, where we start and end.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 55


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Then we cleanup by providing our new max array size allocated (n) and setting the xyz
double pointer to the newly realloc'd and malloc'd space, tmp.
 Not as difficult as you might have imagined it to be, right? What if we're done with our
array? We should free it!
for (i = 0; i < n; i++)
{
free(xyz[i]);
}
free(xyz);
The above code free's each entry in the xyz array (the actual double pointers to real data) and
then we free the pointer to a pointer reference. The statements cannot be reversed, because
you'll lose the pointer reference to each 3-entry double array!
CHARACTER ARRAYS AND STRINGS

STRING:
A string is a sequence of character that is treated as a single data item.
Ex.
C close not support string as a data type it allows us to represent string as character array
Operations :
1.reading and writing strings.
2.combinig strings together
3.copying one string to another
4.comparing strings for equality.
5.extracting a portion of a string .

• Declaring and initializing string variables:


A string variable is any valid c variable name and is always declared as an array of characters.
Syntax:
char string name[size];
-char refers to type of the variable .
-size determines the number of character in the string .
-string name refers to name the string.
Ex.
char city [10];
char name[30];
Character arrays may be initializes when they are declared a character arrays to be initialized
in two forms.
Ex.
char city[a]=”new York”;
char city [a]={„n‟,‟e‟,‟w‟,‟y‟,‟o‟,‟r‟,‟k‟,‟10‟};

The compiler assigns a character string to a character array it automatically assign a null
character (‟10‟) at the end of the string.
The size should be equal to the maximum number of character in the string plus one.

• Additional features:
To initialize a character array without specifying the number of elements .
The size of the array will be determined automatically based on the number of elements
initialized .
Ex.
char s[] ={ „g‟,‟o‟,‟O‟,‟D‟,‟10‟};
We can also declare the size much longer than the string size in the initialized.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 56


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Ex.
char s[10]=”GOOD”;
Memory allocation
good\o\o\o\o\o\o

READING STRING FROM TERMINAL

Two Ways Be Reading String


1.using scanf function
2.using get char and gets functions

1. using scanf function:


scanf can be used with %s formed specifications to read in a string of characters
Ex.
char a[10];
User can also specify the field with using the form 5ws in the scanf statements for reading a
specified number of character from the input string.
Ex.
scanf(“%ws”,n);
• The width w is equal to or greater than the number of characters typed the entire string will
be stored in the string variable
• The width w is less than the number of character in the string the excess character will be
truncated
Ex.
char name [10];
scanf(“%s”,name);
1. input string kamal will be stored as KAMAL \O ?
2. input string VIJAY will be stored as VIJAY\0

Problem:
 Scanf function is termination its input on the first white space it finds.
 A white space includes blanks ,tabs, carriage, returns, form, feeds, and, new line.
 The scanf function automatically terminates the string that is read with a null
character

Ex.
char a[0];
scanf(“%s”,a);

Input string :
New York
Memory a NEW \0………
To read the entire string ,it use two character arrays of appropriate size .
char a [5],a[5];
scanf(“%s%s”,a,a);
A NEW \0 A1=YORK \0

READING A LINE OF TEXT:


A format specification, edit set conversion code % [n] that can be used to read line
containing a variety of characters including whitespaces.
char line [80];

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 57


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
scanf(“%[\n]”,line);
scanf function read a live of input from the keyboard
.
2. Using getchar and gets function :
getch()
To read a single character from the terminal .
Ex.
char c;
C=getchar();
gets()
To read a string of text containing whit is to use the library function available in the <stdio.h>
,<string.h>header file.
Ex.
gets(line);
printf(“%s”,line);or printf(“%s”,gets line):

Problem:
If cannot assign one string to another string directly
Ex:
S=”ABC”;
S1=s2;
Example program:
#include<stdio.h>
void main()
{
char s1[80],s2[80];
int I;
scanf(“%s”,s1);
for(i=0; s1[i] !=‟10‟;i++)
s2[i]=s1[i];
printf(“%s”,s2);
printf(“ no of characters=%d”,i);
}
Writing string to screen:
Two ways to writing string to screen they are
1.using printf() function
2.using putchar () and puts function .

i. using printf function:


The printf() function with %s format to print string to the screen the format %s can be used
to display an array of characters that is termination by the null character.
Ex.
printf(“%s”,name);
User can display the precision with which the array is displayed

Ex.
Printf(“%10-43”,name);
Input string:

I N D 1 V 1 D U A 1
Output string:
I N D 1

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 58


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

It indicates that the first four character are to be printed in a filed with to colums
Example:
#include<stdio.h>
void main ()
{
int c,d;
char s[ ]="cprogramming";
for(c=0;c<=11;c++)
{
d=c+1;
printf("%-12*s\n",d,s);
}
for(c=11;c>=10;c--)
{
d=c+1;
printf"%-12,*s\n",d,string);
}
}

ii.Using putchar and puts functions


putchar() is a character handling function it is used to output the values of character variables.
Ex:
charch='A';
put char (ch);
put() printing string values iis to use the function puts declared in the header file <stdio.h>
Syntax:
puts(variable name);
Ex:
charch='A'
gets(line);
puts(line);
Arithmetic operations on characters:
A character constant or character variable is used in an expressions, it is automatically
converted into an integer value by the system ie. character equivalent ASCII value
Ex
x='a';
printf("%d",x);
output:
a
It is also use character constants in relational expressions.
Ex:
I (ch>='A'&&ch<='Z')
ii x=ASCII value of '7'-ASCII value of 'a'
=-55-48
x=7
Ato i() it convert a string of digits into their integer values
syntax:
integer variable=atoi(string);
EX:
number="1988";
year=atoi(number);

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 59


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Ex:
#include<stdio.h>
void main()
{
char c;
for ( c=65;c<=122;c++)
{
if (c>90&&c<97)
continue;
printf ("14d-%c",c,c);
}
printf("1\n");
}

STRING HANDLING FUNCTIONS:


String handling function can be used to carry out many of the string manipulations.
The most commonly used string handling functions are,
Function Action
strcat() Concatenates two strings
strcmp() Compares two strings
strcpy() Copies one string over another
strlen() Finds the length of a string
strrev() Reverse the given string
strupr() Uppercase conversion of given string
strlwr() Lowercase conversion of the given string

1. Strcat() function:
The strcat()function joins two strings together
Syantax :
stracat (string1,string2);
Example:
#include<stdio.h>
void main()
{
char s1[]="very";
chars2[]="good";
strcat(s1,s2);
print("%s",s1);
}
Output:
very good
Strcat function may also append a string constant to a string constant to as tring variable.
Example:
strcat (s1,"Good");
C permits nesting of strcat functions
Syntax:
strcat(strcat (string1,string2)string3);
It allowed and concatenates all the three strings together. The resultant string is stored in
string.
Example:
scanf("%s",s1)
strcat(strcat(strcat(s1,"Naresh"),"Kumar");
printf("%s",s1);
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 60
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
output:
Input string s1=Mr
output string s1=Mr.Nareshkumar

2.strcmp()function:
strcmp() function compares two string to find out whether they are same or different.
the two strings are compared character by character until there is a mismatch or end of the strings is
reached, whichever occurs first.
If the two strings are identical strcmp() returns a value zero. if they are not, same it returns the
numeric difference between the ASCII value of the first non-matching pairs of character.

syantax:
strcmp(string1,string2);
Example:
strcmp(name1,name2);
strcmp("Ran","Ram");
strcmp(name1,"Hassan");

Example Program:
#include<stdio.h>
void main()
{
char s1[ ]=="Jerry";
char s2[ ]="Ferry";
inti,j,k;
i=strcmp(s1,"Jerry");
j=strcmp(s1,s2);
printf("%d%d",i,j);
}
output :
0 4

3. strcpy() function:
strcpy( ) function copies the contents of one string into another.
strcpy( ) function works almost like a string assignment operator.
syantax:
strcpy (string1,string2);
Program:
main()
{
char s1[20];
char s2[]=vijay;
strcpy(s1,s2);
printf("%S",S1);
}

output:
s1= vijay
s2= vijay

4. strlen() function:
strlen() counts the number of character presents in a string.
Syantax:
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 61
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
integer variable name = strlen(string);
Integer variable recieves the value of the lengeth of the string.
Example:
c=strlen ("vijay");
Program:
#include<stdio.h>
void main()
{
chair c[ ]="All is well";
int i;
i=strlen(c);
printf("%d",i);
}
output:
11

5. Strrev ()function :
It reverse the input string character by character.
syntax:
strrev(string);
Example:
#include<stdio.h>
void main()
{
char s1[ ]="vijay";
chars2[ ];
s2=strrv(s1);
printf("%s",s2);
}
output:
yajiv

Table of strings:
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:
static char city [] []={"chennai","madurai", “madurai", “krishnagiri"};

C H E N N A I
M A D U R A I
K R I S H N A G I R I

USER DEFINE FUNCATIONS:

FUNCATION:
A function is a independent section of code that performs a specific task. C function can be
classified into two categories
1. Library function c printf , scanf, etc.
2. User define function (main etc)

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 62


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
1.Library function:
Library function are not required to be written library function that are predefined in the
header files .
Ex.
1. printf( )
2. scanf( )
3. sqrt( )
4. cos( )
5. stdio.h

2. User-defined function:
A user defined function has be developed by the user at the time of writing a program.
Ex.
Main()
 Need for user defined functions:
1. When the same of statement must be repeated several times in various parts of a program
these statement can be placed in a function and invoked whenever required.
2. When user define function are used in a program the number of lines of code decreases.
3. Easier to understand debug and test.
4. Usage of user define functions leads to modular and structured programming.
5. User defined function can be include in the c library allowing other usage to utilize them.
It facilitates top-down modular programming.
Ex.
Top-down modular programming using function multi function program:

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 block box that takes some data from the main
function and return a value.
The inner details of operations are invisible to the rest of the program.
main()
{
Function1();
Function2();
}
Function1();
Function2();
}
Function1();
}
}
Function2();
}
Function3();
}
Function3();
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 63


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Example:
#include<stdio.h>
void main()
{
printfline();
printf(“ welcome to aac”);
printline();
}
void printline()
{
int i;
for (i=1;i<40;i++)
printf(“ –“);
printf(“\n”);
}

Output:
Welcome to aac
 Characteristics of modular programming:
1. Each module should do only are thing
2. Communication between modules is allowed only by a calling module
3. A module can be called by one and only one higher module .
4. No communication can take place directly between modules that‟s do not have calling called
relationship.
5. All module are designed as single entry single edit system using control structures.

 Elements of user defined function:


1. Function definition
2. Function call
3. Function declaration
4. Function definition (or) function implementation it is an independent program
module that is specially written to implement thee requirements of the function.

 Elements :
1. Function name.
2. Function type
3. List of parameters
4. Local variables declaration
5. Function statements
6. Return statements
Parts:
1.function header
2. function body

 Syntax:
function type function name (parameter list)
{
Local variable declaration;
Executable statements;
Return statements; }

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 64


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
 Function header:
Function header consists of three forts there are
1. Function name
2. Function type
3. Formal parameter list
 Function name and function type:
 Function type:
 The function type specified the type of value that the function is expected to
return to the program calling the function .
 If the return type is not explicitly specified compiler will assume that it is an
integer type .
 If the return type is not returning anything then wee need to specify the return
type as void.
 Function name:
The function name parameter list declares the variables that will receive the data sent by
the calling program.

Ex:
1. float mul(float x,float y)
{
}

2. int sum (int a int b)


{
}
A function need not always receive values from the calling program a function have
no formula parameter lit is empty use keyword void to between the parentheses
Ex.
void printline(void)
{
printf(“ no return values “);
}
 Function body:
The function body contains
1. Local variables declaration
2. Executable statements
3. Return statements

Example:
int sum (int a,int b)
{
int c;
c=a=b;
return c;
}

 Return values and their types:


A function may or may not send back any value to the calling function using return
statements
Function can return only one value or none for every function call.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 65


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Syntax:
return;
(or)
return (expressions);
The are several forms return their value
1) No return value:
-Return statement does not return any values
-When a return is executed the control is immediately passed back to the calling function
Ex.
if (n<i)
return;

2) Return statement with a expression:


Return the value of the expression
Ex.
int sum (int a,int b)
{
int c;
return();
}
Or
return(a+b);

3) More then one return statement:


A function may have more then one return one return statements. The value returned is based
on certain conditions
Ex:
if(x<=0)
return(0);
else
return(1);

Function calls
A function can be called by simply using the function name followed by a list of actual
parameters (arguments) enclosed parentheses.
 Syntax:
Function name (argument list )

Ex.
main( )
{
int c;
c=sum(10,20); /* functo call */
printf(“%d”,c);
}
Function call sends two integer values to called function
int sum (int a,int b)
{
int c; \* local variable declaration )*/
c=a+b;
return c;
}
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 66
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
A function that does not return any value may not be used in expression but can be called into
perform certain takes specified in the function

Ex.
main( )
{
printline( )
}

 Importance of function call.


1. The actual parameters are more than the formal parameters the extra actual argument
will be discarded
2. Actual parameters less than a the formal parameters the unmatched formal arguments
will be initialized to garbage value
3. Any mismatch in data type may also result in some garbage value.

 Function declaration:
All function in a c program must be declared before they are invoked. A function
declaration (function prototype) consist of four parts
1. Function type ( return type)
2. Function name
3. Parameter list
4. Terminating semicolon.
Syntax:

Function type-function name –(parameter list)

Ex:
int mul (int m,int n); /* function prototype */
int mul (int ,int);
int mul (int a, int b);
 A function does not return any parameters and does not return any value
void display (void);
 Prototype declaration may be placed in two places in a program.
 Above all type the function (including main) inside a function definition
 Global prototype:
When we place the declaration above all the function the prototype is referred to a global
prototype .such declarations are available for the function in he program
 Local prototype:
When we place it in function definition the prototype is called a local prototype.
Ex.
void printline(void); /*global prototype */
main()
{
printline();
}
void printline (void)
{
int i;
for(i=1;i<=35;i++)

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 67


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
printf(“%d”,i0;
printf(“\n”);
}

Importance :
 Parameters list must be separated by commas
 The type must match the type of parameters in the function definition in numbers &
order
 Parameters names in the declaration is optional
 Function has no formal parameters the list is written as void
 The return type is optional when the function return int type data
 The declared type do not match with the types in the function definition compiler will
produce an error.
 Parameters names do not need to be the same in the prototype declaration and the
function definition parameters:
To pass data from one function to another function is called parameters passing.
1.Declaration (prototype)
2.Function call
3.Function definition

 Formal parameters:
The parameters used in prototype and function definition are called formal parameters
and those used in function calls are called actual parameters.
Ex
int sum (int a, int b)

 Actual parameters:
Actual parameters used in a calling statements may be simple constants variables or
expression .
Ex.
int sum (10,20);
Formal and actual parameters must match exactly in type , order and number.

 Category of function:
A function depending on whether arguments are present or not and whether a value is
return or not
1. Function with no arguments and no return values
2. Function with no arguments and no return values
3. Function with no arguments and one return values
4. Function with no arguments and but return values
5. Function that return multiple values.
1. Function with no arguments and no return value :
The function does not contain any formal parameters and it does not return anyvalue to call
calling function .
The is no data transfer between the calling function and the called function.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 68


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example :
#include<stdio.h>
void main()
{
sum();
}

f1() Valus of F2(f) int sum()


{ { arguments {
F2(a) int a=10 ,b =20,c;
} NOreturn } c=a+b;
values printf(“%d”,c);
}

2. Function with arguments but no return vales:


Data communication between calling function and the called function with arguments but no
return value Ie. One way common arguments communication.
The called function receives the values from the calling function but it does not send any
value to the calling function.
One way data communication
Example :
#include<stdio.h>
void sum (int a ,int b);
void main()
{
int a=10 ; b=20;
sum(a,b); }

void sum (int x,int y)


{
int z;
z=x=y;
printf(“%d”,z);
} F() No output F2()
{ {
F2()
} no input }

3. Function with arguments and one return :


The called function receivers the values from the calling function and calling function also
returns the values to the calling function
Data communication between the callings functions and return a value.
The way data communication.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 69


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
f1()
F2(f)
{……………..
{
………………
Retune(e);
F2(a)
}
……………….}.

Example :
#include<stdio.h>
int sum (inta,int b);
void main()
{
int a=0 ,b=20,c;
c=sum (a,b);
printf(“%d”,z);
}
int sum (int x,int y)
{
int z;
z=x+y;
return(z);
}

4. Function no arguments but return values :


The called function does not receive any values from the calling function but it sends the
value to the calling function.
f1() F2(f)
{…………….. {
……………… Retune(c);
F2(a) }
……………….}.

Example :
#include<stdio.h>
int sum (void)
{
int c;
c=sum();
printf(“%d”,c); }
int sum ( void)
{
int x=10,y=20 z;
z=x+y;
retrun(z);
}

5. Function that return multiple values:


The arguments not any only to receive information but also to send back information to the
calling function the arguments that are used to send out information are called output parameters
The sending back information through arguments using operator and indirection operator (*).

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 70


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Example :
#include<stdio.h>
void sum (int x, inty ,int *s intxd);
void main()
{
int x=20 , y=10,s,d;
sum(x,y,&,&d);
printf(“$=%d\n d=%d\n,s,d);
}
void sum (int a,int b,int *sum,int *diff)
{
*sum= a+b;
*diff = a-b;
}
Hearer the actual arguments
-x and y are input arguments
- s and d are output arguments
We pass the actual values of x and y to the function the values of s and d are stored in the
memory
Rules for pas pointers:
 Type of the actual and formal arguments must be same.
 Actual arguments must be the address of variable that are local to the calling header must
be prefried by indirection operator *
 To access the value of an actual arguments in the called function we use corresponding
formal arguments prefixed with indirection operator *
 Nested of function:

Calling one function from within another function is called nesting of function .
Syntax:
main()
{
Function1();
}
Function1()
{
Function2();
}
Function2()
}
}
Example:
main ()
{
{
palindrome()
}
reverse();
getch();
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 71


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
RECURSION:
A function should calls itself until a condition has satisfied is called recursive function.
Ex.
Factorial using recursion
#include<stdio.h>
#include<conio.h>
void main()
{
int x, f;
scanf(“%d”,&n);
f=factorial (x);
printf(“%d”,f);
}

factorial(int n)
{
int fact;
return(1);
else
fact =n* factorial (n-1);
return(fact);
}

Output:
5
Value:120
Evaluation of output
=5* factorial(4)
=5*4 * factorial (3)
=5*4*3* factorial(2)
=5*4*3*2* factorial
=5*4*3*2*1 = 120
Advantage:
1) Recursion reduces the comp lenity of the problem
2) Program implemented by recursion will be smaller in length
3) The recursion program can have any number of netting levels
4) The recursion technique is more natural and compact

PASSING ARRAYS TO FUNCTION:


One pass one dimensional an array to a called function it, is sufficient to list the name of the
array , without any subscripts and the size of the array as arguments .

Ex:
float largest (float array [ ], int size )
Array [] refers to array name and the fair of brackets informs the compiler that the arguments array
of numbers of elements in the array
Example:
#include<stdio.h>
void main ()
{
float largest (float a[ ], int n);

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 72


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
float value [4] ={ 2.5,4.75,1.2,3.6};
printf(“%f ,largest (value)4);
}
float largest (float a[ ], int n)
{
int i ;
float max ;
max =a[10];
for(i=1; i<n; i++)
if(max<a[i])
max=a[i];
return (max);
}
Output:
3.6
ii). Two dimensional al arrays:
To pass multi- dimensional array to functions
1. The function must called by passing only to the array name
2. The function deifications must indicates that the array has two dimension by including
two set of brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration should be similar to the function header.
Example:
#include <stdio.h>
void main()
{
int m=3,n=2;
int matrix [m][n]={{1,2,},{3.4},{5,6}};
mean = avg(matrix, m.n);
printf(“%f”, float sum=0);
for(i=0;i<;i++)
for(j=1;j<n;i++)
sum=sum+x[i][j];
return ((sum/(m x n));
}

PASSING STRING TO FUNCTION:


String are treated as character array.
 Rules for passing string to function:
1. String to be passed must be declared as a formal arguments of the function when
it is defined.
Example:
void display (char name[])
{

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 73


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
2. Function prototype must show that the arguments is a string .
Example:
void display (char s[]);
3. A call be a function must have a string array name without subscripts as its
actual arguments.
Example:
Display (name);

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 74


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
UNIT – IV

STRUCTURE AND UNIONS

STRUCTURES:
Structure is a derived data type which consists of different data type. Combined together in a
single room or template, its known as heterogeneous data type.
Syntax:
Struct tagname
{
Data type member 1;
Data type member 2;
----------------
----------------
};

 Here struct is a keyword.


 Tag name is the name of the structure.
 Member1,Member2,..........., Member n one individual member declaration.
 Entire definition is considered as statements each member declared independently.
Ex:
struct book
{
char title[20];
char author[15];
int pages;
};

Memory allocation:
 Title-> array of 20 characters
 Author-> array of 15 characters

DECLARING STUCTURE VARIABLES:


A structure variables of any other data type.
It includes
1. The keyword struct
2. The structure tagname
3. List of variable names separated by commas.
4. A terminating semicolon.
Syntax:
struct tagname
}
Data type member1;
Data type member2;
---------------
----------------
};
struct tag name list of variable:

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 75


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Ex :
struct book
{
char title [20];
char author [15];
float price;
};

struct book, book1,book2; Here, book is the name of the structure, book1,book2 as a structure
variable each variable has three members.

Importance Of Structure Definition:


 The member names must be unique with a particular structure.
 Storage class cannot be assigned to an individual member.
 Structure definitions appear at the beginning of the program .title, before any variables or
functions are defined. They may also appear before the main.

Accessing structure members:


 Access and design values to the members of a structure in a number of ways.
 The members themselves are not variables, they should be linked to the structure variables.
 The link between a member and a variable is established using the
member operator(.)or dot operator(or) period operator.

Syntax:
structure variable. structure member

Ex:
struct book
{
char author[15];
char title[20];
float price;
};
void main()
{
struct book b;
scanf(“%s%s%f”,&b.title,&b.author,&b,price);
printf(“%s%s%f”,b.title,b.author,b.price);
}

Output:
Input string:
Programming in c
Balagurusamy
235
Result String:
Programming in C
Balagurasamy
235

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 76


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Structure initialization:
This is an alternate and simplest way of assigning the members of a structure at the
declaration of the actual variable.
Syntax:
struct structure variable= {datamember1,datamember2,………..data member n};

1. Intialize a structure inside the function :


Example:
#include<stdio.h>
void main()
{
struct book
{
char title[20];
char author[15];
float price;
};
struct book={“c”,”B.gurusamy”,230.0};
----------
}

2. Initialize a structure outside the function:


Ex:
struct book
{
char title[20];
char author[15];
float price;
}
b={“c”, ”B.gurusamy”, 235.0};
main()
{
struct book b2 ={“c++”, “B.gurusamy,”325.0};
-------------
-------------
}
Elements:
 Keyword struct.
 Structure tag name.
 Name of the variable to be declared.
 A set of values for the member of the structure variable, separated by commas
and enclosed in braces.
 Terminating semicolon.
Rules:
 It cannot initialize individual member inside the structure template.
 Order of values enclose in braces must match the order of member in the
structure definition.
 Uninitialized member will be assigned default values it only at the end of
the list.
a. Zero for integer and floating point number.
b. „\o‟ for character and string.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 77


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

COPYING AND COMPARING STRUCTURE VARIABLES:


Two variables at the same structure type can be copied the same way as ordinary variables.
structure variable1= structure variable2;
Ex:
b1=b2;
C does not permit any logical operations on structure variables
Ex:
b1==b2
b1! =b2
C permits comparing member individually
Ex:
X= ((b1.title==b2.title)&&(b1.author==b2.author))? 1 : 0;

EXAMPLE PROGRAM:
# include <stdio.h>
struct book
{
char title[20];
char author[15];
float price;
};
void main()
{
int x;
struct book b1={“c”,”gurusamy”, 235.0};
struct book b2={“c++”,”gurusamy”,325.0};
struct book b3;
b3=b1;
x=((b3.title==b1.ttle)&&(b3.author,b3.price))? 1: 0
if(x= =1)
{
printf(“b1 and b3 are same”);
Printf(“%s%s%f”,b3.title,b3.author,b3.price);
}
else
{
printf (“b1 and b3 are different”);
}
OUTPUT :
B1 and b3 are different

ARRAYS OF STRUCTURES:
To declare an array of structures: a structure is first defined and then an array variable of that
type is declared.
An array of structure is stored inside the memory in the same way as a multi-dimensional
array.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 78


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Ex:
main()
{
struct book
{
char name;
float price;
int pages;
};
struct book b[100];
int i;
for(i=0; i<=99; i++)
{
scanf(“%c%f%d”,&b[i].name,&b[i].price,&b[i].pages);
printf(“%c%f%d”,b[i].name,&b[i].price,b[i].pages);
}

ARRAYS WITHIN STRUCTURES:


 The member of structure need not be an individual one. If the members are the same type and
more in member
 C allows usage of single or multidimensional array of typeint , float, char or double within a
structure.

Example :
struct book
{
char title [20];
char author[20];
float price;
} b;
PROGRAM:
#include<stdio.h>
struct marks
{
char sname[20];
int sub[3];
int total;
}s;
void main()
{
int i=0;
int total;
scanf (“%s”, s. sname);
}
while (i<2)
{
scanf(“%d”,s.sub[i]);
i++;
}
i=0;
while (i<2)

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 79


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
{
total +=s.sub[i];
i++;
}
printf (“%d”, total);
}

STRUCTURES WITHIN STRUCTURES:


Structure within a structure means nesting structure. Nested structure usually exist only.
 More complicated program.
 Size of the structure can be very large
 An array of structure is desired inside one structure definition.

Example :
struct book
{
char b name[25];
char author[20];
int edition;
Float price;
};
struct issue
{
char borrower[20];
char dt.o.issue[8];
struct book b;
}iss;
Initialization:
struct issue iss= {“vijay”,”28/12/93”},{“c”,”gurusamy”,4,235.00};

To access the elements of issue


iss.borrower
To access the elements of the structure book which is part of another
structure issue.
iss.b.author
iss.b.bname
iss.b.edition
iss.b.price

STRUCTURE AND FUNCTIONS:


C supports the passing of structure values of arguments to functions.
There are three methods by which the values of a structure can be transferred from one function to
another.
 Passing each members of the structure as actual arguments.
 Passing a copy of the entire structure to the function.
 Passing the address of the structure to the function using pointer.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 80


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
General format:
Sending a copy of a structure to the called function.
Function name (structure variable name);
Called function takes the following form

data type function name (structure st_name)


{
-------------------------
-------------------------
return (expression);
}

Rules:
1. The structure variable used as the actual argument and the corresponding formal
argument in the Called function must be of the same struct type.
2. The return expression can be a simple variable or a structure variable or simple
expression.
3. When a functions returns a structure; it must be assigned to a structure of identical
in the calling function.
4. Called functions must be declared in the calling function appropriately.
EXAMPLE:
#include<stdio.h>
main()
{
struct{char name[20]; int name; float amt;}xyz;
gets (xyz.name);
scanf(“%d”,xyz.num);
scanf(“%f”,xyz.amt);
calculate(xyz);/*passing the structure*/
}
calculate (struct {char name[20];
int numb;
float amt; }abc)
{
float si,rate=5.5,year=2.5;
si=(abc.amt*rate*year)/100;
printf (“%f”,si);
return;
}

Size of structures:
We normally use structures, unions , arrays to create variables of large sizes. The actual size of
these variables in terms of bytes may change from machine to machine.
We use the unary operator sizeof to tell us the size of a structure.
SYNTAX:
sizeof (struct x)
Will evaluate the member of bytes required to hold all the member of the structure x.
If Y is a simple structure variable of type struct x. then the expression is
sizeof(y)

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 81


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
UNIONS:

The union is a data type having the similar concept of structures. The declaration for a
union is identical to that of a structure, except that the keyword “UNION” must be substituted in
place of struct.

Declaration of union:
Syntax:
union<tag_ name>
{
<union member (s)>
} <list of union variables>;

 Where keyword union identifies the beginning of a Union definition.


 It is followed by a tag which is the name given to the union
 Members of union must be enclosed inside the braces.
 Then list of variables are to be mentioned followed by semicolon.
 This whole set of union declaration is termed as a template

Ex:
union student
<int age :
char sex ;
}Un,vz, (or) union student union variables s1, s2, s3;

Example:
#include<stdio‟h>
void main()
{
union demo
{
int age;
char sex;
float percent;
};
union demo d;
d.age =15;
d.sex=‟m‟;
d. percent= 38.22;
printf (“%d\n” ,d.age);
d.sex=‟F‟;
printf (“% cln”,d.sex);
getch();
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 82


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Difference between structure and union

Structure Union

1. The struct keyword is used to start the 1. The union keyword is used to start the
declaration of structure declaration of a union.

2.Memory allocated is separate for all 2.Memory allocated is common for all the
members declared within the structure members

3. The maximum size is allocated Is greater 3.The maximum memory size allocated is
than or equal to the sum of all the equal to the memory size of the larger
individual members declared. number.

4. All the individual members can be accessed 4. Only one member can be accessed at a
at a time. time.

BIT-FIELDS:

While declaring integer data type members within structure ,its size will be 16 bits. There are
occasions where data items require much less than 16 bits space ,there by waste of memory space.
We can overcome the wastage of space by specifying the bit length specifies the number of
bits that should be allotted to a member.(here member can be considered as a bit –field)

These bit-fields can be useful for a number of reasons:


1. If storage is limited , we can store several Boolean (true\false) Variables in one byte.
2. Certain devices transmit status information encoded into one or more bits with in a byte .
3. Certain encryption routines need to access the bits within the byte.
A bit- field must be a member of a structure or union.
Syntax:
Struct<tag name>
{
<date type ><names>:bit-length;
<date type><names> : bit –length;

….

};
Here data types is the type of the bit –field, and bit-length is the number of bits in the field. The
data type of bit-field must behind, signed, or unsigned.
Ex:
struct employee
{
unsignedint age :7;
unsigned int sex:1;
unsigned int children:4;
}emp;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 83


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
RULES:
Only n lower bits will be assigned to an n-bit number so data type cannot take values larger than 15.
Bit fields are always converted to integer type for computations.
We are allowed to mix normal members with bit fields.
The unsigned definition is important ensures that no bits are used as+- flag . If bit fields are too
large, next bit field may be stored consecutively in memory or in the next word of memory.

POINTER:
A pointer is a variable which holds the address of another variable. This process allows the
indirect access to the objects.

UDER STANDING POINTERS:


To understand pointer helps to compare them to normal variable.
A normal variable is a location in memory that can hold a values
For example when we declare a variable I is an integer two bytes of memory are set aside for it.
Ex:
int i=5;
float f=3.14;
variable value address
I 5 2000
J 3.14 2002
In the above table I and f are two normal variables with values 5 and 3.14 respectively. These
variables are stored in 2000 and 2002 memory locations respectively.

ACCESSING THE ADDRESS OF A VARIABLE:


The address of a variable can be obtained using the address operator(&)
Ex:
int i=5 (suppose if I stored in memory locations 20560, then we can use
printf (“ the address of I is:%u”, & i);
Which will print 20560
We have used %u to print the address since memory address one unsigned integers

DECLARING POINTERS AND INITIALIZING:


A pointer is a variable that points to another variable. A pointer points to other variable by
holding a copy of its address We put an asterisk(*) in front of the variable name then it will be a
pointer.
SYNTAX:
data type*pointer name;
Ex:
int *a
We can initialize the pointer by staring the address of another variable of same type.
int i=5
int *ptr; //declaring a pointer
ptr= $i; // Initializing a pointer
Accessing a variable through its pointer:
If we put the asterisk .in front of a pointer, It will be the same thing as using the variable it
points to.
Ex:
int *= 5;
int *xptr=$x;
printf (“%d\n”, x);
printf (“%d\n”, xptr);

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 84


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
When a pointer is encounter , the computer knows that it is dealing with an address in memory.
It is called as dereferencing a pointer.
Example:
#include (stdio.h)
void main ()
{
int i ,j;
int *p;
p=&I;
*p=5;
j=I;
printf (“%d%d%d\n”,I,j,xp);
}
return 0 ;

Chain of Pointers (or) Pointers on Pointers:


A pointer is a variable that holds address of another variable.This variable it self can be
another pointer.
Accessing a variable value through a pointer refers to direct addressing.
However a pointer being a variable can point to another pointer variable that leads to what is
known as indirect addressing.
int *ptr;
int **ptr;
The first declaration is a pointer declaration.
Where ptr is pointer to int data type value . The second declaration indicates that pptr is an
integer pointer that can hold the address of another integer pointer variable say ptr.
int a=10;
int *ptr;
int **ptr;
ptr=&a;
pptr=&ptr;

The following diagram shows the concept of a pointer to a pointer


a ptr pptr
10 2010 2008
2010 2008 2006
Example:
#include<stdio.h>
void main ()
{
int a, *b **c,***d,****e;
a= 100;
b=&a;
c=&b;
d= &c;
e=&d;
printf (“in a =%d, b=%u c=%d d=%u e=%u”, a ,b, c, d ,e);
printf (“in %d %d d%d”, a, a+*b +**c, ***d,+****e);
}
Output:
a=100 b=4200 c= 4198 d =4296 e=4194
100 300 200

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 85


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Pointer Expressions:
I ) Pointer Assignments:
We can assign one pointer to another pointer. It is similar of assigning one variable value to an
another variable .When both pointers one some type then we can go for assignment.
Ex: int a =10, b= 20;
int *ptr 1, *ptr 2;
ptr1 =&a; a b
ptr2 =&b; 10 20
ptr1=ptr2
2004 2005
Ptr1 ptr2
2004 2006
a b
10 20
2004 2005
2006 2006
Printf (“The values at ptr1 and ptr2 are : %d%d%”,*ptr**ptr2); will display 20 and 20.

(ii) Pointer comparisons:


We can compare two pointers in a rational expression.
int a[5] = {10,20,30,40,50}
int *ptr1 *ptr2;
ptr1 = &a[o];
ptr2 = &a[3];
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
2002 2004 2006 2008 2010

ptr1=&a[0]
Ptr1 Ptr2
2002 2008
4000 4002
ptr2=&a[3]
Ex:
if (ptr1<ptr2)
printf(“ptr1 points to lower memory than ptr2\n”);
else
printf(“ptr1 points to higher memory than ptr2\n”);
then based on ptr1 address the statement will be printed.

iii) Pointer Arithmetic


it can be incremented, decremented and a value can be added, subtracted, to a pointer in order
to modify the content of the pointer variable.
Let ptr be an integer pointer with current value of 2000.
ptr Pointer name
2000 value
4028 ptr‟s address

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 86


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Now ptr ++ => 2002

Ex.2 :
main ()
{
int n =10; n ptr1
int*ptr; 10 2002
ptr=&n; 2002 4015
ptr++; after p++
nptr
10 2004
2002 4015
printf(“%u\n”,ptr);
}
o/p =>2004

Example program:
#include <studio.h>
void main ( )
{
int a,b,x,y;
int *ptr1, *ptr2;
a=10;
b=20;
ptr1 = &a;
ptr2 = &b;
x=*ptr1+*ptr2;
y=*ptr2/*ptr1;
printf(“The value of X=%d\n”,x);
printf(“The value of Y=%d\n”,y);
*ptr1 =*ptr1+10;
*ptr2=*ptr2+5;
printf(“\n a =%d, b=%d,a,b);
printf(“\n a =%d, b=%d”,*ptr1,*ptr2);
}
The value of x=30
The value of y=2
a=10, b=20
a=20, b=100

POINTERS AND ARRAYS:

1.Pointers and dimensional array:


Pointers can be to access the elements in an array. The basic advantage of using
pointers to arrays involves convenience and reduction in memory space for program
code.
int a[5]= {10,20,30,40,50};
10 20 30 40 50
Then int x ptr;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 87


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Defines a pointer variable ,ptr suitable for holding the address of an integer variable .
Now the address of the start of array can be assigned to ptr as shown below.
ptr= &a(o)is same as ptr = a
Example:
#include <stdio.h>
void main()
{
int a[5]={10,20,30,40,50};
int i;
int *ptr;
ptr=a;
for(i=0,i<5;i+f)
{
printf(“Address=%u Element=%d\v”,ptr,*ptr),
}
} ptr++;

ii)Pointers and two dimensional arrays :


A pointer to a single dimensional array contains the address of the first element. In 2
dimensional arrays the address of the element in the first row and the first column of an
array is assigned to the pointer variable.
int*ptr;
ptr=A;
The address of A[0][0] is assigned to ptr . if we do ptr++,the pointer variable points to
A[0][1].

Example :
#include<stdio.h>
void main( )
{
int A[3][3]={{10,20,30},{40,50,60},{70,80,90}};
int i,j;
for(i=0;i<=2;i++)
{
printf(“\n”);
for( j=0;j<=2;j++)
printf(“%d”,*(*(a+i)+j));
}
}
Output:
10 20 30
40 50 60
70 80 90

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 88


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Pointers and char.strings:
If we want to store enormous amount of strings/messages, then the statement:
char *ptr[5];
Sets up an array capable of holding the address of five character variables. Each character
might be the beginning of a message. These messages can be set up in memory and elements of the
pointer array initialized to point to the messages.
ptr[0]= “welcome to C language”;
ptr[1]=”welcome to aac\n”;
We used pointers
char*ptr[]={“welcome to c language\n”,”welcome to aac\n”};

Example:
#include<stdio.h>
void main()
{
int choice;
char*ptrs[]={“welcome to c language\n”,”welcome to aac\n”};
printf (“%s”,ptrr[choice]);
return 0;
}

ARRAYS OF POINTERS:
A pointer variable always contains an address of another variable, but an array of pointers can
contain address of many variables or address of array elements or any other address.
int a=10,b=20,c=30,d=40,e=50;
We require 5 integer pointers to store the address of 5 integer variable mentioned above.
int *ptr1,*ptr2,*ptr3,*ptr4,Ptr5;
Then we can store the address as shown below:
{
ptr1=&a;
ptr2=&b; instead of declaring 5 integer pointer it can declared as int*
ptr3=&c; ptr[5];
ptr4=&d;
ptr5=&e;
}

Example :
#include<stdio.h>
void main()
{
int a=10, b=20,c=30,d=40,e=50;
int**[5];
*[0]=&a; *[1]=&b; *[2]=&c; *[3]=&d; *[4]=&e;
for(i=0;i<5;i++)
{
printf (“Elements%d=%d”,i+1,*ptr(i));
}
}
Output:
Element1=10 Element 2 =20 element 3=30
Element 4=40 Element 5=50

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 89


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
In the above program the address of a,b,c,d and e are assigned to x[0],x[1],x[2],x[3],x[4]
respectively.
a b c d e
10 20 30 40 50
2002 2004 2006 2008 2010
X[0] x[1] x[2] x[3] x[4]
2002 2004 2006 2008 2010
4100 4102 4104 4106 4108

POINTERS AND FUNCTIONS:


Using pointers as function parameters:
We have actually been using variables parameters in the scanf function, that‟s why we have to
use the &on variables used with scanf.
The parameters to the function are passed in two ways:
1. Call by value
2. Call by reference
1.Call by value:
The process of passing the actual values of variables to the function is known as call by value.
Example:
# include<stdio.h>
void swap (int i, int j)
{
int t ;
t=i; i=j; j=t;
}
void main()
{
int a,b;
a=5;
b=10;
printf (“a=%d b=%d\n”,a,b);
swap(a,b);
printf (“a=%d b=%d\n”,a,b);
}

OUTPUT :
a=5 b=10
a=10 b=5

2.Call by reference:
The process of passing the addresses of actual variables to the function is known as call by
reference
Example:
# include<stdio.h>
void swap (int *i, int *j)
{
int t;
t=*I;
*i=*j;
*j=t;
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 90


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
void main()
{
int a,b;
a=5,b=10;
print f (“a=%d b=%d\n”,a,b);
swap (&a, &b);
print f (“a=%d b=%d\n”, a,b);
}
OUTPUT:
a=5 b=10
a=10 b=5

DIIFERENCE BETWEEN CALL BY VALUE &CALL BY REFERENCE

CALL BY VALUE CALL BY REFERENCE


Only the value is passed The address is passed
Separate memory locations for Only one memory location for both formal
Formal and actual parameters are and actual parameters is created
Created
The changes made to the formal Changes made to the formal parameters
Parameters does not affect the affects original value of the actual
Values of actual parameters parameter
Slow CPU spends time to create Fast ,the manipulation with the address is
Memory locations for formal faster than the ordinary
Parameters and to store the values of actual variables
parameters in them

FUNCTIONS RETURNING A POINTER :


To return a pointer from a function the function definition and any corresponding
function declarations must indicate that the function will return a pointer. This is accomplished
by preceding the function name by an asterisk (*). The asterisk must appear in both function
definition and function declaration .
Example:
#include <stdio.h>
int *largest (int*,int*)
{
int a=10.b=20;
int*ptr;
ptr=largest(&a,&b);
printf(“\n the largest number is :%d”,”ptr”);
}
int *largest (int*ptr1,int*ptr2)
{
if(*ptr1>*ptr2)
return ptr1;
return ptr2;
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 91


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

POINTERS TO FUNCTION:
A function has a physical location in memory that can be assigned to a pointer. This address is
the entry point of the function and it is the address used when a function is called a pointer to a
function. We can obtain the address of a function by using the function‟s name without parenthesis
or arguments. The name of the function itself represents the starting address of function definitions.
This address can be assigned to a pointer to function variable.

Syntax:
data type(*pointer variable) (argument list of function);

Example:
#include <stdio.h>
#include<conio.h>
int sum (int a, int b)
{
int c ;
c=a+b;
printf(“the sum =%d”, c);
}
void main()
{
int(*ptr)(int,int);
ptr= sum ;
printf(“function sum is located at u address \n”,ptr);
printf(“function sum is located at u address \n”,sum);
(*ptr)(10,20);
getch();
}
Output:
Function sum is located at 4855 address
Function sum is located at 4855 address
The sum is =30

POINTERS AND STRUCTURES:


When we declared a structure variables for using pointers that is called pointers in structures .
Example:
struct inventory
{
char name[20];
int number ;
float price;
}
product [2];
*ptr;
Here the ptr is a pointer variable where we used as a structure variable it gives the pointer
reference to the structure member variable.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 92


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

UNIT – V

FILE MANAGEMENT IN C
INTRODUCTION:

FILE:
A file is a collection of records which are stored permanently on secondary storage devices
such as disk.
I/O operations pose two major problems:
i. It becomes cumbersome and time consuming to handle large volume of data through
terminals.
ii. The entire data is lost when either the program is terminated or the computer is tuned off.
It is therefore necessary to have a more flexible approach where data can be stored on the disks and
read whenever necessary, without destroying the data. This method employs the concept of files to
store data. C supports a number of functions that have the ability to perform basic file operations,
which include:
 Naming a file,
 Opening a file,
 Reading data from a file,
 Writing data to a file, and
 Closing a file.

There are two distinct ways to perfume file operations in C. The first one is known as the low-
level I/O and uses UNIX system calls.
The second method is referred to as the high-level I/O operation and uses functions in C‟s
standard I/O library.

High level I/O Functions

Function name Operation


fopen() Creates a new file for use.
Opens an existing file for use.
fclose() Closes a file which has been opened for use.
getc() Reads a character to 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 from a file.
getw() Reads an integer from a file.
putw() Writes an integer to a file.
fseek() Sets the position to a desired point in the file.
ftell() Gives the current position in the file.
rewind() Sets the position to the beginning of the file.

Defining and Opening a File


If we want to store data in a file in the secondary memory, we must specify certain things
about the file, to the operating system. They include:
1. Filename.
2. Data structure.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 93


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
3. Purpose.
Filename is a string of characters that make up a valid filename for the operating system. It
may contain two parts, a primary name and an optional period with the extension.
Examples: Input.data
Store
PROG.C
Student.c
Text.out
Data Structure of a file is defined as FILE in the library of standard I/O function definitions.
Therefore, all files should be declared as type FILE before they are used. FILE is a defined data type.
When we open a file, we must specify what we want to do with the file. For example , we
may write data to the file or read the already existing data.
Syntax:
FILE *fp;
Fp = fopen(“filename”,”mode”);

Explanation of syntax
The first statement declares the variables fp as a “pointer to the data type FILE”. As stated
earlier, File is a structure that is defined in the I/O library.
The second statement opens the file named filename and assigns an identifier to the FILE
type pointer fp.
The second statement also specifies the purpose of opening this file. The mode does this job.
Mode can be one of the following:
r open the file for reading only.
w open the file for writing only.
a open the file for appending(or adding) data to it.
The file name and mode are specified as strings. They should be enclosed in double quotation marks.
Trying to open a file
1. When the mode is „writing‟ a file with the specified name is created if the file does not exist.
The contents ate deleted, if the file already exists.
2. When the purpose is „appending‟, the file is opened with the current contents safe. A file with
the specified name is created if the file does not exist.
3. If the purpose is „reading‟, and if it exists, then the file is opened with the current contents
safe otherwise an error occurs.
Consider the following statements:
FILE *p1,*p2;
P1=fopen(“data”,‟ “r”);
P2=fopen(“results”, “w”);
Many recent compilers include additional modes of operation. They include:
r+ The existing file is opened to the beginning for both reading and writing.
w+ Same as w except both for reading and writing.
a+  Same as a except both for reading and writing.

CLOSING A FILE:
A file must be closed as soon as all operations on it have been completed
Syntax
fclose (file _pointer);
Example:
----------------------
----------------------
File *p1, *p2;
P1 = fopen(“INPUT”, “w”);
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 94
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
P2= fopen(“OUTPUT”, “r”);
-------------------
-------------------
fclose(p1);
fclose(p2);
fclose all():
The close all the files associated with the file pointers.
Syntax:
Int fcloseall();
 If it is success returns the number of files closed.
 If it‟s error-EOF (ENDOF FILE)

INPUT /OUTPUT OPERATIONS ON FILES


Input/ Output operations carried out through function calls such as scanf, printf, fscanf,
fprintf.
There are two types of I/O operations on files.

1. Formatted I\O functions.


2. Unformatted I\O functions.

1. Formatted I\O functions:


Formatted I\O functions are used to read and write all types of data values.
1.fscanf () 2.frintf()

1.fscanf(): fscanf() function reads formatted data. It reads data from the current position of file
pointer into the location given by the argument.
Syntax
fscanf(fp,”controlstring”,argument);
here
 fp is a file pointer.
 Control string like %d %f.....etc.,
 Arguments are the list of data items.
Example:
fscanf(f1,”%s%d%f”, name , &rno,&sal);
2.fprintf(): fprintf ( )function prints formatted data to the file. The printf function formats and prints a
series of characters and values to output file.
Syntax
fprintf(fp,”contro lString”, arguments);
here
 fp is a file pointer.
 Control string like %d %f.....etc.,
 Argument is converted and output according to corresponding formal specification
format.
Example
fprintf(f1,”%s%d%f”, ename,eno, sal);
fprintf(f1,”%s%d%f”, “vijay”,1234,600.75);

2.UnFormatted I\O functions.

i.Character I\O functions:


To read and write a unformatted character file. There are two basic functions.
1.fgetc() 2.fputc()

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 95


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
a). fgetc ( )  The fgetc( ) function read a single character from the current position of the
associated file pointer.
File that has been opened in a read mode.
Syntax:
variable = fgetc(fp);
here
 fp is a file pointer.
 variable is a character type.
 fgetc is a build-in functions.
Example:
File *fp;
char ch;
fp = fopen (“file”,”r‟);
while(fp!=EOF)
{
ch=fgetc();
}
b). Fputc ( ) The fputc() function writes a single a single character to the file at the current
position.
File is opened with mode “W”.
Syntax:
fputc(ch,fp);
ch is a character variable.
fp is a file pointer.
Example:
File *fp;
char ch;
fp = fopen (“file”,”w‟);
while(ch=getchar( )!=‟\n‟)
{
fputc(ch,fp);
}

STRING I\O FUNCTIONS:


To read and write strings to the files. There are two basics functions.

1. fgets( ) 2.fputs( )
a) fgets( ): To read a string, from file.
Syntax:
fgets(String, variable, size, filepointer);
Example:
fgets(char,s[50],int n, file *fp);
b) fputs( ): To write the contents of the string at specified position. The terminating
character(„10‟) is not copied.
Syntax:
fputs(string variable, fp);
Example:
fputs(S, fp);

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 96


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
ERROR HANDLING FUNCTIONS:-
Error handling functions deals with when an error occur and how to detect rectify the error
the following
Common error situations :
 Trying to open a file with invalid file name.
 Trying to read a file which does not exit.
 Device over flow.
 Trying to use a file that has not been opened.
 Trying to use a file to write a write protected file.

There are three basic error handling functions.


1.feof( ) 2. Ferror 3.Null pointer.
1. ferror( ) :-
The ferror function reports the status of the file.
It returns a non-zero value when the error has occurred and a value of zero indicates that no
error has occurred.
Syntax :
ferror(file pointer);
Example:
main()
{
File *fp;
char ch;
fp = fopen(“sam.txt”, “w”);
ch = fget(fp);
if (ferror (fp))
{
printf (“error from sam.txt”);
}
floes(fp);
}
2 feof( ) function:-
The feof( ) function can be used to test for an end of file condition. It returns non zero if end
has been reached otherwise zero.
Syntax :
feof(file pointer);
Example:
main( )
{
File *fp;
char ch;
fp=fopen(“file.txt”, “r”);
while (ch= fget(fp)!=EOF)
{
printf(“%c”,ch);
if(feof(fp))
printf(“file reached |EOF”);
fclose(fp);
}
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 97


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
3.Null pointer:- The file could not be opened properly due to errors the fopen( ) functions a null
value .
Syntax:
#define Null 0(Zero).

Example:
main( )
{
File *fp;
fp = fopen(“s1.txt”, “r”);
if (fp= = NULL)
{
printf(“Error in opening file”);
}
exit( );
}

RANDOM ACCESS FILES:-


Reading and writing of files sequentially is not advisable when there is huge amount of data.
It may be necessary to access a particular part of file.
Functions:
1. ftell ( ) 2. fseek( ) 3. rewind( )

1 ftell( ) :This function is used to know the current pointer position of the file form the beginning the
position value is long int.
Syntax:
long int variable = ftell(fP);
Or
position = ftell(fp);
here
fp is a file pointer & position is a current pointer position.
Example
n=ftell(fp);
2 fseek( ):
fseek function is used to move the file position to a desired location with in the file.
Syntax:
fseek(file ptr, offset, position);
Here
 File ptr is the file pointer of the file.
 Offset is the number of bytes / characters should be moved from desired position.
 Position specify the seek position like from beginning ending or current position.

Values Constants Meaning


0 Seek_set Beginning of file
1 Seek_Cur Current position
2 Seek_End End of the file

fseek( ) function returns integer values. It returns


 0 (zero) on Success.
 Non-zero on errors.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 98


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Example:
1. fseek(fp, OL,o) or fseek(fp, OL, SEEK_SET)
2. fseek(fp,n,1) or fseek (fp,n,SEEK_CUR)
3. fseek(fp,-n,1) or fseek(fp,-n,SEEK_CUR)
4. fseek(fp,-n,2) or fseek(fp,-n,SEEK_END)
5. fseek(fp,OL,2) or fseek(fp,OL,SEEK_END)

3.rewind ( ): This function is used to move the pointer to beginning of file.


rewind( ) functions helps us in reading a file more than once, without having to close and
open the file.

A file is opened for reading or writing a rewind is device implicitly.


Syntax:
rewind(fp);
Example:
rewind(f1);

COMMAND LINE ARGUMENTS:


Command line arguments is a parameter supplied to a program when the program is invoked.
This parameter may represent a filename the program should process.
To access the command line arguments, we must declare the main function and its
parameters.
Syntax:
main(int argc, char * argv [ ])
{
--------------------------------------
--------------------------------------
}
Here
argc – count the number of arguments on the command line. The size of the array will be equal to
the value of argc.
argv- It is a argument vector and represent an array of character pointers that point to the command
line arguments.
The first parameter in the command line is always the program name and therefore argv[0] always
represents the program name.
Example
C :> add 10 20
Here
 Add is the filename where the executable code of a program is stored.
 10 and 20 one the arguments.
Advantages:
Command line arguments are used to eliminate the need for the program to represent the user
to enter the filename during execution.

Program
#include <stdio.h>
void main(int argc, char *argv[ ])
{
int a, b, sum;
a = ato i(arg v[1]=);
b=ato i(arg v[2]);
sum=a+b;

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 99


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
printf(“%d”,sum);
}

c:\> Add 10 to 15
Example Program :

#include <stdio.h>
void main(int argc, char * argv[ ])
{
FILE *fp;
int i;
char word[15]);
fp=fopen(argv[1],”v”);
printf(%d”,argc);
for(i-2;i<argc;i++)
fprintf(fp,”%s”,argv[i]);
fclose(fp);
printf(“%s”,argv[1]);
fp=fopen(argv[1], “v”);
for(i=2;i< argc;i++)
{
fscanf(fp,”%s”,word);
fprintf(“%s”,word);
}
fclose(fp);
for(i=0;i<argc;i++)
printf(“%s”,argv[i]);
}

PREPROCESSOR:
 Preprocessor is a tool to make the program easy to read, easy to modify, portable and more
efficient.
 Preprocessor, as its name implies, is a program that process the source code before it passes
through the compiler.
 Preprocessor directives are placed in the source program before the main line.
 They all begin with the symbol # in column one and do not require a semicolon at the end.
A preprocessor directives facilities
1) File Inclusion
2) Macro Substitution facilities
3) Compiler control directives
 The preprocessor directives appear before the function main()
 But they appear anywhere in a c program
 It modifies the c source code before compilation.
 Any preprocessor directive must begin with the character #.
 Any number of white space, character may follow or precede #.
 There is no semicolon to end any preprocessor facility.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 100


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
 If a directive spans over more than one line, the continuation is marked by a backslash at the
end of the current line followed by pressing the Enter key.

Different types of directives, are


Define error include
Elif if line
Else ifdef pragma
Endif ifndef undef

HEADER FILES :
 Definitions and declarations of common objects shared by many programs may be available
in one or more files. these files are known as header files.
 A complete source code uses multiple header files when it makes use of common objects
 The header files are included in a program by # include directive.

Two forms of #include directive


1) #include “file name”
2) #include <file name>
 First form is used the preprocessor searches the current directory that contains the source file
first .if it fails in the directory it searches the standard directories.
 second form the preprocessor searches the file specified only in the standard directories.
Stdio.h :
- all input/output operations are carried out through function calls such as printf and scanf.
- there are special function exits in standard for input and output operations in c.
- these functions are collectively known as the standard I/O library.
- each program that uses a standard input/output function must contain the statement.
 # include <stdio.h> at he beginning.
- any preprocessor directive must begin with the character #
- #include directive tells the preprocessor to replace the lines containing it by the contents
of the specified file.
- stdio.h is an abbreviation for standard input /output header file.
- the instruction #include <stdio.h> tells the compiler to search for a file named stdio.h and
place its conents at this point in the program.

MACRO SUBSTITUTION FACILITIES :


 Macro substitution is a process where an identifier in a program is replaced by a predefined
string.
- #define statement is used for this purpose
- #define followed by identifier and a string, with atleast one blank space between
them.
1) Simple Macro substitution
2) Argumented Macro substitution
3) Nested Macro substitution

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 101


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

1) Simple Macro Substitution:


- Simple String replacement is commonly used to define constants.
Example:
#define COUNT 100
#definePI 3.145
- All macro is capitals to identify them as symbolic constants.
#defineM 5
total=M*value;
printf(“M=%d\n”,M);
Macro with arguments:
 Preprocessor permits us to define more complex and more useful form of replacement
#define identifier(f1,f2,..,fn) String
- The identifier f1,f2,…,fn are the formal macro arguments.
Example:
#define CUBE(X) (x*x*x)
we can use this
Volume = CUBE(side);
- is a macro call statement with arguments similar to function call.
The preprocessor would expand as
Volume = (side *side * side);
Example 2:
Volume = CUBE(a+b)
Expand as
Volume = CUBE(a+b * a+b * a+b);

NESTING OF MACROS:
 We can also use one macro in the definition of another macro.
#defineM 5
#defineN M+1
 result= (M > N) ? M : N;

DIFFERENT TYPES OF DIRECTIVES


define include if elif else endif
Substitution facilities are provided using
#define directive /manifests.
#define AUTHORS “S.THAMARAI \ MURUGESAN “

Program :
#define BEGIN
main()
{
#define END
}
#define EQUAL = =
#define READ(N) scanf(“%d”,&n)
#define WRITE(N) printf(“%d \n “,N)
BEGIN

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 102


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
int i;
READ (i);
if(I EQUAL 5)
WRITELN(i);
END
#define ROW 5
#define MARKS (BRINDHA,TOTAL)”BRINDHA secured TOTAL MARKS”
main(){
char s1[] =”the matrix has ROW rows “;
char s2[] =MARKS(“BRINDHA”,95);
printf(“%s\n”,s1);
printf(“%s\n”,s2);
}
OUTPUT :
The matrix has ROW rows.
BRINDHA secured TOTAL marks.
CONDITIONAL COMPILATION :
#if
#elif
#else
#endif are control structures.

General formats :
# if const-expression
#elif const-expression
#else
#if const-expression.
#define TYPE-I 1
#define TYPE-F 1
# if TYPE-I
char type[]=”INTEGER”;
#elif TYPE-F
char type[]=”FLOAT”;
#else
char type[]=”CHARACTER”;
#end if
#define ODD(N) if(N%2)printf(“%d is add\n”)
main ()
{
int i;
for(i=0;i<10;i++)
{
if(i!=0) ODD(i);
else
printf(“%d is even \n”);
}
}

OUTPUT:
1 is odd
2 is even
3 is odd
4 is even
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 103
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

17UCAP02- PROGRAMMING IN C PRACTICAL

1. To find the total and average percentage obtained by a student for 6 subjects

AIM:
Write a simple C program to find the total and average percentage obtained by a student for
six subjects.

ALGORITHM :

Step 1: Start the program.


Step 2: Declare the required input variables name as char and no, m1, m2, m3, m4, m5, m6 as int
and output variables total , average , percentage as float.
Step 3: Read the input values as name, no, m1, m2, m3, m4, m5, m6.
Step 4: Calculate the total , average , percentage values for the given six subjects.
Step 5: Print the Reg.No , Name , Tamil-II , English – II , C , Allied Maths-II , Internet , EVS
subjects marks and Total , Average , Percentage values.
Step 6: Stop the program.

FLOWCHART :

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 104


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
PROGRAM :

#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
int no,m1,m2,m3,m4,m5,m6;
float total, average, percentage;
clrscr();
printf("************Input***************\n");
printf("Enter the Reg.No \n");
scanf("%d",&no);
printf("Enter the Name of the Student \n");
scanf("%s",name);
printf("Enter marks of six subjects: \n");
scanf("%d%d%d%d%d%d",&m1, &m2, &m3, &m4, &m5, &m6);
total = m1 + m2 + m3 + m4 + m5 + m6;
average = total / 6.0;
percentage = (total / 600.0) * 100;
printf("************Output***************\n");
printf("Reg.No : 17UCA%d\n",no);
printf("Name : %s\n",name);
printf("Tamil-II : %d\nEnglish-II: %d\nC : %d\n",m1,m2,m3);
printf("Allied-Maths-II : %d\nSBEC-I-Internet : %d\nEVS : %d\n",m4,m5,m6);
printf("Total marks : %.2f\n", total);
printf("Average marks : %.2f\n", average);
printf("Percentage : %.2f", percentage);
getch();
}

************Input***************\
Enter the Reg.No
1803
Enter the Name of the Student
M.Nareshkumar
************Output***************\
Reg.No : 17UCA1803
Name : M.Nareshkumar
Tamil-II : 78
English-II : 70
C : 80
Allied-Maths-II : 90
SBEC-I-Internet : 75
EVS : 70
Total Marks : 463
Average Marks : 77.16
Percentage : 77.16 %

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 105


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

2. To check whether a given character is vowels or not using Switch – Case statement.

AIM:
Write a simple C program to check whether a given character is vowels or not using Switch –
Case statement.

ALGORITHM :

Step 1: Start the program.


Step 2: Declare the required input variables ch and ch1 as char.
Step 3: Read the input values ch as the given input character.
Step 4: To convert ch into ch1 = tolower(ch).
Step 5: Apply the ch1 input value to switch statement and check the case label which is matching to
the relevant input choice.
Step 6: Print the result, whether the given input character is vowel or not.
Step 7: Stop the program.

FLOWCHART :

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 106


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM :

#include<stdio.h>
#include<conio.h>
void main()
{
char ch , ch1;
clrscr();
printf("**************Input***********\n");
printf("Enter any alphabet: ");
scanf("%c", &ch);
ch1 = tolower(ch);
printf("**************Output***********\n");
switch(ch1)
{
case 'a': printf("It‟s Vowel");
break;
case 'e': printf("It‟s Vowel");
break;
case 'i': printf("It‟s Vowel");
break;
case 'o': printf("It‟s Vowel");
break;
case 'u': printf("It‟s Vowel");
break;
default : printf("Sorry! You are entered character is not vowel");
}
getch( );
}

**************Input***********
Enter any alphabet: E
**************Output***********
It‟s Vowel

**************Input***********
Enter any alphabet: D
**************Output***********
Sorry! You are entered character is not vowel

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 107


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
3. To print the numbers 1 to 10 along with their squares.

AIM:
Write a simple C program to print the numbers 1 to 10 along with their squares.

ALGORITHM :

Step 1: Start the program.


Step 2: Declare the required input variables i, n as integer.
Step 3: Read the input value n.
Step 4: Do the for loop , for ( i = 1 ; i<=n ; i++).
Step 5: Print the result i and i * i.
Step 6: Stop the program.

FLOWCHART :

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 108


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
PROGRAM :

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

void main()
{
int i,n;
clrscr();
printf("************Input************\n");
printf("Enter the n value\n");
scanf("%d",&n);
printf("************Output***********\n");
printf("i i * i\n");
printf("------------\n");
for(i = 1; i <= n; i++)
{
printf("%d %d\n", i, i * i);
}
getch();
}

************Input************
Enter the n value
10
************Output***********
i i*i
-------------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 109


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
4. To find the sum of ‘n’ numbers using for do-while statement.

AIM:
Write a simple C program to find the sum of „n‟ numbers using for do-while statement.

ALGORITHM :

Step 1: Start the program.


Step 2: Declare the required input variables i, n , sum = 0 as integer.
Step 3: Read the input value n and assign i =1.
Step 4: Inside the Do statement print the i value and compute the sum = sum + i , then increase the i
value using i++.
Step 5: Check the while condition while(i <= n).
Step 6: Print the n and sum value.
Step 7: Stop the program.

FLOWCHART :

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 110


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM :

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

void main()
{
int i,n,sum=0;
clrscr();
printf("************Input***********\n");
printf("Enter the how many terms\n");
scanf("%d",&n);
i=1;
printf("************Output**********\n");
do
{
printf("%d+",i);
sum=sum+i;
i++;
}
while(i<=n);
printf("\n\nSum of first %d numbers = %d\n",n,sum);
getch();
}

************Input***********
Enter the how many terms
12

************Output**********
1+2+3+4+5+6+7+8+9+10+11+12+

Sum of first 12 numbers = 78

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 111


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
5. To find the factorial of a given numbers using function.

AIM:
Write a simple C program to find the factorial of a given numbers using function.

ALGORITHM :

Step 1: Start the program.


Step 2: Declare the global function factorial( int ).
Step 3: Inside the main function declare the input variable no as integer.
Step 4: Read the input value no.
Step 5: Print the no and factorial ( no ) value.
Step 6: Inside the function definition factorial ( int n) declare the variables i and fact=1 as integer.
Step 7: Do the for loop , for (i=1 ; i<=n ; i++)
Step 8: Compute the fact = fact * i and return the result fact value to main function using return(fact)
statement.
Step 9: Stop the program.

FLOWCHART :

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 112


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM :

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

int factorial(int);

void main()
{
int no;
clrscr();
printf("*************Input*************\n");
printf("Enter a number to calculate it's factorial\n");
scanf("%d",&no);
printf("*************Output************\n");
printf("Factorial of %d is = %d\n", no, factorial(no));
getch();
}

int factorial(int n)
{
int i;
int fact = 1;
for( i = 1 ; i <= n ; i++ )
fact = fact * i;
return ( fact );
}

*************Input*************
Enter a number to calculate it's factorial
5

*************Output************
Factorial of 5 is = 120

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 113


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
6. To swap two numbers using call by values and call by reference.

AIM:
Write a simple C program to swap two numbers using call by values and call by reference.

ALGORITHM :

Step 1: Start the program.


Step 2: Declare the global function swap(int , int) and swap1(int* , int*).
Step 3: Inside the main function declare the input variable x , y as integer.
Step 4: Read the input values x and y.
Step 5: Print the x and y value then call the function swap(x , y) and swap1(&x , &y) and print the
result.
Step 6: Inside the function definition swap( int x , int y) declare the variable t and assign t = x ,
x = y , y =t , then print the x , y values.
Step 7: Inside the function definition swap1( int *a , int *b) declare the variable t and assign t = *a ,
*a = *b , *b = t.
Step 8: Stop the program.

FLOWCHART :

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 114


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

PROGRAM :

#include<stdio.h>
#include<conio.h>
void swap(int , int);
void swap1(int* , int*);
void main()
{
int x, y;
clrscr();
printf("***********Input************\n");
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("*************Output**********\n");
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
printf("After Swapping the numbers using call by value method\n");
swap(x , y);
printf("After Swapping the numbers using call by reference method\n");
swap1(&x , &y);
printf("x = %d\ny = %d\n", x, y);
getch();
}
void swap( int x, int y )
{
int t ;
t=x;
x=y;
y=t;
printf("x = %d\ny = %d\n", x, y);
}
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 115
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

void swap1(int *a, int *b)


{
int t;
t = *b;
*b = *a;
*a = t;
}

***********Input************
Enter the value of x and y
20
30
*************Output*********
Before Swapping
x = 20
y = 30
After swapping the numbers using call by value method
x = 30
y = 20
After swapping the numbers using call by reference method
x = 30
y = 20

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 116


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
7. To find the smallest and largest element in an array.

AIM:
Write a simple C program to find the smallest and largest element in an array.

ALGORITHM :

Step 1: Start the program.


Step 2: Declare the input variables arr[10] , i , size as integer and output variables max ,
min as integer.
Step 3: Read the input size value.
Step 4: Do the for loop , for (i=0 ; i<=size ; i++)
Step 5: Read the arr[i] values.
Step 6: Assign max = arr[0] , min = arr[0].
Step 7: Do the for loop , for ( i=1 ; i<size ; i++)
Step 8: Check the condition if(arr[i]>max) then assign max = arr[i] and if(arr[i] < min) then assign
min = arr[i].
Step 9: Print the max and min result values.
Step 10: Stop the program.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 117


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

FLOWCHART :

Start

int arr[10]
int i ,max , min

Read size

for i=0 to i < size do

Read arr[i]

i++

max =arr[0]
min = arr[0]

for i=1 to i < size do

if (arr[i] > max) max = arr[i]

if (arr[i] < min) min = arr[i]

Print max , min

Stop

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 118


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
PROGRAM :

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

void main()
{
int arr[10];
int i, max, min, size;
clrscr();
printf("**********Input***********\n");
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in the array\n");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max = arr[0];
min = arr[0];
for(i=1; i<size; i++)
{
if(arr[i]>max)
{
max = arr[i];
}
if(arr[i]<min)
{
min = arr[i];
}
}
printf("***********Output**********\n");
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
getch();
}

**********Input***********
Enter size of the array: 5
Enter elements in the array
10
5
30
60
45
***********Output**********
Maximum element = 60
Minimum element = 5

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 119


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
8. To performing Matrix multiplication.

AIM:
Write a simple C program to perform matrix multiplication.

ALGORITHM :

Step 1: Start the program.


Step 2: Declare the required input and output variables a[5][5] , b[5][5] , c[5][5] , i , j , k , m , n
as integer.
Step 3: Read the input row and column value as m , n.
Step 4: Do the for loop , for (i=0 ; i<m ; i++) and for (j=0 ; j<n ; j++)
Step 5: Read the first input matrix a[i][j] values.
Step 6: Do the for loop , for (i=0 ; i<m ; i++) and for (j=0 ; j<n ; j++)
Step 7: Read the second input matrix b[i][j] values.
Step 8: Do the for loop , for (i=0 ; i<m ; i++) and for (j=0 ; j<n ; j++)
Step 9: Assign c[i][j] = 0 and Do the for loop , for (k=0 ; k<n ; k++)
Step 10: Calculate c[i][j] = c[i][j] + a[i][k] * b[k][j].
Step 11: Do the for loop , for (i=0 ; i<m ; i++) and for (j=0 ; j<n ; j++)
Step 12: Print the multiplication matrix value c[i][j].
Step 13: Stop the program.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 120


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

FLOWCHART:
Start

int a[5][5] , b[5][5] , c[5][5]


int i , j , k, m , n

Read m , n

for i=0 to i < m do

for j=0 to j < n do

Read a[i][j]

j++

i++

for i=0 to i < m do

for j=0 to j < n do

Read b[i][j]

j++

i++

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 121


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

for i=0 to i < m do

for j=0 to j < n do

c[i][j]=0

for k=0 to k < n do

c[i][j] = c[i][j] + a[i][k]*b[k][j]

k++

j++

i++

for i=0 to i < m do

for j=0 to j < n do

Print c[i][j]

j++

i++

Stop

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 122


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
PROGRAM :

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

void main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,m,n;
clrscr();
printf("***************Input*************\n");
printf("\nEnter the row and column of input matrix\n");
scanf("%d %d",&m,&n);
printf("\nEnter the First matrix->\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf("\n*************Output*************\n");
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t",c[i][j]);
}
}
getch();
}

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 123


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

***************Input*************
Enter the row and column of input matrix
2
2

Enter the First matrix->


10 4
6 3

Enter the Second matrix->


2 3
4 5

*************Output*************
The multiplication of two matrix is
36 50
24 33

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 124


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

9. To find the sum of an integer array using pointers.

AIM:
Write a simple C program to find the sum of an integer array using pointers.

ALGORITHM :

Step 1: Start the program.

Step 2: Declare the required input and output variables n , numArray[10] , i ,sum = 0 , *ptr as

integer.

Step 3: Read the n value .

Step 4: Do the for loop , for (i=0 ; i<n ; i++)

Step 5: Read the numArray[i] values.

Step 6: Assign ptr = numArray.

Step 7: Do the for loop , for (i=0 ; i<m ; i++)

Step 8: Calculate the sum value sum = sum + *ptr and increase the ptr value using ptr++.

Step 9: Print the sum result value.

Step 10: Stop the program.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 125


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

FLOWCHART :

Start

int n , numArray[10]
int i , sum = 0 , *ptr

Read n

for i=0 to i < n do

Read numArray[i]

i++

ptr = numArray

for i=0 to i < n do

sum = sum + *ptr


ptr++

i++

Print sum

Stop

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 126


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
PROGRAM :

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

void main()
{
int n,numArray[10];
int i, sum = 0;
int *ptr;
clrscr();
printf("*************Input***********\n");
printf("\nEnter the number of elements : ");
scanf("%d",&n);
printf("\nEnter the element values\n");
for (i = 0; i < n; i++)
scanf("%d", &numArray[i]);
ptr = numArray; /* a=&a[0] */
for (i = 0; i < n; i++)
{
sum = sum + *ptr;
ptr++;
}
printf("***************Output************\n");
printf("The sum of array elements : %d", sum);
getch();
}

*************Input***********
Enter the number of elements : 6
Enter the element values
20
30
60
40
50
10

***************Output************
The sum of array elements: 210

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 127


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

10. To copy the contents of one file into another file.

AIM:
Write a simple C program to copy the contents of one file into another file.

ALGORITHM :

Step 1: Start the program.

Step 2: Declare the required input and output variables FILE *fp , *fp1 , *fp2 and ch as char.

Step 3: Open the input file fp = fopen(“sample.txt” , “w”) and enter the input contents then press

ctrl + z.

Step 4: Check the while condition while( ( ch = getchar( ) ) ! = EOF ) inside the loop putc(ch , fp)

value then close the fp file.

Step 5: Assign fp1 = fopen(“sample.txt” , “r”) and fp2 = fopen(“output.txt” , “w”).

Step 6: Check the while(1) condition , inside the loop assign ch = fgetc(fp1) and if(ch == EOF) then

break otherwise putc(ch , fp2) .

Step 7: Print file copied successfully then fclose(fp1) , fclose(fp2).

Step 8: Assign fp= fopen( “Output.txt” , “r”).

Step 9: Print the contents of output.txt file using while(( ch = getc(fp)) != EOF) then print ch.

Step 10: Close the file fclose(fp).

Step 12: Stop the program.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 128


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

FLOWCHART :
Start

FILE *fp , *fp1 , *fp2


char ch

fp = fopen(“sample.txt”,”w”)

while( ( ch = getchar( ) ) != EOF

putc( ch , fp)

fclose( fp)

fp1 = fopen(“sample.txt”,”r”)
fp2= fopen(“output.txt”,”w”)

while(1)

ch = fgetc(fp1)

(ch == EOF) break

Putc(ch ,fp2)

fclose(fp1 ,fp2)

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 129


19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

fopen(“Output.txt”,”r”)

while( ( ch = getc(fp)) != EOF

Print ch

fclose(fp)

Stop

PROGRAM :

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp,*fp1,*fp2;
char ch;
clrscr();
printf("*****************Input**************\n");
fp = fopen("Sample.txt", "w");
printf("Enter data to Sample.txt file and Press ctrl + z after entering the details in to a file :\n");
while( (ch = getchar()) != EOF)
{
putc(ch,fp);
}
fclose(fp);
fp1 = fopen("Sample.txt", "r");
fp2 = fopen("Output.txt", "w");
while (1)
{
ch = fgetc(fp1);
if (ch == EOF)
break;
else
putc(ch, fp2);
}
ARIGNAR ANNA COLLEGE - KRISHNAGIRI 130
19UCA02 - PROGRAMMING IN C M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
printf("**************Output*************\n");
printf("File copied Successfully!\n");
fclose(fp1);
fclose(fp2);
fp = fopen("Output.txt", "r");
printf("The Copied contents of Output.txt file are:\n");
while((ch = getc(fp)) != EOF)
{
printf("%c",ch);
}
fclose(fp);
getch();
}

*****************Input**************
Enter data to Sample.txt file and Press ctrl + z after entering the details in to a file :
Arignar Anna College(Arts and Science) – Krishnagiri
ALL IS WELL
ctrl + z

**************Output*************
File copied Successfully!

The Copied contents of Output.txt file are:


Arignar Anna College(Arts and Science) – Krishnagiri
ALL IS WELL

RESULT:

Thus the above c program is created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE - KRISHNAGIRI 131

You might also like