0% found this document useful (0 votes)
10 views190 pages

C Material

Uploaded by

naros31105
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)
10 views190 pages

C Material

Uploaded by

naros31105
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/ 190

‘C’ programming R.V.R. & J.C.

COLLEGE OF ENGINEERING

Computer: - it is an electronic device which accepts data at its input,


process it
by doing some kind of manipulations and produce the output in desired format.
Block diagram of a computer:

 The computer consists of four blocks, they are


(1) Input unit (2) central processing unit (3) output unit (4) auxiliary memory unit
Input unit:-
 Input unit is provided for man to machine communication
 Accepts data in human readable form, convert into machine readable form and
send to CPU.
 A computer may have one or more input devices, depending upon its type, size
and use.
 Key board and mouse is most common input devices
Other ex: - punch card reader, punched paper tape reader, optical scanner,
magnetic ink character reader (MICR), voice data entry terminal (VDE).
Central processing unit (CPU):-
 It consists of 3 units, control unit (CU),arithmetic logic unit(ALU) and memory
unit(MU)
 The main functionality of CPU is
o Control the sequence of operations as per the stored instructions.
o Issue commands to all parts of the computer
o Store data and instructions
o Process the data and send results to output
Control unit (CU):-
 The control unit control and co-ordinate all operations of the CPU, input and
out put devices like
o It gives command to transfer the data from input unit to memory unit
to ALU
o It stores the program in the memory, access instructions one by one
and Issue appropriate commands to other units according to the
instruction.
o It transfers the results from ALU to the memory unit and output unit
o It fetches the required instructions from the main storage and
interprets it by sending appropriate signal to the concerned hardware
device.

1
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

ALU :-
 It carries out all arithmetic operations like addition, subtraction,
multiplication and division.
 It also performs all logical operations.
OUTPUT DEVICES:
 Display screen/Visual display unit/Monitor
- Monochrome
- Colored

 Printers ---- (1) Impact


(2) Non Impact – ex. Inkjet printers

Character Printers ---- (1) Dot Matrix


(2) Daily wheel printer
Line Printers
Page/ Laser printer
 Plotters --- Are used to produce output containing graphics/ diagrams.
MEMORY:-
(!) Main Memory (2) Secondary Storage Devices
 RAM - Magnetic Tapes
 ROM - Magnetic Disks
 PROM,EPROM,EEPROM - Floppy Disk
- Hard Disk

4 Binary digit –1 bit Disk Drives


4 bits – 1 Nibble 1024 B – 1 KB
8 bits – 1 Byte 1024 KB – 1 MB
16 bits (2 bytes) – 1 Half Word 1024 MB – 1 GB
32 bits(4 bytes) – 1 Full Word
64 bits (8 bytes) – 1 Double Word

MEMORY UNIT:-
 It is used to store programs and data
 It is mainly two types, they are
(1) main memory (or) primary memory/Immediate Access Storage(IAS)
which is part of CPU
(2) Auxiliary Memory/ Secondary Storage, which is External to the CPU.

OUTPUT: - output unit is provide to machine to man communication


 Receives the information from CPU in readable form and present it to the user in a
desired form
 A computer may have one or more output devices depending upon use. The visual
display unit (VDU) and printers are the most commonly used devices.

INPUT DEVICES:-
 Key Board – It is most commonly used input device.
 Mouse – It is used to position the cursor on the screen.
 Track ball – It is a mouse variation, essentially a mouse lying on its back.
 Light Pen – you move the pointer and select items on the display screen by
directly pointing to the objects on the screen with the pen
 Touch Screen

2
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Memory:
 Memory is used to store , programs and data
 It is mainly two types
o Primary/main/Immediate Access Storage(IAS)
o Auxiliary memory/Secondary Storage

Main Memory
 It is also called as primary memory and it is available inside the CPU
 Just entered data and currently using data is available in the memory. It is a fast
memory, made up of large number of cells
 Different types of primary memory is
1) RAM ( Random Access Memory)
All the data entered into the system is directly stored in RAM. The users have direct
access to their part of memory i.e. the user can read and write into this memory

- Hence this memory is also known as Read/Write memory


- the contents of this memory is not permanent because once the system is
switched off (or) Power goes the contents are erased. Hence it is volatile memory.

2) Rom(Read Only Memory)


In this part of memory some instructions are permanently loaded during the
manufacturing of the computer
- These instructions are globally used by the user
- No changes can be done in this memory

3) PROM( Programmable Read Only Memory)


In this part of the memory the user can put the data according to this specification
using a special device known as prom-programmer. Once the chip has been
programmed, the recorded information cannot be changed. This is non-volatile
memory

4) EPROM ( Erasable Programmable Read only Memory )


It is similar to PROM, but erasing can take place by exposure of ultra violet light.

5) EEPROM ( Electrically Erasable Programmable Read Only Memory)


EEPROM can be easily reprogrammed by the application of small voltage

Secondary Storage:
It is also called as External Storage Devices
 The main purpose of the external storage is retain data and programs for further
use
 If information is stored in an external storage medium then the operator can
retrieve it as and when required, thus avoid repeat typing.
 It is now volatile memory ( permanent)
 The popular external storage devices are
(1) Magnetic tapes.
(2) Magnetic disks.

Magnetic tapes

3
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

It provides serial access. Therefore you have to read all the previous records to
reach a particular record.
 information can be erased by recording new information in its place
 the tape is ferromagnetic coating on a plastic base and is similar to the tape used
in tape recorder

Magnetic disks

It allows direct access but can also be used in serial mode if required
 Each disk consists of a number of invisible concentric circles called tracks. each
track further divided into sectors
Magnetic disks are two types

(1) Floppy disk: - this is the most common storage medium used on personal
computers. Information can be recorded or read by inserting it into a disk drive
connected to the computer.
(2) Hard Disk:- it is used for storing large volume of information. These are very fast in
reading and writing and storing than floppy disk.

Disadvantages:- cannot make backup copies, not transportable, expensive when


compared to floppy, can’t removed from drives.

Binary codes: - binary codes are used for i/o operations


 numeric codes
 alphanumeric codes

Numeric codes: - when 0-9 decimal digits were coded in binary using a sequence of 0’s
and 1’s the system is called as a numeric coding system. Ex: BCD

Alphanumeric codes :- when 0-9 decimal digits, A – Z , a – z , + , * , - , / , ^ , < , > , = , : , ; , “ , ‘ ,


[ ], { } , ( ),CTRL,ALT. were given codes in binary using a sequence of 0’s and 1’s then the
coding system is called as Alphanumeric coding system.

 ASCII ( American Standard Code For Information Interchange) 7 – bit range 0-127
 EBCDIC (Extended Binary Coded Decimal Interchange) 8-bit range 0-225
 UNICODE defines a fully international characters set that can represent all of the
characters in all human languages
Generally Unicode characters are represented by escape sequences. It is 16-bit
I.e. 2 bytes and it ranges from 0 to 65,536.
High-level languages (HLL) :-
A Set of languages developed which are very close to our native languages, such
are called as HLL. These are designed that to provided high-level control structures, i/o
facilities, hardware independent and soon.
Ex:- Basic , Cobal , Fortran, Pascal.
Advantages:-
(1) easy to learn and easy to understand than machine or assembly language
(2) less time to write
(3) Easy to maintain.
(4) It is better to documentation.
Hardware: - it is a term used to represent the physical and tangible components of the

4
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

computer itself. I.e. those components can be seen.


Ex: - Input, Output, Memory Devices, CPU etc.

Software: - The set of instructions is called as a program. These set of programs are
called Software.
 The hardware can’t function without software and software is created by people
 Types of software
(1) System Software
(2) Application Software

Hence both software are necessary for the computers

System Software: - System Software includes all routines that inside the computer
memory and helps the user to write or execute application programs. This facilities the
communication between user and computer
Ex: - Assembler, Compiler, Interpreter, Editors.

Application Software: - Application programs are written for solving a specific problem.
Ex: - Word Processing, billing etc.

Translators: - Translators are software that accepts one language as input and convert it
into another language. the input for any translator is called source language (code) and
output of any translator is called as object language (code).

Compiler: - It is s/w, which accepts the High-level language program as input and
produces the machine code as output.

Assembler: - it is software which accepts the assembly language as i/p and produce
machine code as o/p.

Operating system: - it is system software, which controls the execution of computer


programs and which may provide scheduling, debugging, I/O control, accounting,
compilation storage management, data management and related services.

Operating System functions:-

(1) Memory management. (2).CPU management. (3).Device management.


(4).I/O device management. (5) File management. (6).User Interface.
It provides an interface between hardware and the user programs. It is the first program
run on computer when the computer boots up.
Algorithm: - it is a finite set of instructions that represent the step by step logical

5
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

procedures for solving a problem

Properties of Algorithms:-
(1) input:- zero or more inputs
(2) output – at least one quantity is produced
(3) Definiteness – each instruction is clean and unambiguous.
(4) Finiteness – the algorithm should terminate after a finite number of steps. It
should not enter into infinite loop.
(5) Effectiveness: - each operation must be simple and should complete in a finite
time.
Algorithm can be written in English like sentences. Algorithm written in English like
language is called pseudo code.

(1) Write an algorithm for finding average of given 3 numbers?


(A) step -1 : Read values
Read A,B and C
Step -2: Compute
Sum = A + B + C.
Avg = Sum/3.
Step -3: Display O/P.
Print Avg.
Step – 4: Stop.

(2) Write an algorithm for finding sum of given ‘n’ numbers.


(A) step -1 : Read values
Read N.
Step -2: Initialization.
Count=1; Sum = 0;
Step -3: Perform the Loop
Repeat through step -4 while count <=n
Step – 4: Read and Compute
Read x
Sum=Sum+x;
Count=Count+1;
Step -5: Display O/P.
Print Sum.
Step – 6: Stop.
(3) Write an algorithm for factorial of a given number.
(A) Step -1: Read values
Read N.
Step -2: Initialization.
Count=1; Fact = 1;
Step -3: Perform the Loop
Repeat through step -4 while count <=n
Step – 4: Compute
Fact = Fact * Count
Count=Count+1;
Step -5: Display O/P.
Print Fact.
Step – 6: Stop.
(4) Write an algorithm for finding the reverse of a given number

6
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

(A) Step -1: Read values


Read N.
Step -2: Initialization.
Rev = 0;
Step -3: Perform the Loop
Repeat through step -4 while n>0.
Step – 4: Compute
Rev = Rev * 10 + N mod 10
N = N /10;
Step -5: Display O/P.
Print Rev.
Step – 6: Stop.

Flowchart:-
A Flowchart is a practical representation of an algorithm that uses boxes of
different shapes to denote different types of instructions.

 A flowchart shows the flow of operations in pictorial form, any error in the logic of the
problem can be detected very easily.
Flowchart symbols:-
A few symbols are needed to indicate the necessary operations in a flowchart. These
symbols have been standardized by the ANSI(American National Standard Institute).

1) Terminal:- The terminal (oval) symbol as the name implies is used to indicate the
beginning <START>, ending <STOP> and pause <HALT> in the program logic flow.

It is the first and last symbol in the program logic.

2) Input/Output:- The input/output(parallelogram) symbol is used to denote any


function of an Input/output device in the program.

3) Processing:- A processing symbol (Rectangle) is used in a flowchart to represent


arithmetic and data movement instructions.

4) Flow lines:- Flow lines with arrow Heads are used to indicate the flow operations i.e.
the exact sequence in which the instructions are to be executed.

5) Decision :- The decision <Diamond> symbol is used in a Flowchart to indicate a


point at which a decision has to be made and a branch to one of two or more

7
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

alternate points is possible.

6) Connectors: - if a flowchart becomes very long the flow lines start crises crossing
at many places that cause confusion and reduce understandability of the flowchart.

7) Predefined Process:- the predefined process(Double sided rectangle) symbol is


used in flowcharts to indicate modules or subroutines are specified.

8) Annotation: - The annotation (Bracket with broken line) symbol is used in


flowcharts to indicate the descriptive comments or explanation of the instruction.

----------------

Program Development Steps:-


!) Understand the problem
2) Examine the data
3) Plan the O/P.
4) Designing the solution.
5) Selecting test data.
6) The actual coding.
7) Testing.

In 1960, FORTRAN – Scientific Applications.


COBOL – Commercial
In 1963 – CPL
1967 – BCPL
1970 – B
1972 – C – by Dennis Ritchie at AT&T Bell Telephone Laboratories.

History & Evolution of ‘c’:


 ‘c’ was developed in the year 1972 by Dennis Ritchie at bell telephone laboratories

8
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

inc.
 ‘c’ is a middle level language, because it combines the best features of high-level
languages with the control and flexibility of assembly language.
 ‘c’ is a general purpose structured programming language that has much in
common with the best of the HLL
Features and Applications of ‘c’ language:-
 c is general purpose structured programming language
 c is powerful efficient, compact and flexible.
 C is highly portable
 C is a robust language whose rich set of built in functions and operators can be
used to write any program.
 C is well suited for writing system software as well as application programming.
 C has the ability to extend itself. We can continuously add our own functions to the
existing ‘c’ library functions.
 ‘c’ programs can be run on any of the different computer with little or no alteration.
 C is widely available commercial ‘c’ compilers are available on most personal
computers, mini and mainframes.
 C language allows to a memory location with the help of printer which holds the
address of the memory location.
 C language allows dynamic memory allocation of memory i.e. a program can
request the OS to allocate/release memory.
 C language allows manipulations of data at the lowest level i.e. bit level
manipulations.
 C is a case-sensitive language.

Basic Structure of ‘c’ program

Documentation Section // optional

Link Section // optional

Definition Section // optional

Global Section // optional

main() function Section //must


{
Declaration part
Declaration part
}

Sub Program Section //optional

Function1
Function 2
o A ‘c’ Function 3 program is
a group of building

9
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

blocks called functions.


o A function is a subroutine that may include one or more statements designed to
perform a specific task.
o To write a ‘c’ program, we first create functions and then put them together.
o Any ‘c’ program may contain one or more sections as given below
o The documentation section consists of comment lines giving the name of the
program, the author and other details.
o The comments beginning with two characters /* and ending with the characters
*/.
o No space can be included between these pair of characters, any characters may
include in either upper case or lower case.
o The link section provides to the compiler to link functions from system library
Ex: - stdio.h, math.h
o The definition section can defines all symbolic constants.
o There are some variables that are used one or more functions, such variables are
called global variables and are declared in the global declaration section i.e. out
side of all the functions.
o Every ‘c’ program must have one main() function section
o This main() section can have two parts
(1) Declaration part
(2) Execution part.
o The Declaration part Declare all the variables that are used in the executable part.
o There is at least one statement in the executable part.
o These two parts can appear between opening and closing braces.
o The program execution begins at the opening braces and ends at the closing
braces.
o The closing brace is the logical end of the program.
o All the declaration and Executable statements ends with a semicolon.

 The sub program section contains user defined functions that are called in the
main() function.

o User defined functions are generally placed immediately after the main
function.
My First “c” program:

1. /* My First c Program */
2. main()
3. {
4. /* prints the string */
5. printf(“welcome to c world \n”);
6. }

 The first and fourth lines are commented lines. These are used in a program to
enhance its readability and understanding.
 Comment lines are not executable statements and anything between /* and */
ignored by the compiler.
 These comment lines can be inserted whenever we want.
 The second line indicates the system that the name of the program in main() and
the execution begins at this line.

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

 The main() is a special function used by ‘c’ to tell the computer where the
program starts.
 Every program must have exactly one main function.
 If we have more than one main() function the compiler cannot know where the
program begins.
 The empty pair of parenthesis immediately following main indicates that the
function has no arguments.
 The opening brace ‘{‘ in the third line marks the beginning of the function main
and the closing braces ‘}’ is the last line indicates the end of the function.
 The statements between these two braces are the function of the body. Here the
function body consist of 2 statements one is comment line and another is printf
line is an executable statement.
 The printf function to be printed out every thing which appears in between
quotation marks, here the o/p will be “ welcome to c world”.
Executing a ‘c’ program under MS-DOS system:
C program execution involves the following series of steps.
(1) Creating the program: - the text of a program is called the source code, is a
sequence of statements to be executed by the machine. This source code is usually
stored in files with the extension .c.
(2) compiling and Linking of the program :- before a program is made to run, it must
be translated by the compiler to give .OBJ files and then linked by the linker to give
.EXE file
3) Executing the program: - The extension of executable codes is .EXE. A ‘c’ program
with an extension .EXE can be run in DOS prompt mode.

‘C’ tokens:
 The smallest individual units in a program are called Tokens. The ‘c’ tokens are
classified as (1) key words (2) Identifiers (3) constants (4) operators (5) Strings.

Character Set:- The characters that can be used to form words, numbers, expressions ,
data types, constants, variables and key words.

 The characters in ‘c’ are grouped into 4 categories.


(1) Alphabets  A,B,C,……….X,Y,Z and a,b,c,………..x,y,z.
(2) Digits  0,1,2,3,4,5,6,7,8,9.
(3) Special characters  ~ ` ! @ # $ % ^ & * ( ) _ - + = { } [ ] | \ : ;
“ ‘ < > , . ? /
(4) White spaces  blank space, horizontal tab, vertical tab, carriage return,
new line, form feed.

Keywords and Identifiers:


In ‘c’ every word is classified into either keyword or an identifier. All keywords have fixed
meaning and these meanings cannot be changed.
Keywords serve as a basic building block for program statements. All the
keywords must be written in lower case.
Ex::- auto, double, int, struct, long, extern, float, if, else, goto, default, do, for, while, short.
 identifiers refers to the names of the variables, functions and arrays. These are user
defined names.
Rules for identifiers:
1) Identifiers can consist of letters and digits must begin with an alphabet or
underscore. Should not contain with space.

11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

2) Both uppercase and lowercase are permitted although an uppercase is not


equivalent to the corresponding lowercase letters.
3) It cannot be a keyword.
4) An identifier can be any length while most compilers of ‘c’ languages recognize
only the first eight characters.
Constants and Variables:
The Alphabets, numbers and special symbols when properly combined to form
constants and variables.

Constants:- constants are fixed values that do not change during the extension of a
program.
Ex: The equation 5x + 2y = 45.
Here 5,2,45 cannot change, these are called constants. Where as quantities x and
y can vary or change hence these are called variables.

Constant classification:
Real constants:
 real constants are constants which are having decimal points,
 real constants can be represented in 2 forms,
(1) Fractional. (2) Exponential.

Fractional form:
 Rules to be followed to write real constants in fractional form.
It is same as for integer constant expect
 Fractional form should have at least one decimal point.
 It ranges from -3.4 e 38 to 3.4 e 38.

Valid Invalid
-3.6 -3.6*7
+6.99 -6. 7
Exponential form:
A real constant in exponential form is represented in 2 parts
(1) Mantissa part (2) Exponent part.
Rules: 1) The mantissa & exponent part is separated by e.
2) The mantissa part can be +ve or –ve.
3) Its default sign is +ve.
4) The exponent part must contain at least one digit.
5) The exponent can be either +ve or _ve.
6) Special symbols, blank space etc are not allowed.

Range: -3.4 e 38 to 3.4 e 38.

Valid invalid
5.5 e 3 1.1*2
0.01 e 25 1e2

Character constant:-
These are combination of characters, digits, special symbols etc.,

12
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Single character constants :


it is either a character or digit or special symbol enclosed with single quote i.e. ‘ ‘
 The maximum length of a Single character constant is 1.
 The range is -128 to 127.

Valid invalid
‘a’ “abc”
‘1’ ‘a”
‘+` ‘12”

String constants/ multiple character constants:


A string constant is a sequence of characters contain either characters (or) special
symbols (or) digits enclosed with in double quotes i.e. “ “
 The maximum length of a string constant is the no.of characters present in it.

Valid invalid
“abc” ‘xyz”
”a123” ‘1’
“1/56”
Difference A single character in c is having associated ASCII value but string constant
is not having ASCII value.
ASCII  American Standard Code for Information Interchange.

Numeric constants: These are classified into


1) Integer constants.
2) Real constants.
Integer constant: An integer constant is to be a sequence of digits.
Rules for constructing integer constants:
1) An integer constant must have at least one digit.
2) It must not have a decimal point.
3) It could be either +ve or –ve.
4) If no sign precedes an integer constant it is assumed to be +ve.
5) No commas, blank spaces are allowed.
6) The allowable range of integer constants is -32768 to 32767.
7) Integer constants may be specified in decimal, octal or hexadecimal notation.
A Decimal Integer constant: - It consists of a sequence of one or more decimal digits 0
through 9 preceded by an optional sign, the first digit of the sequence cannot be 0 inless
the decimal integer constant is 0.
Ex: 0, 276, 3412, 31467, -7123.

An Octal Integer constant:- It consists of the digit 0 followed by a sequence of one or


more octal digits 0 through 7.
Ex: 012, 07134, 07777.

An Hexadecimal Integer constant:- It consists of the digit 0, followed by a sequence of


the letter x or X, followed by a sequence of one or more Hexadecimal digits 0 through 9
or letter a thru f or A thru F.
Ex: 0XI1F, 0XABC, 0X9A2F, 0XFFFF.
Real constant : A real constant are sequence of digits with a decimal point.
Rules for constructing a real constant:
1) A Real constant must have at least one digit.

13
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

2) It must have a decimal point.


3) It cold be either +ve or –ve.
4) No commas, blank spaces are not allowed.
Ex: 1.0, 1. ,0.712, 34.576, -7.123

 In exponential form of representation the real value will represents in two parts. The
part appearing before ‘e’ is called mantissa, where as the part followed is called
exponent.
Integer
(coef) e ( Integer) = (coef) X 10

Variable: - A variable is a data name which can be used to store a data and a variable
may take different values at different times, during execution.
Rules:
1) A variable name is any combination of 1 to 8 alphabet digits or underscore.
2) The first character in the variable name must be an alphabet.
3) No commas, blank spaces are not allowed.
4) No special symbol other than under score is used to form a variable.
Ex: Basic_pay, Net_sal, month_sal

Declaration of Variables:

Keyword Data type Variable name


Integer int int a;
Floating float float b;
Characters char char c; char c[10];

Syntax: <Data_type> <var1> <var2> ……….<varn>;


Ex: int n,count;
float price,sal;
char name;
Scope of variables:- Scope of variables implies to the availability with in a program.

 Variables have two types.


(1) Local (2) Global.

 A variable with a global scope is accessible to all statements in a program but the one
with local scope is restricted to be accessed by only certain selected statements in the
program, in which it is defined.

 Global variable are declared outside all functions where as local variables are defined
inside a function.

Initialization & Assigning values to variables.

Values can be assigned to variables by using the assignment operator. An assignment


statement implies that the value of the variable on the left of the equal sign is equal to
the value of the quantity of the right.
Syntax:- Variable name = constant;
Ex: int a=10;
‘c’ permits multiple assignment in one line like
int a=10,b=34,c=23;

14
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

x=y=z=45;
a=b=c=temp;

Data type size Format specifies


Int 2 bytes %d
float 4 bytes %f
char 1 byte %c (or) %s

printf():- (output function)

 printf function is used to display output values on the screen.


Syntax: printf(“format specifiers”,<arg_list>);
Ex 1) Write a program to print the statement “Sun rises in the east.”
main() main()
{ {
printf(“Sun rises in the east.”); (or) printf(“Sun”)
} printf(“rises”);
OUTPUT: printf(“in the east.”);
Sun rises in the east.
Ex 2) Write a program to print “ “sun” rises in the ‘east’ ”.
main()
{
printf(“\”sun\” rises in the \’east\’”);
}
OUTPUT:
“sun” rises in the ‘east’.
Ex 3) write a program to print the following format
Country capital
India Newdelhi
England London
Japan Tokyo
main()
{
printf(“Country \t Capital\n”);
printf(“-----------\t ---------\n”);
printf(“India \t Newdelhi\n”);
printf(“England \t London\n”);
printf(“Japan \t Tokyo\n”);
}
 conversion of algebric expression into ‘c’ expression.
Al exp c exp
a+b a+b
a-b a-b
2
a a*a
2
(a+b) (a+b)(a+b)
2 2
x +y /x+y (x*x)+(y*y)/(x+y)
3 2 2 3
x + y /(x-y) z (x*x*x)+(y*y)/((x-y)*(x-y)*z*z*z).

ex 4) Write a program to print 10+20=30


10-20=-10
10*20=200.

15
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

main()
{
printf("%d+%d=%d\n",10,20,10+20);
printf("%d-%d=%d\n",10,20,10-20);
printf("%d*%d=%d\n",10,20,10*20);
}
OUTPUT:
10+20=30
10-20=-10
10*20=200
ex 5) Write a program to print following format
There are 365 days in a year
3.14 is the pi value
+ is an operator
good morning.
main()
{
printf(“There are %d days in a year\n,365”);
printf(“%f is the pi value\n”,3.14);
printf(“ %c is an operator”,+);
printf(“%s”,good morning);
` }
Scanf() function:
 scanf() is used to read values from the key board.
Syntax: scanf(“format specifiers”,&arg1,&arg2,……&argn);
(or)
Syntax: scanf(“format specifiers”,&var1,&var2,……&varn);
Ex 1) main()
{
int a=10;
float b=3.14;
char c= ‘+’;
printf(“a=%d\n b=%f\n c=%c”,a,b,c);
}
 Write a program to read integer, float, character values from keyboard and print them.
main()
{
int a;
float b;
char c;
printf("enter the integer value\n");
scanf("%d",&a);
printf("enter the float value\n");
scanf("%f",&b);
printf("enter the character value\n");
scanf(" %c",&c);
printf("a=%d b=%f c=%c",a,b,c);
}
OUTPUT:
enter the integer value
9

16
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

enter the float value


3.56
enter the character value
S
a=9 b=3.560000 c=S
ex 3) main()
{
int a;
float b;
char c;
printf(“enter int,float,char:\n”);
scanf(“%d %f %c”,&a,&b,&c);
printf(“a=%d b=%f c=%c”,a,b,c);
}
Escape sequences:-
It is always begin with a backward slash and is followed one or more special characters.
 It is a name given to a back slash constant.
 It is a combination of back slash with other character.
 It is treated as a single character through it is having 2 characters.
Character Escape Sequence ASCII Value
Bell (alert) \a 007
Back space \b 008
Horizontal tab \t 009
Vertical tab \v 011
New line (linefeed) \n 010
Form feed \f 012
Carriage return \r 013
Quotation mark (“) \” 034
Apostrophe (‘) \’ 039
Question mark (?) \? 063
Backslash (\) \\ 092
Null \0 000

Data Types:-
 Each data type has predetermined memory requirement and an associated range
of values.
 Each programming language has its own data types.
ANSIC Supports 4 types of data types
1) Primary (Fundamental) Data Type.
2) User – defined Data Type.
3) Derived Data Types.
4) Empty Data Set.
 All ‘c’ compiler support 4 Fundamental data types, namely Integer (Int),
Character (char), Floating Point (float) and Double-precision floating point (double).

Integer: - ‘c’ provides three different types of integers. They are int, short and longint.
The difference between these 3 integers is the no. of bytes to occupy the range of values.

17
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Type Bytes required Range


Short int 2 -32768 to 32767(-2 15 to 2 15 -1).
Int 2 -32768 to 32767(-2 15 to 2 15 -1).
Long int 4 -2147483848 to 2147483847(-2 31 to 2 31 -1)
Unsigned short 2 0 to 65535( 0 t0 2 16 -1).
Unsigned int 2 0 to 65535( 0 t0 2 16 -1).
Unsigned long int 4 0 to 4294967295(0 to 2 32-1).

Float: - like integers floats are divided into 3 types. They are float, double and
Long double. The differences between these 3 floats are the no of bytes to occupy and
the range of values.

Type Description Size Range


Float Single precision 4 3.4e -38 to 3.4e 38
Double Double precision 8 1.7e-308 to 1.7e308
Long double Extended precision 10 3.4e-4932 to 3.4e4932

Characters:- A char is a data type which can store an element of machines character set
and will occupies 1 byte. It is two types, they are signed char and unsigned char.
The differences between these two types are the range of values.

Type Size Range


Signed Char 1 -128 to 127
Unsigned char 1 0 to 255

User defined data types:- c supports a feature known as “type definition” that allows
users to define an identifier that would represents an existing data type.

Syntax:typedef type identifier;


Where type refers to an existing data type and identifier refers to the “new “name given
to the data type.
Ex: typedef int units;
typedef float marks;
here units refers for int datatype and marks refers for float datatype.

Units batch1, batch2;


Marks sub1,sub2;
The disadvantage of typedef is that we can create meaningful datatype names for
increasing the readability of the program.

enumerated data type:-

enum identifier { value1, value2,……………valuen};

We can declare variables to their as follows:


enum identifier v1,v2,v3,………..vn;

the enumerated variables v1,v2,……vn can only have one of the values
value1,value2,……..valuen.

The assignments of the following types are valid

18
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

v1= value3; v3=value1;

ex: enum day{Monday,Tuesday,………Sunday};


enum day week_st,week_end;
week_st=Monday;
week_end=Friday;

The definition and declaration of enumerated variables can be combined in one


statement
Ex: enum day{Monday,….Sunday}week_st,week_end;

1) Write a program to calculate area of a circle.


A) #include<stdio.h>
main()
{
int r;
float area,pi=3.14;
printf(“enter the radius \n”);
scanf(“%d”,&r);
area=pi*r*r;
printf(“area=%f”,area);
}

2) Write a program to calculate area of a triangle.


A) #include<stdio.h>
main()
{
int b,h;
float area;
printf(“enter the breadth and height of the triangle \n”);
scanf(“%d %d”,,&b,&h);
area=(b*h)/2;
printf(“area=%f”,area);
}

3) Write a program to calculate area of a rectangle.


A) #include<stdio.h>
main()
{
int l,b;
float area;
printf(“enter the length and breadth of the rectangle \n”);
scanf(“%d %d”,&l,&b);
area=l*b;
printf(“area=%f”,area);
}
4) Write a program to calculate area of a square.
A) #include<stdio.h>
main()
{

19
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

int a,area;
printf(“enter the side of the square \n”);
scanf(“%d “,&a);
area=a*a;
printf(“area=%d”,area);
}

Type Qualifiers: - Short, long, sign or unsigned identifiers may precede some of the
scalar data types to specify the number of bits used for representing the respective type
of data in memory. They are known as qualifiers or modifiers. Suppose 16 bits used to
represent an integer in a system, then the most significant bit is used as sign bit and
other 15 bits are used for representing the magnitude. In the case of signed int as shown
below.

(a)
15 14…………………1 0
sign
bit MAG
0-14 bits

Signed int representation.

(b)

magnitude
15-0.

In the case of unsigned bit all the 16 bits are used for the magnitude representation.

The following table shows the qualifiers and data type representations.

Data Type Qualifier that precede Resulting data type

Int Long, short, unsigned, signed, Long int, short int,


Unsigned long, unsigned short Unsigned int, unsigned
Signed long, signed short. short int, signed long int,
Signed short int.

Char Signed, unsigned Signed char,


Unsigned char.

Double Long Long.

Types of operators:

In ‘c’ operators can be classified into various categories based on their utility and action.
A list of operators types is given below

20
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

 Arithmetic operators.
 Relational operators.
 Logical operators.
 Assignment operators.
 Increment and Decrement operators.
 Conditional operators.
 Bitwise operators.
 Comma operators.

Arithmetic operators : it can perform arithmetic operations and can be classified into
unary and binary arithmetic operators. It can operate on any built-in data type.

A list of arithmetic operators and their meanings are given bellow:


Operator meaning

+ Addition (or) unary plus.


- Subtraction (or) unary minus.
* Multiplication.
/ Division.
% Modulo Division (Remainder after division).
Note: - c has no operator for exponentiation. A function pow(x,y) exists in math.h which
y
returns x
 The unary – operator has the effect of multiplying operand by -1.
Integer arithmetic: - when 2 operands such as x and y are declared as integers, an
arithmetic operation performed on these integers is called Integer arithmetic. It always
yields an integer value.
Ex: (1) Int x=16, y=5; Ex: 6/8 = 0
X+y = 21 -6/-8 = 0
x-y = 11 -6/8 = 0 (or) -1
x*y = 80
x/y = 1

(2) #include<stdio.h>
main()
{
int month,days;
printf(“enter the number of days \n”);
scanf(“%d”,&days);
months=days/30;
days=days%30;
printf(“ months is %d days are %d”,months,days);
}

ex: 265 --- months is 8days are 25.


364 --- months is 12 days are 4.
45 --- months is 1 days are 15.
Floating Point arithmetic: - (FPA) Floating point arithmetic involves operands of real
type in decimal or exponential notation. The remainder operator % is not applicable to
FPA.
Ex : - float a=14.0, b= 4.0;

21
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

P = a/b = 3.5000
Q= b/a = 0.285714
R = a+b = 18.0000

Mixed Mode arithmetic:- in this mode, if either of the operands is real, the resultant
value is always a real value.
Ex: 35/5.0 = 7.0
Here 5.0 is a double constant, 35 is converted to a double and result is also a double.

Relational Operators:-
 Arithmetic operators are used to evaluate arithmetic expressions, relational operators
are used to compare arithmetic, logic and character expressions.

 Compressions can be done with the help of relational operators.

 Each of these operators compares their left hand side with their right hand side.

 The whole expression involving the relational operator then evaluates to an integer.
It evaluates 0 if the condition is false, and 1 if it is true.
Sequence of operators and operands evaluated to a single value.
Operator Meaning
< Lessthan
<= Lessthan (or) Equal to
> Greaterthan
>= Greaterthan(or)Equal to
== Equal to
!= Not Equal to
Ex:- #include<stdio.h>
main()
{
int I,j;
printf(“enter two values \n”);
scanf(“%d %d”,&I,&j);
if(i==j)
pritf(“both are equal \n”);
else
printf(“both are not equal \n);
}

Logical operators:
 it is used to compare or evaluate logical and relational expressions. There are 3
logical operators in c.

Operator meaning
&& logical AND.
|| logical OR.
! logical NOT.
 An expression involving && and || is some times called compound expression, since
the expression involves two other expressions, i.e. each of these operators (&& and ||)
take two expressions, one to the left and another to right.

22
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Logical AND :- ex a>b && x==10

Logical OR :- ex a<m || a<n

Logical NOT:- the ! Operator takes single expression and evaluates to true if the
expression is false, and evaluates to false if the expression is true.

Ex: !(x>=y)  x<y

The ! Operator is convict to use when you want to test whether the value of a variable is
zero.

If(!i)
Printf(“the value of I is zero \n);

 !i – this is true only when if the value of I is 0.

Increment and decrement operators:-

 The increment and decrement operators are very useful in ‘c’ language. These are
extensively used in for and while loops.
The syntax is ++<variable> --<variable>
<variable>++ <variable>--

 The operator ++ adds 1 to the operand and – subtracts 1 from the operand. These
operands manifest in two forms i.e. prefix and postfix.
Ex: the ++ operator can be used in two ways.
++m and m++ (these two are different operations).

 The first expression immediately increments the value ‘m’ by 1.


main()
{
Int n,m=1;
n=++m;
printf(“ prefix operation :n=%d”,m=%d\n”,n,m);
}
prefix oeration: n=2,m=2.

 The expression ++m will increment first, and then this value is assigned to n, resulting
in having the same value.
 main()
{
Int n,m=1;
n=m++;
printf(“ postfix operation :n=%d”,m=%d\n”,n,m);
}
postfix operation n=1,m=2
 The expression m++ will first evaluate the value of m, resulting is 1 being assigned to
n and then the value of m being incremented to 2.

Bitwise operators:

23
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

 A bitwise operator operates on each bit of data. These operators are used for testing,
complementing or shifting bits to the right or left.
 Usually these operators are not useful in cases of float and double variables.

Operator Meaning
& Bitwise AND.
| Bitwise OR.
^ Bitwise XOR.
<< Left Shift (Shift Left).
>> Shift Right.
~ compliment.
Bitwise AND: - c = a & b;
Each bit in ‘c’ will be 1 only if the corresponding bits in both a and b are 1.
a = 1101 13
b = 0111 7
------------
a&b= 0101
------------
Bitwise OR: - c = a | b;
‘a’ bit in c will be 1 whenever at least one of the corresponding bits in a or b is 1

a = 1101 13
b = 0111 7
------------
a/b= 1111
------------
Bitwise XOR: - c = a ^ b;

a = 1101 13
b = 0111 7
------------
a^b= 1010
------------

Left Shift Operator: - The left-bit Shift operator, << is a binary operator.
C= a<<3 a = 1101 1101
1110 11010
0111 110100
1011 0110,1000

Right Shift Operator:- The Right Shift operator, >> is a binary operator.

C=a>>2 a = 1101 1101


01101
0011,01

Shifting negative numbers :

a= -3 0011

24
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

1100
------
1
------
1101
------
’s
(1) To find 2 complement
 Complement to the given number.
 And add 1 to complement number.

Bitwise complement operator:-


This operator is a unary operator. It gives the value got by complementing each bit of the
operand.

Conditional Operator (ternary operator)


The conditional operator consist of two symbols
(1) The question mark(?)
(2) The colon (:)
The syntax for this is

(Condition)?(expression 1):(expression 2)
Larger = i > j ? i : j ;
Here i > j is condition for testing
? mark is conditional operator
i is for expression1.
j is for expression2.

 if condition is true it returns first expression and condition is false it returns second
expression

 This is the only operator in c that takes 3 operands.

1) Write a program to find maximum of two numbers by using conditional operator.


A) #include<stdio.h>
main()
{
int I,j,larger;
printf(“enter two numbers\n”);
scanf(“%d %d”,&I,&j);
lager=I >j ? I : j;
printf(“the larger of given two numbers is %d:”,larger);
}

Special operators:-
Comma operator:- A set of expressions separated by comma is a valid construct in the
‘c’ language.
Ex: int i , j;
Here I and j are declared as integers.

Consider the following statement that makes use of the comma operator.

25
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

i = ( j = 3 , j + 2);
the right hand side consists of two expressions separated by comma. These
expressions are evaluated from left to right.
First the value 3 is assigned to j and then the expression j + 2 is evaluated.
The value of the entire comma-separated expression is the value of the right most
expression. Hence the value assigned to i would be 5.
Ex: c= ( a = 10, b =20 , a + b);
First a =10 , b = 20 and a + b = 30 is assigned to c.

Other Operators:
Sizeof:- The operator sizeof gives the datatype or the variable in terms of bytes occupied
in the memory. The sizeof operator returns the no. of bytes the operand occupies in
memory. The operand may be a variable, a constant or a data type.

Ex: sizeof (int); -- it returns 2 bytes.

Address of operator:- The address of operator (&) returns the address of the variable.
The operand may be a variable, a constant
m= &n;
here address of n is assigned to m. this m is not an ordinary variable, it is a variable
which holds address of another variable.

Value at address operator:- The value at address operator (*) returns the value stored at
a particular address. The value at address operator is also called indirection operator.
Ex: x = *m;
Here the value at address of m is assigned to x and m is going to hold the address.

TYPE CONVERSION:
The process of converting one data type value into another data type is called Type
conversion. This is two types
(1) Implicit / coercion.
(2) Explicit / Type casting.

Implicit type conversion:- The process of converting one type value into another value
implicitly by the compiler is called implicit type conversion (or) coercion.

Explicit type conversion:- The process of converting one type into another value explicitly
by programmer is called Explicit type conversion (or) type casting.

Type cast operator:- ‘c’ permits mixing of constants and variables of different types in an
expression, but during evaluation, it follows a definite rule of type conversion.

In an expression, if two operands are of different types, then the lower type value is
automatically converted in higher type. This process is implicit type conversion (or)
automatic type conversion (or) type coercion, but in some situations we need to convert
one type value into another explicitly. This process is known as explicit type conversion
(or) type casting.
Syntax: ( type name) expression;
main() main()
{ {
int a; char x;

26
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

a=(int)’a’; x=(char)65;
printf(“ %d”,a); printf(“ %c”,x);
} }

O/P – 97 O/P – A

main()
{
int a=10;float b=3.14;
printf("value of a is %d \n",a);
printf("address of a is %u \n",&a);
printf("value of b is %f \n",b);
printf("address of b is %u \n",&b);
}

OUTPUT :-

value of a is 10
address of a is 3221207028 (Assumption)
value of b is 3.140000
address of b is 3221207024( Assumption).

main()
{
int a=10;float b=3.14;
printf("value of a is %d \n",*(&a));
printf("address of a is %u \n",&a);
printf("value of b is %f \n",*(&b));
printf("address of b is %u \n",&b);
}

OUTPUT:-
value of a is 10
address of a is 3221210948
value of b is 3.140000
address of b is 3221210944

 Assume ‘k to be an integer variable and ‘a to be float variable then the values of k and
a for the following are

k = 2/9 = 0; a = 2/9 = 0.000000


k = 2.0/9 = 0; a = 2.0/9 = 0.2222222
k = 2/9.0 = 0; a = 2/9.0 = 0.2222222
k = 2.0/9.0 = 0; a = 2.0/9.0 = 0.222222
1) Write a program to find maximum of given 3 numbers using conditional operator.
A) #include<stdio.h>
main()

27
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
int a,b,c,max;
printf("enter 3 numbers \n");
scanf("%d %d %d", &a,&b,&c);
max=(a>b)&&(a>c)?a:(b>c)?b:c;
printf("maximum number is %d",max);
}
OUTPUT:
enter 3 numbers
3
7
9
maximum number is 9.

2) Write a program for preincrement and postincrement.


main()
{
int a=10;
printf("a=%d \n",a);
++a;
printf("a=%d\n",a);
a++;
printf("a=%d\n",a);
}

OUTPUT:
a=10
a=11
a=12

3) Write a program for predecrement and postdecrement.


#include<stdio.h>
main()
{
float a=10.9;
printf("a=%f \n",a);
--a;
printf("a=%f\n",a);
a--;
printf("a=%f\n",a);
}

OUTPUT:
a=10.900000
a=9.900000
a=8.900000

4) Write a program for preincrement and postincrement


#include<stdio.h>
main()

28
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
int a=10,b;
b=a++;
printf("a=%d b=%d\n",a,b);
b=++a;
printf("a=%d b=%d\n",a,b);
}

OUTPUT:
a=11 b=10
a=12 b=12

5) Write a program for predecrement and postdecrement.


main()
{
float a=9.9,b;
b=a--;
printf("a=%f b=%f\n",a,b);
b=a++;
printf("a=%f b=%f\n",a,b);
}

OUTPUT:
a=8.900000 b=9.900000
a=9.900000 b=8.900000
6) Write a program for sizeof() operator.
main()
{
int a=10;float b=5.6; char c='*';
printf("size of(a)=%d\n",sizeof(a));
printf("size of(b)=%d\n",sizeof(b));
printf("size of(c)=%d\n",sizeof(c));
}

OUTPUT :
size of(a)=4
size of(b)=4
size of(c)=1

7) Write a program for “<” operator


main()
{
int a=10,b=20;
printf("a<b:%d",a<b);
}
OUTPUT:
a<b:1
 In the above program if a=20 and b=20 then the o/p is a<b:0
8) Write a program for <=

main()

29
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
int a=10,b=20;
printf("a<=b:%d",a<=b);
}

OUTPUT:

a<=b:1

9) Write a program for ==

main()
{
int a=20,b=20;
printf("a==b:%d",a==b);
}
OUTPUT:

a==b:1

10) Write a program for !

main()
{
int a=-10;
printf("a=:%d\n",a);
printf("!a=%d\n",!a);
printf("!!a=%d\n",!!a);
}

OUTPUT:

a=:-10
!a=0
!!a=1

Type conversions in Expressions:


Automatic Type conversion: if the operands are of different types, the lower type is
automatically converted into the higher type before the operation proceeds. And the
result is of the higher type.

Ex: Int i,x;


float f;
double c;

long int l;
x=l/i+i*f–c

Rules that are applied while evaluating expressions:

 All short and char are automatically converted to int, then

30
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

1) If one of the operands is long double, the other will be converted to long double
and result will be long double.
2) else if one of the operands is double, the other will be converted to double and
the result will be double.
3) else if one of the operands is float, the other will be converted to double and the
result will be float.
4) else if one of the operands is unsigned long int, the other will be converted to
double and the result will be unsigned long int.
5) else if one of the operands is long int, and the other is unsigned int then

a) if unsigned int can be converted to long int, the unsigned int operand will be
converted as such and the result will be long int.
b) else both operands will be converted to unsigned long int and the result will be
unsigned long int.
6) else if one of the operands is long int, the other will be converted to double and
the result will be long int.
7) else if one of the operands is unsigned int, the other will be converted to double
and the result will be unsigned int.

example:

x = (int) 7.5  7.5 is converted to integer by truncation.


A = (int) 21.3/(int) 4.5  evaluated as 21/4 and the result would be 5.
B = (double) sum/n  division is done in floating point mode.
Y = (int) a + b  a is converted to integer and then added to b.
Z = (int) (a + b)  the result of a+b is converted to integer.
P = cos((double)x)  converts x to double before using it.

Ex (1): x = (int)( y + 0.5)


Suppose y is 27.6 then first (y + 0.5) will be executed and then the result would
be 28.1.this result stored in x.
i.e. x = (int) (28.1)
x = 28.
Hence the resultant value of x is 28.

Ex (2): when y and p are double and m is int


 y = p + m;
 y = p + (double) m;

Operator precedence and associativity:-


 Each operator in c has a precedence associated with it.
 This precedence is used to determine how an expression involving more than one
operator is evaluated.
 The operators at the higher level of precedence are evaluated first.
 The operators of the same precedence are evaluated either L to R or R to L depending
on the level. This is known as associativity property of an operator.

Precedence level Operator Operation Associativity

31
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

1 () Functional call(or) LR


Parentheses
[] Array subscript LR
. Dot LR
 Arrow LR

2 ! Logical NOT RL


~ One’s compliment RL
- Unary minus RL
++ Increment RL
-- Decrement RL
& Address of RL
* Indirection RL
(data_type) Cast operator RL
sizeof( ) Sizeof special RL
operator RL

3 * Multiplication LR
/ Division LR
% Modulus LR

4 + Addition LR
- Subtraction LR
5 << Left shift LR
>> Right shift LR
6 < Less than LR
> Greater than LR
<= Less than or equal to LR
Grater than or equal to
>= LR

7 == Equal to LR
!= Not equal to LR
8 & Bitwise AND LR
9 ^ Bitwise XOR LR
10 | Bitwise OR LR
11 && Logical AND LR
12 || Logical OR LR
13 ?: Conditional RL
14 = += -= *= /= Simple and compound RL
%= >>= <<= &= assignment
^= |=

15 , Comma LR
Ex: x = 20, y = 5;
If ( x == 10 + 15 && y <10)
If( x == 25 && y<10)

32
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Here y<10 is executed first, then


X==25  false
Y < 10  true
If( false && true )  it returns 0.
Hence the result is 0.

Preprocessor Directives:- Preprocessor directives are instructions given by us to the


compiler and are executed before the process of compilation
(OR)
A c-preprocessor is a program that processes our source program before it is passed to
the compiler.

 Preprocessor commands are also known as preprocessor directives. they begin with
# symbol. Some of the preprocessor directives are
(1) macro expansion.
(2) file inclusion.

Macro Expansion:- Macro Expansion is defined as


# define name text is called macro definition (or) macro.
Herename represents macro template. Andtext represents macro expansion.

 write a program to find min of two numbers if first no is less than the second no.
then print ‘1’ other wise print ‘0’.
A) #include<stdio.h>
#define true 1
#define false 0
main()
{
int a,b;
printf("enter two numbers\n");
scanf("%d %d",&a,&b);
(a<b)?printf("%d",true):printf("%d",false);
}

OUTPUT:
enter two numbers
3
5
1
OUTPUT:
enter two numbers
5
3
0

 #include<stdio.h>
#define AND &&
#define OR ||

33
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

main()
{
int a=10,b=20,c;
c=a>b AND b<=20 OR a!=10;
printf("%d",c);
}

OUTPUT:
0

 #include<stdio.h>
#define P printf
#define S scanf
main()
{
int a;
P("enter a number\n");
S("%d",&a);
P("a=%d",a);
}

OUTPUT:

enter a number
9
a=9.

 #define LINE printf("HELLO GOOD MORNING\n");


main()
{
LINE;
LINE;
}

OUTPUT:
HELLO GOOD MORNING
HELLO GOOD MORNING

 #include<stdio.h>
#define LINE printf("one\n");printf("two\n");printf("three\n");
main()
{
LINE;
}

OUTPUT:
one
two

34
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

three

 #include<stdio.h>
#define LINE {printf("one\n");printf("two\n");printf("three\n");}
main()
{
LINE;
}

OUTPUT:
one
two
three

File Inclusion:
 #include directive is used for file inclusion.
 #include directive causes of one file to be included in another file.

Syntax:#include “filename” (or) #include<filename>

In general we write

#include<stdio.h> or #include”stdio.h”

This statement causes entire contents of the file to be replaced in the program at that
point. In general a file to be included is having .h extension.

Here h — represents header file.

Files to be included in our program are header files, because they contain statements
which when declared replaces their contents at the beginning of our program.

Header files ex:- #include<math.h>


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

 Preprocessor directives can be placed at anywhere in the program, but in general,


they are placed at beginning of the program.

 Write a program to calculate simple interest and compound interest.

35
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

#include<math.h>
main()
{
float p,r,ci,si;
int n,t;
printf("Enter Principle Amount\n");
scanf("%f",&p);
printf("Enter the rate of Interest\n");
scanf("%f",&r);
printf("Enter the number of years\n");
scanf("%d",&n);
printf("Enter the number of times the interest compounded per year\n");
scanf("%d",&t);
si=(p*n*r)/100;
ci=p*pow(1+(r/n),n*t);
//p=principle amount
//r=annual nominal interest rate(as decimal)--r/100
//n=the number of time the interest is compounded per year
//t=the number of years
//ci=amount after time t
//sample data p=1500,r=0.043,n=4,t=6then ci=1938.84
printf("the simple interest is %f\n",si);
printf("The compound Interest is %f\n",ci);
}

OUTPUT:- Enter Principle Amount


1500
Enter the rate of Interest
.043
Enter the number of years
4
Enter the number of times the interest compounded per year
6
the simple interest is 2.580000
The compound Interest is 1938.836792
1) Write a program to convert centigrade to Fahrenheit and vice versa.
main()
{
float c,f;
printf("enter temperature in celcius\n");
scanf("%f",&c);
f=(c*9/5)+32;
printf("eqivalent fahrenheit is %f\n",f);
printf("enter the temperature in fahrenheit\n");
scanf("%f",&f);
c=(f-32)/1.8;
printf("eqivalent celcius is %f\n",c);
}
OUTPUT:
enter temperature in celcius
10

36
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

eqivalent fahrenheit is 50.000000


enter the temperature in fahrenheit
50
eqivalent celcius is 10.000000

2) Write a program to get given character is vowel (or) not.


#include<stdio.h>
main()
{
char ch;
printf("enter a character\n");
scanf(" %c",&ch);
(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')?printf(" %c is vowel",ch):printf("
%c is not a vowel",ch);
}
OUTPUT:
enter a character
a
a is vowel
OUTPUT:
enter a character
f
f is not a vowel.

3) Write a program to check the given character is digit or not


#include<stdio.h>
main()
{
char ch;
printf("enter a charecter\n");
scanf(" %c",&ch);
(ch>=48 &&ch<=57)?printf(" %d is digit",ch):printf(" %d is not a digit",ch);
}
OUTPUT:
enter a charecter
3
51 is digit.

OUTPUT:
enter a charecter
r
114 is not a digit.

4) Write a program to check the given character is in upper case . if it is in upper


case then it convert into lowercase.

main()

37
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
char ch;
printf("enter a charecter\n");
scanf(" %c",&ch);
(ch>=65 &&ch<=90)?printf(" %c is in upper case\n",ch):printf(" %c is not in
upper case\n",ch);
ch=ch+32;
printf("after conversion in lower case ch=%c\n",ch);
}

OUTPUT:
enter a charecter
S
S is in upper case
after conversion in lower case ch=s
OUTPUT:
enter a charecter
k
k is not in upper case
after conversion in lower case ch=ï

5) Write a program to convert upper case letter to lower case.

#include<stdio.h>
main()
{
char ch;
printf("enter a chrecter \n");
scanf(" %c",&ch);
ch=ch+32;
printf("after conversion ch=%c\n",ch);
}
OUTPUT:
enter a chrecter
K
after conversion ch=k

6) Write a program to convert lower case letter to upper case.

main()
{
char ch;
printf("enter a chrecter \n");
scanf(" %c",&ch);
ch=ch-32;
printf("after conversion ch=%c\n",ch);
}

OUTPUT:
enter a chrecter
k

38
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

after conversion ch=K

7. main()
{
Int a=65;
printf(“value of a is =%d”,a);
printf(“corresponding character is a=%c”,ch);
}

OUTPUT:
a=65
A

Input and Output Functions:


Some of the built in function are used to read the input from the key board and display
the output on the screen. The following three types of I/O functions are important for
writing programs in ‘c’.

Character oriented I/O


1) getchar()
2) putcahr()

Formated I/O functions


1) scanf
2) printf

String I/O functions


1) gets()
2) puts()

getchar() function:- (Single character input)

 The function getchar() is used to read a single character from the key board.
 This function returns the integer value of the character in the machines character
code. If the system uses the ASCII character code, then the ASCII value of the character
is returned.
 The general format for using this function is
variable = getchar();

Where the variable may be either int or char data type. The getchar() function does not
take any argument.

Putcahr() function:- (Single character output)

 The putchar() function transmits a single character to a standard output device.


 The character being transmitted will normally be represented as a character-type
variable.
 It must be expressed as an argument to the function, enclosed in parentheses.
following the world putchar.
The general format for using this function is

39
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Putchar(variable);
Where the variable may be represented by an integer constant or a character constant.
Ex: char c;
C=getchar(); putchar(c); putchar(65);

Scanf() function:- (Entering Input data)

Input data can be entered in to the computer from a standard input device by means of
the ‘c’ library function scanf.
This function can be used to enter any combination of numerical values,
single characters and strings. This function returns the no.of data items that have been
entered successfully.
The general format for scanf() function is

Scanf(“control_string”,argument_list);

Where control_string contains the required formatting specifications enclosed with in


double quotes and argument_list contains the address of the memory locations where
the input data is stored.
 The addresses are separated by commas.
 The control_string consist of individual groups of characters with one character
group for each input data item.
 Each charater group must begin with a percent sign(%).
 In its simplest form, a single character group will consist of the percent sign, followed
by a conversion character. This indicates the type of the corresponding data item.
Conversion character meaning
%c Single character
%d integer
%f float
%h short int
%i decimal, hexa decimal,octal
%o octal
%s string
%u unsigned int
%x hexadecimal
%[ ] string, may include white space characters.
 The following points should be kept in mind while using scanf() function.
1) To read the value of a variable belonging to any one of the fundamental data
types, the operator & gives the address of the operator ‘&’. The operator & gives
the address of the variable to which it is applied.
2) The order and the type of conversion specification must match the argument in
the argument_list.

Ex: char ch;


Int a;
float b;
scanf(“%d %f %c”,&a,&b,&ch);
Input & Output functions:
( pic remainng)
Unformatted input functions:-

40
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

getchar():- This function is used to read a single character from the key board. This
function does not requires any arguments. So, it is followed by empty parentheses.

Syntax:- character_ variable = getchar();


The getchar() requires enter key to be passed after inputting the character. The
getchar () echos the given character on the screen.

Ex:- main()
{
char ch;
ch = getchar();
printf(“ %c”,ch);
}

OUTPUT:
a
a.

getch():- This function is used to read a single character from the key board. But it does
not echoes the given character on the screen and also it does not require enter key to
pressed.

Ex: main()
{
char ch;
ch = getch();
printf(“ ch=%c”,ch);
}
OUTPUT
Ch = a

getche():- This function is used to read a single character from standard input device
i.e. keyboard. Like getch() it doesn’t required any enter key to be pressed. Unlike getch()
it echoes the given character on the screen.

Syntax:- Character_ variable = getche();

Ex: main()
{
char ch;
ch = getche();
printf(“ch=%c”,ch);
}
OUTPUT:
ch=a
ch=a

gets():- The gets() is used to read a string of values (or) no. of characters from the
keyboard.

41
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Syntax: gets(string_name);

Here string_name represents previously defined character array.

Ex: Write a program to read name of a person and print it.

#include<stdio.h>
main()
{
char name[20];
printf(“Enter name of a person”);
gets(name);
printf(“name is=%s”,name);
}

output:
Enter the name of a person
Sachin
Name is =sachin

Difference between scanf() and gets():

Scanf() stops reading when it gets a space or when it reads a space, but gets()
reads characters including spaces but it stops reading when its gets a new line
characters. Gets() reads new line character and in the place of new line character it
replaces null character.

Unformatted output function:

Putchar(): The putchar() is used to output or to print a single character on the screen.
Syntax: putchar(character_variable);
Putchar(‘character_constant’);

Ex:
#include<stdio.h>
main()
{
putchar(‘a’);
putchar(‘=’); output: a=0
putchar(‘0’);
}
puts():This function is used to output or to print string of values or group of characters
on the screen.

Syntax: puts(string_name);
Puts(“string_constant”);

Ex:
#include<stdio.h>
main()
{

42
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

char name[20]=”HELLO”; output: HELLO


puts(name);
}

Difference between printf() function and puts() function.


When we are using printf statements, we have to explicitly specify \n with each
statement in order to print output in multiple lines, but when we use puts() there is no
need to specify \n. The puts() after printing a statement places the cursor to the
beginning of the next line.

Formatted input function:


Scanf(): It is used to read values in a given specified format.
Syntax: scanf(“format specifiers”,&arg1,&arg2, &argn);

Format specifiers Datatype


%d int
%u unsigned int
%d or %hd signed short int
%hu unsigned short int
%ld long int
%lu unsigned long int
%f float
%e float value in exponent form
% both fractional form or exponential form
%lf double
%Lf long double
%o octal
%x hexadecimal
%c single character
%s group of characters or string

 #include<stdio.h>
main()
{
int a,b,c;
printf(“Enter 3 numbers:”);
scanf(“%3d%3d%3d”,&a,&b,&c);
printf(“a=%d\n b=%d\n c=%d\n”,a,b,c);
}
output:
123 456 789 12 345 678 1 234 5678
a=123 a=12 a=1
b=456 b=345 b=234
c=789 c=678 c=567

 main()
{
char name[20];

43
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf(“Enter a name:”);
scanf(“%5s”,&name);
printf(“%s”,name);
}
output:
ANILKUMAR
ANILK
ANIL KUMAR
ANIL

scanf() can also be used to restrict a set of values when we are inputting some
characters.

main()
{
char name[20];
scanf(“%[aeiou]”,name);
printf(“%s”,name);
}
output:
aeiou

main()
{
char name[20];
scanf(“%[a-z A-Z 0-9]”,name);
printf(“%s”,name);
}
output :
All combinations will be printing

main()
{
char name[20];
scanf(“%[^aeiou]”,name);
printf(“%s”,name);
}

putch():- This function is used to write a character word.

main()
{
char ch;
printf(“print any key\n”);
scanf(“ %c”,&ch); (or) ch=getchar();
putch(ch);
}

printf:- The printf is used to print value on the screen in the given format.

44
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Syntax:- printf(“format_specifiers”,argument_list);

Data type field  %d


%f
%c
%s
here %f indicates conversion character,
 for integer mode %d is used.
 for real mode %f, %lf,%Lf.
 for character mode %c or %s.

Integer mode output(%nd):- here ‘n’ indicates in how many digits places the given value
to be filled.
main()
{
Int a=123;
Printf(“%5d\n”,a);
Printf(“%4d\n”,a);
Printf(“%3d\n”,a);
Printf(“%2d\n”,a);
Printf(“%d\n”,a);
}

float mode output(%n.df):- here ‘n’ indicates in how many no.of digits to be printed after
the decimal point.
main()
{
Float pi=3.141592;
Printf(“%10.6f”,pi);
Printf(“%10.5f”,pi);
Printf(“%10.4f”,pi);
Printf(“%10.3f”,pi);
}
character mode output(%ns):- here ‘n’ indicates in how many digits places.
main()
{
Char name[10]=”rvrjc”;
Printf(“%8s”,name);
Printf(“%9s”,name);
Printf(“%10s”,name);
}

Statement:- It is an expression (Or) a function call i.e. terminated with a ;

Compound statement:- A compound statement is a collection of statement or group of


statements enclosed between curled braces.

Control Statements or Control Structures:-


1) selection of control structures (or) decision control statements.
2) Iterative control statements (or) repetitive control statements.

45
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Selection control statements:-

These selection control statements are used to execute the statements in the program
depending on a given particular condition.

(1) if (2) if else (3) nested if else (4) else if ladder (5) switch.

If:- This statements is used to execute a single statement or group of statements based
on a condition.

Syntax:- if(expression) (or) if(expression)


Statement; {
Statement 1;
Statement 2;
…………….
…………….
Statement n;
}
if the given expression is true, then the statements in the block are executed and the
control goes to the next statement after the if block.

if the given expression is false, then the statements in the if block are not executed,
control goes to the next statement of the if expression.

Here expression can be any type which evaluates to either true (or) false.

Flow chart for if statement:-

 Write a program to determine whether a given person is eligible to vote or not.

#include<stdio.h>
main()

46
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
int age,
printf(“enter the age of the person\n”);
scanf(“%d”,&age);
if(age>=18)
printf(“ person is eligible to vote\n”);
}

if-else:- This if-else control statement is also known as two way decision control
structure.

Syntax:- if(expression)
{
statement 1;
statement 2;
……………
……………
statement n;
}
else
{
statement 1;
statement 2;
…………….
…………….
statement n;
}

if the given expression is true, then the statements in the if block are executed and the
control goes to the first statement immediately below the else block.

if the given expression is false, then the statements in the if block are not executed, but
the statements in the else block are executed and the control goes to the next statement
after the else block.

Flow chart:-

Nested – if else statement:


When a series of decisions are involved, we may have to use more than one
if-else statements in nested form.

47
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

The general format is

If(expression1)
{
statement1;
statement2;
……………
statement n;

if(expression 2)
{
statement1;
statement2;
……………
statement n;
}
else
{
statement1;
statement2;
……………
statement n;
}
}
else
{
statement1;
statement2;
……………
statement n;
}
}
1) Write a program to find the maximum number from the given three numbers.
A)
main()
{
int a,b,c,max;
printf("enter the values for a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
if(a<b)
{
if(b<c)
max=c;
else
max=b;
}
else
{
if(a<c)
max=c;

48
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

else
max=a;
}
printf("the maximum number of %d %d %d is%d",a,b,c,max);
}
OUTPUT:
enter the values for a,b,c
4
9
5
the maximum number of 4 9 5 is 9.
else-if ladder:- the syntax of else-if ladder is

if(expression)
{
statement 1;
statement 2;
……………
……………
statement n;
}
else if(expression)
{
statement 1;
statement 2;
…………….
…………….
statement n;
}
else if(expression)
{
statement 1;
statement 2;
…………….
…………….
statement n;
}
…………………
…………………
else(expression)
{
statement 1;
statement 2;
…………….
…………….
statement n;
}
 write a program to check whether the given character is in lower case or upper case
or digit or special character.

#include<stdio.h>

49
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

main()
{
int c;
printf("enter the character\n");
c=getchar();
if(c>='a' && c<='z')
printf("the given character is in lower case\n");
else if(c>='A' && c<='Z')
printf("the given character is in upper case\n");
else if(c>='0' && c<='9')
printf(" the given character is digit\n");
else
printf(" the given character is special character\n");
}

OUTPUT:

enter the character


G
the given character is in upper case

enter the character


s
the given character is in lower case

enter the character


9
the given character is digit

enter the character


(
the given character is special character

 Write a program to read 3 subject marks of a student and find his average and print
the class he got according to his average.
Average class
Above 70 distinction..
60-69 First.
50-59 second.
35-49 third.
<=34 fail.

main()
{
int m1,m2,m3;
float avg;
printf("enter the 3 subjects marks of a student\n");
scanf("%d %d %d",&m1,&m2,&m3);
avg=(m1+m2+m3)/3.0;
printf("the average is %f\n",avg);
if(avg>=70)

50
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf("the student got distinction\n");


else if(avg>=60 && avg<=69)
printf(" the student got first class\n");
else if(avg>=50 && avg<=59)
printf("the student got second class\n");
else if(avg>=35 && avg<=49)
printf("the student got third class\n");
else
printf("the student is failed\n");
}

OUTPUT:

enter the 3 subjects marks of a student


88
89
90
the average is 89.000000
the student got distinction

enter the 3 subjects marks of a student


67
68
69
the average is 68.000000
the student got first class

enter the 3 subjects marks of a student


56
57
58
the average is 57.000000
the student got second class

enter the 3 subjects marks of a student


45
46
47
the average is 46.000000
the student got third class

enter the 3 subjects marks of a student


45
34
23
the average is 34.000000
the student is failed

 Write a program to find electricity bill based on

51
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

SWITCH STATEMENT:
This switch control structure is used for making multi-way decision or multipath
decision.

Syntax:
switch(expression)
{
case value1: statement 1;
statement 2;
.
.
.
statement n;
break;

case value2: statement 1;


statement 2;
.
.
statement n;
break;

.
.

case value n: statement 1;


statement 2;
.
.
.
statement n;
break;
default: statement 1;
statement 2;
.
.
.
statement n;
break;  optional.
}

1. The switch control structure is having more readability than using if control
structures.

2. The switch control structure is used mainly in menu driven programs.

3. In the switch control structures if the given expression matches with value 1 then
the statements in that case are executed and control comes to the first
statement after the switch control structure due to the presence of break
statement.
4. If the given expression does not matches with value1 then it goes for checking

52
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

value 2 and .….. value n.

5. If no switch case is matched with the given expression then automatically


statements in the default case are executed and control comes out of the switch
case.

6. The expression must be an integer expression or character expression which


yields either integer value or char value.

Write a program to read a number and print its corresponding week day.

main()
{
int day;
printf(“Enter number of week day:\n”);
scanf(“%d”,&day);
switch(day)
{
case 1: printf(“MONDAY”);
break;
case 2: printf(“TUESDAY”);
break;
case 3: printf(“WEDNESDAY”);
break;
case 4: printf(“THURSDAY”);
break;
case 5: printf(“FRIDAY”);
break;
case 6: printf(“SATURDAY”);
break;
case 7: printf(“SUNDAY”);
break;
default: printf(“Invalid Week day\n”);

Ourput:

Enter Number of week day:


2
TUESDAY

 Write a program to read a number and print its corresponding month name

main()
{

53
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

int day;
printf(“Enter number of the month:\n”);
scanf(“%d”,&day);
switch(day)
{
case 1: printf(“JANUARY”);
break;
case 2: printf(“FEBRUARY”);
break;
case 3: printf(“MARCH”);
break;
case 4: printf(“APRIL”);
break;
case 5: printf(“MAY”);
break;
case 6: printf(“JUNE”);
break;
case 7: printf(“JULY”);
break;
case 8: printf(“AUGUST”);
break;
case 9: printf(“SEPTEMBER”);
break;
case 10: printf(“OCTOBER”);
break;
case 11: printf(“NOVEMBER”);
break;
case 12: printf(“DECEMBER”);
break;

default: printf(“Invalid Month \n”);

output:
Enter number of the month:
5
MAY

 Write a program to read 2 numbers and perform arithmetic operations on those 2


numbers based on the given operator.

main()

54
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
int a,b;
char operator;
printf(“Enter 2 numbers\n”);
scanf(“%d%d”,&a,&b);
printf(“Enter your choice\n”);
printf(“ + Addition \t – Subtration \t *Multiplication \t / division \t %Modulo \n”);
scanf(“%c”,&operator);

switch(operator)
{
case ‘+’:printf(“%d + %d =%d\n”,a,b,a+b);
break;
case ‘-’:printf(“%d - %d =%d\n”,a,b,a-b);
break;
case ‘*’:printf(“%d * %d =%d\n”,a,b,a*b);
break;
case ‘/’:printf(“%d / %d =%d\n”,a,b,a/b);
break;
case ‘%’:printf(“%d % %d =%d\n”,a,b,a%b);
break;
default: printf(“enter invalid operator\n”);
}
}

Output:
Enter 2 numbers
10 20
+
10+20=30
flow chart for switch case:-

Points to b remembered when using switch control structure


1. In switch control structure the expression can be an integer or a character value.
2. In switch control structure the order of cases is not important.

Eg: main()
{
int n=3;
switch(n)
{
case 4: printf(“Four”);
break;
case 3: printf(“three”);
break;

case 2: printf(“two”);
break;

default: printf(“Four”);
break;

55
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

}
}

3. In switch statement every case must end with break statement.


4. In switch statement we can have cases with no executable statements even
through those cases are not having any executable statements. They are used
for specific purposes.

Eg: main()
{
char ch;
printf(“Enter a character”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘a’:
case ‘A’:
case ‘e’:
case ‘E’:
case ‘i’:
case ‘I’:
case ‘o’:
case ‘O’:
case ‘u’:
case ‘U’:printf(“The Given character is vowel”);
break;
default: printf(“The character is constant\n”);
}
}

output:
Enter a character
A
The Given character is vowel
5. In switch statement these can be some cases having integer type arguments,
there can be some cases having char type.
6. In switch statement if a statement is present, then it must belong to some
particular case is the switch otherwise that statement is not executed forever.

Eg; main()
{
int n=1;
switch(n)
{

56
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf(“Good Morning”);
case 1:printf(“One\n”);
case 2:printf(“Two\n”);
default: printf(“Hello”);
}
}

7. In switch statement we should not write conditions in the cases. But we can write
conditions in the expression.
8. In switch statement unlike if control structure the entire statements is a
particular case are not written in cur lee braces.
9. Using switch case, we can write more structured programs than using if
statement.

1) Write a program to find whether the given no is +ve or –ve and the given no is even or
odd.
main()
{
int n,ch;
printf(“Enter the value of n”);
scanf(“%d”,&n);
printf(“Enter your choice”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: if(n>=0)
printf(“%d is positive”,n);
else
printf(“%d is negative”,n);
break;

case 2: if(n%2==0)
printf(“%d is EVEN”,n);
else
printf(“%d is ODD”,n);
break;
default: printf(“No condition is satisfied”);
}
}
output:
Enter the value of n
6
Enter your choice
1
6 is positive

2) write a program to check the given character is vowel or consonant.


A)
main()
{

57
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

char ch;
printf("enter a character \n");
scanf(" %c",&ch);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("%c is vowel",ch);
else
printf("%c is not vowel",ch);
}

OUTPUT:
enter a character
s
s is not vowel

enter a character
i
i is vowel

3) write a program to check the given character is alpha numeric or not.


A)
main()
{
char ch;
printf("enter a charecter \n");
scanf(" %c",&ch);
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch>='0'&&ch<='9'))
printf("%c is alpha numeric",ch);
else
printf("%c is not alpha numeric",ch);
}

OUTPUT:

enter a character
k
k is alpha numeric
enter a character
9
9 is alpha numeric
enter a character
?
? is not alpha numeric

rd
4) Write a program to swap the contents of two variables without using 3 variable.
A) main()
{
int a,b;
printf("enter the two numbers\n");

58
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

scanf("%d %d",&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf("after swaping a=%d b=%d",a,b);
}
OUTPUT:
enter the two numbers
5
4
after swaping a=4 b=5
5) Write a program to convert the given character in to lower case.
A) main()
{
char ch;
printf(" enter a character\n");
scanf(" %c",&ch);
if(ch>=65&&ch<=90)
{
ch=ch+32;
printf("the given character in lower case %c",ch);
}
else
printf(" %c is not a upper case",ch);
}
OUTPUT:
enter a character
s
s is not a upper case
enter a character
S
s
6) write a program to convert the character in to upper case.
A) main()
{
char ch;
printf(" enter a character\n");
scanf(" %c",&ch);
if(ch>=97&&ch<=122)
{
ch=ch-32;
printf("the given character in upper case %c",ch);
}
else
printf(" %c is not lower case",ch);
}
Iterative control structures (or) Repetitive structures:

 while
 do-while
 for

59
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

These structures are used to repeatedly execute a particular statements (or) group of
statements based on a given condition.

While: - entry controlled loop (or) pre-condition testing loop.


Syntax: while(expression)
{
Statement 1;
Statement 2;
……………..
Statement n;
}
Here expression represents any expression which evaluates to either true (or) false.

The statements in the while loop are executed till the expression is true. When
expression in the while loop is false, then control goes to first statement immediately
below the while loop.

Flow chart:-

 Write a program to print “hello” 10 times using while loop.


#include<stdio.h>
main()
{
Int i=1;
While(i<=10)
{
Printf(“hello\n”);
I++;
}
}

 Write a program to find factorial of given number.


#include<stdio.h>
main()
{
int n,i=1,fact=1;

60
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf("enter a number\n");
scanf("%d",&n);
while(i<=n)
{
fact=fact*i;
i++;
}
printf("factorial of %d is %d",n,fact);
}

OUTPUT:-
enter a number
5
factorial of 5 is 120
enter a number
9
factorial of 9 is 362880.

 Write a program to print multiplication table.

#include<stdio.h>
main()
{
int n,i;
printf("enter the number\n");
scanf("%d",&n);
i=1;
while(i<=10)
{
printf("%3d x %3d = %3d\n",n,i,n*i);
i++;
}
}
OUTPUT:-
enter the number
9
9x 1= 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
Do-while: - Exit controlled loop (or) post condition testing loop

The do-while loop performs the test at the bottom rather than at the top.
The do-while loop starts with the keyworddo, followed by the body of the loop.

61
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Syntax:do
{
Statement 1;
Statement 2;
……………..
Statement n;
}while(expression);

After executing the body of the loop it reaches while, the expression specified is
evaluated. If it is found to be true, automatically loop back to the top and re-enter the
body of the loop.
At the time of testing, the condition evaluates as false, then the control breakout
the do-while loop.
 Print hello 10 times using do-while.
main()
{
Int I;
do
{
printf(“hello\n”);
i++;
}while(i<<=10);
}

 Factorial of given number using do-while loop.


#include<stdio.h>
main()
{
int n,i=1,fact=1;
printf("enter a number\n");
scanf("%d",&n);
do
{
fact=fact*i;
i++;
}while(i<=n);
printf("factorial of %d is %d",n,fact);
}
OUTPUT:
enter a number
4
factorial of 4 is 24

Differences between while and do-while loop.

1) The while loop is called precondition testing loop because the condition is
checked initially before the statements are executed. Do-while loop is called past
condition testing loop that means condition is checked once the statements are

62
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

executed.
2) In the while loop, there is no semicolon at end of condition, but in do-while there
must be semicolon at end of condition.
3) In the while loop, the statements may executed or may not be executed
depending on conditions. But in do-while the statements are executed at least
one type whether the given condition is true/false.

Ex:
main() main()
{ {
While(4<1) do
{ {
printf(“hello\n”); printf(“hello\n”);
} }while(4<1);
} }

O/P : ----- O/P:hello

 Write a program to find sum of digits of a two digit number.

#include<stdio.h>
main()
{
int n,a,sum=0;
printf("enter a number\n");
scanf("%d",&n);
a=n%10;
sum=sum+a;
n=n/10;
sum=sum+n;
printf("sum=%d",sum);
}
OUTPUT:
enter a number
31
sum=4

 Write a program to find sum of digits of a three digit number.


#include<stdio.h>
main()
{
int n,a,sum=0;
printf("enter a number\n");
scanf("%d",&n);
a=n%10;
sum=sum+a;
n=n/10;
a=n%10;
sum=sum+a;
n=n/10;
sum=sum+n;

63
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf("sum=%d",sum);
}
OUTPUT:
enter a number
143
sum=8.

For loop:- This is used when the statements are to be executed more than once. This is
the most widely used iteration construct.

Syntax:for (initialization; expression (or) condition; increment (or) decrement);


{
statement 1;
statement 2;
…………….
…………….
statement n;
}

 in the for loop the initialization section is executed afterwards the given condition is
checked. If the given condition is true, the statements in the for loop are executed and
the control comes to increment/decrement section and then the goes to conditional part.

Note: the initialization part is executed only for the first time only.

Flow chart:-

 write a program to print hello 10 times using for loop.


main()
{
int I;
for(i=0;i<=10;i++)
printf(“hello\n”);
}

 write a program to find factorial of given number.


main()
{
int n,i,fact=1;
printf("enter the number\n");

64
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

scanf("%d",&n);
for(i=1;i<=n;i++)
fact=fact*i;
printf("the factorial of %d is %d",n,fact);
}

OUTPUT:
enter the number
6
the factorial of 6 is 720.
 write a program to display multiplication table for given number.
#include<stdio.h>
main()
{
int n,i;
printf("enter the number\n");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d x %3d = %3d\n",n,i,n*i);
}
OUTPUT:
enter the number
5
5x 1= 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
 Write a program to print 1 to n natural numbers.
main()
{
int I,n;
printf(“enter a number\n”);
scanf(“%d”,&n);
i=1;
while(i<=n) do for(;i<=n;i++)
{ { {
printf(“%d”,i); printf(“%d”,i); printf(“%d”,i);
i++; i++; }
} }
}
 Write a program to print n to 1 natural numbers.

main()
{
int I,n;

65
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf(“enter a number\n”);
scanf(“%d”,&n);
while(n>=1) do for(;n>=1;n--)
{ { {
printf(“%d”,n); printf(“%d”,n); printf(“%d”,n);
n--; n--; }
} }while(n>=1);
}
 Write a program to find sum of digits of a given number by using loops.
main()
{
int n,a,sum=0;
printf(“enter a number\n”);
scanf(“%d”,&n);
while(n>0) do for(;n>0;n=n/10)
{ { {
a=n%10; a=n%10; a=n%10;
sum=sum+a; sum=sum+a; sum=sum+a;
n=n/10; n=n/10; }
} }while(n>0);
printf(“ sum=%d”,sum);
}

 write a program to find reverse (or) image of a given number by using loops.
main()
{
int n,a,m,rev=0;
printf(“enter a number\n”);
scanf(“%d”,&n);
m=n;
while(n>0) do for(m=n;n>0;n=n/10)
{ { {
a=n%10; a=n%10; a=n%10;
rev=rev*10+a; rev=rev*10+a; rev=rev*10+a;
n=n/10; n=n/10; }
} }while(n>0);

printf(“ reverse of the given number%d is %d”,m,rev);


}
 write a program to print even no’s up to n.
main()
{
int n,i=2;
printf(“enter the number\n”);
scanf(“%d”,&n);
while(i<=n)
{
if(i%2==0)
printf(“%d”\n”,i);
i++;
}

66
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

 write a program to print Fibonacci series up to given number.

#include<stdio.h>
main()
{
int a=0,b=1,c,n;
printf("enter the number\n");
scanf("%d",&n);
printf("%d %d",a,b);
c=a+b;
while(c<=n)
{
printf("\t%d",c);
a=b;
b=c;
c=a+b;

OUTPUT:

enter the number


15
0 1 1 2 3 5 8 13

 Write a program to find the given number is Armstrong (or) not.


#include<stdio.h>
main()
{
int n,m,a,b,sum=0;
printf("enter a number\n");
scanf("%d",&n);
m=n;
while(n>0)
{
a=n%10;
b=a*a*a;
sum=sum+b;
n=n/10;
}
printf("sum=%d\n",sum);
if(sum==m)
printf("the given number is armstrong\n");
else
printf("the given number is not armstrong number\n");
}
OUTPUT:

enter a number
153
sum=153

67
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

the given number is Armstrong

enter a number
345
sum=216
the given number is not Armstrong number

 write a program to find whether the given number is prime or not.

#include<stdio.h>
main()
{
int n,i=2,c=0;
printf("enter the number\n");
scanf("%d",&n);
while(i<n) for(i=2;i<n;i++)
{ {
if(n%i==0) if(n%i==0)
c++; c++;
i++; }
}
if(c==0)
printf("%d is prime",n);
else
printf("%d is not prime",n);
}

OUTPUT:

enter the number


7
7 is prime

enter the number


4
4 is not prime

 Write a program to read multiple lines using scanf() function.

#include<stdio.h>
main()
{
char name[20];
printf("enter the multiple lines\n");
scanf("%[^\t]",name);
}
Type modifiers:
The type modifiers are used to change or to alter the basic meaning of the given
data type. The type modifiers are used to redirect the given data type to take only
specified range of value.
The following are the different type modifiers.

68
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

 Signed
 Unsigned
 Short
 Long
All these can be applied to int.

signed
unsigned signed
int long char unsigned
short

float -- long
double -- long

 Write a program to calculate average of given ‘n’ numbers.


#include<stdio.h>
main()
{
int i=1,n,sum=0,m;
float avg;
printf("enter the number\n");
scanf("%d",&n);
m=n;
while(n>=i)
{
sum=sum+n;
n--;
}
printf("sum=%d\n",sum);
avg=(float)sum/m;
printf("avg=%f\n",avg);
}
OUTPUT:
enter the number
3
sum=6
avg=2.000000

 Write a program to print the following sequence.


main()
{
int i=1,j,n;
printf("enter the number\n");

69
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

scanf("%d",&n);
while(i<=n)
{
j=1;
while(j<=n)
{
printf("\t*");
j++;
}
printf("\n");
i++;
}
}

OUTPUT:
enter the number
2
* *
* *
enter the number
3
* * *
* * *
* * *
To find whether the number is perfect (or) deficient (or) abundant no

main()
{
int i,n,sum=0;
printf("enter the number\n");
scanf("%d",&n);
for(i=1;i<=n/2;i++)
{
if(n%i==0)
sum=sum+i;
}
if(sum==n)
printf("%d is perfect number\n",n);
else if(sum<n)
printf("%d is deficient number\n",n);
else
printf("%d is abundant number\n",n);
}

OUTPUT:
enter the number
6
6 is perfect number

70
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

enter the number


4
4 is deficient number

enter the number


24
24 is abundant number
 write a program to print sum of divisors of a number
main()
{
int i=1,n,sum=0;
printf("enter the number\n");
scanf("%d",&n);
for(i=1,sum=0;i<=n;i++)
{
if(n%i==0)
sum=sum+i;
}
printf("sum is %d \n",sum);
}
OUTPUT:
enter the number
6
sum is 12

enter the number


2
sum is 3
 Write a program to find the given number is palindrome (or) not.
main()
{
int n,a,m,rev=0;
printf(“enter a number\n”);
scanf(“%d”,&n);
m=n;
while(n>0)
{ for(m=n;n>0;)
a=n%10; {
rev=rev*10+a;
n=n/10; }
}
if(rev==m)
printf(“ given number %d is palindrome”,m);
else
printf(“ given number %d is not palindrome”,m);
}
Continue: The continue statement whenever executed causes the rest of current
iteration to be skipped and causes next iteration to begin, subjecting to the truth of the
controlling condition.
Syntax: continue;

71
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Break : This break statement terminates the execution of the loop and the control is
transferred to the statement immediately following the loop.
Syntax: break;

Infinite loops:-

Ex:- while(-6) do for(;;)  infinite loop.


{ {

} }while(11);

Arrays
An array is a collection of elements of similar type, those sharing a common name and
occupies contiguous locations.

Arrays are 3 types.

72
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

1) Single dimensional arrays.


2) Double dimensional arrays.
3) Multi dimensional arrays.

DECLARATION OF ARRAYS
Array may be of one dimensional or multi dimensional. Declarations of the one
dimensional arrays, two dimensional arrays and three dimensional arrays are as follows.

Declaration of a one dimensional array

The syntax of the declaration of a one dimensional array is

data_type arrayname1 [size1], arrayname2 [size2]…arraynameN [sizeN];

Here data_type refers to the data type of the elements in the array and it can be a
primitive data type. arrayname1, arrayname2…..etc refers to the identifiers which
represent the array name. Size is an integer expression representing total number of
elements in the array.

Example
int Num[10];

It is the declaration of a one dimensional array which defines an integer array name Num
of size 10 and that represents a block of 10 consecutive storage locations. Here each
element in the array is represented by Num[0], Num[1],….,Num[9], where 0, 1, 2, …, 9
represents subscripts or indices of the array.

In general Num [ i ] refers to the ith element of the array. The representation of
one dimensional array in memory is as follows.

Num[0] Num[1] Num[2] Num[3] Num[4] Num[5] Num[6] Num[7] Num[8] Num[9]

1024 1026 1028 1030 1032 1034 1036 1038 1040 1042
Addresses

In the memory representation of one dimensional array each element is


referenced by its name of the array with the subscript and the addresses. The name of
the array it self represents the base address of that entire array.

Let us consider the above example Num it self represent the base address of the
entire array. &Num [0] also represents the base address. &Num [5] represents the
th
address of the 6 element in the array Num, and it is calculated using the formulae
th
Address of the i element = base address + i * scale factor

73
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

The scale factor is the number of byes allocated for each element of the array.
The address of array Num [5] is calculated as
&Num [5] = 1024 + 5 * 2 = 1034.
Here &Num [5] is also represented as (num+5).

Write a program to read an array and print that array.


#include<stdio.h>
main( )
{
int a[10], i, n ;
printf (“ Enter how many values you want to read : “);
scanf (“ %d “, &n );
for( i=0; i<n; i++ )
{
printf ( “ Enter the value of a[%d] : “ , i );
scanf (“ %d “, &a[ i ]);
}
printf (“ The array elements are ; “);
for( i=0; i<n; i++ )
printf (“ \t %d “, a[ i ]);
}

Declaration of a two dimensional array

The syntax of the declaration of a two dimensional array is


data_type array_name [size1][size2];

Here data_type refers to the data type of the elements in the array and it can be a
primitive data type. array_name refers to the identifiers which represent the array name.
Size1 is an integer expression representing the row size in the array and Size2 is also an
integer expression representing the column size in the array. In a two dimensional array
two subscripts are used in two pairs of square brackets.

The total number of elements in a two dimensional array is calculated by


multiplying number of rows and the number of columns. In a two dimensional array the
values are stored in a row major order.

Example
int Num[2][2];
It is the declaration of a two dimensional array which defines an integer array name Num
of row size 2 with column size 2 and that represents a block of 4 consecutive storage
locations. Here each element in the array is represented by Num[0][0],
Num[0][1],Num[1][0] and num[1][1].
th th
In general Num[ i ][ j ] refers to the element of the i row and j column in the
array. The representation of a two dimensional array in the memory is as follows.

Num[0][0] Num[0][1] Num[1][0] Num[1][1]

1024 1026 1028 1030


Addresses 74
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

In the memory representation of a two dimensional array each element is


referenced by its name of the array with row and column subscripts, and by the
addresses. The name of the array it self represents the base address of that entire array.

Let us consider the above example Num it self represent the base address of the
entire array. &Num [0][0] also represents the base address. &Num [1][0] represents the
address of the 2nd row 1st column element in that array Num, and it is calculated using
the formulae

Address of the [ i, j]th element = base address + i * total no of columns * scale factor + j * scale factor

The scale factor is the number of byes allocated for each element of the array.
The address of array Num [1][1] is calculated as
&Num [1][1] = 1024 + 1 * 2 *2 + 1*2= 1030.

Write a program to read a two dimensional array and print that array.
#include<stdio.h>
main( )
{
int a[10][10], i, j, m, n ;
printf (“ Enter the number of rows and columns: “);
scanf (“ %d %d“, &m, &n );
for( i=0; i<m; i++ )
{
for( j=0; j<n; j++ )
{
printf ( “ Enter the value of a[%d][%d] : “ , i, j );
scanf (“ %d “, &a[ i ][ j ]);
}
}
printf (“ The array elements are ; “);
for( i=0; i<m; i++ )
for( j=0; j<n; j++)
printf (“ \t %d “, a[ i ][ j ]);
}

Declaration of a three dimensional array

The syntax of the declaration of a three dimensional array is

data_type array_name [size1][size2][size3];


75
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

In the three dimensional array 3 subscripts are placed as three pairs of square brackets,
Where as size1 represents the number of pages, size2 represents the number of rows
and size3 represents the number of columns. The total number of elements in a three
dimensional array is calculated as No of pages * No of rows * No of columns.

Example
int a[2][2][2];

The total number of elements= 2 * 2 * 2 =8.

The value in the kth page, ith row and jth column is referred to by a[ k ][ i ][ j ]. The memory
representation of a three dimensional array is as follows.

a[0][0][0] a[0][0][1] a[0][1][0] a[0][1][1] a[1][0][0] a[1][0][1] a[1][1][0] a[1][1][1]

1024 1026 1028 1030 1032 1034 1036 1038


Page0 page1

Write a program to read p pages, m rows and n columns of elements and print them.
#include<stdio.h>
main()
{
int a[3][3][3], i, j, k, p, m, n;
printf ( “ Enter how many page numbers, rows and columns you want\n “);
scanf ( “ %d %d %d “, &p, &m, &n);
for( k=0; k<p; k++)
{
for( i=0; i<m; i++)
{
for( j=0; j<n; j++)
{
printf ( “ Enter element for a[%d][%d][%d] : “,k, i, j);
scanf ( “ %d “, &a[ k ][ i ][ j ]);
}
}
}

for( k=0; k<p; k++)


{
for( i=0; i<m; i++)
{
for( j=0; j<n; j++)
{

76
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf ( “The value in a[%d][%d][%d] = %d “,k, i, j, a[ k ][ i ][ j ] );


}
}
}

INITIALISATION OF ARRAYS

The elements of an array may be assigned with the values using initialization
instead of reading them by the I/O functions. An array can be initialized in its declaration
only. The lists of values are enclosed in braces. The values are separated by commas
and they must be constants or constant expressions.

One dimensional array can be initialised as given below.


int a[4]={10,20,30,40};
The values with in the braces are scanned from left to right and assigned them to a[0],
a[1], and soon.

A two dimensional array can be initialised as given below.


int a[3][2]={20,30,40,50,60,70};
The values are assigned to the array elements according to the order of the storage in
the memory. The above example can also be represented as
int a[3][2]={{20,30},{40,50},{60,70}};
Here, the initialised values with in the inner braces are assigned to each row.

If the number of values initialised for an array is less than the size mentioned, the
missing elements are assigned to zero.
Example
int a[3][4]={ {1,2},{3,4,5} };
In the above example the elements a[0][0], a[0][1] of the 0th row and a[1][0], a[1][1]
and a[1][2] of the 1st row are initialised with the values 1,2,3,4 and 5 respectively. All the
other elements are initialised to zero. If the number of initial values exceeds the size of
the array, it is an error.

Example
int a[3][4]={1,2,3,4,5};
In the above example the values are assigned from left end to a[0][0], a[0][1],
a[0][2], a[0][3] and a[1][0] according to the order of the storage representation.

The size of a one dimensional array need not be mentioned in its initialization. In
this case, the compiler will count the values assigned and take it as the size of that array.
In multi dimensional arrays the leftmost subscript may be omitted and all others must
be specified.
Example
int x[ ]={1,2,3,4,5};
The initialization makes the array x having 5 elements
Example
int a[ ][2]={1,2,3,4};
The initialization makes the array a having 2 rows and 2 columns.

77
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

For example a ten element array all having value 1 is initialised as


int num[10]={1,1,1,1,1,1,1,1,1,1};
But, an indirect way of initializing many elements of the array to zero value may be done
as follows because missing elements are assigned zero value automatically.
int num[10]={0};

Example
float x[ ][3]={{1},{2},{3}};
The declaration represents a three by three array with only the first element in each row
is initialised.

Example
float x[ ][3]={ {1,2,3} };
The above declaration represents a one by three array. Hence, the internal braces are
important in fixing the size of the dimension when leftmost dimension is omitted. The
missing elements of a initialised array are assigned the value zero.

 write a program to find maximum and minimum elements in the given array.

#include<stdio.h>
main()
{
int a[20],i, n, max, min;
printf ( "Enter value of n : ");
scanf ( "%d" , &n);
for( i=0; i<n; i++)
{
printf ( "Enter element for a[%d] : ",i );
scanf ( "%d", &a[ i ]);
}
max=min=a[0];
for( i=1; i<n; i++)
{
if(max < a[ i ])
max=a[ i ];
if(min > a[ i ])
min=a[ i ];
}
printf ( "Maximum element =%d\n Minimum element=%d\n", max, min);
}

OUTPUT:

Enter value of n : 5
Enter element for a[0] : 2
Enter element for a[1] : 5
Enter element for a[2] : 6
Enter element for a[3] : 3

78
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Enter element for a[4] : 8


Maximum element =8
Minimum element=2

 Write a program to find no.of +ve and –ve elements in the given array.

main()
{
int a[10],p=0,n=0,i,x;
printf("enter the size of the array \n");
scanf("%d",&x);
printf("enter the elements in the array\n");
for(i=0;i<x;i++)
scanf("%d",&a[i]);
for(i=0;i<x;i++)
{
if(a[i]>0)
p++;
else
n++;
}
printf("no.of +ve numbers are %d",p);
printf("no of -ve numbers are %d",n);
}

OUTPUT:
enter the size of the array
5
enter the elements in the array
2
-8
5
-9
1
no.of +ve numbers are 3no of -ve numbers are 2

 Write a program to find given element is present in the array or not.


main()
{
int a[10],n,i,ele,c=0;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");

79
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\nenter the serching element\n");
scanf("%d",&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
c++;
}
if(c>0)
printf("the element is found and %d times occurred\n",c);
else
printf("the element is not found\n");
}

OUTPUT:

enter the size of the array


5
enter the elements in to the array
3
1
9
4
2
the array elements are
3 1 9 4 2
enter the serching element
2
the element is found and 1 times occurred

 write a program to copy one array elements to another array.

main()
{
int a[10],b[10],n,i;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements in A are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=0;i<n;i++)
b[i]=a[i];
printf("\n the array elements in B are\n");

80
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

for(i=0;i<n;i++)
{
printf("%d\t",b[i]);
}
}

OUTPUT:

enter the size of the array


5
enter the elements in to the array
2
1
4
3
5
the array elements in A are
2 1 4 3 5
the array elements in B are
2 1 4 3 5

 Write a program to print the elements in reverse order.

main()
{
int a[10],n,i;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements in A are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n the reverse elements in A are\n");

for(i=n-1;i>=0;i--)
{
printf("%d\t",a[i]);
}
}

OUTPUT:

enter the size of the array


5
enter the elements in to the array
1
2

81
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

3
4
5
the array elements in A are
1 2 3 4 5
the reverse elements in A are
5 4 3 2 1

 Write a program to write the given number in words.

main()
{
int a[10],n,i,size;
printf("enter the number\n");
scanf("%d",&n);
i=0;
while(n>0)
{
a[i]=n%10;
n=n/10;
i++;
}
size=i;
for(i=size-1;i>=0;i--)
{
switch(a[i])
{
case 0:printf("zero\t");break;
case 1:printf("one\t");break;
case 2:printf("two\t");break;
case 3:printf("three\t");break;
case 4:printf("four\t");break;
case 5:printf("five\t");break;
case 6:printf("six\t");break;
case 7:printf("seven\t");break;
case 8:printf("eight\t");break;
case 9:printf("nine\t");break;
}
}
}
OUTPUT:
enter the number
2345
two three four five
 write a program to find the binary equivalent of the given number

main()
{
int a[10],n,i,size;
printf("enter the number\n");
scanf("%d",&n);

82
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

i=0;
while(n>0)
{
a[i]=n%2;
n=n/2;
i++;
}
size=i;
for(i=size-1;i>=0;i--)
{
printf("%d\t",a[i]);
}
}
OUTPUT:
enter the number
12
1 1 0 0

 Write a program to reverse the contents of the array in given 2 positions.


main()
{
int a[10],n,i,j,k,temp=0;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\nenter the positions to be reversed\n");
scanf("%d%d",&j,&k);
temp=a[j-1];
a[j-1]=a[k-1];
a[k-1]=temp;
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}

OUTPUT:
enter the size of the array
5
enter the elements in to the array
1
2
3
4
5
the array elements are

83
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

1 2 3 4 5
enter the positions to be reversed
3
4
1 2 4 3 5
 Write a program to replace an element in the array with the given element.
main()
{
int a[10],n,i,old,new,c=0;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\nenter the element to be replaced\n");
scanf("%d",&old);
printf("enter the replacing elment\n");
scanf("%d",&new);
for(i=0;i<n;i++)
{
if(a[i]==old)
{
a[i]=new;
c++;
}
}
if(c==0)
printf("the element is not found\n");
else
{
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
}

OUTPUT:
enter the size of the array
5
enter the elements in to the array
1
2
3
4
5
the array elements are
1 2 3 4 5
enter the element to be replaced
4

84
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

enter the replacing elment


9
1 2 3 9 5

 Write a program to sort the array elements in ascending order.


main()
{
int a[10],n,i,j,k,temp=0;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf(“after sorting the array elements are\n”);
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
 Write a program to find sum of array elements.
main()
{
int a[10],i,n,sum=0;
printf("enter the array size\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("the sum of the array elements is %d",sum);
}
OUTPUT:
enter the array size
5
enter the array elements
1
2
3

85
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

4
5
the sum of the array elements is 15

 Write a program to find sum of even no’s of sum of odd no’s in the given array.
#include<stdio.h>
main()
{
int a[10],i,n,evensum=0,oddsum=0;
printf("enter the array size\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d",a[i]);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
evensum=evensum+a[i];
else
oddsum=oddsum+a[i];
}
printf("the sum of the even numbers are %d\n",evensum);
printf("the sum of odd numbers are %d\n",oddsum);
}
OUTPUT:
enter the array size
5
enter the array elements
1
2
3
4
5
the array elements are
12345
the sum of the even numbers are 6
the sum of odd numbers are 9

 Write a program to read elements from the keyboard and display the even number
array and odd number array separately.
#include<stdio.h>
main()
{
int a[10],i,n,e[10],o[10],oi=0,ei=0;
printf("enter the array size\n");

86
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
e[++ei]=a[i];
else
o[++oi]=a[i];
}
printf("\nthe even numbers array is\n");
for(i=1;i<=ei;i++)
printf("%d\t",e[i]);

printf("\nthe odd numbers array is\n");


for(i=1;i<=oi;i++)
printf("%d\t",o[i]);
}

OUTPUT:
enter the array size
6
enter the array elements
1
2
3
4
5
6
the array elements are
1 2 3 4 5 6
the even numbers array is
2 4 6
the odd numbers array is
1 3 5

 Write a program to print Fibonacci series using arrays.


main()
{
int a[10],n,i;
a[0]=0;
a[1]=1;
for(i=2;i<10;i++)
{
a[i]=a[i-1]+a[i-2];
}
for(i=0;i<10;i++)

87
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf("%d\t",a[i]);
}
OUTPUT:

0 1 1 2 3 5 8 13 21 34

 Write a program for linear search


main()
{
int a[10],i,x;
printf("enter a number\n");
scanf("%d",&x);
printf("enter the array elements\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<10;i++)
printf("%d\t",a[i]);
for(i=0;i<10;i++)
if(a[i]==x)
break;

if(a[i]!=x)
printf("%d elememt is not found\n",x);
else
printf("%d element is found\n",x);
}

OUTPUT:
enter a number
9
enter the array elements
1
2
3
4
5
5
6
7
8
9
the array elements are
1 2 3 4 5 5 6 7 8 9
9 element is found
 /* A menu driven program to display statistical parameters
using one-dimensional arrays
i) Mean ii) Medain iii) Mode iv) Variance v)Standard deviation*/

#include<math.h>
#define maxsize 10

88
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

main()
{
int n,a[maxsize],ch,i,j,t,flag,it,y;
float mean,mode,median,var,sd,sum;
printf("enter howmany numbers do u want to give\n");
scanf("%d",&n);
printf("enter the elements in the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the elements in the array are\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
do
{
printf(" 1.mean\n 2.median\n 3.mode\n 4.varience\n 5.standard deviation\n
6.exit \n");
printf("enter your option\n");
scanf("%d",&ch);
switch(ch)
{
case 1: sum=0;
for(i=0;i<n;i++)
sum=sum+a[i];
mean=sum/n;
printf("the mean of the given numbers is %f\n",mean);
break;
case 2: for(it=0;it<n-1;it++)
{
for(j=0;j<n-1;j++)
{
if(a[j]<a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
if(n%2!=0)
median=a[n/2];
else
median=(a[n/2]+a[(n/2)-1])/2.0;
printf("the median is %f %d %d\n",median,a[n/2],a[n/2-1]);
break;

case 3: mode=((3*median)-(2*mean));
printf("the mode is %f\n",mode);
break;

case 4: sum=0;
for(i=0;i<n;i++)

89
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
y=(a[i]-mean)*(a[i]-mean);
sum=sum+y;
}
var=sum/n;
printf("the varience is %f\n",var);
break;
case 5: sd=sqrt(var);
printf("the standard deviation is %f\n",sd);
break;
case 6: exit();
break;
default : printf("invalid option\n");
break;

}
}while(ch<=6);
}

 /* A menu driven program with options(using one-dimensional array)


1)To insert an element into array
2) To delete an element
3)To print elements
4)To prints elements in reverse order
5)To remove duplicates */
#include<stdio.h>
int a[10],n;
void read();
void display();
void reverse();
void insert();
void delete();
void rem();

main()
{
int choice;
while(1)
{
printf("\n1.read\n2.display\n3.reverse\n4.insert\n5.delete\n6.remove\n");
printf("7.exit\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:read(); break;
case 2:display(); break;
case 3:reverse(); break;
case 4:insert(); break;
case 5:delete(); break;
case 6:rem(); break;
case 7:exit(); break;

90
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

}
}
}
void read()
{
int i;
printf("Enter a number:");
scanf("%d",&n);
printf("\nEnter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display()
{
int i;
printf("The array elements are:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}

void reverse()
{
int i,j,temp;
for(i=0,j=n-1;i<j;i++,j--)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
display();
}

void insert()
{
int i,pos,ele;
printf("Enter the position to insert:");
scanf("%d",&pos);
if(pos<1 ||pos>n)
{
printf("\nNot valid position:");
return;
}
printf("\nEnter the element to be insert:");
scanf("%d",&ele);
for(n++,i=n-1;i>pos-1;i--)
{
a[i]=a[i-1];
}
a[pos-1]=ele;
display();
}

91
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

void delete()
{
int i,pos,ele,c=0;
printf("Enter element to delete:");
scanf("%d",&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
for(pos=i;pos<n-1;pos++)
a[pos]=a[pos+1];
n--;
i--;
c=1;
}
}

if(c==0)
{
printf("The element is not found in the array:\n");
}
display();
}
void rem()
{
int i,j,pos,c=0;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
for(pos=j;pos<n-1;pos++)
a[pos]=a[pos+1];
n--;
j--;
c=1;
}
}
if(c==0)
{
printf("The duplicate element is not :\n");
}
display();
}
Arrays in functions:-

Return type function_name(type arrayname[ ], ……….);

Functions with single dimensional arrays:-

Function prototype

92
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Syntax:- returntype functionname(data type arrayname[size],data type number);

Function call:-
Functionname (arrayname, size);

Function definition:-
returntype functionname((data type arrayname[size],data type number)
{
statement 1;
statement 2;
…………….
…………….
Statement n;
}
 Write a program to read and print array elements.
void read(int a[],int n);
void display(int [],int);
main()
{
int a[10],n;
printf("enter the no of elements\n");
scanf("%d",&n);
read(a,n);
display(a,n);
}
void read(int a[10],int n)
{
int i;
printf("enter the array elemnets\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display(int a[10],int n)
{
int i;
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
OUTPUT:-
enter the no of elements
5
enter the array elemnets
2
4
1
3
5
the array elements are
2 4 1 3 5

93
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

 The default mechanism in which the variables are passed to function is call by value.
 The default mechanism in which the array is passed to function is call by reference.
 Write a program to insert an element into the array.
void read(int a[],int n);
void display(int [],int);
int insert(int[],int,int,int);
main()
{
int a[10],n,pos,ele;
printf("enter the no of elements\n");
scanf("%d",&n);
read(a,n);
printf("before element insertion\n");
display(a,n);
printf("enter the element to insert\n");
scanf("%d",&ele);
printf("enter the position that the element to be insert\n");
scanf("%d",&pos);
n=insert(a,n,pos,ele);
printf("after element insertion\n");
display(a,n);
}
void read(int a[10],int n)
{
int i;
printf("enter the array elemnets\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display(int a[10],int n)
{
int i;
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
int insert(int a[10],int n,int pos,int ele)
{
int i;
if(pos<1||pos>n)
{
printf("insertion is not possible\n");
return;
}
else
{
for(n++,i=n-1;i>pos-1;i--)
a[i]=a[i-1];
a[pos-1]=ele;
}

94
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

return n;
}

OUTPUT:
enter the no of elements
5
enter the array elemnets
1
2
3
4
5
before element insertion
the array elements are
1 2 3 4 5
enter the element to insert
9
enter the position that the element to be insert
3
after element insertion
the array elements are
1 2 9 3 4 5

 Write a program to copy one array elements into another by using functions.

void read(int a[],int n);


void display(int [],int);
void copyarray(int [],int [],int n);
main()
{
int a[10],b[10],n;
printf("enter the no of elements\n");
scanf("%d",&n);
read(a,n);
copyarray(a,b,n);
printf("the first array elements are\n");
display(a,n);
printf("the second array elements are\n");
display(b,n);
}
void read(int a[10],int n)
{
int i;
printf("enter the array elemnets\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display(int a[10],int n)
{
int i;
printf("the array elements are\n");

95
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void copyarray(int a[10],int b[10],int n)
{
int i;
for(i=0;i<n;i++)
b[i]=a[i];
}
OUTPUT:
enter the no of elements
5
enter the array elemnets
1
2
3
4
5
the first array elements are
1 2 3 4 5
the second array elements are
1 2 3 4 5
 Write a program to copy two array elements into third array.
void read(int a[],int n);
void display(int [],int);
void copy(int [],int,int [],int,int []);
main()
{
int a[10],b[10],c[20],m,n,p;
printf("enter the no of elments in A array\n");
scanf("%d",&m);
printf("enter the no of elements in B array\n");
scanf("%d",&n);
p=m+n;
printf("enter A elements\n");
read(a,m);
printf("emter B elements\n");
read(b,n);
copy(a,m,b,n,c);
printf("A elements are\n");
display(a,m);
printf("B elements are\n");
display(b,n);
printf("C elements are\n");
display(c,p);
}
void read(int a[10],int n)
{
int i;
printf("enter the array elemnets\n");
for(i=0;i<n;i++)

96
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

scanf("%d",&a[i]);
}
void display(int a[10],int n)
{
int i;
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void copy(int a[10],int m,int b[10],int n,int c[20])
{
int i,j=0;
for(i=0;i<m;i++)
{
c[j]=a[i];
j++;
}
for(i=0;i<n;i++)
{
c[j]=b[i];
j++;
}
}
OUTPUT:
enter the no of elments in A array
3
enter the no of elements in B array
3
enter A elements
enter the array elemnets
1
2
3
emter B elemets
enter the array elemnets
4
5
6
the A array elements are
1 2 3
the B array elements are
4 5 6
the C array elements are
1 2 3 4 5 6
 Write a function that takes 3 arguments array,no.of elements, searching element and
it returns 1 if the searching element is found other wise it returns 0.
Int search(int a[],int n,int x)
{
int I;
for(i=0;i<n;i++)
{

97
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

if(a[i]==x)
return 1;
}
return 0’
}

 Write a program for binary search.

Double dimensional arrays (DDA):-

A double dimensional array is a collection of single dimensional arrays.

Syntax:- datatype variable_name [size] [size];


(or)
datatype variable_name [row size] [column size];
here variable name indicates name of the DDA and row size indicates no.of rows with in
the DDA & column size indicates no.of columns that are present with in each row.
 the total number of elements in DDA = rs *cs

ex:-
int a[2][2]; col 0 col 1
A[0][0] 100 A[0][1] 102
B[0][0] 104 B[0][1] 106

Float b[2][3]
Col 0 col 2 col 3
B[0][0] B[0][1] B[0][2]
B[1][0] B[1][1] B[1][2]

Initialization of DDA:-
1) compile time initialization
2) runtime initialization.

Compile time initialization:-

 Write a program to read value into DDA & print them.


main()
{
int a[3][2]={10,20,30,40,50,60};
int i,j;
printf("the array elements are\n");
for(i=0;i<3;i++)
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
OUTPUT:
the array elements are
10 20 30 40 50 60

98
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

Note: when a DDA is initialized at the time of its declaration then, specification of row
size is optional, but column size must be compulsorily specified why because depending
upon the no. of columns, the computer assumes the no. of rows.

Ex:- int a[][3] = { 10,20,30,40,50,60 };


(or)
Int a[3][2] = { {10,20},{30,40},{50,60} };

 Write a program to read DDA elements using runtime initialization process.

main()
{
int a[5][5],i,j,m,n;
printf("enter number rows and columns\n");
scanf("%d %d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter a[%d][%d] element\n",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf("the DDA elements are\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
}

OUTPUT:
enter number rows and columns
2
3
enter a[1][1] element
1
enter a[1][2] element
3
enter a[1][3] element
5
enter a[2][1] element
2
enter a[2][2] element
4
enter a[2][3] element
6
the DDA elements are
1 3 5 2 4 6
 Write a program to find no. of even no’s & no. of odd no’s in the given matrix and also

99
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

find sum of even no’s and sum of odd no’s.


main()
{
int a[5][5],i,j,m,n,e=0,o=0,evensum=0,oddsum=0;
printf("enter number rows and columns\n");
scanf("%d %d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter a[%d][%d] element\n",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf("the DDA elements are\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]%2==0)
{
e++;
evensum=evensum+a[i][j];
}
else
{
o++;
oddsum=oddsum+a[i][j];
}
}
}
printf("no of evens = %d\n",e);
printf("no of odds = %d\n",o);
printf("even sum =%d\n",evensum);
printf("odd sum = %d\n",oddsum);
}
OUTPUT:
enter number rows and columns
2
2
enter a[1][1] element
1
enter a[1][2] element
2
enter a[2][1] element
3
enter a[2][2] element
4

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

the DDA elements are


1 2 3 4
no of evens = 2
no of odds = 2
even sum =6
odd sum = 4
 Write a program to find biggest and smallest element in the given matrix and also find
their positions.
main()
{
int a[5][5],i,j,m,n,big,small,brp,srp,bcp,scp;
printf("enter number rows and columns\n");
scanf("%d %d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter a[%d][%d] element\n",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf("the DDA elements are\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
big=small=a[0][0];
brp=bcp=srp=scp=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>big)
{
big=a[i][j];
brp=i;
bcp=j;
}
if(a[i][j]<small)
{
small=a[i][j];
srp=i;
scp=j;
}
}
}
printf("the biggest element is = %d\n",big);
printf("the biggest elementlocation is a[%d][%d]=%d\n",brp+1,bcp+1,a[brp][bcp]);
printf("the smallest elment is=%d\n",small);
printf("the smallest elmentlocation is a[%d][%d]=%d\n",srp+1,scp+1,a[srp][scp]);
}

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

OUTPUT:
enter number rows and columns
2
3
enter a[1][1] element
1
enter a[1][2] element
2
enter a[1][3] element
3
enter a[2][1] element
4
enter a[2][2] element
5
enter a[2][3] element
6
the DDA elements are
1 2 3 4 5 6
the biggest element is = 6
the biggest elementlocation is a[2][3]=6
the smallest elment is=1
the smallest elmentlocation is a[1][1]=1

Functions with 2 dimensional arrays:-

Syntax for calling function (or) function call ():-

function _name(arrayname,rowsize,columnsize);
 function definition(called function)
returntype function_name(datatype var[ row ][ col ],int m,int n);
 function prototype:-
returntype function_name(datatype var[ row ][ col ],int m,int n);

(or)
returntype function_name(datatype var[ ][ col ],int m,int n);
(or)
returntype function_name(datatype [ ][ col ],int ,int );
(or)
returntype function_name(datatype [ row ][ col ],int ,int );

 Write a program to read & print matrix elements using functions.


void read(int [][5],int,int);
void display(int [][5],int,int);
main()
{
int a[5][5],m,n;
printf("enter the size of the matrix\n");
scanf("%d %d",&m,&n);
read(a,m,n);
display(a,m,n);

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

}
void read(int b[][5],int m,int n)
{
int i,j;
printf("enter matrix elememts\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
}

void display(int b[][5],int m,int n)


{
int i,j;
printf("the matrx elements are\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\t",b[i][j]);
}
OUTPUT:
enter the size of the matrix
2
3
enter matrix elememts
1
2
3
4
5
6
the matrx elements are
1 2 3 4 5 6

 Write a program to find sum of diagnol elements in the matrix.


void read(int [][5],int,int);
void display(int [][5],int,int);
void diagonal(int [][5],int,int);

main()
{
int a[5][5],m,n;
printf("enter the size of the matrix\n");
scanf("%d %d",&m,&n);
read(a,m,n);
display(a,m,n);
diagonal(a,m,n);
}

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

void read(int b[][5],int m,int n)


{
int i,j;
printf("enter matrix elememts\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
}
void read(int [][5],int,int);
void display(int [][5],int,int);
void diagonal(int [][5],int,int);
main()
{
int a[5][5],m,n;
printf("enter the size of the matrix\n");
scanf("%d %d",&m,&n);
read(a,m,n);
display(a,m,n);
diagonal(a,m,n);
}
void read(int b[][5],int m,int n)
{
int i,j;
printf("enter matrix elememts\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
}

void display(int b[][5],int m,int n)


{
int i,j;
printf("the matrx elements are\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\t",b[i][j]);
}
void diagonal(int a[][5],int m,int n)
{
int i,j,sum=0;
if(m==n)
{
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(i==j)
sum=sum+a[i][j];
printf("sum=%d",sum);
}
else
printf("\ngiven matrix is not square matrix\n");
}

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

OUTPUT:
enter the size of the matrix
2
2
enter matrix elememts
1
2
3
4
the matrx elements are
1 2 3 4
sum=5

 Write a program to make the given matrix as unit matrix.


void read(int [][5],int,int);
void display(int [][5],int,int);
void unit(int [][5],int,int);
main()
{
int a[5][5],m,n;
printf("enter the size of the matrix\n");
scanf("%d %d",&m,&n);
read(a,m,n);
printf("before unit matrix\n");
display(a,m,n);
unit(a,m,n);
printf("after unit matrix\n");
display(a,m,n);
}
void read(int b[][5],int m,int n)
{
int i,j;
printf("enter matrix elememts\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
}

void display(int b[][5],int m,int n)


{
int i,j;
printf("the matrx elements are\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\t",b[i][j]);
}

void unit(int a[][5],int m,int n)


{
int i,j;
if(m==n)

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(i==j)
a[i][j]=1;
else
a[i][j]=0;
}
else
printf("\ngiven matrix is not square matrix\n");
}
OUTPUT:
enter the size of the matrix
2
2
enter matrix elememts
1
2
3
4
before unit matrix
the matrx elements are
1 2 3 4
after unit matrix
the matrx elements are
1 0 0 1
 Write to interchange the given two row elements in a matrix.
Void interchange(int a[][5],int m,int n)
{
int I,j,r1,r2,temp;
printf(“enter the rows to be interchanged\n”);
scanf(“%d %d”,&r1.&r2);
if(r1<1 || r1>m || r2<1 || r2>n)
{
printf(“invalid row numbers\n”);
return;
}
for(j=0;j<n;j++)
{
temp = a[r1 -1][ j ];
a[r1 -1][ j ] = a[r2 -1][ j ];
a[r2 -1][ j ] =temp;
}
}
 Write to transpose a given matrix.
Void tranpose(int a[][5],int m,int n)
{
int b[5][5],I,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
b[ j ][ I ]= a [ I ] [ j ];

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf(“ the resultant matrix\n”);


display(b,m,n);
}
 write a program to multiply two matrices.
Void mul(int a[5][5],int b[5][5],int m,int n,int q)
{
int c[5][5],I,j,k;
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf(“the resultant matrix is\n”);
display(c,m,q);
}
 Write a program to add two matrices.
Void add(int a[5][5],int b[5][5],int m,int n,int q)
{
int c[5][5],I,j,k;
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
c[i][j]=0;
{
c[i][j]=c[i][j]+a[i][j]*b[i][j];
}
}
printf(“the resultant matrix is\n”);
display(c,m,q);
}

 A menu driven program with the options(using DDA)


1) To perform A+B.
2) To perform AXB.
3) To find transpose of matrix A.
4) To check A=B or not.
Where A and B are the matrices. conditions related to the size to be tested.

#include<stdio.h>
void read(int [][],int,int);
void display(int [][],int,int);
void add(int [][],int,int,int [][],int,int);
void mul(int [][],int [][],int ,int,int);
void trans(int [][],int,int);
void check(int [][],int [][],int,int);

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

main()
{
int a[5][5],b[5][5],m,n,p,q,i,j,choice;
do
{
printf("\n1.Read\n2.A+B\n3.AxB\n4.Transpose\n5.Check A=B\n6.exit");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:printf(" Enter the A matrix size:");
scanf("%d%d",&m,&n);
printf("Enter A matrix elements:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

printf(" Enter the B matrix size:");


scanf("%d%d",&p,&q);
printf("Enter B matrix elements:");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);

printf("A matrix elements are:\n");


display(a,m,n);
printf("B matrix elements are:\n");
display(b,p,q);
break;
case 2:if(m==p&&n==q)
add(a,m,n,b,p,q);
else
printf("Addition is not possible:");
break;
case 3:if(n==p)
mul(a,b,m,n,q);
else
printf(" Multiplication is not possible:");
break;
case 4:trans(a,m,n);
break;
case 5:if(m==p&&n==q)
check(a,b,m,n);
else
printf("Not equal");
break;
case 6:exit(0);
break;
}
}while(choice!=6);
}

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

void add(int a[5][5],int m,int n,int b[5][5],int p,int q)


{
int c[5][5],i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("The resultant matrix is:");
display(c,m,n);
}

void mul(int a[5][5],int b[5][5],int m,int n,int q)


{
int c[5][5],i,j,k;
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("The resultant matrix is:");
display(c,m,q);
}

void trans(int a[5][5],int m,int n)


{
int b[5][5],i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
b[j][i]=a[i][j];
printf("The resultant matrix is:");
display(b,n,m);
}

void check(int a[5][5],int b[5][5],int m,int n)


{
int i,j,c=0;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(a[i][j]==b[i][j])
c++;
if(c==m*n)
printf(" Both the matrices are equal:");
else
printf(" Not equal");
}

10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

void display(int a[5][5],int m,int n)


{
int i,j;
for(i=0;i<m;i++)
{ printf("\n");
for(j=0;j<n;j++)
{
printf("%d ",a[i][j]);

}
printf("\n");
}

11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

FUNCTIONS

Function:- A function is a collection of statements (or) group of statements enclosed in


curled braces provides specified task.
Syntax :- return type function_name( [args] )
{
statement 1;
statement 2;
…………….
…………….
statement n;
}

Declaration: Return type function_name(arguements);


Here function_name indicates name of function and return type indicates the type of
value returned by function. The arguments indicate the values which are received by the
function. Args are optional.
 A function must contain at least one executable statement. Other wise that
function is called as dynamic function.
 In the c-program execution starts 1st statement in the main function, the closing
brace of main function is the logical end of c-program.
 In c language, we can write any no.of functions but there must be only one main
function.

Functions

Pre-defined functions. user defined functions.


(or)
System built functions.
(or)
Built-in functions.
(or)
Library functions.

Advantages of functions:-
1) Code of the program is reduced.
2) Time saved.
3) Memory consumption is also reduced.
4) Readability of program also increases.
5) Error checking is minimized.

 main()
{
printf(“main function\n”);
one();
two();
three();
}
void one()
{

11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

printf(“one\n”);
}
void two()
{
printf(“two\n”);
}
void three()
{
printf(“three\n”);
}

 Code reusability:-
void line();
main()
{
printf(“ countries\n”);
line();
printf(“India \t usa \n”) ;
line();
printf(“new delhi \t washington \n”);
}
void line()
{
int I;
for(i=1;i<=10;i++)
printf(“-------------“);
}
Function prototype:- It defines a template which instructs the compiler about the details
of function, such as the name of the function, the no.of arguments the function is taking
and the type of arguments and the type of value returned by the function.

Different types of writing functions:-


1) functions with no arguments and no return value.
2) functions with arguments and no return value.
3) functions with no arguments and return value.
4) functions with arguments and return value.

 Write a program to add two numbers.


void add();
main()
{
add();
}
void add()
{
int a,b;
printf(“enter two numbers\n”);
scanf(“%d %d”,&a,&b);
printf(“sum=%d”,a+b);
}

11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

 Write a program to print given no is even or odd.


void evenodd();
main()
{
evenodd();
}
void evenodd()
{
int n;
printf(“enter the number\n”);
scanf(“%d ”,&n);
if(n%2==0)
printf(“given no %d is even”,n);
else
printf(“given no %d is odd”,n);
}

 Write a program to find factorial of a given number.

void fact();
main()
{
fact();
}
void fact()
{
int n,fact=1,m;
printf("enter the number\n");
scanf("%d",&n);
for(m=n;n>0;fact=fact*n,n--)
{
}
printf("factorial of %d is %d",m,fact);
}

OUTPUT:

enter the number


5
factorial of 5 is 120

 Write a program to find given number is prime or not.

void prime();
main()
{
prime();
}

11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

void prime()
{
int n,i=2,c=0;
printf("enter the number\n");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
c++;
}
if(c==0)
printf("%d is prime",n);
else
printf("%d is not prime",n);
}

OUTPUT:
enter the number
7
7 is prime
enter the number
4
4 is not prime

II type

void add(int a,int b);


main()
{
int a,b;
printf(“enter the values for a and b\n”);
scanf(“%d %d”,&a,&b);
add(a,b);
}

void add(int x,int y)


{
printf(“sum=%d”,x+y);
}

void evenodd(int n);


main()
{
int n;
printf(“enter a number\n”);
scanf(“%d”,&n);
evenodd(n);
}
void evenodd(int n)

11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

{
if(n%2==0)
printf(“%d is even”,n);
else
printf(“%d is odd”,n);
}
III type
void factorial(int n,int fact,int m);
main()
{
int n,fact=1,m;
printf("enter a number\n");
scanf("%d",&n);
factorial(n,fact,m);
}
void factorial(int n,int fact,int m)
{
for(m=n;n>0;fact=fact*n,n--)
{
}
printf("factorial of %d is %d",m,fact);
}
OUTPUT:
enter a number
5
factorial of 5 is 120
III type
void prime(int n,int i,int c);
main()
{
int n,i=2,c=0;
printf("enter the number\n");
scanf("%d",&n);
prime(n,i,c);
}
void prime(int n,int i,int c)
{
for(i=2;i<n;i++)
{
if(n%i==0)
c++;
}
if(c==0)
printf("%d is prime",n);
else
printf("%d is not prime",n);
}

OUTPUT:
enter the number
7

11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

7 is prime
enter the number
4
4 is not prime

IV type :

void avg();
main()
{
avg();
}
void avg()
{
int a,b,c;
float avg;
printf("enter the values of a,b,c\n");
scanf("%d %d %d",&a,&b,&c);
avg=(a+b+c)/3.0;
printf("average is %f",avg);
}

OUTPUT:

enter the values of a,b,c


3
6
9
average is 6.000000

II type :
void average(int a,int b,int c,float avg);
main()
{
int a,b,c;
float avg;
printf("enter the values of a,b,c\n");
scanf("%d %d %d",&a,&b,&c);
average(a,b,c,avg);
}
void average(int a,int b,int c,float avg)
{
avg=(a+b+c)/3.0;
printf("average is %f",avg);
}

OUTPUT:
enter the values of a,b,c
2
6

11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING

5
average is 4.333333
I – TYPE II - TYPE

void addition(); void addition(int a,int b);


main() main()
{ {
addition(); int a,b;
} printf("enter the values a and
void addition() b\n");
{ scanf("%d %d",&a,&b);
int a,b; addition(a,b);
printf("enter the values a and }
b\n"); void addition(int a,int b)
scanf("%d %d",&a,&b); {
printf("sum is %d",a+b); printf("sum is %d",a+b);
} }
OUTPUT:
enter the values a and b OUTPUT:
3
5 enter the values a and b
sum is 8 4
6
sum is 10
III – TYPE
int addition(); IV – TYPE
main()
{ int addition(int a,int b);
int sum; main()
sum=addition(); {
printf("sum=%d",sum); int a,b;
} printf("enter 2 numbers\n");
int addition() scanf("%d %d",&a,&b);
{ printf("sum=%d",addition(a,b));
int a,b,c; }
printf("enter 2 numbers\n"); int addition(int x,int y)
scanf("%d %d",&a,&b); {
c=a+b; return(x+y);
return c; }
}
OUTPUT:
OUTPUT:
enter 2 numbers
enter 2 numbers 9
4 31
9 sum=40
sum=13

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

I – Type : In this case the functions doesn’t contain any arguments as well as the no return
values.
II – Type : In this case the functions will accept the arguments and doesn’t contains any return
values.
III – Type : In this case the functions will accept the arguments and it contains the return values.

I – TYPE
void factorial();
main()
{
factorial();
}
void factorial()
{
int n,fact=1,m;
printf("enter a number\n");
scanf("%d",&n);
for(m=n;n>0;fact=fact*n,n--)
{
}
printf("factorial of %d is %d",m,fact);
}

OUTPUT:
enter a number
6
factorial of 6 is 720

II - TYPE
void factorial(int n,int fact,int m);
main()
{
int n,fact=1,m;
printf("enter a number\n");
scanf("%d",&n);
factorial(n,fact,m);
}
void factorial(int n,int fact,int m)
{
for(m=n;n>0;fact=fact*n,n--)
{
}
printf("factorial of %d is %d",m,fact);
}

OUTPUT:
enter a number
4
factorial of 4 is 24.
Global variable:- It is a variable which is declared outside of all the functions in the program.

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Once a variable is declared as global, it’s life time is present during the entire program.
A global variable is known to every function in the program and it’s value can be
accessed, modified by any function.

int x;
void one();
void two();
main()
{
x=10;
printf(“ x in main=%d”,x);
one();
two();
}
void one()
{
x=20;
printf(“ x in one=%d”,x);
}

void two()
{
x=30;
printf(“ x in two=%d”,x);
}


int x;
void one();
void two();
main()
{
x=10;
printf("x in main is %d\n",x);
one();
two();
printf("x in main is %d\n",x);
}
void one()
{
int x=20;
printf("x in one is %d\n",x);
}
void two()
{
int x=30;
printf("x in two is %d\n",x);
}

OUTPUT:

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

x in main is 10
x in one is 20
x in two is 30
x in main is 10

When local variable and global variable are having the same name, then in the function in which
the local variable is declared, the global variable will not be effected that means local variable is
given highest priority than global variable.

Constant variable:- It is a variable whose value cannot be changed in the program. When a
variable is declared as a constant, we have to give initial value to that variable at the time of it’s
declaration.

Syntax: - const datatype variable_name;


(or)
const datatype variable_name=value;

ex:- main()
{
Const float pie=3.141592;
Printf(“pie=%f”,pie);
}

Static variable:- A static variable is variable which retains (or) gets it’s value between the
function calls. A Static variable initialized to zero when it is declared.
Syntax: Static datatype variable_name;
Ex:- static int x;
static float y;
static char c;

Void display();
main()
{
Int I;
for(i=1;i<=10;i++)
display();
}
void display()
{
static int count=1;
printf(“%d\t”,count);
count++;
}
OUTPUT:-

1 2 3 4 5 6 7 8 9 10

To pass arguments to a function:-

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

There are two ways in which we can pass arguments through a function
1) call by value mechanism
2) call by reference mechanism

call by value:- In call by value mechanism, when arguments are passing through called function,
then duplicate copies of actual arguments are created and those values are passed to called
function.
If any modification is done in the called function then those changes will effect only to
the variables which are declared in that function, those changes will not affect the actual
arguments because only values are passed to that function but not their addresses.

void exchange(int,int);
void main()
{
int a=10,b=20;
printf("before a=%d \t b=%d\n",a,b);
exchange(a,b);
printf("after a=%d \t b=%d\n",a,b);
}
void exchange(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
OUTPUT:
before a=10 b=20
after a=10 b=20

 calling convention:- calling convention indicates the order in which the arguments are passed
to called function. Then the ‘c’ language follows is 2nd order

1st order – LR.


nd
2 order – RL.
int main(void)
{
int a=10;
printf("%d \t %d \t %d",a,++a,a++);
}

OUTPUT:

12 12 10

Call by reference:- In this mechanism, the values of actual arguments are not passed to the
called function but their addresses are passed through the called function. Then any

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

modification which is done in the actual function will affect the actual arguments that is present
in the calling function, why because the parameters in the called function are now pointing to
the arguments present in the called function.

Ex:-

void exchange(int *,int *);


int main(void)
{
int a=10,b=20;
printf("before a=%d \t b=%d\n",a,b);
exchange(&a,&b);
printf("after a=%d \t b=%d\n",a,b);
}
void exchange(int *p,int *q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}

OUTPUT:
before a=10 b=20
after a=20 b=10

Default arguments:-

#include<stdio.h>
void display( int =10,int =50,int =100);
int main()
{
display(10,20,30);
display(10,20);
display(10);
display();
}
void display(int a, int b,int c)
{
printf("%d %d %d\n",a,b,c);
}

OUTPUT:
10 20 30
10 20 100
10 50 100
10 50 100
 note: -this program works in .cpp environment only.

Default arguments must be given from right to left.


Parameters/Arguments

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

1) Actual parameters/arguments.
2) Formal parameters/arguments.
3) Dummy parameters/arguments.

Actual parameters:- Actual parameters are the parameters that are present in the calling
function, and these values are passed to called function when that function is called.

Formal parameters:- Formal parameters are present in the called function, and are used to
receive the values that are passed from calling function when that function is called.

Dummy parameters:- Dummy parameters are present in the function prototype, since they don’t
receive any values, the arguments in the function prototype are called dummy parameters.
Ex:- void display(int,float,char) // here int, float,char are dummy parameters.
main()
{
display(10,3.4,’+’); // here 10,3.4,+ are actual parameters.
}
void display(int a,float b,char c)
{
Printf(“%d %f %c”,a,b,c); //here int a,float f, char c are formal parameters.
}

Argument:- It is a value present in the calling function, which is passed to called function.

Parameter:- It is a variable present in called function to receive the value from calling function.

Void:-
1) The “void” keyword that is present before the function definition specifies that, that
function is not going to return any value.
2) The void keyword that is present in the parenthesis of a function indicates that the
function doesn’t take any arguments.
Ex:-
void hello(void); (or) void hello()
main() main()
{ {
hello(); hello(void);
} }
void hello() void hello(void)
{ {
printf(“hello”); printf(“hello”);
} }

Default return type:- the default return type of any function in c- language is “int”.

Local variables:- A variable which is declared in a function becomes local to that function. The
scope and lifetime of the local variable will be in existence only when the function is running in
which it is declared.

Ex:- void hello();


main()

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

{
Int x=10;
printf(“x in main=%d”,x);
hello();
}
void hello()
{
Int y=20;
printf(“ y in hello is %d”,y);
}

 Here x & y are local variables. X belongs to only main function and y belongs to only hello
function.

Recursion:- Recursion is the process in which a function calls itself.


(or)
A function is said to be recursive if there is a statement in that function which calls the same
function.

Recursion is called as “circular definition”.


There are 2 types of recursions are available.
1) Direct recursion 2) indirect recursion.

When a program is done using recursion, then there must be any if statement written in that
function which is used to break the recursion process i.e. to exit from the function. Otherwise,
that the function is executed infinite times.


main()
{
int n,fact,m;
printf("enter a number\n");
scanf("%d",&n);
m=n;
for(fact=1;n>=1;n--)
fact=fact*n;
printf("factorial of %d is %d",m,fact);
}

OUTPUT:

enter a number
5
factorial of 5 is 120

recursion:

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

int factorial(int);
main()
{
int n,fact;
printf("enter a number\n");
scanf("%d",&n);
fact=factorial(n);
printf("factorial of %d is %d",n,fact);
}
int factorial(int n)
{
int f;
if(n==1)
return 1;
else
f=n*factorial(n-1);
return f;
}
OUTPUT:

enter a number
6
factorial of 6 is 720
 Write a program to find sum of digits of a given number using recursion.
main()
{
int n,a,sum=0;
printf("enter a number\n");
scanf("%d",&n);
while(n>0)
{
a=n%10;
sum=sum+a;
n=n/10;
}
printf("%d",sum);
}
OUTPUT:

enter a number
113
5

Recursion:
int sumd(int);
main()
{
int n,sum=0;
printf("enter a number\n");
scanf("%d",&n);
sum=sumd(n);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

printf("the sum of digits %d is %d\n",n,sum);


}
int sumd(int n)
{
int sum;
if(n==0)
return 0;
else
sum=n%10+sumd(n/10);
return sum;
}
OUTPUT:

enter a number
123
the sum of digits 123 is 6

 Write a program to print Fibonacci numbers upto given number.

void fib(int,int,int);
main()
{
int n;
printf("enter a number\n");
scanf("%d",&n);
fib(0,1,n);
}
void fib(int a,int b,int n)
{
int c;
c=a+b;
if(c>n)
return;
else
{
printf("%d\t",c);
a=b;
b=c;
fib(a,b,n);
}
}

OUTPUT:
enter a number
8
1 2 3 5 8

 Write a program to print GCD of given two numbers.


#include<stdio.h>

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

main()
{
int m,n,res;
printf("enter the values for m and n\n");
scanf("%d %d",&m,&n);
res=gcd(m,n);
}
gcd(int m,int n)
{
if(m%n==0)
printf("the gcd is %d",n);
else
gcd(n,m%n);
}
OUTPUT:
enter the values for m and n
45
9
the gcd is 9

Storage classes in C language:

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

A variable is considered to a name given to the memory location in which a constant


value can be stored. To define a variable, it is not sufficient to specify the data type of the
variable, but also we must specify storage class for the variable. The data type specifies which
type of value it can store. when a variable is given some value, that value can be stored in two
locations in the system. One is memory and the other location is CPU registers. Now storage
class specifies at which location the variable value is to be stored.

The storage class specifies the following:

1. Where the variable could be formed.


2. The default/initial value the variable is taking.
3. The scope of the variable: scope indicates in which block or in which function the variable can
be formed.
4. The life time of the variable: lifetime indicates how long the variable exists in that function (or)
in that block.

Types of storage classes:

1. automatic storage class


2. register storage class
3. static storage class
4. extern storage class

Automatic storage class:

When a variable is declared under automatic storage class then that variable value is
stored in memory, the variable by default contains garbage value.

The scope of that variable is present only in that function or in that block, in which it is
declared.

The lifetime of that variable will remain in existence only when the block (or) the function
is running in which a variable is declared.

Auto keyword is used to specify automatic storage class.


#include<stdio.h>
main()
{
auto int i=1;
{
auto int j=2;
printf(“%d”,j);
printf(“%d”,i);
}
printf(“%d”,j);/*it will not because j is not declared in the main block*/
printf(“%d”,i);
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

OUTPUT:
2
1
error
1

Automatic storage class:


Storage: memory
Default value: garbage value
Scope: in block,function in which it is declared.
Lifetime: exists only when block ,function is running.

Register storage class:

Variables which are declared under this class are accessed faster than variables which
are declared using other storage classes.
Register storage class is used whether we require retrival of variables value faster.
In general, register storage class are used to develop loop counter variables.
Register storage class is not used for all the data types, it is used only for integers and
character values.
Because register has a capacity of max 16bits, registers cannot hold the values of float,
double, and long double.

Storage: CPU register


Default value: garbage value
Scope: in block, function in which it is defined.
Lifetime: exists only when block, function is running.

Example:
#include<stdio.h>
main()
{
register int a=1;
{
register int a=2;
printf(“%d”,a);
}
printf(“%d”,a);
}

OUTPUT:

2 1

Static storage class:

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Storage: memory
Default value: zero
Scope: local to block, function in which it is defined.
Lifetime: persists value between function calls.
Example:
#include<stdio.h>
main()
{
static int a=1;
{
static int a=2;
printf(“%d”,a);
}
printf(“%d”,a);
}

OUTPUT:
2 2

Extern storage class:

Extern keyword is used to declare variables under external storage class.


When variables are declared using extern, they becomes global variables that means their value
can be accessed during entire program.

Storage: memory
Default value: zero
Scope: global (during entire program)
Lifetime: exists during the entire program.

Example:
#include<stdio.h>
extern int x;
void one();
main()
{
printf(“%d\n”,x);
x=100;
one();
}
void one()
{
printf(“%d”,x);
}
OUTPUT:

0
100
STRINGS

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

A string is a collection of characters/ group of characters that ends with a null character.
A string is an array of characters that ends with a null character.
Ex: India
The null character is present at the end of string/ character array.
The null character is represented by ‘\0’.
The ASCII value of null character is zero.
The purpose of null character is it indicates that, that is the end of string.

Declaration of character array or string


Syntax: data type arrayname [size];
Char arrayname [size];
Here arrayname indicates name of the character array and size indicates the number of
characters it can store.

Ex: char a[10];


Char b[20];

Initialization of character array or strings:


1. Compile time initialization.
2. Run time initialization.

Compile time initialization :

Char name[10]=”RVRJC”;
Char name[ ]=”RVRJC”;
Char name[10]={‘R’,’V’,’R’,’J’,’C’};
Char name[ ]={‘R’,’V’,’R’,’J’,’C’};

Write a program to read a string and print the string in different ways
#include<stdio.h>
main()
{
char name[]="India";
int i;

for(i=0;i<5;i++)
printf("%c",name[i]);

for(i=0;name[i]!='\0';i++)
printf("%c",name[i]);

printf("%s",name);

puts(name);
}
Output:

India India India India

Run time initialization:


#include<stdio.h>

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

main()
{
char str[20];
for(i=0;i<10;i++)
scanf(“%c”,&str[i]);
puts(str);

scanf(“%s”,&str);
puts(str);

scanf(“%s”,str);
puts(str);

gets(str);
puts(str);
}

NOTE: If the no of characters entered in the string is lessthan the string size, then
compiler places a null character at the first empty location in the string.
Ex: char str[10]=”RVR”;

STRING LIBRARY FUNCTIONS:


1. strlen() ---- string length
2. strcpy()---- string copy
3. strcat() ---- string concatenation
4. strrev() --- string reverse
5. strcmp()--- string comparison
6. strlwr() --- string lower
7. strupr()--- string upper

strlen(): This function is used to find the length of string.i.e no of characters present in it;
This function return no of characters in the string expect null character.

Syntax: strlen(string);

1. Write a program to find length of string using library function


#include<stdio.h>
#include<string.h>
main()
{
char str[20];
int length;
printf ("\nEnter a string");
gets(str);
length=strlen(str);
printf("Length of string=%d",length);

OUTPUT

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Enter a string : kishore


Length of string=7

2. Write a program to find length of string with out using library function

#include<stdio.h>
main()
{
char str[20];
int i,length=0;
printf("\nEnter a string");
gets(str);

for(i=0;str[i]!='\0';i++)
length++;
printf("Length of string=%d",length);

}
OUTPUT
Enter a string : krishna
Length of string=7

strcpy () :- This function is used to copy contents of one string into another string.
Syntax:- strcpy(string1,string2);
Destination source
3. Write a program to copy one string into another string using library function.
#include<stdio.h>
#include<string.h>
main()
{
char str[10],temp[10];
printf(“\nEnter a string:”);
gets(str);
strcpy(temp,str);
puts(str);
puts(temp);
}
OUTPUT
Enter a string: Anil kumar
Anil kumar
Anil kumar

4. Write a program to copy one string into another string without using library function.
#include<stdio.h>
main()
{
char str[10],temp[10];
int i;
printf(“\nEnter a string:”);
gets(str);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

for(i=0;str[i]!=’\0’;i++)
{
temp[i]=str[i];
}
temp[i]=’\0’;
puts(str);
puts(temp);
}
OUTPUT
Enter a string: Anil kumar
Anil kumar
Anil kumar

strcat():- This function is used to concatenate two string values i.e. contents of one string are
attached with the contents of another string.
Syntax:- strcat(string1,string2);
Here contents of string2 are append to contents of string1.

The string concatenation function replaces the null character in the first string and appends the
second string from that point onwards.

5. Write a program to concatenate two strings using library function.


#include<stdio.h>
#include<string.h>
main()
{
char s1[30]=”ABC”,s2[30]=”DEF”,s3[30]=”GHI”;
strcat(s1,s2);
strcat(s1,s3);
puts(s3);
puts(s2);
puts(s1);
}
OUTPUT
GHI
DEF
BCDEFGHI

6. Write a program to concatenate two strings with out using library function.
#include<stdio.h>
main()
{
char s1[30]=”ANIL”,s2[30]=”KUMAR”,s3[30]=”ARUN”;
int i,j;
for(i=0;s1[i]!=’\0’;i++)
{}
for(j=0;s2[j]!=’\0’;j++)
{
s1[i]=s2[j];
i++;

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

}
for(j=0;s3[j]!=’\0’;j++)
{
s1[i]=s3[j];
i++;
}
s1[i]=’\0’;
puts(s1);
}
OUTPUT
ANILKUARARUN

strrev():-this function is used to reverse the contents of given string.


Syntax:- strrev(string);
7. Write a program to reverse the contents of a string using library function
#include<stdio.h>
#include<string.h>
main()
{
char str[20];
puts(“Enter a string :”);
scanf(“%s”,str);
puts(“Before reverse:”);
puts(str);
strrev(str);
puts(“After reverse”);
puts(str);
}

OUTPUT
ANIL
LINA
8. Write a program to reverse the contents of a string without using library function
main()
{
char str[20],temp;
int i,j,length;
puts(“Enter a string :”);
scanf(“%s”,str);
length=strlen(str);
for(i=0,j=length-1;i<j;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
puts(str);
}

OUTPUT
ANIL

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

LINA

strcmp():- This function is used to compare two string values whether they are equal, which one
is bigger or smaller string. This function returns zero value if both strings are equal, it returns
less than zero value or negative value, if the first string is less than second string. it returns
greater than zero value if the first string is greater than second string.
Syntax:- strcmp(string1,string2);
It performs comparison on the two strings based on the ASCII value of the characters
present in the string.

9. Write a program to compare two strings using string library functions


#include<stdio.h>
#include<string.h>
main()
{
char str1[20],str2[20];
int n;
printf(“Enter string1:”); gets(str1);
printf(“Enter string2:”); gets(str1);
n=strcmp(str1,str2);
if(n==0)
printf(“Both strings are equal:”);
else if(n>0)
printf(“string1 is greater than string2”);
else
printf(‘String1 is less than string2:’);
}
OUTPUT:
Enter string1:ANIL
Enter string2:KUMAR
String1 is less than string2

10. Write a program to compare two strings with out using string library functions
#include<stdio.h>
main()
{
char str1[20],str2[20];
int i,j;
printf(“Enter string1:”); gets(str1);
printf(“Enter string1:”); gets(str1);
i=j=0;
while(str[i]!=’\0’ || str2[j]!=’\0’)
{
if(str1[i]>str2[j])
{
printf(“%s > %s”,str1,str2);
exit(0);
}
else if(str1[i]<str2[j])
{

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

printf(“%s < %s”,str1,str2);


exit(0);
}
else
{
i++;
j++;
}
}
printf(‘Both Strings are equal:’);
}
OUTPUT:
Enter string1:ANIL
Enter string2:KUMAR
String1 lessthan string2.

strlwr():- This function is used to convert uppercase letters in a string into lowercase.
Syntax:- strlwr(string);

11. Write a program to convert a string into lowercase using library function.
#include<string.h>
main()
{
char str[20];
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”);
puts(str);
strlwr(str);
printf(“After conversion:”);
puts(str);
}
OUTPUT:
Enter a string:ANIL
Before conversion: ANIL
After conversion: anil
12. Write a program to convert a string into lowercase using library function.
#include<string.h>
main()
{
char str[20]; int i;
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”); puts(str);
for(i=0;str[i]!=’\0’;i++)
if(isupper(str[i])
str[i]=tolower(str[i]);
printf(“After conversion:”); puts(str);
}
OUTPUT:
Enter a string:ANIL

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Before conversion: ANIL


After conversion: anil

13. Write a program to convert a string into lowercase without -using library function.
#include<stdio.h>
main()
{
char str[20]; int i;
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”); puts(str);
for(i=0;str[i]!=’\0’;i++)
if(str[i]>=’A’ && str[i]<=’Z’)
str[i]=str[i]+32;
printf(“After conversion:”); puts(str);
}
OUTPUT:
Enter a string:ANIL
Before conversion: ANIL
After conversion: anil

strupr():- This function is used to convert lowercase letters in a string into uppercase.
Syntax:- strupr(string);

14. Write a program to convert a string into uppercase using library function.
#include<stdio.h>
#include<string.h>
main()
{
char str[20];
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”);
puts(str);
strupr(str);
printf(“After conversion:”);
puts(str);
}
OUTPUT:
Enter a string:anil
Before conversion: anil
After conversion: ANIL
15. Write a program to convert a string into uppercase using library function.
#include<stdio.h>
#include<string.h>
main()
{
char str[20]; int i;
printf(“\nEnter a string:”);
scanf(“%s”,str);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

printf(“ Before conversion:”); puts(str);


for(i=0;str[i]!=’\0’;i++)
if(islower(str[i])
str[i]=toupper(str[i]);
printf(“After conversion:”); puts(str);
}

OUTPUT:
Enter a string:anil
Before conversion: anil
After conversion: ANIL

16. Write a program to convert a string into uppercase without -using library function.
#include<stdio.h>
main()
{
char str[20]; int i;
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”); puts(str);
for(i=0;str[i]!=’\0’;i++)
if(str[i]>=’a’ && str[i]<=’z’)
str[i]=str[i]-32;
printf(“After conversion:”); puts(str);
}
OUTPUT:
Enter a string:anil
Before conversion: anil
After conversion: ANIL

Passing string to a function


Function prototype:-
Return-type function name(char string name[size]); or
Return-type function name(char [size]); or
Return-type function name(char []);
Calling function:-
Function name(string name);
Called function:-
Return-type function name(char string name[size])
{

}
here ‘size’ is optional.

Write a program to read and print string values using functions.

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

#include<stdio.h>
void read(char [20]);
void display(char []);

main()
{
char str[20];
read(str);
display(str);
}

void read(char s[20])


{
printf("\nEnter a string:");
gets(s);
}

void display(char s[])


{
printf("The string is:");
puts(s);
}

output:
Enter a string: sai krishan
The string is: sai Krishna

Write a program to find whether the given string is palindrome or not?

#include<stdio.h>
void read(char [20]);
void display(char []);
void palindrome(char []);

main()
{
char str[20];
read(str);
display(str);
palindrome(str);
}

void read(char s[20])


{
printf("\nEnter a string:");
gets(s);
}

void display(char s[])


{
printf("The string is:");

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

puts(s);
}

void palindrome(char s[20])


{
int length,c=0,i,j;
length=strlen(s);
for(i=0,j=length-1;i<=j;i++,j--)
if(s[i]==s[j])
c++;
if(c>=length/2)
printf("The string is palindrome:");
else
printf("Not palindrome");
}

output:
Enter a string: madam
The string is: madam
The string is palindrome

Enter a string: sai krishan


The string is: sai Krishna
Not palindrome

Double dimensional character arrays:-


Collection of single character arrays

Syntax:- char variable name[size1][size2]; or


char variable name[row][column];

Here variable name indicates name of the double dimensional character array. Here row size
indicates no of strings it can store and column size indicates the size of each string.

Initialization of double dimensional character arrays:-


Compile time initialization
Run time initialization.
Compile time initialization:-

Char names[10][20]={{‘I’,’N’,’D’,’I’,’A’,’\0’},
{‘A’,’S’,’I’,’A’,’\0’},
{‘E’,’U’,’R’,’O’,’P’,’E’,’\0’}};
char names[][20]={{‘I’,’N’,’D’,’I’,’A’,’\0’},
{‘A’,’S’,’I’,’A’,’\0’},
{‘E’,’U’,’R’,’O’,’P’,’E’,’\0’}};
char names[10][20]={“INDIA”,”ASIA”,”EUROPE”};

char names[][20]={“INDIA”,”ASIA”,”EUROPE”};

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Write a program to print the contents of double dimensional character array in different ways.

#include<stdio.h>
main()
{
char names[][20]={"ASIA","EUROPE","INDIA"};
int i,j;
/* first way*/
for(i=0;i<3;i++)
{
for(j=0;names[i][j]!='\0';j++)
printf("%c",names[i][j]);
printf("\n");
}
/* second way*/
for(i=0;i<3;i++)
{
for(j=0;j<strlen(names[i]);j++)
printf("%c",names[i][j]);
printf("\n");
}

/* third way*/
for(i=0;i<3;i++)
printf("%s\n",names[i]);

/* fourth way*/
for(i=0;i<3;i++)
puts(names[i]);

output:-
ASIA EUROPE INDIA
ASIA EUROPE INDIA
ASIA EUROPE INDIA
ASIA EUROPE INDIA

Run time initialization:-

#include<stdio.h>

main()
{
char names[10][20];
int i,j;
/* first way*/
for(i=0;i<3;i++)
for(j=0;j<10;j++)
scanf("%c",&names[i][j]);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

for(i=0;i<3;i++)
puts(names[i]);

/* second way*/

for(i=0;i<3;i++)
scanf("%s",names[i]);
for(i=0;i<3;i++)
puts(names[i]);

/* third way*/
for(i=0;i<3;i++)
gets(names[i]);
for(i=0;i<3;i++)
puts(names[i]);
}

Write a program to print number of times the given name is present in a double dimensional
character array.

#include<stdio.h>
main()
{
char names[10][20],temp[20];
int i,n,c=0;

printf("\nEnter no of names");
scanf("%d",&n);

for(i=0;i<n;i++)
gets(names[i]);

printf("\nThe names are:");


for(i=0;i<n;i++)
puts(names[i]);

printf("Enter the searching string:");


gets(temp);

for(i=0;i<n;i++)
if(strcmp(names[i],temp)==0)
c++;
if(c>0)
printf("No of times %s occured=%d",temp,c);
else
printf("%s is not found:",temp);
}

Output:-
Enter no of names:4

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Anil
Anil
Sunil
Anil
The names are:
Anil
Anil
Sunil
Anil
Enter the searching string: Anil
No of times Anil occurred=3.

Enter no of names:4
Anil
Anil
Sunil
Anil
The names are:
Anil
Anil
Sunil
Anil
Enter the searching string: Kumar
Kumar is not found.

Double dimensional character arrays with functions:-


Function prototype:-
Return-type function name(char array name[][size],int);
Calling function:-
Function name(array name,no of strings);
Called function:-
Function name(char array name[][size],int n)
{

Write a program to read and print the students names using functions.

#include<stdio.h>
void readnames(char [][20],int);
void displaynames(char [][20],int);

main()
{
char names[30][20];
int n;

printf("\nEnter no of names you want to enter\n");


scanf("%d",&n);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

readnames(names,n);
displaynames(names,n);
}

void readnames(char names[][20],int n)


{
int i;
for(i=0;i<n;i++)
{
printf("Enter %d names",i+1);
scanf("%[^\n]",names[i]);
//gets(names[i]);
}
}
void displaynames(char names[][20],int n)
{
int i;
printf("\nThe names are:\n");
for(i=0;i<n;i++)
puts(names[i]);
}

Write a program to sort the given names alphabetically in ascending order.

#include<stdio.h>
void read(char [][20],int);
void display(char [][20],int);
void sort(char [][20],int);

main()
{
char names[30][20];
int n;

printf("\nEnter no of names you want to enter\n");


scanf("%d",&n);

read(names,n);
printf("Before sorting names are:");

display(names,n);
sort(names,n);
printf("After sorting names are;");
display(names,n);
}

void read(char names[][20],int n)


{

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

int i;
for(i=0;i<n;i++)
{
printf("Enter %d names",i+1);
gets(names[i]);
}
}
void display(char names[][20],int n)
{
int i;
printf("\nThe names are:\n");
for(i=0;i<n;i++)
puts(names[i]);
}
void sort(char names[][20],int n)
{
char temp[20];
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(strcmp(names[j],names[j+1])>0)
{
strcpy(temp,names[j]);
strcpy(names[j],names[j+1]);
strcpy(names[j+1],temp);
}
}

Write a program to sort the given names alphabetically in ascending order according to their
length..

if(strlen(names[j],names[j+1])==0)
{ (same as above)
strcpy(temp,names[j]);
strcpy(names[j],names[j+1]);
strcpy(names[j+1],temp);
}

POINTERS

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

A pointer is a variable, which holds the address of another variable of the same type.

Advantages of pointers

1. Pointers are more efficient in handling arrays and data tables.


2. Pointers can be used to return multiple values from a function via function arguments.
3. Pointers permit references to functions and these by facilitating passing of functions as
arguments to other functions.
4. The use of pointer arrays to character string results in saving of data storage space in
memory.
5. Pointers allow c to support dynamic memory management.
6. Pointers provide an efficient tool for manipulating dynamic data structures, linked lists,
queues, stacks and trees.
7. Pointers reduce length and complexity of programs.
8. Pointers increase the execution speed and these reduce the program execution.

Pointer Declaration: The general syntax for pointer declaration is


Data-type *pointer-name(variable name).
Here * indicates the next one is a pointer variable of type given datatype.
Ex. Int *p; p – location name, 20-value at location, 1000 – location address.

Pointer initialization: The general syntax for pointer initialization is ptr variable name = &variable
name;
Ex: int a=10; Float pi=3.14; char *x;
Int *p; float *q; char r;
P=&a; q=&pi; x=&r;

Declaration and initialization of pointer variable: ex: int a=10; int *p=&a;

Accessing pointer variable:


*ptrvariable name; Here * indicates value at address is pointer variable.
Ex: int a=10; int *p=&a; printf(“%d”,*p);

 #include<stdio.h>
main()
{
int a=10;
int *p=&a;
printf(“address of a=%u\n”,&a);
printf(“address of a=%u\n”,p);
printf(“address of a=%u\n”,&p);
printf(“address of a=%u\n”,a);
printf(“address of a=%u\n”,*(&a));
printf(“address of a=%u\n”,&p);
}
o/p: Address of a =1000
Address of a =1000
Address of a =2000

Value of a =10
Value of a =10

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Value of a =10

 #include<stdio.h>
main()
{
int a=10;
int *p=&a;
int *q=p;
printf(“ a=%d”,a);
printf(“ a=%d”,*(&a));
printf(“ a=%d”,*p);
printf(“ a=%d”,*q);
*q=200;
printf(“ a=%d”,a);
}

 #include<stdio.h>
main()
{
int a=10;
int *p=&a;
int **q=&p;
int ***q=&q;
printf(“ Address of a=%u\n”,&a);
printf(“ Address of a=%u\n”,p);
printf(“ Address of a=%u\n”,*q);
printf(“ Address of a=%u\n”,**r);
printf(“ Address of p=%u\n”,&p);
printf(“ Address of p=%u\n”,q);
printf(“ Address of p=%u\n”,*r);
printf(“ Address of q=%u\n”,&q);
printf(“ Address of q=%u\n”,r);
printf(“ Address of r=%u\n”,&r);
}
o/p: Address of a=1000
Address of a=1000
Address of a=1000
Address of a=1000

Address of p=2000
Address of p=2000
Address of p=3000

Address of q=3000
Address of q=3000

Address of r=4000

 #include<stdio.h>
main()

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

{
int a=10;
int *p=&a;
int **q=&p;
int ***r=&q;
printf(“ a=%d”,a);
printf(“ a=%d”,*(&a));
printf(“ a=%d”,*p);
printf(“ a=%d”,**q);
printf(“ a=%d”,***r);
}
o/p:
a=10
a=10 a=10 a=10 a=10

Passing pointer to a function:

 void fun(int *);


main()
{
int a=10;
fun(&a);
}
void fun(int *p)
{
printf(“a=%d”,*p);
}
o/p:a=10

 void fun(int *);


main()
{
int a=10;
int *p=&a;
fun(&p);
}
void fun(int *q)
{
printf(“a=%d”,*q);
}
o/p:a=10

 void fun(int **);


main()
{
int a=10;
int *p=&a;
fun(&p);
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

void fun(int **q)


{
printf(“a=%d”,**q);
}
o/p:a=10

 void fun(int **);


main()
{
int a=10;
int *p=&a;
int **q=&p;
fun(&q);
}
void fun(int **q)
{
printf(“a=%d”,**q);
}
o/p:a=10

Returning pointers from function:

 int *fun();
main()
{
int *p
p=fun();
printf(“a=%d”,*p);
}
int *fun()
{
int a=10;
return &a;
}
o/p:a=10

 int **fun();
main()
{
int **p
p=fun();
printf(“a=%d”,**p);
}
int *fun()
{
int a=10;*p;
return &p;
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

o/p:a=1264036

 char ***fun();
main()
{
char ***r
r=fun();
printf(“%c”,***r);
}
char ***fun()
{
char s=’+’;
char *p=&s;
char **q=&p;
return &q;
}
o/p:+

Pointer and single dimensional arrays:

 main()
{
int a[5]={10,20,30,40,50};
int i;
for(i=0;i<5;i++)
printf(“%u %d %u %d”,&a[i],a[i],(a+i),*(a+i));
}
a[i]=*a(p+i)
a[0]=*(p)
a[0]=*(1000)
a[0]=10

a[i]=*(a+i)
a[i]=*(1000+2)
a[i]=20

&a[i]=a+i* no. of bytes.


&a[0]=a+0x2 =1000
&a[i]=a+1x2=1002

Any array is also called as constant pointer.

 main()
{
int a[5]={10,20,30,40,50};
int i,*p;
p=&a[0];
for(i=0;i<5;i++)
printf(“%d\n”,p[i]);
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

o/p:10 20 30 40 50

 main()
{
int a[]={10,20,30,40,50};
int i,*p;
p=&a[0]; (or) p=a;
for(i=0;i<5;i++)
{
printf(“%d\n”,p[i]);
p++;
}
}

o/p:10 20 30 40 50

Advantages of pointer over arrays:

 main()
{
char s[10];
char *p;
s=”hello”; * incompatible type argument
p=”hello”
puts(p);

o/p:hello

 main()
{
char s[10]=”hello”,str2[10];
char *s1=”hello”,*s2;
str2=str1; * incompatible type argument
s2=s1;
puts(s1);
puts(s2);

o/p:hello
o/p:hello

Address of operator (&) ampersand:

It returns the address of the variable. The operand may be variable, a constant.
Ex: int n,*m;M=&n;
Hence address of n is assigned to m; This ‘m’ is not a ordinary variable, it is a variable which
holds the address of other variable.

Value at address operator (*) indication or dereferencing operator:

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

It return the value stored at a particular address.


It is also called indication operator.
Ex: int m; int *m;x=*m;
Int n,x,*m;
N=5;m=&n;x=*m;
Hence the value at address of m is assigned to x and m is going to hold the address.

Dynamic memory allocation:-

Memory allocation for variable is two types.


(1) static memory allocation.
(2) Dynamic memory allocation.

Static memory allocation (SMA) :- The process of allocating memory to variables at compile
time is called SMA (or) compile time allocation.

Ex:- int a[10]= {10,20,30};


Int *a={10,20};
Char *s=”hello”;
Float b[5]={0.5,1.1};

These all are static memory allocation.

Int a[3]= {10,20,30,40,50}

0 1 2 3 4
10 20 30 40 50
1000 1002 1004

int a[10]= {10,20};

0 1 2 3 4 5 6 7 8 9
10 20
1000 1002

nd th
in the above figure from 2 cell to 9 cell wastage of memory is arising.

 array has no bounce checking.

Use: - programs work properly by taking all elements.

Disadvantage: - system halts (or) hangs.

Dynamic memory allocation (DMA) :- the process of allocating memory to variables at the
runtime is called DMA (or) runtime allocation.

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Code space

Stack space

Global name space

Separate storage

Free memory (or)


Memory pool (or)
Heap

RAM (Main Memory)  this information given by us is stored in RAM.

Memory management functions:-

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

These files having the header file #include<alloc.h>

Malloc():- this function is used to allocate required no.of bytes to the variable at run time.

Syntax:- pointer_variable = (data type *) malloc(no.of elements * sizeof(datatype));

 int *a;
a=(int *) malloc(5*sizeof(int));
a 0 1 2 3 4
10

1000 1000 1002 1004 1006 1008

5 * 2 = 10 bytes of memory is created and starting address of that is created memory it passed to a.

 float *b;
b=(flaot *) malloc(10* sizeof(flaot));
b 0 1 2 3 4 5 6 7 8 9
10
100 104 108 ……………………………………….
100 10*4= 40 bytes.

 char *c;

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

c=(char *) malloc(20* sizeof(char));

10

2000

0 1 2 3 ………………………………………………..

100 101 …………………………………………………………..

here 20 * 1 = 20 bytes is created.

 Write a program to read and print array elements using DMA.

main()
{
int *a,I,n;
printf(“enter the no.of elements\n”);
scanf(“%d”,&n);
a=(int *) malloc(n * sizeof(int));
printf(“enter the array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i); // &a[i]
printf(“the array elements are\n”);
for(i=0;i<n;i++)
printf(“%d”,*(a+i)); // a[i]
}
Calloc() :- This function is used to allocate required amount of memory to the variable at runtime.
 This function allocates a no. of individual continues memory allocations to the variables.
Syntax: pointer_variable = (datatype *) calloc((no.of elements * sizeof(datatype));

Ex: - int *a;


A= (int *) calloc(5,sizeof(int));

A 0 1 2 3 4
10
100
100 102 104 106 108

Differences between malloc() and calloc() functions:-

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

1.The malloc() allocates entire 1. This function allocates a number of


memory as a single contiguous block
individual contiguous memory
locations.
2. The default memory allocation 2. The default memory allocation
contains garbage values. contain zero

3. malloc() function takes only a 3. calloc() function takes two


single argument. arguments to allocate memory.

4. malloc() in general is used to 4. This function is used to allocate


allocate memory for the basic data memory for the user defined datatypes.
types. Ex: arrays,structures,unions etc.

realloc(): This function is used to allocate memory to the variables again at runtime.

Syntax: pointer variable=realloc(ptrvariable,newmemorysize);

Ex: #include<stdio.h>
#include<stdlib.h>
main()
{
char *s;
s=(char*)calloc(5,sizeof(char));
strcpy(s,”HELLO”);
puts(s);
s=(char *)realloc(s,9);
strcpy(s,”HELLO HAI”);
puts(s);
}
output:
HELLO
HELLO HAI

free(): This function is used to delete or to deallocate the allocated memory for the pointer
variable.

Syntax: free(pointervariable);

Ex: #include<stdio.h>
main()
{
float *a;
a=(float*)malloc(5*sizeof(float));
if(a==NULL)
{
printf(“Memory is not allocated”);
}
else
{

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

printf(“Memory is allocated”);
}
free(a);
}

output:
Memory is allocated.

Pointers and Double dimensional arrays:

Int a[2][2]={{10,20},30,40}};
0 1
A[0] 10 20
A[1] 30 40

10 th address = &a[0][0]=a[0]+1=1000+0*2=1000
20 th address = &a[0][1]=a[0]+1=1000+1*2=1002
30 th address = &a[1][0]=a[1]+1=1004+0*2=1004
40 th address = &a[1][1]=a[1]+1=1004+1*2=1006

Address Values
&a[i][j] =a[i]+j a[i][j]=*(a[i]+j)
=*(a+i)+j =*(j+a[i])
=j+*(a+i) =*(j+*(a+i))
=*(*(a+i)+j)

Ex: #include<stdio.h>
main()
{
int a[3][2]={{10,20},{30,40},{50,60}};
int i;
for(i=0;i<3;i++)
printf(“a[%d] array address=%u”,i,a[i]);
}

output:
a[0] array address=1000
a[1] array address=1004
a[2] array address=1008

Write a program to read and print matrix elements;

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

main()
{
int a[5][5],m,n,i,j;
printf("Enter no of rows and columns:\n");
scanf("%d%d",&m,&n);
printf("Enter matrix elements are:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nThe matrix elements are:");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d",a[i][j]);
}
}

output:
Enter no of rows and columns: 2 2
Enter matrix elements are: 10 20 30 40
The matrix elements are:
10 20
30 40

Write a program to read and print matrix elements using array of pointers and dynamic
memory allocation.

main()
{
int *a[10];
int i,j,m,n;
printf("Enter the size of the matrix:");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
a[i]=(int *)malloc(n*sizeof(int));
printf("Enter matrix elemnts are:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",*(a+i)+j);
printf("\n");
printf("\nthe matrix elements are:");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d",*(*(a+i)+j));
}
}
output:

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Enter no of rows and columns: 2 2


Enter matrix elements are: 10 20 30 40
The matrix elements are:
10 20
30 40

#include<stdio.h>
main()
{
int a[4][2]={{10,20},{30,40}};
int *p,i,j;
//p=a;
p=&a[0][0];
p=a[0];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%d",*(p+i*2+j));
printf("\n");
}
}

output:
10 20
30 40

Pointers and double dimensional character arrays:


(pic remain)
Char names[10][20]={“APPLE”,”BAT”};

Write a program to read and print different strings using pointers and dynamic memory
allocation:

r *)m all oc#include<stdio.h>


main()
{
char *names[10];
int i,n;
system("clear");
printf("\nEnter no of names:");
scanf("%d",&n);
for(i=0;i<n;i++)
names[i]=(cha (20*sizeof(char));
printf("\nEnter names:");
for(i=0;i<n;i++)
{
printf("Enter %d name:",i);
gets(names[i]);
}

printf("\nThe names are:");

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

for(i=0;i<n;i++)
puts(names[i]);

}
output:
Enter no of names:
5
Enter names:
Enter 0 name:ANIL
Enter 1 name:Kumar
Enter 2 name:Kiran
Enter 3 name:Dileep
Enter 4 name:Vasu
The names are:
ANIL
Kumar
Kiran
Dileep
Vasu

Ragged array: Arrays having varying length in columns are called as ragged arrays.

Ex: char *names [10]={“ASIA”,”INDIA”,”UK”};

Write a student data file(rollno, name, rank, date of birth) and code a program

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

with options(use pointers & structures)


(i) Listing names, dob sorted on names
(ii) Listing names, dob sorted on dob
(iii)Listing names, dob sorted on names, dob

#include<stdio.h>
#include<string.h>
struct student
{
char name[10];
int rno;
int rank;
struct dateofbirth
{
int day;
int month;
int year;
}dob;
};
void read(struct student *s[],int);
void display(struct student *s[],int);
void sortnames(struct student *s[],int);
void sortdob(struct student *s[],int);
void sortnamesdob(struct student *s[],int);
void swap(struct student *,struct student *);
main()
{
struct student *s[10];
int i,n,ch;
printf("Enter no of students:\n");
scanf("%d",&n);
while(1)
{
printf("1.Read\n2.Display\n3.Sort by names\n4.Sort by dob\n");
printf("\n5.Sort by names dob\n6.Exit\n");
printf("Enter your choice::\n");
scanf("%d",&ch);
switch(ch)
{
case 1:read(s,n);break; case 2:display(s,n);break;
case 3:sortnames(s,n);break; case 4:sortdob(s,n);break;
case 5:sortnamesdob(s,n);break; case 6:exit();break;
}
}
}

void read(struct student *s[10],int n)

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

{
int i;
for(i=0;i<n;i++)
{
s[i]=(struct student*)malloc(sizeof(struct student));
printf("Enter %d student details:\n",i+1);
printf("Enter name:\n");
scanf("%s",s[i]->name);
printf("Enter Rollno\t Rank\t");
scanf("%d%d",&s[i]->rno,&s[i]->rank);
printf("Enter dob(dd-mm-yyyy)\n");
scanf("%d%d%d",&s[i]->dob.day,&s[i]->dob.month,&s[i]->dob.year);
}
}

void display(struct student *s[10],int n)


{
int i;
printf("The student details are:\n");
printf(" NAME\t ROLLNO\t RANK\t DOB \n");
for(i=0;i<n;i++)
{
printf(" %s %d %d %d-%d-%d\n",s[i]->name,s[i]->rno,s[i]->rank,
s[i]->dob.day, s[i]->dob.month,s[i]->dob.year);
}
}

void sortnames(struct student *s[10],int n)


{
int i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-1;j++)
if(strcmp(s[j]->name,s[j+1]->name)>0)
swap(s[j],s[j+1]);
display(s,n);
}

void swap(struct student *p,struct student *q)


{
struct student temp;
temp=*p;
*p=*q;
*q=temp;
}
void sortdob(struct student *s[10],int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-1;j++)
if(s[j]->dob.year>s[j+1]->dob.year)
swap(s[j],s[j+1]);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

else if(s[j]->dob.year==s[j+1]->dob.year)
{
if(s[j]->dob.month>s[j+1]->dob.month)
swap(s[j],s[j+1]);
else if(s[j]->dob.month==s[j+1]->dob.month)
{
if(s[j]->dob.day>s[j+1]->dob.day)
swap(s[j],s[j+1]);
}
}
display(s,n);
}

void sortnamesdob(struct student *s[10],int n)


{
int i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-1;j++)
if(strcmp(s[j]->name,s[j+1]->name)>0)
swap(s[j],s[j+1]);
else if(strcmp(s[j]->name,s[j+1]->name)==0)
{

if(s[j]->dob.year>s[j+1]->dob.year)
swap(s[j],s[j+1]);
else if(s[j]->dob.year==s[j+1]->dob.year)
{
if(s[j]->dob.month>s[j+1]->dob.month)
swap(s[j],s[j+1]);
else if(s[j]->dob.month==s[j+1]->dob.month)
{
if(s[j]->dob.day>s[j+1]->dob.day)
swap(s[j],s[j+1]);
}
}
}
display(s,n);
}

STRUCTURES

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

A structure is a user defined data type which can store elements of different data types
(or) same data types.

Syntax for declaring structures:-

struct structurename
{
datatype var1;
…..
….
Datatype var2;
}
Eg:- struct student struct employee
{ {
char name[20]; char name[20];
int rno; int id;
}; float salary;
};
Syntax for creating structure variables:-

struct structurename variable;


(or)
struct structurename var1, var2,…..varn;
struct student s1, s2;

S1 S2
name[20] name[20]
rno rno

22 bytes 22 bytes
Accessing structure members:-

struct student
{
char name[20]; members of structures
int rno;
};

struct student s;
(.) dot operator
s.rno;

Structure variable declaration types:-

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

1) sruct structure var1, var2, …..varn;


2) struct structurename
{
datatype var1;
……
……
datatype var2;
}var1, var2, var3,….varn;
3) struct
{
datatype var1;
……
……
datatype var2;
}var1, var2,….varn;

Compile time initialization of structures:-

1) #include<stdio.h>
main()
{
struct student
{
char name[20];
int rno;
};
struct student s1={“aa”,825};
struct student s2={“bb”,826};
printf(“s1 derails \n”);
printf(:%s %d”, s1.name, s1.rno);
printf(“s2 derails \n”);
printf(“%s %d”, s2.name, s2.rno);
}

O/P:-
s1 details S1 S2
aa 825
s2 details Name: aa Name: bb
bb 826 Rno: 825 Rno: 826

2) #include<stdio.h>

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

main()
{
struct student
{
char name{20];
int rno;
}s1={“aa”, 825}, s2={“bb”, 826};
printf(“s1 details \n”);
printf(“ %s %d”,s1.name, s2.name);
printf(“s2 detials \n”);
printf(“ %s %d”, s2.name, s2.name);
}

3) #include<stdio.h>
main()
{
struct
{
char name[20];
int rno;
}s1={“aa”, 825}, s2={“bb”, 826};
printf(“s1 detials \n”);
printf(“%s %d”, s1.name, s1.rno);
printf(“s2 details \n”);
printf(“%s %d”, s2.name, s2.rno);
}

4) #include<stdio.h>
main()
{
struct
{
char name{20];
int rno;
}s1,s2;
strcpy(s1.name, “aa”);
s1.rno=825;
strcpy(s2.name, “bb”);
s2.rno=826;
}

Write a program to find net salary of an employee.


GS = Basic + HRA + DA + TA
Ded = PF + IT
NS = GS – Ded

Array of structures:-

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Syntax:- struct student s[10];

0 1 2 3 9
s

name name
rno rno

 Write a program to read and print no. of student details:

struct student
{
char name[20];
int rno;
};
main()
{
struct student s[20];
int i, n;
printf(“Enter no. of students “);
scanf(“ %d ”, &n);
for (i=0;i<n;i++)
{
printf(“Enter %d student details”, i+1);
printf(“Enter name:”);
gets(s[i].name); (or) scanf(“%s”, s[i].name);
printf(“Enter number:”);
printf(“%d”, &s[i].rno);
printf(“\n The student details are \n”);
for(i=0;i<n;i++)
printf(“%s %d\n”, s[i].name, s[i].rno);
}
}

O/P:-
Enter no. of students: 2
Enter 1 student details:
Enter name aa
Enter rno 825
Enter 2 student details:
Enter name bb
Enter rno 826

Parameter passing mechanism for structure variables (call by value mechanism):-

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

struct student
{
char name[20];
int rno;
}
void change (struct student);
main()
{
struct student s = {“aa”, 825};
printf(“ Before change”);
printf(“%s %d”, s.name, s.rno);
change(s);
printf(“After change”);
printf(“%s %d”, s.name, s.rno);
}
void change (struct student p)
{
strcpy (p.name, “bb”);
p.rno = 826;
}

O/P:-
Before change
aa 825
After change
bb 826

Call by reference mechanism:-

structure definition is same as above


void change (struct student *);

modifications
change (s);

void change(struct student *p)


{
strcpy(p name, “bb”);
p  rno =826;
}

Passing arrays of structures to functions:-

Calling function  functionname (structurename);


Called function  returntype functionname ( struct structurename var[size])
Prototype function  returntype functionname (struct structurename vat[]);

 Write a program to read student details & print them

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

rno); struct student


{
char name[20];
int rno;
}
void read (struct student[], int);
void display(struct student[], int);
main()
{
struct student s[20];

int n;
printf(“Enter no. of students”);
scanf(“%d”, &n);
read(s,n);
display(s,n);
}

void read(struct student s[], int n)


{
int i;
for(i=0;i<n;i++)
{
printf(“Enter %d student details “, i+1);
printf(“ Enter name, rno”);
gets(s[i].name);
scanf(“%d”, &s[i].rno);
}
}
void display (struct student s[], int n)
{
int i;
printf(“ The student details are \n”);
for(i=0;i<n;i++)
printf(“%s %d\n”,s[i].name, s[i].rno);
}

 copying of contents of one structure variable into another structure variable.


1. copying member by member
2. Entire members at a time

Ex:-
struct student
{
char name[20];
int rno;
};

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

main()
{
struct student s={“aa”, 100}, t;
strcpy(t.name, s.name);
t.rno=s.rno;
puts(t.name);
printf(“%d”,t.rno);
}
O/P:-
aa
100

Ex:-
struct student
{
char name[20];
int rno;
};
main()
{
struct student s = {“aa”, 100},t;
t = s;
puts(t.name);
printf(“%d”, t.rno);
}

 Write a program to read student marks and find his average and print the details in the
descending order according to the average.

Struct student
{
char name[20];
int rno;
int m,p,c;
float avg;
};

void read(struct student [], int);


void display(struct student [], int);
void avge(struct student [],int);

main()
{
struct student s[50];
int n;
printf(“Enter number of students\n”);
scanf(“%d”,&n);
read(s,n);
printf(“ Before finding average”);
display(s,n);
avge(s,n);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

printf(“After finding average”);


display(s,n);
}

void read(struct student s[],int n)


{
int i;
for(i=0;i<n;i++)
{
printf(“ Enter name:”);
gets(s[i].name);
printf(“ Enter rno”);
scanf(“ %d”,&s[i].rno);
printf(“ Enter marks\n”);
scanf(“%d%d%d”,&s[i].m,&s[i].p,&s[i].c);
s[i].avg=0;
}
}

void display ( struct student s[], int n)


{
int i;
printf(“ \n The student details are :\n”);
for(i=0;i<n;i++)
printf(“%s%d%f”, s[i].name, s[i].rno, s[i].avg);
}

void avge (struct student s[], int n)


{
int i, j;
struct student temp;
for(i=0;i<n;i++)
s[i].avg=(s[i].m+s[i].p+s[i].c)/3.0;
for(i=0;i<n-1;i++)
for(j=0;j<n-1;j++)
if(s[j].avg<s[j+1].avg)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}

 write a program to find net salary for the number of employees and print them using
functions.

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Returning structures from functions:

struct student
{
char name[20];
Sint rno;
}

struct student fun( );

main( )
{t
struct student p;
p=fun( );
printf(“ %s %d”,p.name,p.rno);
}

struct student fun( )


{
struct student s={“aa”,825};
return s;
}

struct student
{
char name[20];
int rno;
};

struct student **fun();

main( )
{
struct student **q;
q=fun( );
printf(“%s%d”,(*q)->name,(*q)->rno);
}

struct student **fun( )


{
struct student s={“aa”,825};
struct student *p=s;
return &p;
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

write a program to add, sub, mul and div of two complex numbers.

struct complex
{
int real;
int img;
}

struct complexadd(struct complex, struct complex);


struct complexsub(struct complex, struct complex);
struct complexmul(struct complex, struct complex);
struct complexdiv(struct complex, struct complex);

void display( struct complex);

main()
{
struct complex c1,c2,c3,c4,c5,c6,c7;
printf(“ Enter first complex number\n”);
scanf(“%d%d’,&c1.read, &c1.img);
printf(“ Enter the second complex number”);
scanf(“%d%d’,&c2.read, &c.img);
printf(“ c1=”);
display(c1);
printf(“ c2=”);
display(c2);
c3=add(c1,c2);
printf(“c1+c2=”);
display(c3);
c4=sub(c1,c2);
printf(“c1-c2”);
display(c4);
c5=mul(c1,c2);
printf(“c1*c2=”);
display(c5);
c6=div(c1,c2);
printf(“c1/c2”);
display(c6);

}
void display( struct complex c)
{
printf(“%d+i%d”,c1.real,c1.img);
}
struct complexadd(struct complex x, struct complex y)
{
struct complex temp;
temp.real=x.real+y.real;
temp.img=x.img+y.img
return temp;
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

struct complexsub(struct complex x, struct complex y)


{
struct complex temp;
temp.real=x.real-y.real;
temp.img=x.img-y.img
return temp;
}

struct complexmul(struct complex x, struct complex y)


{
struct complex temp;
temp.real=(x.real*y.real)-(x.img)*(y.img);
temp.img=(x.real*y.img)+(x.img)*(y.real);
return temp;
}

struct complexdiv(struct complex x, struct complex y)


{
struct complex temp;
temp.real=((x.real*y.real)-(x.img)*(y.img))/(x.real*x.real)+y2;
temp.img=((x.img*y.real)+(x.real*y.img))/(x.real*x.img)+y2;
return temp;
}

structures within structures:(Nested structures)

structures within structures means nesting of structures

syntax:

struct structurename1
{
datatype var1;
.
.
.
.
datatype varn;
struct structurename2
{
datatype var1;
.
.
.
.
datatype varn;
};
.
.

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

.
.
struct structurename n
{
datatype var1;
.
.
.
.
datatype varn;
};
};

example:

struct student
{
char name[20];
int rno;
struct date
{
int day;
int month;
int year;
};
};

compile time initialization for nested structures

struct student
{
char name[20];
int rno;
struct date
{
int day;
int month;
int year;
};
};

main( )
{
struct student s={“aa”,825,28,3,2008};
printf(“%s %d %d %d %d”,s.name, s.rno, s.day, s.month, s.year);
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

struct student
{
char name[20];
int rno;
struct date
{
int day;
int month;
int year;
};
};

main( )
{
printf(“%s%d-%d-%d”, s.name, s.rno, s.day, s.month, s.year);
}

runtime initialization:
struct student
{
char name[20];
int rno;
struct date
{
int day;
int month;
int year;
}d;
};
main()
{
struct student s;
printf(“ Enter student name”);
gets(s.name);
printf(“Enter roll number”);
scanf(“%d”,&s.rno);
printf(“Enter details:”);
scanf(“%d%d%d”,&s.d.day,&s.d.month,&s.d.year);
printf(“%s%d%d-%d%d”,s.name,s.rno,s.d.day,s.d.month,s.d.year);
}

self –referential structure:


in a structure, if one or more numbers are pointers pointing to the same structure, then this
structure is known as self-referential structure.
Example:
typedef struct vertex
{
int data;
struct vertex *np;
}NODE;

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

struct student
{
char name[20];
int rno;
struct student *next;
};
A self-referential structure is one which contains a pointer to its own type.

Pointer structure:

Syntax: struct structurename *ptrvariable;


Example: struct student *s;

Example1:
Struct student
{
char name[20];
int rno;
};
main()
{
struct student s,*p;
printf(“enter student details\n”);
gets(s.name);/* or gets(p->name); or gets((*p).name);*/
printf(“enter roll number”);
scanf(“%d”,&s.rno);/* &p->rno*/
printf(“\n student details are:\n”);
printf(“%s%d\n”,s.name,s.rno);
printf(“%s%d\n”,(*p).name,(*p).rno);
}
Example2:
Struct book
{
char title[20];
int pages;
float price;
};

main(0
{
struct book B,*p;
p=&B;
strcpy(B.title,” C made easy”);
strcpy(B.author,”Herbert skhildt”);
B.pages=250;
B.price=230.50;
record(p);
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

void record(struct book*p)


{
printf(“ book title:%s\n”,p->title);
printf(“ Author:%s\n”,p->author);
printf(“number of pages:%d\n”,p->pages);
printf(“price:%5.2f\n”,p->price);
}

. (dot)operator is used to access the structure member.

Struct p,*p1;
P1=&p;

Here p1 which is a pointer to a structure is assigned the address of the structure variable
person p.

Accessing structure variables using pointers:

Structure members may be accessed using pointers to structures by the use of special
operators ->(arrow operator).

Struct student
{
char name[20];
int rno;
}

struct student s,*s1;

s1=&s; -> assigns the address of s to s1


s1->name; -> access s name
s1->rno; -> access s rno.

UNIONS:

A union is a user defined data type. Which is used to store elements of different data types.
Syntax:
union name
{
datatype var1;
.
.
datatype varn;
};
union follows the same syntax as structures, and are declared the keyword union.

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Example:
union mem
{
int a;
float b;
char c;
};

in this declaration ‘b’ requires 4 bytes,because it is of float type.This is largest storage for
union.the compiler allocates a storage place to hold enough the largest number.

Struct data union data


{ {
int a; 2 int a; 2
float b; 4 float b; 4(max)
char c; 1 char c; 1
}; };
2b 4b 1b

Struct student
{
char name[20];
int rno;
float marks;
};
main()
{
struct student s;
printf(“size of s=%d”,sizeof(s));
}

union student
{
char name[20];
int rno;
float marks;
};
main()
{
union student s;
printf(“size of s=%d”,sizeof(s));
};

example of self-referential structre

struct student
{
char name[20];
int rno;
struct student *next;
};

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

main()
{
struct student *s;
s=(struct student *) malloc(sizeof((struct student));
strcpy(s->name,”hello”);
s->rno=825;
s->next=(struct student *)malloc(sizeof(struct student));
}

Examples for enum data types:

Enum dept
{
Physics, chemistry, zoology;
}

Program:

#include<stdio.h>
main ()

{
enum day

{
sun,mon,tue,wed,thu,fri,sat;
};
enum day day1;

day1=sat;
If (day1==sat!! day1==sun)
Print (“holyday”);
Else
Printf (“working day”);

day1=3; /* Wednesday */
If (day==0!! day1==6)
Printf (“holiday”);
Else
Printf (“\n working day”);

Typedefit is used to create an alternative name for the data types.

Ex:- 1.int a=10;


Typedef int;
2. Struct student;
Typedef struct student next;

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Null statement: - it is a statement which does nothing.

Eg: void hello ()


main ()
{
Int I;
For (i=0; i<n; i+=)
Hello ();
}
Void hello ()
{
Printf (“hello\n”);
}
2. If (a>0);

3. main ()
{
int I, count=0;
For (i=0;i<10;i++)
{
Count=count+5;
}
Printf (“%d%d”, I, count);
}

Null pointer: - it is a pointer whose value is initialization to zero is called null pointer.

Ex;-main ()

{
Int *p=0;
}

Dazzling pointer:- A pointer whose value is not initialized is know as dazzling pointer.

Enumerated data types: it is used to assign name to constants or giving values to names.
It is represented by keyword –enum;

Eg:- 1.enum{
Off 0;
On 1;
};
2. Enum shap
{
Circle 0
Line 1;
Double line 2
Triangle 3;
Square 4;
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

3. Enum
{
White, 0;
Black=100;
Blue;
Green=200;
Red;
Violet;
}

Difference between structures and union:

Structures union

1. Each member occupies its own memory All the memory use the same memory space
Space.
2. Struct keyword in used to define a structure. Union keyword id used to define a
union.
3. All the members can be initialized. Only the first member can be
initialized.
4. The members are stored in continuous the members are stored in continuous
memory locations. locations

 Differences between arrays and structures.

Arrays Structures

1. An array is a single entity representing A structures is a single entity


Items of same data types representing
items of different data types
2. Individual entries in an array are called Individual entries in a structures are called
elements members.
3. An array declaration allocates memory Structure definition allocates
Space for its elements memory space for its members.
4. The elements of an array are stored in the member of a structure are not stored in
Continuous locations continuous memory locations

 What in the use of (.) Operator /member operator/period operator.

Individual members must be linked to the structure variables in order to make then more
meaningful.

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Files
A file is a defined data type used as data structure.
A file is also known as a string.
Files are used to stored data permanently to the external stores devices such as
floppy disc and
Also to read data from external storage devices.

Operations on files:-

------------ Open the file.


------------ Updating a file (read, Write).
------------ Close the file.

File Pointers:

File pointer in the internal name or logical name given to the file which is opened
for specific purpose.

File *filepointername;

Fopen ();- This function is used to open a file in the specified mode.
Syntax:-
File pointer=fopen (“filename”,” opening mode”);

Opening mode indicates

Mode Symbol

Read “r”
Write “w”
Append “a”
Read write “r*”
Write read “w+”

Ex: -- fp=fopen (“student.c”,”r”);

This function returns file descriptor to the file pointer if the file in opened
successfully, otherwise it returns null pointer.

Fclose ():

This function is used to close the opened file.

Syntax:fclose (file pointer);

FILE ACCESSING:
1. Sequential accessing.
2. Random Accessing.

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Sequential access file functions:

1. putc()
2. fputc()
3. getc()
4. fgetc()
5. fputs(0
6. fgets()
7. fprintf()
8. fscanf()
9. fwrite()
10. fread()
11. feof()

Random access file functions:

1. fseek()
2. ftell()
3. rewind()

Putc ():-- This function is used to write character by character into the file.

Syntax: --- putc (character, fp);


Fputc ():--This function is used to write character by character into the file.

Syntax:--fputc (character, fp);


Getc ():--This function is used to read single character from the file.

Syntax:--character variable=getc (fp);


Fgetc ():--This function is used to read single character from the file

Syntax:--character variable=getc (fp);

Write a program to write and read some text into file character by character.

#include<studio.h>

main ()
{
File *fp;
Char ch;
Fp=fopen (“fruits.c”,”w”);
Ch=getchar ();
While (ch! =EOF)
{
Putc (ch, fp);
Ch=getchar ();
}
Fclose (fp);
Fp=open (“fruits.c”,”r”);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Ch=getc (fp);
While (ch! =EOF)
{
Printf (“%c”, ch);
Ch=getc (fp);
}
Fclose (fp);
}

Feof ():--This function is used to indicate end of file. This function returns zero, if the end office
is not reached. This function returns non-zero, if the end of file is reached.

Syntax:-feof (fp);
Fputs ():--This function is used to write a string into the file.

Syntax:-fputs (string, fp);

Fgets ():--This function is used to read a string from the file.

Syntax:- fgets(string,no.characters,fp);

Write a program to write and read contents into the file or to demonstrates fputs () and fgets ().
main ()
{
File **P;
Char str [20];
Int i, n;
Printf (“enter the no of strings :”);
Scanf (“%d:, &n);
Fp=fopen (“fruits.c:,”w”);
` for (i=1;i<=n;i++)
{
Printf (“enter the string”);
gets (str);
fputs (str, fp);
}
fclose (fp);
fp=fopen (“fruite.c”,”r”);
Printf (“The file contents “);
While (! feof (fp))
{
fgets (str, 5, fp);
Printf (“%s”, str);
}
fclose (fp);
}
fprintf ():--This function is used to write formatted input into the file.
Syntax:-fprintf (fp,”format specifiers”, arg1, arg2……argn);
Fscan ():--This function is used to read formatted out put from the file.
Syntax:--fscanf (fp,”formatspecifier”, &arg1, &arg2…&argn);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Write a program to demonstrate fprintf () and scanf ()

#include<stdio.h>
main ()
{
File **p;
Char name [20];
Int rno, rank;
Int I, n;
Printf (“Enter the no. of students”);
Scanf (“%d”, &n);
Fp=fopen (“student.c”,”w”);
For (i=1; i<=n;i++)
{
printf (“Enter the name”);
gets (name);
Printf (“enter the rno, rank”);
Scanf (“%d%d”, &rno, &rank);
fprintf (fp,”%s\t%d\t%d\n”, name, rno, rank);
}
fclose (fp);
fp=fopen (“student.c”,”r”);
fscanf (fp,”%s\t%d\t%d\t”, &name, &rno, &rank);
While (! feof(fp))
Printf (“%s%d%d\n”, name, rno, rank);
fscanf (fp,”%s\t%d\t%d\t”, name, &rno, &rank):
}
}
fwrite ():--This is used to write an entire structure into file.

Syntax:-fwrite (& structure variablename, sizeof (structure), n, fp);

Fread ():--This function is used to read a structure from the file.

Syntax :-( &structure variablename, sizeof (structure), n, fp);

Write a program to demonstrate fwrite () and fread () functions.

Struct student
{
Char name [10];
int rno, rank;
}
main ()
{

Struct student s;
Int i, n, temp;
File *fp;
Fp=fopen (“student.c”,”w”);
Printf (“enter no. of student details”, i+1);

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Scanf (“%d”, &n);


For (i=0; i<=n; i++)
{
printf (“enter the student details”,i+1);
Printf (“enter the name, rno, rank”);
Scanf (“%s%d%d”, s.name,&s.rno,&s.rank );
Fwrite (&s, sizeof (struct student), I,fp);
}
fclose (fp);
Fp=fopen (“student.c”,”r”);
printf (“the student details are”);
fread (&temp, sizeof (struct student), 1,fp);
While (! feop (fp))
{
Printf (“%s%d%d”, temp.name, temp.rno, temp.rank);
fread (%temp, sizeof (struct student), 1, fp);
}
fclose (fp);
}

Random Access files

rewind ():-This function is used to remove the file pointer to the starting position of the file.

Syntax:-rewind (fp);

#include<stdio.h>
main ()
{
File *fp;
Char ch;
Fp=fopen (“country.c”,”r”);
Printf (“file contents are”);
Ch=getc (fp);
While (! feof (fp))
{
putchr (ch);
Ch=gets (fp);
}
rewind (fp);
printf (“Again file contents are”);
ch=getc (fp);
While (! feof (fp))
{
Put char (ch);
ch=getc (ch);
}
fclose (fp);
}

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

ftell ():-this function is used to indicate the position of the file pointer. This function returns
the long integer value.

Syntax:-ftell (fp);

fseek ():-This function is used to move the file pointer either forwards or backwards to the
specified no. of byte the given position.

Syntax:-fseek (fp, offset, position);

Here offset indicates no. of bytes to move from the given position.
Here position can take three values.

0 indicates beginning of the file.


1 current position
2 end of the file.

Ex: - fseek (fp, 0l, 0) move to the begin of the file.


fseek (fp, 0l, 1) file pointer stay at current position.
fseek (fp, 0l, 2) move to the end of file.
fseek (fp, n, 0) move n bytes from the beginning of the file.
Fseek (fp, n, 1)move n bytes from current position.
fseek(fp, -n, 1) move n bytes backwards for current position.
fseek (fp, -n, 2)move n bytes backwards from the end of file.

Ex:- #include<stdio.h>
main()
{
File *fp;
Char ch;
Fp=fopen (“alphabet.c”.”r”);
If (fp==null)
{
Printf (“file is not opened for reading”);
}
n=ftell (fp);
rintf (“fp ps=%d”, n);
fseek (fp, 5, 0);
rintf (“fp pos=%d”, ftell (fp));
fseek (fp, 2, 1);
rintf (“fp pos=%d”, ftellp));
fseek (fp, -7, 2);
rintf (“fp, ol, 0);
printf (“fp pos=%d”, ftell (fp));
}
fclose (fp);
}

Output:

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Fp pos=0;
Fp pos=5;
Fp pos=7;
Fp pos=19;
Fp pos=0;

Command Line Arguments:

The arguments which are given at the command prompt and are passed to the main function.

Syntax:-Main (int argc, char *argv [ ]);


{
-----
------
}

Here argc contain no. of arguments given at the command prompt. Argc is called
count. Argv is known as argument vector, which contains the arguments given at
the command prompt starting from zero.

Write a program to print arguments given at the command prompt.

main (int argc, char *argv [])


{
Int i;
Printf (“no. of arguments =%d”, argc);
Printf (“Arguments are”);
For (i=0;i<argc;i++)
puts (argv[i]);
}

$ Anil red blue green


Out Put:
No. of arguments =4:
Argv[0]Anil
Red
Blue
Green

11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.

Write a program to copy contents of one file into another file using command line arguments.

#include<stdio.h>
main (int argc, char *argv[])
{
File *fp1,*fp2;
Char ch;
If (argc!=3)
{
printf (“In sufficient no. of arguments”);
exit (0);
}
fp1=fopen (argv[1],”r”);
if (fp1==NULL)
{
Printf (“source file not opened”);
exit (0);
}
fp2=fopen (arg [2],”w”);
If (fp2==null)
{
Printf (“destination file is not appended”);
Exit (0);
}
ch=getc (fp1);
While (! feof (fp1))
{
Putc (ch, fp2);
ch=getc (fp1);
}
fclose(fp1);
fclose(fp2);

11

You might also like