You are on page 1of 147

VAISHNAVI ACADEMY

C
PROGRAMMING
First Year Engineering
Semester II – Common to all Branches

By Nitin Sir

Nitin Sir
Module Detailed Content Hrs.
01 Introduction to Computer, Algorithm and 06
Flowchart.
1.1 Basic of computer : Turing Model, Von
Neumann Model, Basics of Positional
Number Systems, Introduction to
Operating Systems and component of an
operating system.
1.2 Algorithm & Flowchart: Three construct
of algorithm and flowchart : Sequence,
Decision and reparation.
02 Fundamentals of C-Programming 06
2.1 Character set, Identifier and Keywords,
Data types, Constants, Variables.
2.2 Operators: Arithmetic, Relational and
Logical, Assignment, Unary, Conditional,
Bitwise, Comma, other operators.
Expression, Statements, Library functions,
Pre-processor.
2.3 Data Input and Output: getchar(),
putchar(), scanf(), printf(), gets(), puts().

03 Control Structures 12
3.1 Branching: If statement, if-else statement,
multiway decision.
3.2 Looping: while, do-while, for
3.3 Nested control structure : switch
statement, continue statement break
statement, goto statement
04 Functions and Parameter 06
4.1 Function: Introduction of function,
function main, defining a function,
accessing a function, function prototype,
passing arguments to a function, recursion.
4.2 Storage Classes: auto, externs, static,
register.

Nitin Sir Page 1


05 Arrays, Strings, Structure and Union 14
5.1 Array: Declaration, Definition, accessing
array element, one dimensional and
multidimensional array.
5.2 String : Basic of string, array of string ,
functions in string.h
5.3 Structure: Declaration, initialisation,
structure within structure, Operation on
structure, Array of structure.
5.4 Union: Definition, difference between
structure and union, operations on a union.
06 Pointer and Files 08
6.1 Pointer: Introduction, definition and uses
of pointers, address operator, pointer
variables. pointer arithmetic, pointer with
function.
6.2 Files: types of file, File operations, opening,
closing, creating, reading, processing file.

Nitin Sir Page 2


CHAPTER – 1
Fundamental of C- Programming
Introduction to Computer, Algorithm and Flowchart
Write a short note on Turing model.

A Turing machine is an abstract machine that manipulates symbols on strip of


tape according to table of rules. The more practical form of the same is called as
a mathematical model.

The Turing model forms the basis of software development. it shows the
behaviour expected from the system to be designed. Using a Turing model, one
can design and develop the step expected in the procedural oriented
programming

Write a short note on Von Neumann model.

It is made of a monitor (standard display unit), CPU (Central processing unit)


and keyboard (standard input device).

A Computer can be visualized as a system with input/output (I/O) devices,


Central processing Unit (CPU) and the memory interconnected.

Nitin Sir Page 3


BASICS OF POSITIONAL NUMBER SYSTEM
The number system is used for representing the information. The number
system has different bases and the most common of them are the decimal,
binary, octal, and hexadecimal. The base or radix of the number system is the
total number of the digit used in the number system.

Types of Number Systems

1. Decimal Number System


2. Binary Number System
3. Octal Number System
4. Hexadecimal Number System

1. Decimal Number Systems


The number system is having digit 0, 1, 2, 3, 4, 5, 6, 7, 8, 9; this number system
is known as a decimal number system because total ten digits are involved. The
base of the decimal number system is 10.

2. Binary Number System (Base 2. Digits used: 0, 1)

Computer can understand only binary language.


Binary number system can have only two representations namely ‘0’ or ‘1’.
All numbers and characters are to be represented using ‘0’ or ‘1’ only.
The conversion from binary to decimal and decimal to binary can be done as
shown below with examples.
Decimal to binary

e.g. (𝟓)𝟏𝟎 = ( ? )𝟐
Quotient Remainder
2 5

2 2 1

2 1 0
0 1
(𝟓)𝟏𝟎 = (𝟏 𝟎 𝟏)𝟐

Binary to decimal:

Converting a binary number to a decimal number is:

Nitin Sir Page 4


Multiply the binary digits (bits) with powers of 2 according to their positional
weight.

E.g. (11100)2 = ( ? )10

= 1 1 1 0 0

=1* (2)4 +1* (3)3 +1* (2)2 + 0* (2)1 +0* (2)0

= 16+8+4+0+0

= (28)10

3. Octal Number System (Base 8. Digits used: 0 to 7)


The octal system has the base of eight as it uses eight digits 0, 1, 2, 3, 4, 5, 6, 7.

Converting Decimal to Octal

Steps:

1. Divide the decimal number by 8. Treat the division as an integer


division.
2. Write down the remainder (in octal form).
3. Divide the result again by 8. Treat the division as an integer
division.
4. Repeat step 2 and 3 until result is 0.
5. The octal value is the digit sequence of the remainders from the last to
first

Hexa Decimal Number System (Base 16. Digits used: 0 to 9, Letters used: A-
F)
These numbers are used extensively in microprocessor work.The hexadecimal
number system has a base of 16, and hence it consists of the following sixteen
number of digits.

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.

Converting Decimal to Hexadecimal

Steps:

Nitin Sir Page 5


1. Divide the decimal number by 16. Treat the division as an integer
division.
2. Write down the remainder (in hexadecimal).
3. Divide the result again by 16. Treat the division as an integer
division.
4. Repeat step 2 and 3 until result is 0.
5. The hex value is the digit sequence of the remainders from the last to
first

(2861)10 = (B2D)16

There are various operations that are performed on binary data like AND,
OR, EXOR and NOT.

1. AND: The output is 1 if and only if A AND B (A&B being the inputs) are 1.

A (INPUT) B(INPUT) Y(OUTPUT)


0 0 0

0 1 0

1 0 0

1 1 1

2. OR : The output is 1 if and only if A or B (A&B being the inputs) is 1.

A (INPUT) B(INPUT) Y(OUTPUT)


0 0 0

0 1 1

1 0 1

1 1 1

Nitin Sir Page 6


3. NOT : The output is NOT A (A being the input ) i.e. complement of A

A(INPUT) Y(OUTPUT)
0 1

1 0

4. EXOR: The output is 1 if and only if EXCLUSIVELY A OR B (A&B being


the inputs ) are 1.

A (INPUT) B(INPUT) Y(OUTPUT)


0 0 0

0 1 1

1 0 1

1 1 0

Nitin Sir Page 7


ALGORITHM
Q.3) what do you mean by algorithm? Which points you should consider
while developing an algorithm?

A sequential solution of any problem written in English language is called as


algorithm.
• Algorithm is finite Set of instruction that specifies a sequence of operation to be
carried out in order to solve a specific problem.
• The process of the programming is as shown in the Fig 1.2.1

Defining a Problem

Algorithm development

Program implementation

• An algorithm can also be defined in simple terms as description of the steps


necessary to solve a problem. The algorithm should define the procedure to
perform the given task.
• Graphical representation of an algorithm can be done using flowchart or pseudo
code algorithm.

PROPERTIES OF ALGORITHM
Q. 4) Points to consider while developing an algorithm

The algorithm should have following properties associated with it


(i) Non-ambiguity: Each of the statement in the algorithm must be clear and
precise. There should not be ambiguity in any of the statement.
(ii) Range of Input: The range of input for which algorithm work and there
should be clear indication for the range of inputs for which the algorithm may
fail.
(iii) Multiplicity: Algorithm can be written in English language or by the
graphical representation called as flowchart or the pseudo code.
(iv) Speed: It should produce the result as fast as possible or efficiently.
(v) Finiteness: Algorithm should be finite i.e there should not be infinite
condition leading to a never ending procedure and hence never completing the
task.

Nitin Sir Page 8


DEVELOPING AN ALGORITHM
Q. 5) Rules for writing an algorithm in Pseudo code form.

1. The algorithms should always begin with “START” and end with “STOP”.
2. To accept input from the user, we will use “INPUT” or the “READ”.
3. To display output on the monitor, we will use “PRINT” statement. The
words to be displayed as it is will be written in double quotes while the
variables whose values are to be displayed will not be in double quotes.
4. We will use the basic arithmetic operators to indicate the operations.
5. We will use “AND”, “OR” and “NOT” to indicate conjunction, disjunction
and negation respectively.
6. To check conditions we can use the “IF” “THEN” and “ELSE”
CONSTRUCTS.
7. To Jump from one step to another the construct used is “GOTO”, statement
is always associated with a step number

Algorithm 1: Write an algorithm to accept a number and display its


square.

• Algorithm
Step I : Start
Step II : Input a number
Step III : Calculate the square of the user entered number.
Step IV : Display the calculated result.
Step V : Stop

• Pseudo code
Step I : START
Step II : PRINT “Enter a number”
Step III : Input n
Step IV : a=n*n
Step V : PRINT a
Step VI : STOP

Nitin Sir Page 9


Algorithm 2: Write an algorithm to accept two numbers and display its
product.

• Algorithm
Step I : Start
Step II : Input two numbers.
Step III : Calculate product of two number.
Step IV : Display product.
Step V : Stop

• Pseudo code

Step I : START
Step II : PRINT “Enter two numbers”
Step III : Input a,b
Step IV : x=a*b
Step V : PRINT x
Step VI : STOP

Algorithm 3: Write an algorithm to display first ten natural numbers.

• Algorithm
Step I : Start
Step II : Initialize the counter with value as 1
Step III : Check if counter is greater than 10, if yes then goto step VII.
Step IV : Display the value of counter variable.
Step V : Increment the counter variable.
Step VI : Goto step III
Step VII : Stop

• Pseudo code

Step I : START
Step II : i=1
Step III : IF i>10 THEN GOTO Step VII.
Step IV : PRINT i
Step V : i=i+1
Step VI : GOTO step III
Step VII : STOP.

Nitin Sir Page 10


Algorithm 4: Write an algorithm find the factorial of a number.

• Algorithm
Step I : Start
Step II : Input a number
Step III : Initialize the counter with value as 1.
Step IV : Check if counter is greater than user entered number, if yes
then goto step VIII.
Step V : Multiply the fact variable with counter value.
Step VI : Increment the counter variable.
Step VII : Goto step IV
Step VIII : Display the value of factorial.
Step IX : Stop

• Pseudo code

Step I : START
Step II : PRINT “Enter a number”
Step III : Input n.
Step IV : i=1, fact=1;
Step V : IF i>n THEN GOTO step IX.
Step VI : fact=fact*i
Step VII : i=i+1;
Step VIII : GOTO step V;
Step IX : PRINT fact;
Step X : STOP.

3. Write an algorithm to sort set of numbers in ascending order. For the


above problem, in which case the time complexity is calculated.

Step I : START
Step II : Input N as size of the list
Step III : PRINT ‘Enter list of elements’
Step IV : For I ←0 to N – 1 DO Repeat step 5
Step V : INPUT A[I]
Step VI : FOR I←N – 1 DOWNTO 1 DO Repeat step 7
Step VII : FOR j←0 TO I – 1 DO Repeat step 8
Step VIII: IF A[j] > A[j+1] THEN
Begin
TEMP ← A[j]
A[j] ← A[j+1]

Nitin Sir Page 11


A[j+1] ←TEMP
End
Step IX : FOR I ←0 TO N – 1 Repeat step 10
Step X : PRINT A[I]
Step XI : STOP

Time complexity for the above algorithm must be measured for the average case
as well as worst case (array is in descending order ).When we have N elements
than the number of comparisons required for sorting the complete list will be
given as follows.
Number of comparison = (N – 1) + (N – 2)+……….+2+ 1
=(N(N-1)) / 2 = (𝑁 2 -N) / 2
Time complexity of this algorithm will be O(𝑁 2 ) in average case as well as
worst case.

Nitin Sir Page 12


FLOWCHART
A Flowchart is a graphical representation of an algorithm to show sequence of
steps. Flowchart gives flow of algorithm in sequence.
Following are symbols used for making flowchart.
SYMBOL NAME DESCRIPTION
Terminal Defines the start and end of a
flowchart.

Input / Output Used to perform input and


Output operations.

Process, Instruction Manipulation of data


(Assignment and mathematical
computations)
Flow Lines Define logical sequence or
direction of flowchart.

Decision Process, Decision or branch


conditions using relational
operators.(e.g. If / ELSE etc.)
Connector Connector (connect one part of
the flowchart to another)

Q.6) Advantages & Disadvantages of Using Flowcharts


Advantages
• Communication: Flowcharts are better way of communicating the logic of a
system to all concerned.
• Effective analysis: With the help of flowchart, problem can be analysed in
more effective way.
• Proper documentation: Program flowcharts serve as a good program
documentation, which is needed for various purposes.
• Efficient Coding: The flowcharts act as a guide or blue print during the
systems analysis and program development phase.
• Proper Debugging: The flowchart helps in debugging process.

Limitations of Using Flowcharts:


• Complex logic: Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
Nitin Sir Page 13
• Alterations and Modifications: If alterations are required the flowchart may
require re-drawing completely.

Flowchart 1: Draw a flowchart to find the product of two numbers.


Solution:
START

Accept num1, num2

Product=num1 X num2

Display product

STOP

Flowchart 2: Draw a flowchart to find the square of a numbers.


Solution:

START

Accept a
num

Mult=num x num.

Display Mult

STOP

Nitin Sir Page 14


Flowchart 3: Write an algorithm and draw flowchart to accept marks of 4
subjects and display grade.

Step 1: Input M1, M2, M3, M4


Step 2: GRADE  (M1+M2+M3+M4)/4
Step 3: IF (GRADE < 50) THEN
Print “FAIL”
ELSE
Print “PASS”
END IF

Flowchart 4: Write an algorithm and draw a flowchart to find the larger of


two numbers A and B.

ALGORITHM
Start
Step 1: Input A, B
Step 2: IF (A>B) THEN
Read A, B
MAX=A
ELSE
IS
MAX=B
A>B
END IF
Step 3: PRINT “The largest value is”, MAX Max=A Max=B

Display
Max

End

Nitin Sir Page 15


Flowchart 5: Write an algorithm and draw a flowchart to find the number
is even or odd.

ALGORITHM
Start
Step 1: Input num
Step 2: IF (num%2==0) THEN
Read num
PRINT “the number is even”;
ELSE
IS
PRINT “the number is odd”; num%2=0

END IF
Step 3: STOP Print “The number is even” Print “The number is odd”

End

Flowchart 5: Draw a flowchart to find the sum of first 50 natural numbers.

Step 1: Start.

Step 2: Initialise SUM=0 and N=0

Step 3: N=N+1

Step 4: SUM=SUM+N

Step 5: IF N=50 ? THEN go to step 6.

ELSE goto step 3

Step 6: Display SUM.

Step 7: End.

Nitin Sir Page 16


Flowchart 6: Write an algorithm and draw a flowchart that will calculate
the roots of a quadratic equation 𝒂𝒙𝟐 + 𝒃𝒙 + 𝒄 = 𝟎. (May-13 ) 6M

Hint: d = sqrt (𝒃𝟐 − 𝟒𝒂𝒄), and the roots are:


START
x1 = (–b + d)/2a and x2 = (–b – d)/2a

Step 1 : Start Input


Step 2 : Input a, b, c a, b, c

Step 2 : d sqrt (𝑏 2 − 4 × 𝑎 × 𝑐)
−𝑏+𝑑
dsqrt(𝒃𝟐 − 𝟒 × 𝒂 × 𝒄)
Step 3 : x1 ( )
2×𝑎

Step 4 : x2 (
−𝑏−𝑑
) x1(–b + d) / (2 x a)
2×𝑎

Step 5 : PRINT X1, X2


X2 (–b – d) / (2 x a)
Step 6 : Stop

Print
x1 ,x2

STOP

Nitin Sir Page 17


SGFXU

Nitin Sir Page 18


What is ‘C’
C is programming language used to write program and execute them.

C is a procedural programming language. It was initially developed by


Dennis Ritchie in the year 1972.

It is a low programming level language close to machine language

It is widely used in the software development field

Features of ‘C ’
1) It is a procedural language
2) It is high level language
3) It is used for software development.
4) ‘C’ language is a first step for programmer to start
5) It is reliable, simple , & easy to use.

Where is C used? Key Applications


1. 'C' language is widely used in embedded systems.
2. It is used for developing system applications.
3. It is widely used for developing desktop applications.
4. Most of the applications by Adobe are developed using 'C'
programming language.
5. It is used for developing browsers and their extensions. Google's
Chromium is built using 'C' programming language.
6. It is used to develop databases. MySQL is the most popular database
software which is built using 'C'.
7. It is used in developing an operating system. Operating systems such
as Apple's OS X, Microsoft's Windows, and Symbian are developed
using 'C' language. It is used for developing desktop as well as mobile
phone's operating system.
8. It is used for compiler production.
9. It is widely used in IOT applications.

Nitin Sir Page 19


Structure of c program

A C program basically consists of the following parts −

• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments

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

/* Comments */
This is a comment block, which is ignored by the compiler. Comment
can be used anywhere in the program to add info about the program or
code block, which will be helpful for developers to understand the existing
code in the future easily.

#include<stdio.h>

This is a preprocessor command. That notifies the compiler to include the


header file stdio.h in the program before compiling the source-code.

int/void main()
int/void is a return value, which will be explained in a while.
This is the main function, which is the default entry point for every C
program and the void in front of it indicates that it does not return a value.

Braces
Curly braces which shows how much the main() function has its scope.

printf()

This is another pre-defined function of C which is used to be displayed text


string in the screen.

return 0

At the end of the main function returns value 0.

Nitin Sir Page 20


TOKENS OF C:-
• The C programs are made up of different things termed as tokens.
The different tokens of C are
o Character set
o Keywords
o Identifiers
o Constants and variables
o Data types
o Operators

CHARACTER SET OF C
Character Set Example
Alphabets (Upper case and A, B, C ……Z
lower case) a, b, c …….z
Digits (numbers) 0, 1, 2, 3. .. .. . .. 9
Special Symbol @, #, $, ^, &, *, +, _, /, <, >

KEYWORDS:-
• There are some special words that have a predefined meaning for the C
compiler known as keywords.
• Keywords are a set of words which are reserved for the certain operations and
hence are also sometimes referred as reserved words.
• These words cannot be used as identifiers.
• There are 32 Keywords in C
• The keywords used in C are as given below:
auto double Int struct
break else Long switch
case enum register typedef
char extern Return union
const float Short unsigned
continue for signed void
default goto Sizeof volatile
do if Static while

Nitin Sir Page 21


IDENTIFIERS:-
Identifiers are name given to different user defined things like variables,
constants, functions, array, structures, unions, etc.

some rules need to follow while making these identifiers.

These rules are stated below :


• A Variable name consists of any combination of alphabets, digits and
underscores.
• It should not start with the digit; the first character of the variable name
must either be alphabet or underscore.
• Commas and blanks are not allowed in the variable name.
• Special symbols are not allowed except underscore.
• You cannot use Keywords (reserve words) as variable name.

DATA TYPES IN C :-
• What type of data can a variable hold is called data type?
• The data type decides the type of data required for storing in the memory.
• The data types of C can be divided into two types: primary and secondary data
types.

Nitin Sir Page 22


CONSTANTS
• Constants are values given to the identifiers that do not change throughout the
execution of the program.
• Constants can be defined either by writing the keyword const before the data
type by using #define.
• Constants are used to declare the values that remain constant, for e.g. value of
pi.

Declaration

– const float PI=3.14;


– #define PI 3.14

WAP to find area and circumference of circle

#include <stdio.h>
#include<conio.h>
void main ()
{
float area, r, circ;
const float pi=3.14;
printf ("Enter a radius of circle: ");
scanf ("%f", & r);
area = pi * r * r;
circ = 2 * pi * r;
printf ("Area of Circle is %f \n",area);
printf ("Circumference of circle is %f \n",circ);
return (0);
}

ESCAPE SEQUENCES
• Escape sequence is a character followed by a backslash (\).
• They are used specially to perform some operations like going to new line,
providing a horizontal tab, vertical tab etc.
• The following is a list of escape sequences.
\n Newline
\t Horizontal Tab
\v Vertical Tab
\b Backspace
\r Carriage Return

Nitin Sir Page 23


\f From feed
\a Audible Alert (bell)
\\ Backslash
\? Question mark

OPERATORS
• Operators are different symbols used to perform operations on operands.
• The operators are one of the tokens of C.
• There are different types of operators classified based on their functions

Unary Operators
o These are operators that require only one operand

1. Unary minus (-) :


o It changes the algebraic sign of the variable to which it is preceded.
o For e.g. if x = 3 and y = 6 then
y = -x;
will make the value of y as -3.

2. Address of operator (&) :


o This operator returns the address of the variable associated with it.
o For e.g. y = &x;
o The memory address allocated to variable x will be copied into
variable y.

3. Casting operator or type conversion:


o It is used to convert one data type to another data type.
o The casting operator is used for type conversion
o E.g int x=4;
Float y=5.1
Then x=(int) y; // result in x will be stored as 5

Nitin Sir Page 24


Write a program to accept a float number and display the integer part
using type casting operator.

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
float b;
clrscr();
printf(“enter float number”);
scanf(“%f”.&b);
a = (int)b;
printf(“the integer part of the number is %d”,a);
getch();
}
output:
enter a float number : 3.14
the integer part of the number is: 3

Write a program to display average of 5 subject.


#include<stdio.h>
#include<conio.h>
int main()
{
int Marks1, Marks2, Marks3, Marks4, Marks5,Add;
float Avg;
printf("\nEnter marks for five subject::");
scanf("%d%d%d%d%d",&Marks1,&Marks2,&Marks3,&Marks4,&Mark
s5);
Add = Marks1+Marks2+Marks3+Marks4+Marks5; //implicit typecast
Avg = (float)(Add)/5;
printf("\nAvg is = %f",Avg);
getch();
return 0;
}

4. Increment operator (++) :


o It increases the value of the variable by one and stores the result in
the variable itself.
o For e.g. if x =4,
Then x++; \\ Will make the value of x equal to 5.

Nitin Sir Page 25


o Operator “++” can be place after operand “x++” (also called as
post increment operator) and before operand “++x” (also called as
pre increment operator).
o In post increment : x=4;
Then y=x++; will make value of y=4 and x=5;
o In pre increment: x=4
Then y=++x; will make value of y=5 and x=5

Decrement Operator ( --) :


o It decreases value of the variable by one and stores the result in the
variable itself.
o For e.g. if x = 4,
o Then x --; \\ Will make the value of x equal to 3.
o Operator “--” can be place after operand “x--” (also called as post
decrement operator) and before operand “--x” (also called as pre
decrement operator).
o In post decrement : x=4;
Then y=x--; will make value of y=4 and x=3;
o In pre decrement: x=4
Then y=--x; will make value of y=3 and x=3

Write the output of the following program

#include<stdio.h>
#include<conio.h>
void main()
{
int x=4, y=9;
int z;
z=(x++)+(--y)+y;
Printf(“Value=%d\n”,z);
z=(--x)+x+(y--);
printf(“Value=%d\n”,z);
getch();
}
O/P : Value=20

Value=16

Nitin Sir Page 26


Write the output of the following program

#include<stdio.h>
#include<conio.h>
void main()
{
int x=10, y , z;
z=y=x;
y-=--x;
z-=x--;
x-=--x-x--;
printf(“x=%d y=%d z=%d”, x, y, z);
}
O/P: x=6 y=1 z=1

5. Size of operator
This operator is used to know the size of variable required to store value in
memory.
Size of operator can also find size of a data type.
e.g
1. sizeof(int) will return value as 2.
2. char a;
sizeof(a); will return 1

Binary Operators: -
Operators that require two operands are called as binary operators.

1. Arithmetic Operators:-
• This are set of operators used to perform basic arithmetic operations like
addition, subtraction, multiplication and division.
• There are five operators in this set. They are :
1. + to find the sum
2. - to find the difference
3. * to find the product
4. / to find the quotient after division
5. % to find the remainder after division
Division ‘/’ operator is used to find quotient and MOD ‘%’ operator is
used to find remainder after division of two numbers.

2. Bitwise operators :-

Nitin Sir Page 27


• The operator which works on each bit of data is known as bitwise operator.
• They perform different operations on bits of a data like AND, OR, EXOR,
NOT etc…
• The operators are listed below :
1. & to perform bitwise AND operation.
2. | to perform bitwise OR operation.
3. ~ to perform bitwise NOT operation.
4. ^ to perform bitwise EXOR operation.
5. << to perform bitwise left shift operation.
6. >> to perform bitwise right shift operation.
1. Bitwise AND operation (&)
5 & 3 =1
( 5 )10 = (0 1 0 1)2
( 3 )10 = (0 0 1 1)2
(0 0 0 1)2 = (1)10
2. Bitwise OR operation ( |)
12 | 9 =13
( 12 )10 = (1 1 0 0)2
( 9)10 = (1 0 0 1)2
(1 1 0 1)2 = (13)10
3. Bitwise EXOR operation (^)
8 ^ 10 =2
( 8 )10 = (1 0 0 0)2
(10)10 = (1 0 1 0)2
(0 0 1 0)2 = (2)10
4. Bitwise NOT operation (~)
~ 7 = -8
(7)10 = (0 1 1 1)2
(1 0 0 0)2 = (−8)10
5. Left shift operator : <<
This statement will shift binary digit to the left by 1 digit.
3<<2 = 12
( 3)10 = (0 0 0 0 0 0 1 1)2
After shifting left once = ( 0 0 0 0 0 1 1 0)2
After shifting left twice = ( 0 0 0 0 1 1 0 0)2 =( 12)10

6. Right shift operator : >>


This statement will shift binary digit to the right by 1 digit.
13>>3 = 1
Nitin Sir Page 28
(13)10 = (0 0 0 0 1 0 1 1)2
After shifting right once =(0 0 0 0 0 1 0 1)2
After shifting right twice =(0 0 0 0 0 0 1 0)2
After shifting right thrice =(0 0 0 0 0 0 0 1)2 =(1)10

3. Logical operators :-
• Logical operators are used to evaluate conditions or expressions.
• The logical operators are AND and OR.
• AND Operator (&)
o The AND operators checks for all conditions to be true then only it
returns true else false.
o For example a statement
o y >5 && y <10;
o will result in “true” i.e. 1 if the value of y is greater than 5 AND
less than 10, else it will result in false i.e.0
• OR Operator :-
o The OR operator checks for any one or all conditions from the
given conditions to be true then it evaluates true.
o Otherwise if all conditions are false then it returns false.
o For example a statement
o y >5 || y <10;
o will result in “true” i.e. 1 if the value of y is greater than 5 OR less
than 10, else it will result in false i.e.0

4. Relational Operator: -
• The relational operators are used to test the relation between two variables or
a variable and constant.
• The operators like
o ‘<’ (less than)
o >’ (greater than)
o “= =” (equality operator)
o ‘<=’ (less than equal to)
o ‘>=’ (greater than equal to)
o ‘!=’ (not equal to)

5. Assignment Operators and Statements


• These operators are used to assign the value of the expression or variable on
the right of the assignment operator to the variable on its left.
E.g b=10;
Nitin Sir Page 29
• Assigning the value of 10 to variable b.
E.g a+=b means a=a+b similarly we can apply multiplication & division
operators.

Conditional Operators
• Conditional operator is also known as ternary operator.
• The operator that requires three operands is called as ternary operator.
• Syntax :
(Condition)? Expr1 : Expr2 ;
• It checks for the condition if condition is true then expr1 will be executed
otherwise expr2 will be executed.
E.g. max= (a > b)? a : b;
• This will put the value of a into max if condition is true else the value of b
into max

Write a program to accept two numbers from user and display greatest of
two numbers using conditional operator.

#include<stdio.h>
#include<conio.h>
Void main()
{
int n1 , n2, greater;
printf(“Enter a two number”);
scanf(“%d %d”,&n1,&n2);
greater=(n1>n2)?n1:n2;
printf(“The greater number is: %d”,greater);
getch();
}

Write a program to accept three numbers from user and display the
greatest of three using the conditional operator.

#include <stdio.h>
#include <conio.h>
void main()
{
int n1,n2,n3,greater;
clrscr();
printf(“enter three numbers\n”);
scanf(“%d %d %d”,&n1,&n2,&n3);
Nitin Sir Page 30
greater = (n1>n2)?((n1>n3)?n1:n3): ((n2>n3)?n2:n3));
printf(“the largest number is : %d ”,greater);
getch();
}
Output:
enter three numbers
234
23
33
the largest number is : 234

Use of Standard (Input and Output) Functions


• Inbuilt IO functions are available in C for displaying data on the standard
output device i.e. monitor and accepting the input from the standard input
device i.e. keyboard.
• These IO functions are classified as formatted functions and unformatted

1. Formatted IO Functions
Two formatted IO functions in C
o printf() :- display a data on monitor.
o scanf() :- accept data from keyboard.

printf() :-

The printf statement allows you to send output to screen

Syntax: printf(“Format string”, list of variables or expressions)


Format specifiers
Sr. Format specifier Data type
No.
1 %d For integer type of data
2 %f For float type of data
3 %c For char type of data
4 % lf For double type of data
5 % Lf For long double type of data

Example :
printf(“ The simple interest is %f”, si);

This statement will print the output where the format specifier % f will be
replaced with the float type value of the variable si.

Nitin Sir Page 31


scanf()
Syntax : scanf(“format String”, address of variables);
The address of the variable is obtained with the help of the address of operator
(&)

Example: scanf(“% d”, &x);

This statement is used to accept a int type value from user in the variable x.

2. Unformatted IO Functions
• The unformatted IO functions do not have any format specifier. They are mostly
used to accept and display only one character or a string (string is a set of
characters to make a word or sentence).

The different unformatted IO functions are listed below;

1. getch () : This function is used accept one character from the user.
2. getche () : This function is used accept one character from the user and echo
it to screen (accept input without pressing enter).
3. getchar () : This function is used to accept one character from the user and
echo it (display it on the screen) and also wait after that for the user to press
the enter key.
4. gets () : This function is used to accept a string from the user. We will see in
details of this when studying the chapter on strings.
5. putch() or putchar() :These functions are used to display a character on the
monitor.
6. puts : This function is used to display a string on the monitor.

What is error? Explain different types of error.


While writing c programs, errors also known as bugs in the world of
programming may occur unwillingly which may prevent the program to
compile and run correctly as per the expectation of the programmer.

Basically there are three types of errors in c programming:

1. Runtime Errors
2. Compile Errors
3. Logical Errors

Nitin Sir Page 32


C Runtime Errors

C RUNTIME ERRORS are those errors that occur during the execution of a c
program

Errors which occur during program execution(run-time) after successful


compilation are called run-time errors, One of the most common run-time errors
are

Dividing a number by zero

Trying to open a file which is not created

Lack of free memory space

These types of error are hard to find as the compiler doesn’t point to the line at
which the error occurs.

COMPILE ERRORS

Compile errors are those errors that occur at the time of compilation of the
program. C compile errors may be further classified as:

SYNTAX ERRORS

When the rules of the c programming language are not followed, the compiler
will show syntax errors.

LOGICAL ERRORS

Logical errors are the errors in the output of the program. The presence of
logical errors leads to undesired or incorrect output and are caused due to error
in the logic applied in the program to produce the desired output.

Also, logical errors could not be detected by the compiler, and thus,
programmers has to check the entire coding of a c program line by line.

Programs
C Program to Calculate Simple Interest
#include<stdio.h>
#include<conio.h>
void main()
{

Nitin Sir Page 33


float p,r,n,si;
clrscr();
printf("\nEnter the profit, rate & no of yr\n\n ");
scanf("%f%f%f",&p,&r,&n);
si=(p*r*n)/100;
printf("\nSimple Intrest=%f",si);
getch();
}

WAP for swapping of two number.


#include<stdio.h>
int main()
{
int a,b,temp;
printf("Enter any two integers: ");
scanf("%d%d",&a,&b);
printf("Before swapping: a = %d, b=%d",a,b);
temp = a;
a = b;
b = temp;
printf("\nAfter swapping: a = %d, b=%d",a,b);
return 0;
}
Output:
Enter any two integers: 5 8
Before swapping: a =5 b=8
Before swapping: a =8 b=5

Write a Program to swap values of two integers without using a temporary


variable

#include <stdio.h>
#include <conio.h>
void main()
{
int x , y ;
printf("Enter two integers: ") ;
scanf("%d %d" , &x , &y) ;
printf("x=%d y=%d \n" , x , y) ;
x=x+y ;
y=x-y ;
x=x-y ;
printf("After swapping: \n") ;
printf("x=%d y=%d" , x , y) ;
Nitin Sir Page 34
getch() ;
}
Output:
Enter two integers: 5 8
x=5 y=8
After swapping:
x=8 y=5

WAP to accept the length and breadth of a rectangle from the user.
Calculate and display the area and perimeter.

#include<stdio.h>
#include<conio.h>
void main ()
{
float length, breadth, area, perimeter; clrscr():
printf (“Enter the length and breadth of the rectangle:”);
scanf(“%f%f”, &lenghth, & breadth);
area = length * breadth;
perimeter = 2* (length + breadth);
printf(“The area of rectangle is = % f and its perimeter is = % f”, area,
perimeter);
getch();
}
Output:
Enter the length and breadth of the rectangle: 10
15
The area of rectangle is 150.000000 and its perimeter is = 50.000000

WAP that calculates the roots of quadratic equation.

#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c;
float x1,x2;
clrscr(0;
printf (Enter the coefficients of the quadratic equation :”);

Nitin Sir Page 35


scanf (“%d”%d%”,&a,&b,&c);
x1=(-b+pow((b*b-4*a*c),0.5)))/2*a;
x2=(-b-pow((b*b-4*a*c),0.5)))/2*a;
printf (“the roots of quadratic equation are :% f and %f”, x1,x2);
getch();

Output:

Enter the coefficients of the quadratic equation: 1

2
3

The roots of quadratic equation are : -1.000000 and -1.000000

WAP Find the output of the following program:

#include<stdio.h>

#include<conio.h>

void main()

int x=1;

clrscr();

printf (“%d”%d%d\n”,x,(x=x+2),(x<<2));

x<<2;

printf (“%d”%d%d\n”,++x,++,++x);

getch();

Output

334

644

Nitin Sir Page 36


Questions:-

1. Write algorithm and draw flowchart to calculate roots of quadratic


equations. (6 Marks.) DEC-13, DEC-18, DEC-17
2. Write algorithm to sort set of numbers in ascending order. (6 Marks.)
May-13
3. What is algorithm? Which points to consider while writing algorithm?
(4 M arks.) May, DEC-13, MAR-14, May -16
4. What do you means by efficiency of algorithm? May-13
5. Explain need of flowchart [2 Marks] May-15
6. Explain time complexity of an algorithm [4 M].
7. Explain space complexity of an algorithm [4 M]
8. Draw flow chart for if else and while statement in ‘C’.
9. Define algorithm, Write algorithm to check whether given number is
Armstrong number or not.
10.Write a note on operators, explain any two operators.
11.What do you mean by tokens in C, explain?
12.Explain bitwise operator with example [DEC-2014, MAY-17]
13.Write a program to accept marks of 5 subjects marks, and display total
and average.
14.Write a note on increment and decrement operators.
15.Evaluate following expression :- 3 Marks
i) ! (5+5 > = 10) ans : 0

ii) 5 + 5 = = 10 | | 1 + 3 = = 5 ans: 1

iii) 5.10 || 10 < 20 && 3 < 5 ans: 1

16.Explain logical operators. Write a c program to demonstrate the same.


[4M]
17.Explain Ternary operators with example [5 M].
18.Explain bitwise right shift operator, bitwise x-or operator [4 M].
19.Write an explain unformatted IO functions [4 M].
20.Write a program to print binary equivalent of entered decimal number [5
M) DEC-18
21.Explain gets() and puts() functions of C language, comment on their
parameter and return values.

Nitin Sir Page 37


CHAPTER– 2

Control Structures

Control Flow Statement

Condition Looping Branching


al
• If Statement • For loop
• While loop • Break
• If – else Statement • goto
• Nested if- else • Do-while loop
• continue
• Else if ladder
• Switch - Case

• In programming we need to sometimes control the flow of operation other than


just the sequential statements. In this case we need the control statements.

• Control statements are of two types


1. Selection statements are used to perform the operations based on a
particular condition i.e. if a condition is true performing one task else
perform another task.

2. Iterative statements (Looping) are used to perform certain operation


repetitively for certain number of times. In C we have three iterative
statements viz. for loop, while loop and do-while loop.

Selection: It is decision making statement

• Sometimes, a program requires checking of certain conditions in program


execution.
• C provides various key condition statements to check condition and
execute statements according conditional criteria.

Nitin Sir Page 38


Selection Statement is of following types.

1. If Statement
2. If – else Statement
3. Nested if- else Statement
4. Switch – Case

1. If Statement
Syntax

If (condition)
{
Statements1;
}
the condition given with the if statement is true. Then statements1 are
executed in this case.
If the condition specified in the if statements is false then the statements
named as statements1 are not executed in this case.

2. If Else Statement
Syntax
If (condition)
{
Statements-1;
}
else
{
Statements-2;
}

• The set of statements named as statements 1 in the above syntax are executed
if the condition given with the if statement is true.
• If the condition specified in the if statements is false then the statements
named as statements2 in the above syntax are executed.

Write a program to check entered number is even or odd.


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

Nitin Sir Page 39


printf(“Enter a number\n”);
scanf(“%d”, &n);
if(n%2==0)
{
printf(“%d is even number”,n);
}
else
{
printf(“%d is odd number”,n);
}
getch();
}

3. Nested if-else
In some cases we have to check multiple cases of a particular condition. In
such cases we have to use an nested if-else.
Syntax:
If (condition-1)
{
if(condition-2)
statement1;
else
statement2;
}
else
{
if(condition-3)
statement13;
else
statement4;
}

In this case the first condition is checked, if it is true then statements inside that
if block are executed. But if the condition is false it goes to the else statement.
Again there is a condition with if; the statements are executed if this second
condition is true. Else it again goes to the else and again checks the condition
associated with this if statement.

Write a program to compare three numbers


#include <stdio.h>
#include <conio.h>
void main()
{
int n1,n2,n3;
Nitin Sir Page 40
printf(“Enter three numbers\n”);
scanf(“%d%d%d”, &n1, &n2, &n3);
if(n1>n2)
{
if(n1>n3)
printf(“The largest number is %d”,n1);
else
printf(“The largest number is %d”,n3);
}
else
{
if(n2>n3)
printf(“The largest number is %d”,n2);
else
printf(“The largest number is %d”,n3);
}
getch();
}

4. Else if ladder
If condtion1 is true then statement1 will be executed otherwise condition2 will
be check if it is true then statment2 will be executed otherwise statement 3 will
be executed.
Syntax:
If(condition1)
{
Statment1;
}
elseif(condition2)
{
Statment2;
}
else
{
Statment3;
}

Nitin Sir Page 41


Write a program to display the class according to marks scored.
Marks Class
70-100 Distinction
60-69 First Class
40-59 Second Class
0-39 Fail

#include <stdio.h>
#include <conio.h>
void main()
{
int marks;
printf(“Enter the marks\n”);
scanf(“%d, &marks);
if(marks>=70)
{
printf(“Distinction”);
}
elseif(marks>=60)
{
printf(“First Class”);
}
elseif(marks>=40)
{
printf(“Second Class”);
}
else
{
printf(“Fail”);
}
getch();
}

Switch-Case Selective Statement

• The statement consist of one or more case statements followed by


colon(:).

• Value in the case statement must be integer or character and value must
be unique.

• If case value did not matched then default block gets executed.
Nitin Sir Page 42
• Using switch-case the if-else ladder can be implemented in a much better
way.
Switch (variable or condition)
{
case value1:
Statement1;
Break;
case value2:
Statement2;
Break;
case value3:
Statement3;
Break;
default:
Statement default;
}
Switch Ladder of if else

The keyword switch is used only once. The keyword if and else are used many
time

The keyword case is used many times. The logical OR(I I)operator used many
That is because many cases are to be times to manage the condition.
written.

The break statement is to used to take When all the condition expressions goes
the control out of switch. If all the false the final else part is used to take the
comparisons are a failure then default final action.
part comes in picture.

Nitin Sir Page 43


Write an program to implement calculator with following operation. 6
Marks [Dec-14].
i) Add two numbers iii) Division two numbers
ii) Subtract two numbers iv) Multiply two numbers

#include <stdio.h>
#include <conio.h>
void main()
{
int ch,a=10,b=20;
float ans;
printf("\nMenu");
printf("\n1.ADD\n2.Sub\n3.Mul\n4.Div");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
ans = a + b;
printf("\nRes is %f",ans);
break;
case 2:
ans = a - b;
printf("\nRes is %f", ans);
break;
case 3:
ans = a * b;
printf("\nRes is %f", ans);
break;
case 4:
ans = a / b;
printf("\nRes is %f", ans);
break;
default:
printf("\nWrong ch");
}//end of switch
getch();
return 0;
}

Nitin Sir Page 44


Write a Program to read month number as input and display the month in
words.

#include <stdio.h>
#include <conio.h>
void main()
{
int m ;
clrscr() ;
printf("Enter a month number: ") ;
scanf("%d" , &m) ;
printf("Month in words is: ") ;
switch(m)
{
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("\nWrong Input") ;
break ;
Nitin Sir Page 45
}
getch() ;
}

FOR LOOP

• For is a iterative statement.


It is used to repeat a set of statements number of times.
Syntax:-
for (initializations; condition; increment / decrement)
{
Statement;
}
1. Initialization statement is executed first. They are used to initialize the
value of the variables.
2. The second step is checking the condition. If condition is true then
statement will be excited If the condition is false the execution of the loop
will be terminated.
3. The third step is to execute all the statements inside the curly braces.
These statements will be executed sequentially.
4. The fourth step is the increment / decrement or updating operations.

E.g.:- Program to display hello 10 times.


for(i=1; i<=10; i++)
{
printf(“Hello\n”);
}

o/p
Hello
Hello
Hello
.
.
. Hello

Nitin Sir Page 46


1. Write a program to find the sum of first n natural numbers
where n is entered by user. Note: 1,2,3... are called natural
numbers.

#include <stdio.h>
#include <conio.h>
void main()
{
int n,i, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(i=1;i<=n;i++) //for loop terminates if count>n
{
sum=sum+i;
}
printf("Sum=%d",sum);
return 0;
}
Output:-
Enter the value of n.
5
Sum=15

2. WAP to find Factorial of a user entered number


#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
fact = fact*i;
}
printf("Factorial of %d = %d\n", n, fact);
return 0;
}
Output:-

Enter a number to calculate it's factorial

Nitin Sir Page 47


Factorial of 4 = 24

WHILE LOOP
• While and do-while loops are also for iterative operation.
• The while loop is used when you want to execute a block of code repeatedly
with checked condition before making iteration.
Syntax:
While (condition)
{

Statements;

}
• The operation of the while loop is such that, first the condition is checked. If
the condition is true, then the statements are executed. Once the statements
are executed, the condition is again checked and this keeps on repeating, until
the condition is false. If the condition is false, the statements insides the loop
is not executed, instead the control directly comes out of the loop.

Write a Program to Reverse an Integer entered by user.


#include <stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n=n/10;
}
printf("Reversed Number = %d",reverse);
return 0;
}
Output:-
Enter an integer: 2345
Reversed Number = 5432

Nitin Sir Page 48


Write a program to check whether a number is palindrome or not.
[May-14] 10M

#include <stdio.h>
#include <conio.h>
int main()
{
int n, reverse=0, rem,temp;
printf("Enter an integer: ");
scanf("%d", &n);
temp=n;
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
temp=n/10;
}
if(reverse==temp)
{
printf("%d is a palindrome.",n);
}
else
{
printf("%d is not a palindrome.",n);
}
return 0;
}

WAP to check entered number is Armstrong number


(For example 371 is an armstrong number as 33 + 73 + 13 = 371. )

#include <stdio.h>
int main()
{
int num, sum = 0, temp, rem;
printf("Enter an integer\n");
scanf("%d",&num);
temp = num;
while( num != 0 )
{
rem = num%10;
sum = sum + rem *rem *rem;
Nitin Sir Page 49
num = num/10;
}
if (temp == sum )
printf("Entered number is an armstrong number.\n");
else
printf("Entered number is not an armstrong number.\n");
return 0;
}

DO-WHILE LOOPS

• First the code block is executed and then condition is evaluated.


Syntax
do
{
Statements;
} while (condition);
• First the statements are executed and then the condition is checked.
• If the condition is true the statements are executed again. If the condition is
false, the statements are not executed again.

Eg:-
i=10;
do
{
printf(“%d”);
i++;
} While (i! =0);

Nitin Sir Page 50


Differences between while and do-while loop
while loop do-while loop
1 Syntax 1 Syntax
while (condition) do
{ {
- -
Statements; Statements;
- -
- -
} }while (condition);
2 This is called as a entry controlled 2 This is called as exit
loop. controlled loop,
as the entry inside the loop is as the entry inside this loop is
possible only if the condition is sure i.e. no condition is
true. checked to enter inside the
loop. the exit is possible only
if the condition is false.
3 If the condition is false for the 3 Even if the condition is false
first time, the control will never for the first time the control
enter into the loop. will enter into the loop. Hence
the statements inside the loop
will be executed at least once.

4 There is no semicolon (;) after the 4 There is a semicolon (;) after


condition in the syntax of the the condition in the syntax of
while loop. the do-while loop.
5 e.g 5 e.g
i=1; i=1;
while(i<=5) do
{ {
Printf(“%d”,i); Printf(“%d”,i);
} }while(i<=5);

Nitin Sir Page 51


Q.1 Explain the difference between for, while and do-while loop.
[May-13] 3-Marks.
For While do-while

1. Syntax Syntax Syntax


for (exp1; exp2; exp3) while(condition) do
{ { {
Statement statement statement
} } }while(condition);

2. It is entry checking It is entry checking It is exit checking


loop. loop. loop.

3. Initialisation (exp1) and condition is part of condition is part of


update (exp2) are part of statement statement
the syntax.

4. If the exp2 is false in the If the condition is false Since the statement
first iteration then in the first iteration part is executed first
statement part will not then statement part will and then the condition
executed. not be executed. is checked so
statement will be
always executed at
least once.

5. e.g. e.g.
for(i=1;i<=5;i++) i=1; e.g.
printf(“%d”,i); while(i<=5) i=1;
printf(“%d”,i++); do
will result into output will result into output printf(“%d”,i++);
12345. 12345. while(i<=5);
will result into output
12

Nitin Sir Page 52


Pattern program

Write a program to display following pattern

*
**
***
****

#include <stdio.h>
#include <conio.h>
void main()
{
int i , j , n ;
printf("Enter the number of lines: ") ;
scanf("%d" , &n) ;
printf("Required pattern is as follows: \n") ;
for(i=1 ; i<=n ; i++)
{
for(j=1 ; j<=i ; j++)
{
printf("*”) ;
}
printf("\n") ;
}
getch();
}

Write a program to display following pattern


1
12
123
1234
...
#include <stdio.h>
#include <conio.h>
void main()
{
int i , j , n ;
printf("Enter the number of lines: ") ;
scanf("%d" , &n) ;
printf("Required pattern is as follows: \n") ;
for(i=1 ; i<=n ; i++)
{
for(j=1 ; j<=i ; j++)
Nitin Sir Page 53
{
printf("%d " , j) ;
}
printf("\n") ;
}
getch();
}

Program: write a program to display the following pattern.


1
22
333
4444
55555

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j ;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch();
}

Write a program to display following pattern


A
AB
ABC
ABCD
ABCDE
#include <stdio.h>
#include <conio.h>
void main()
Nitin Sir Page 54
{
int i , j , n ;
for(i=1 ; i<=5 ; i++)
{
for(j=1 ; j<=i ; j++)
{
printf("%c " , j+64) ;
}
printf("\n") ;
}
getch();
}

Write a program to display following pattern


1
23
456
7 8 9 10
...
#include <stdio.h>
#include <conio.h>
void main()
{
int i , j , k=1;
clrscr() ;
printf("Required pattern is as follows: \n") ;
for(i=1 ; i<=4 ; i++)
{
for(j=1 ; j<=i ; j++)
{
printf("%d " ,k) ;
k++;
}
printf("\n") ;
}
getch() ;
}
Output:

Nitin Sir Page 55


Required pattern is as follows:
1
23
456
7 8 9 10

Program: write a program to generate the following patterns.


5
44
333
2222
11111
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j,k=5;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf( “%d”, k);
}
printf(“\n”);
k--;
}
getch();
}

Write a program display following pattern.


****
***
**
*
#include <stdio.h>
#include <conio.h>
void main()
{
int i , j , n ;
clrscr() ;
printf("Enter the number of lines: ") ;
scanf("%d" , &n) ;
Nitin Sir Page 56
printf("Required pattern is as follows: \n") ;
for(i=n ; i>=1 ; i--)
{
for(j=1 ; j<=i ; j++)
{
printf("*") ;
}
printf("\n") ;
}
getch() ;
}
Output:
Enter the number of lines: 4
Required pattern is as follows:
****
***
**
*

Write a program display following pattern.


1234
123
12
1
#include <stdio.h>
#include <conio.h>
void main()
{
int i , j , n ;
clrscr() ;
printf("Enter the number of lines: ") ;
scanf("%d" , &n) ;
printf("Required pattern is as follows: \n") ;
for(i=n ; i>=1 ; i--)
{
for(j=1 ; j<=i ; j++)
{
printf("%d " , j) ;
}
printf("\n") ;
}
getch() ;
}
Output:
Enter the number of lines: 3

Nitin Sir Page 57


Required pattern is as follows:
123
12
1
*/

Write a program to display the following asking the user for the number of
lines in the upper half.

*
***
*****
*******
*********
********
*****
***
*
#include<stdio.h>
#include<conio.h>
void main
{
int i, j, n;
clrscr();
printf(“Enter the number of lines in the upper half:”);
scanf (“%d”,&n);
for (i=1;i<=n;i++)
{
for(j=1;j<=n-I;j++)
{
printf(“ ”);
}
for(j=1;j<=2*i-1;j++)
{
printf(“* ”);
Nitin Sir Page 58
}
for(i=n-1;i>=1;i--)
{
printf(“ ”);
for(j=1;j<=2*i-1;j++)
{
printf(“* ”);
}
printf(“\n ”);
}
getch();
}
Output
Enter the number of lines in the upper half:5
*
***
*****
*******
*********
********
*****
***
*

Write a program to display the following asking the user for the number of
lines.
1
121
12321
1234321
123454321
12345654321

#include<stdio.h>
#include<conio.h>
void main()
{
int i , j , n;
clrscr();
printf(“enter the number of lines”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
Nitin Sir Page 59
{
for(j=1;j<=n-i;j++)
{
printf(“ ”);
}
for(j=1;j<=i; j++)
{
printf(“%d”,j);
}
for(j=i-1;j>=1;j--)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch();
}
OUTPUT:
enter the number of lines : 6
1
121
12321
1234321
123454321
12345654321

Write a program to display the following asking the user for the number of
lines.
1
232
34543
4567654
567858765

#include<stdio.h>
#include<conio.h>
void main()
{
int i , j , n, k;
clrscr();
printf(“enter the number of lines”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
Nitin Sir Page 60
{
printf(“ ”);
}
k=i;
for(j=1;j<=i; j++)
{
printf(“%d”,k);
k--;
}
k=2*i-2;
for(j= 1;j<=i ;j++)
{
printf(“%d”,k);
k--;
}
printf(“\n”);
}
getch();
}
OUTPUT:
enter the number of lines : 6
1
121
12321
1234321
123454321

Program: write a program to display the following pattern.


1
21A
321AB
4321ABC
54321ABCD
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf(“enter the number of lines”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
Nitin Sir Page 61
printf(“ ”);
}
for(j=i;j>=1;j--)
{
printf(“%d”,j);
}
for(j=1;j<= i – 1; j++)
{
printf(“%c”,(64+j));
}
printf(“\n”);
}
getch();
}

OUTPUT:
Enter the number of lines: 5
1
21A
321AB
4321ABC
54321ABCD

Write a program to display the following pattern


1
10
101
1010
10101

#include<stdio.h>
#include<conio.h>
void main
{
int i, j, N;

printf("Enter N: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)

Nitin Sir Page 62


{
// For every odd column print 1
if(j % 2 == 1)
{
printf("1");
}
else
{
printf("0");
}
}

printf("\n");
}
getch();
}

Write a program to display following pattern


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

#include<stdio.h>
void main()
{
int i,j,k;
for(i=0 ; i<=4 ; i++)
{
for(j=4 ; j > i ; j--)
{
printf(" ");
}
for(j=0; j<=i ; j++)
{
if(j%2 == 0)
Nitin Sir Page 63
printf("0");
else
printf("1");
}
printf("\n");
}
return 0;
}

Write a program to display the following pattern


5432*
543*1
54*21
5*321
* 4321
#include<stdio.h>
#include<conio.h>
void main
{
int i, j, n;
clrscr();
for (i=1;i<=5;i++)
{
for(j=5;j>=1;j--)
{
If(i==j)
Printf(“*”);
else
Printf(“%d”,j);
}
printf(“\n”);
}

Nitin Sir Page 64


Program : Write a program to display the following patterns.
ABCD
ABC
AB
A
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j;
clrscr();
for (i=1;i<=4;i++)
{
for(j=1;j<=i-1;j++)
{
printf(“ “);
}
for (j=1;j<=5-i;j++)
{
printf(“%c”,(char)(j+64));
}
printf(“\n”);
}
getch();
}

Nitin Sir Page 65


Write a program to display the following patterns.

1
12A
123AB
1234ABC

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<4-i;j++)
printf(“ “);
}
for(j=1;j<=i;j++)
{
printf(“%d”,j);
}
for(j=1;j<=i-1;j++)
{
printf(“%c”,(char)(j+64);
}
printf(“%n”);
}
getch();
}

Write a program to print following pattern for N lines


5
54
543
5432
54321

#include<stdio.h>
#include<conio.h>
Nitin Sir Page 66
void main()
{
int i, j, k;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=5-i;j++)
{
printf(“ ”);
}
for(j=1,k=5;j<=i;j++)
{
printf(“%d”, k--)’
}
printf(“\n”);
}
getch();
}

Write a program to print the following pattern.


A
BB
CCC
DDDD

#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, n;
printf(“Enter the number of lines:”);
scanf(“%d”, &n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(“ ”);
}
for(j=1;j<=i;j++)

Nitin Sir Page 67


{
printf(“%c”, (j+64));
}
printf(“\n”);
}
getch();
}

Write a Program to convert decimal to binary form.


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n, i;
clrscr();
printf(“Enter a number:”);
scanf(“%d”, &n);
printf(“Binary form is:”);
for(i=15;i>=0;i--)
{
printf(“%d”, n(int) pow(2,i));
n=n%(int)(pow(2,i));
}
getch();
}

Output 1:
Enter a number:12
Binary form is:0000000000001100

Output 2:
Enter a number:8
Binary form is:0000000000001000

Nitin Sir Page 68


Write a program to generate the following patterns.
1
21
123
4321
12345

#include<stdio.h>
#include<conio.h>
void main()
{
int i, j;
for(i=1;i<=5;i++)
{
if(i%2!=0)
{
for(j=1;j<=i;j++)
printf(“%d”, j);
}
else
{
for(j=0;j>=1;j--)
printf(“%d”, j);
}
}

Write a program to generate following patterns.


A
CB
FED
JIHG
ONMLK

#include<stdio.h>
#include<conio.h>
void main()
{
int n , i , j, m=65, k=64;
printf(“Enter n”);

Nitin Sir Page 69


scanf(“%d”, &n);
for(i=1;i<=n;i++)
{
k=k+i;
m=k;
for(j=0;j<=n-i;j++)
printf(“ ”);
for(j=1;j<=i;j++)
printf(“%c”, m--)
printf(“\n”;)
}
}

Write a C program to generate and print first N FIBONACCI numbers


#include <stdio.h>
void main()
{
int n1 =0, n2 =1, sum, n;
printf("Enter the value of n \n");
scanf("%d",&n);
printf("First %d FIBONACCI numbers are ...\n", n);
printf("%d\n", n1);
printf("%d\n", n2);
for(i=1;i<=num-2;i++)
{
sum = n1 + n2;
printf("%d\n", sum);
n1 = n2;
n2 = sum;
}
}

Write a program to calculate sum of series x = 1/2+3/4+5/6+…….n terms.


#include< stdio.h>
#include<conio.h>
void main()
{
int i, j, n;
float sum = 0;
printf(“How many terms\n”);
scanf(“%d”,&n);
j=1;

Nitin Sir Page 70


for(i=1;i<=n; i++)
{
sum = sum+(float)(j)/(j+1);
j=j+2;
}
printf(“sum = %f”,sum);
}
OUTPUT:
enter a number: 3
the value of this series= 2.083333

Write a program to calculate summation of series.


x=1-𝒙𝟐 /2!+𝒙𝟒 /4!-𝒙𝟔 /6!+𝒙𝟖 /8!..... upto n terms. [DEC-15, MAY-16]
#include<stdio.h>
#include<conio.h>
void main()
{
float x,sum,term,denr;
int i,n;
printf(“Enter the Value of x and Number of sums to be sum\t:”);
scanf(“%f%d”,&x,&n);
sum=1;term=1;
for(i=1;i<n;i++)
{
denr = (2*i)*(2*1-i);
term=-term*x*x/denr;
sum=sum+term;
}
printf(“\nthe sum =%f\nNumber of terms = %d\nvalue of x =%f\n
”,sum,n,x);
getch();
}

Write a program to calculate the value of the following series.

Nitin Sir Page 71


1 1 1 1
1+ + + + ⋯+
2! 3! 4! 𝑛!
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,fact=1;
float sum=0.0;
clrscr();
printf(“Enter a number”);
scanf(“%d”,&n);
for(i=1;i<n;i++)
{
fact=fact*i;
sum=sum+1.0/fact;
}
printf(“The value of the series is:%f”,sum);
getch();
}

Write a program to calculate summation of series


1/1! + 2/2! + 3/3! +….+ n/n! [10 M DEC-18]

#include <stdio.h>
#include <conio.h>
void main()
{
double n,f=1,i,sum=0;
printf("\n Enter the value: ");
scanf("%lf", &n);
for (i = 1; i <= n; i++)
{
f = f * i;
sum = sum +(i / f);
}
printf("\n Sum of the above series = %lf ", sum);
getch();
}

Nitin Sir Page 72


Write a program to calculate the sine of an angle using the following series
for x as the angle in radians .
𝒙𝟑 𝒙𝟓 𝒙𝟕 𝒙𝒏
sin x = x- + − …..
𝟑! 𝟓! 𝟕! 𝒏!
Accept the angle in degrees and value of n from user
Program
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
int i, n, fact=1, sign= -1;
float x, numerator, sum, term;
clrscr();
printf(“Enter an angle in degrees and the value of n: ”)
scanf(“%f %d”, &x, &n);
x=x*3.14/180;
term=x;
sum=term;
for(i=3;i<=n;i=i+2)
{
fact=fact*i*(i-1) ;
numerator=pow(x,i);
term=numerator/fact;
sum=sum+sign*term;
sign=sign*term;
}
print(“The value of the series is;%f”,sum);
getch();
}
Write a program to calculate the sum of series
x-x/2!+x/3!-x/4!..........x/n! [6 M May-19]
#include <math.h>
#include <stdio.h>
void main()
{
int n,x,fact=1,sum,i,se;
printf("Enter the value of n:");
scanf("%d",&n);
printf("Enter the value of x:");
Nitin Sir Page 73
scanf("%d",&x);
for(i=1;i<=n-1;i++)
{
fact = fact*i;
sum=sum+sign*x/fact;
sign=sign*-1;
}
printf("The result of series is: %d", sum);
getch();
}

An electric power distribution company charges its domestic consumer as


follows:
Consumption Units Rate of Charge
0-200 o.50 per unit
201-400 Rs. 100 plus Rs. 0.65 per
unit excess of 200
401-600 Rs. 230 plus Rs. 0.85 per
unit excess of 400
601-above Rs. 390 plus Rs. 1.00 per
unit excess of 600
Program should read the units consumed for a customer and calculate the
total bill.

#include<stdio.h>
#include<conio.h>
void main()
{
int units;
float charge;
clrscr();
printf(“Enter the units consumed:”);
scanf(“%d”, &units);
switch(units/200)
{
case 0: charge=units *0.5;
break;
case 1: charge=(units-200) *0.65+100;
break;
Nitin Sir Page 74
case 2: charge=(units-400) *0.85+230;
break;
default: charge=(units-600) +390;
break;
}
printf(“Charges=%f”, charge);
getch();
}

Write a program to find GCD and LCM of two numbers.


#include<stdio.h>
#include<conio.h>
void main()
{
int n1, n2, lcm, gcd;
clrscr();
printf(“Enter two numbers:”);
scanf(“%d %d”, &n1, &n2);
if (n1>n2)
{
lcm=n1;
gcd=n2;
}
else
{
lcm=n2;
gcd=n1;
}
while(lcm%n1!=0 ∥ lcm%n2!=0)
{
lcm++;
}
while(n1%gcd!=0 ∥ n2%gcd!=0)
{
gcd--;
}
printf(“LCM = %d\n GCD = %d”, lcm, gcd);
getch();
}

Nitin Sir Page 75


Output:
Enter two numbers:25
10
LCM = 50
GCD = 5

Branching Statements (Break, Continue and Go to)

Break :-

• Break statement is used to transfer the control of a program to end of


loop.
• When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop
• It can be used to terminate a case in the switch statement
• If you are using nested loops, the break statement will stop the execution
of the innermost loop.
• Syntax
break;

e.g :-

#include <stdio.h>
int main ()
{
int i = 1;
while( i <=10 )
{
printf("value of i: %d\n", i);
if( i= =5)
{
/* terminate the loop using break statement */
break;
}
i++;
}
return 0;
}
O/P

value of i: 1

Nitin Sir Page 76


value of i: 2
value of i: 3
value of i: 4
value of i: 5

Continue statement

continue statement are used to transfer the control of a program to begning on


loop and skip the rest of current statement in loop.

Syntax
continue;
e.g :
for (int j=1; j<=10; j++)
{
if (j==5)
{
continue;
}
printf("%d ", j);
}

Output:

1 2 3 4 6 7 8 9 10

GOTO statement
goto statement are used to transfer the control of a program from one part to
another part.

Syntax
goto label;
..
..
label: statement;

#include <stdio.h>
void main ()
{
int n = 1;
accept :
printf(“Enter a number\n”);
scanf(“%d”, & n);
if(n<0)
Nitin Sir Page 77
{
goto accept;
}
getch();
}

Program to check whether a given number is prime or not

/* Assume 2 is a prime number but 0 and 1 are not */


#include <stdio.h>
#include <conio.h>
void main()
{
int n ,i , flag ;
clrscr() ;
printf("Enter a number: ") ;
scanf("%d" , &n) ;
flag=1 ;
for(i=2 ; i<=n-1 ; n++)
{
if(n%i==0) /* True if number is not prime */
{
flag=0 ;
break ; /* Loop terminates if p is not prime */
}
}
if(flag==0)
printf("%d is not prime" , p) ;
else
printf("%d is prime" , p) ;
getch() ;
}
Output 1:
Enter a number: 1
1 is not prime
Output 2:
Enter a number: 7
7 is prime

Write a program to find GCD and LCM of 2 nos. 6M [Dec-14]


Nitin Sir Page 78
#include <stdio.h>
#include <conio.h>
int main()
{
int a, b, x, y, t, gcd, lcm;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
a = x;
b = y;
while (b != 0)
{
t = b;
b = a % b;
a = t;
}
gcd = a;
lcm = (x*y)/gcd;
printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);
printf("Least common multiple of %d and %d = %d\n", x, y, lcm);
return 0;
}
OUTPUT:
enter a two numbers: 25
10
LCM = 50
GCD = 5

Write a program to display Armstrong nos between 1 to 1000. 6M[May-13]


#include <stdio.h>
#include <conio.h>
int main( )
{
int r,number = 0, c, sum = 0, temp;
printf("Enter an integer upto which you want to find armstrong
numbers\n");
scanf("%d",&number);
printf("Following armstrong numbers are found from 1 to
%d\n",number);
for( c = 1 ; c <= number ; c++ )

Nitin Sir Page 79


{
temp = c;
while( temp != 0 )
{
r = temp%10;
sum = sum + r*r*r;
temp = temp/10;
}
if ( c == sum )
printf("%d\n", c);
sum = 0;
}
return 0;
}

Write a program to generate prime nos between 1 to100. 10M


#include<stdio.h>
#include<conio.h>
{
int main()
int n,j;
clrscr();
printf("Prime numbers between 1 to 100\n");
for(n=3;n<=100;n++)
{
for(j=2;j<n;j++)
{
if(n%j==0)
break;
}
if(j==n)
printf("%d",n);
}
getch();
return 0;
}
OUTPUT:
2 13 31 53 73
3 17 37 59 79

Nitin Sir Page 80


5 19 41 61 83
7 23 43 67 89
11 29 47 71 97

Write a program to display the factors of user entered number.


#include<stdio.h>
#include<conio.h>
void main ()
{
int n, i;
clrscr();
printf(“enter a number”);
scanf(“%d”,&n);
printf(“factors are : \n”);
i= 2;
while(i<n)
{
if(n%i==0)
printf(“%d”\n”,i);
i++
}
getch();
}
Output :
enter a number : 30
factors are:
2
3
5
6
10
15

Questions:-
1. Explain difference between for, while and do while loop. (4 Mks)
2. Write a program to generate patters.
3. Write a program to generate prime nos between 1 to 100. (10M)
4. Write a program to generate following patterns. 10M
Nitin Sir Page 81
5. Explain difference between while and do-while. [5 M]
6. Explain for loop with syntax and example [4 M]
1. Explain switch control statement with example [4 M].
2. Discuss what is need of break statement in switch case [4 M]
3. Explain the following with example 1) goto, 2) continue 3) break [4 M]
4. Write a program print the sum of following series
1+22+33+…….+nn [5 Marks] [MAY-18]
5. Comapre break and continue statements [5 Marks] [MAY-18]
6. Compare if-else and switch statements [5 Marks] [MAY-18]
7. Write a program to calculate number of vowels in the entered string. [6
Marks] [MAY-18]
8. Write a program to print following pattern
i) 5432*
543*1
54*21
5*321
*4321

ii) 5
54
543
5432
54321

Nitin Sir Page 82


CHAPTER 3
FUNCTIONS
• Function is a subprogram that perform particular task.
• Functions are used to break up large programs into named sections.
• The most important feartures of function is that, we can call the function many
times in the same program or in the external program.
• Basically functions are categorized into 2 types as :
1. Library functions (readymade functions)
2. User defined functions.

Why Function

• Block of code (function) that performs task has to be repeated in the


program as many number of times as required.
• Program can be shortened by writing this block of code only once and
using is everywhere.
• To avoid reparation of code.
• To make program modular.
• Reusability of code.
• To make program code readable and easy to maintain.

➢ Advantages of functions:
1. The length of the program gets reduce because functions are called
only whenever they are required.
2. While debugging errors, it becomes easy to find out errors if any.
3. The function written once can be used many times by many
programmers in the same program or in the external program.
4. Functional approach saves time and memory space.

Three program elements involved in using function

 Function prototype

 Function definition

 Call to the function

Nitin Sir Page 83


Function Prototype
<<return_type>> <<function_name>>(parameter list);

Function Defination
• Syntax :-
return _type function _name (argument _list)
{
Statements;
}
1. Return_type is the date type of the data to be returned by function
return_type can be void if no data is return.
The return type of the data can be any of the data types like int, char, float
etc.
2. Function name can be anything as far as rules of identifer is consider.
3. Argument list is set of data type with identifier to accept data passed to the
function when it is called.
4. Statement inside the function are the statement to be executed when
function is called.

Function Call
functionName (parameter list);

A function can be invoked whenever it is needed. It can be accessed by


specifying its name followed by a list of parameter enclosed in parenthesis and
separated by commas.

#include <stdio.h>
int add(int p, int q); // Function Prototype
int main()
{
int a,b,c;
printf(“Enter two numbers\n”);
scanf(“%d %d”,&a,&b);
c=add(a,b); // Calling Function
printf(“\n sum of two number is %d”,c);
return 0;
}
int add(int p, int q) // Function Defination
{
int result;
result=p+q;
Nitin Sir Page 84
return (result);
}

Write a program to find factorial of a number using a function.

#include <stdio.h>
int fact(int); // Function Prototype
void main()
{
int no, ans;
printf(“Enter a number\n”);
scanf(“%d ”,& no);
ans=fact(a,b); // Calling Function
printf(“\n factorial of number is %d”,ans);
getch();
}
int fact(int no) // Function Defination
{
int i, ans=1;
for(i=1;i<=no;i++)
{
ans=ans* i;
}
return ans;
}
O/P
Enter a number: 4
Factorial =24

Library functions

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


together and placed in a common place called library.
• Each library function in C performs specific operation.
• We can make use of these library functions to get the pre-defined output
instead of writing our own code to get those outputs.
• All C standard library functions are declared in many header files which
are saved as file_name.h.
• We are including these header files in our C program using
“#include<file_name.h>” command to make use of the functions those are
declared in the header files.
• When we include header files in our C program using
“#include<filename.h>” command, all C code of the header files are
Nitin Sir Page 85
included in C program. Then, this C program is compiled by compiler and
executed.

Explain any Three string standard library function. 3M [May-13]

S.No Header Description


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

1. stdio.h: I/O functions:


a. getchar() returns the next character typed on the keyboard.
b. putchar() outputs a single character to the screen.
c. printf() as previously described
d. scanf() as previously described
2. string.h: String functions
a. strcat() concatenates a copy of str2 to str1
b. strcmp() compares two strings
c. strcpy() copys contents of str2 to str1
3. math.h: Mathematics functions
a. acos() returns arc cosine of arg
b. asin() returns arc sine of arg
c. atan() returns arc tangent of arg
d. cos() returns cosine of arg
e. exp() returns natural logarithim e
f. fabs() returns absolute value of num
g. sqrt() returns square root of num.
2. time.h: Time and Date functions

a. time() returns current calender time of system


b. difftime() returns difference in secs between two times
c. clock() returns number of system clock cycles since program
execution

Nitin Sir Page 86


Functions in header file math. H

1. pow (x,y)
• This functions is available in the header file “math.h”
• This functions calculate and returns the value of xy.
• The parameters as well the ans returned are of double data type.

double pow (double x , double y)

e.g int x=4, y=2;

ans = pow(x,y); // 16.

2. sqrt(x)
• This function find the square root of the parameter passed to it.
• This functions is available in the header file “math.h”
• This function also accepts parameter of double data type.

double sqrt(double x).

e.g int x=16;

ans = sqrt(x); // 4.

3. ceil(x)

• This function returns the smallest integral value of the parameter passed
to the function.

• It rounds the value of x upward and returns the value.

• this functions is available in the header file “math.h”

double ceil (double x)

e.g :-

double x, val=1.6

x=ceil(val); // x=2.0

4. floor(x)

• This function returns the largest integral value of the parameter passed to
the function.

• It rounds the value of x downward and returns the value.

Nitin Sir Page 87


This functions is available in the header file “math.h”

double floor (double x).

e.g :- double x, val=1.6

x=floor(val); // x=1.0

5. abs()

• This function returns the absolute value of an integer.

• Absolute value of a number is always positive

• This functions is available in the header file “stdlib.h”

int abs(int n);

e.g int x,y=-9;

x=abs(y); // x=9;

6. isalnum()

• It checks if passed character is alphanumberic.

• This function returns non-zero value if c is digit or letter else it returns 0.

• This function is available in “ctype.h” header file.

int isalnum(int c);

e.g int x,y=’d’,z=’+’;

x= isalnum (y); // x=1;

x= isalnum (z); // x=0;

Nitin Sir Page 88


Explain the difference in using call by reference and call by value methods
for argument passing, for swapping 2 numbers. 8M [Dec-14].

Function communicates with each other by Argument passing.


Argument can be passed to a function by two methods.
1. Pass by value
2. Pass by reference

Pass by value (Call by value)

Arguments are passed by value while calling a function in C program.

Coping value of variable is another variable. So any changes made in the copy
will not affect the original location.

#include <stdio.h>
void swap(int a, int b);
int main()
{
int m=10,n=20;
printf(“value before swap m=%d and n=%d”,m,n);
swap (m.n);
printf(“value after swap m=%d and n=%d”,a,b);
}

void swap(int a, int b) // Function Defination


{
int temp;
temp=a;
a=b;
b=temp;
}
O/P

value before swap m=10 and n=20

value after swap m=10 and n=20

Nitin Sir Page 89


Pass by reference (Call by reference)

Arguments are passed by address while calling a function in C program.

Creating link for the parameter to the original location, since the address is
same, changes to the parameter will refer to the original location and value will
be overwritten.

#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m=10,n=20;
printf(“value before swap m=%d and n=%d”,m,n);
swap (&m.&n);
printf(“value after swap m=%d and n=%d”,*a,*b);
}
void swap(int *a, int *b) // Function Defination
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
O/P
value before swap m=10 and n=20
value after swap m=20 and n=10

Difference between call by value and call by reference.

Call by value Call by reference.


When functions are called by passing When functions are called by passing
the values they are called as call by memory addresses (pointers) of
value. values, they are called as by
reference.
It is risky to call function by value There is absolutely no risk when
because values may get conflict or functions are called by passing
interchange in a complicated and address of variables though the
large programs. program is complicated or large.
Call by value wastes the memory. Call by references does not waste
memory, as new variables are not
crated.

Nitin Sir Page 90


Call by value function is less efficient Call by references works more
than call by references. efficiently than call by value.

Write a program to find the value of ncr (combination),using a function.

#include<stdio.h>
#include<conio.h>
void main ()
{
int n,r,ncr ;
int fact (int no);
clrscr();
pintf(“enter the values of n and r”);
scanf(“%d %d ”,&n,&r);
ncr = fact (n) / (fact(r)*fact(n- r));
printf(“ncr=%d”,ncr);
getch();
}
int fact (int no)
{
int i , f=1 ;
for(i= 1; i<=no; i++)
{
f = f * i;
}
return f;
}
OUTPUT:
enter the values of n and r:5
3
ncr = 10

Write a function to check whether a given number is a palindrome or not


using function.
#include <stdio.h>
#include <conio.h>
int palindrome(int n)
{
int r , rev=0 , temp ;
temp=n ;
while(n!=0)
{
Nitin Sir Page 91
r=n%10 ;
rev=rev*10+r ;
n=n/10 ;
}

if(rev==temp)
return 1 ;
else
return 0 ;
}
void main()
{
int n , flag ;
clrscr() ;
printf("Enter a number: ") ;
scanf("%d" , &n) ;
flag=palindrome(n) ;
if(flag==1)
printf("%d is a palindrome" , n) ;
else
printf("%d is not a palindrome" , n) ;
getch() ;
}
Output1:
Enter a number: 24542
24542 is a palindrome

Output2:
Enter a number: 2464
2464 is not a palindrome

Introduction to Recursive Functions


• A function that calls itself is called as a recursive function.
• A recursive function must definitely have a condition that exit from calling the
function again.
• Hence there must be a condition that calls the function itself if that condition
is true. If the condition could also be implemented vice versa i.e. if the
condition is false then the function calls itself else if the condition true, it will
exit from the loop calling itself again.

Nitin Sir Page 92


Write a program to find factorial of a number using recursion
#include <stdio.h>
long int fact(int);
int main()
{
int n,ans;
printf(“Enter a number \n);
scanf(“%d”,&n);
ans=fact(n);
printf(“Factorial of %d is %d” ,n,ans);
return 0;
}
long int fact(int x)
{
long int f;
if(x= =1)
{
return(x);
}
else
{
f=x*fact(x-1);
return (f);
}
}

Write a program to find value of y using a recursive function, where y =


xn
#include<stdio.h>
#include<conio.h>
int exponential (int , int );
void main()
{
int n , x , y;
printf(“Enter the value of x and n \n”);
scanf(“%d %d”,&x , &n);
y = exponential(x, n);
printf(“the value of x raise to is %d”,y);
getch();
}
Nitin Sir Page 93
int exponential (int x , int n)
{
int ans;
if(n == 1)
{
return x ;
}
else
{
ans= x * exponential(x, n-1);
return(ans);
}
}
OUTPUT:
enter the values of x and n
2
6
the value of x raise to n is 64

Write a recursive function to compute sum of first n number beginning


with 1.
#include<stdio.h>
#include<conio.h>
int compute(int);
void main()
{
int no ,sum;
printf(“Enter a number \n”);
scanf(“%d”,&no);
sum= compute (no);
printf(“sum of number from 1 to n %d”,sum);
getch();
}
int compute (int n)
{
int ans;
if(n = = 1)
{
return 1 ;

Nitin Sir Page 94


}
else
{
ans= n + compute(n-1);
return(ans);
}
}
Output :-
Enter a number
10
Sum of 1 to n is 55.

Write a program to display Fibonacci series using recursive function.


#include<stdio.h>
#include<conio.h>
int fibo(int);
void main()
{
int n,i,c,f;
printf(“Enter a number of terms”);
scanf(“%d”, &n);
for(c=1;c<=n;c++)
{
f=fibo(i);
printf(“%d”,f);
i++
}
getch();
}
int fibo(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}

Nitin Sir Page 95


else
{
return (fibo(n-1) + fibo (n-2));
}
}

Write a program for sum of digits use recursive function to calculate


sum of digits of an integer
#include <stdio.h>
#include <conio.h>
int sum(int n)
{
if(n==0)
return 0 ;
else
return( n%10 + sum(n/10) ) ;
}
void main()
{
int n,ans ;
printf("Enter the number: ") ;
scanf("%d" , &n) ;
ans= sum(n);
printf("Sum of digits of %d is %d" , n ,ans) ;
getch() ;
}

/*
Output:

Enter the number: 246


Sum of digits of 246 is 12
*/

Write a program to reverse a number using recursion.


#include <stdio.h>
#include <conio.h>
int rev(int n);
void main()

Nitin Sir Page 96


{
int n,ans ;
printf("Enter the number: ") ;
scanf("%d" , &n) ;
ans= rev(n);
printf("Reverse number is %d" , ans) ;
getch() ;
}

int rev(int n)
{
Static sum,r;
if(n>0)
{
r=n %10;
s=s*10+r;
rev(n/10);
}
else
{
return 0;
}
return sum;
}

Questions :

1. Explain difference between call by value and call by reference. [Dec-14/


May-13] 8Marks.
2. Explain recursion concept. Write a program to display Fibonacci series
using recursion. [May-13]. 8 Marks
3. Write a recursive program to calculate factorial of accepted number.
[May-13]. 6 Marks
4. Write a program using function to print first ‘n’ numbers in Fibonacci
series. [Dec-14] 5 Marks.
5. Write a program using recursive function ‘power’ to compute 𝑥 𝑛
[DEC-14] 8MARKS
Power(x,n) = 1 if n = 0
Power(x,n) = x if n = 1
Power(x,n) = x*power(x, n – 1) otherwise
Nitin Sir Page 97
6. What do mean by Recursion? write a program which will accept two
number, n and r and calculation value of n𝐶𝑟 = n! / r! (n-r) !. Program
should make use of recursion.[May-14] 10Marks.
7. Explain recursion concept. Write a program to display Fibonacci series
using recursion. 8M [May-13]
8. Explain following standard library functions i) Floor() ii) ceil() iii) sqrt ()
9. Explain any 2 library functions in math.h along with its uses [4 M].
10. Explain any three string standard library functions [3 M].
11. State any 2 library function in string.h along with its uses. [4 M].

Nitin Sir Page 98


STORAGE CLASSES FOR SCALAR TYPE DATA

• The different locations in the computer where we can store data and their
accessibility, initial values etc. vary based on the way they are declared. These
different ways are termed as different storage classes.
• In C, we have four storage classes, Namely
1. Automatic
2. Register
3. Static
4. External or Global

1. Automatic storage class


• In this case data is stored in memory
• The initial value of such a variable is garbage
• The scope of the variable is local i.e. limited to the function in which it is
defined.
• The life of such variables is till the control remains in the particular function
where it is defined.
• by default variable declared is of auto storage class.
• For e.g.:

int i;
or
auto int i;

2. Register storage class


• In this case data is stored in CPU register
• The initial value of such variable is garbage.
• The scope of the variable is local i.e. limited to the function in which it is
defined.
• The life of such variable is till the control remains in the particular function
where it is defined.
• For e.g.:
register int i;
• In this case the data is stored in a small memory inside the processor called
as its registers.
• The advantage of such storage class is that since the data is in the processor
itself, its access and operation on such data is faster.
• There is a limitation on the size of the data that can be declared to be
register storage class.
Nitin Sir Page 99
• The data should be such that it doesn’t require more than 4 bytes.

3. Static storage class


• In this case data is stored in memory
• The initial value of such a variable is zero.
• The scope of the variable is local i.e. limited to the function in which it is
defined.
• The life of such variable is till the program is alive.
• For e.g.:
Static int i;
• If a variable is declared static, its value remains unchanged even if the
function execution is completed.
4. Extern storage class

• Initial value is zero.

• Scope of variable is global.

• Lifetime is entire program

Questions:-

1. What do you mean by static and storage class, Explain? [Dec-13] 4


Marks.
2. Explain various storage classes used in c with example. [May-13]
5Marks.
3. What do you mean by auto and extern storage class? Explain with
example [Mar-14].4Marks.
4. Explain array and what need of an array is [4 M].
5. Explain any two storage class with example [4 M].
6. Explain various storage classes used in c with example [5 M].
7. What is significance of storage class illustrate each storage class with
example [4 M].

Nitin Sir Page 100


CHAPTER 4 : ARRAYS

• It is a collection of multiple data of same data type.


• All elements of an array have to be of same type only.
• Array is of two types
• Single Dimensional Arrays
• Multidimensional Arrays.
Single Dimensional Arrays

• It is a collection of data of same data type.


• All elements of an array have to be of same type only. We cannot have an
array of combination of different data types.
• For example to store marks of 30 students in a class, 30 variable would be
required, array provide the solution; since one variable can hold many
elements of similar type.
• The starting index i.e. index of the first element of an array is always zero.
• The index of last element is n-1, where n is the size of the array.

Syntax of declaring an array


Data _type array _name [ array_size ];

• Data _type is the data type like int, float, double etc.
• Array _name is the identifier i.e. the name of an array.
• Array _size is an integer value which determines size of the array

E.g int age[5];

Initilisation of an array :-

age[0]=18;
age[1]=20;

Nitin Sir Page 101


Write a program to accept and display elements of an array.
#include<conio.h>
#include <stdio.h>
void main()
{
int n,i , a[10];
printf(“Enter the number of elements”);
scanf(“%d”,& n);
printf(“Enter the elements of array”);
for(i=0; i<n; i++)
{
Scanf(“%d”, & a[i]);
}
printf(“The elements of array are”);
for(i=0; i<n; i++)
{
printf(“%d\n”, a[i]);
}
getch();
}

Write a program to find largest of ‘n’ numbers taken from user


#include <stdio.h>
#include<conio.h>
void main()
{
int a[30],i, max, n;
printf("Enter the number of elements \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
max = a[0];
for (i = 1; i < n; i++)
{
if (a[i] > max)
{
max = a[i];
}
}
printf("Largest number is %d.\n",max);
Nitin Sir Page 102
getch();
}
Output:-

Enter the number of elements : 5

30

12

14

88

19

The largest number is 88

C program to sort N numbers in ascending order using Bubble sort [May-13,


May-14]
#include<stdio.h>
#include<conio.h>
void main()
{
int a [30],i,j, no,temp;
printf("\nEnter the no of Elements: ");
scanf("%d", &no);
for(i=0;i<no;i++)
{
printf("\n Enter Element");
scanf("%d",&a[i]);
}
for(i=1;i<no;i++)
{
for(j=0;j<no-i;j++)
{
if(a[j] > a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

Nitin Sir Page 103


}
printf("\nSorted array:");
for(i=0;i<no;i++)
{
printf("\t%d",a[i]);
}
getch();
}

Output:-

Enter the no of Elements: 5

Enter Element: 2
Enter Element: 5
Enter Element: 9
Enter Element: 7
Enter Element: 3
Sorted array: 2 3 5 7 9

Write a program to impliment bubble sorting algorithm for sorting


numbers in descending order.[ DEC-13]

#include<stdio.h>
#include<conio.h>
void main()
{
int a [30],i,j, no,temp;
printf("\nEnter the no of Elements: ");
scanf("%d", &no);
for(i=0;i<no;i++)
{
printf("\n Enter Element");
scanf("%d",&a[i]);
}
for(i=1;i<no;i++)
{
for(j=0;j<no-i;j++)
{
if(a[j] < a[j+1])
{
temp=a[j];
Nitin Sir Page 104
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nSorted array:");
for(i=0;i<no;i++)
{
printf("\t%d",a[i]);
}
getch();
}

Output:-

Enter the no of Elements: 5

Enter Element: 2
Enter Element: 5
Enter Element: 9
Enter Element: 7
Enter Element: 3
Sorted array: 9 7 5 3 2

Passing Array to function

Array can be passed to a function by simply giving the name of an array as


arguments.

Write a program to find smallest of ‘n’ numbers taken from user, using
function. [DEC-15]

#include <stdio.h>
int main()
{
int a[30],i, small, n;
printf("Enter the number of elements \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}

Nitin Sir Page 105


small=smallest(a,n);
printf("The smallest number is %d.\n",small);
return 0;
}

int smallest ( int a[] , int n)


{
Int i, small;
small = a[0];
for (i = 1; i < n; i++)
{
if (small>a[i])
{
small = a[i];
}
}
return small;
}
Output:-

Enter the number of elements : 5

30

12

14

88

19

The smallest number is 12.

Write a program to search a number within the array. [DEC-15]

#include<stdio.h>
#include<conio.h>
int search(int a[], int n, int x);
void main()
{
int a [30],i,x, no,index;
printf("\nEnter the no of Elements: ");
scanf("%d", &no);
for(i=0;i<no;i++)
{
Nitin Sir Page 106
printf("\n Enter Element");
scanf("%d",&a[i]);
}
printf("\n Enter the element to be searched:");
scanf(“ %d ”, &x);
index=search(a,n,x);
if(index==n)
{
Printf(“Element Not found\n”);
}
Else
{
Printf(“Element is found at index %d \n”, index);
}
getch();
}
int search(int a[], int n, int x)
{
int i;
for(i=0;i<n-1;i++)
{
if(x = =a[i])
{
break;
}
}
Return i;
}

Nitin Sir Page 107


Write a program in c to accept an array A with a element and seprate it
into two different arrays B. and C in such a way that B contains Odd
number and C contains even numbers. i.e A contains A={3,2,4,2,5,7,8} then
B={3,5,7} and C={2,4,2,8}.
#include<stdio.h>
#include<conio.h>
int search(int a[], int n, int x);
void main()
{
int A [10],B[10],C[10];
int i,j=0,k=0,n;
printf(“Enter the size of array A\n”)
scanf(“%d”, &n);
printf(“Enter the elements of the array”);
for(i=0;i <n;i++)
{
Scanf(“%d”, &A[i]);
}
for(i=0; i <n;i++)
{
if(A[i] % 2== 0)
{
C[j]=A[i]);
j++;
}
else
{
B[k]=A[i];
k++;
}
}
Printf(“The elements of odd array are\n”)
for(i=0; i<j;i++)
{
printf(“%d\n”,B[i]);
}
for(i=0; i<k;i++)
{
printf(“%d\n”,C[i]);
}
getch();
}

Nitin Sir Page 108


Write a program to find the frequency of digit in a set of numbers and
remove duplicates from an array. For ex. Array A={1,2,3,4,2,5,2} frequency of
2 is 3 and resultant array is A={1,2,3,4,5}. [10M May-19]

#include<stdio.h>
#include<conio.h>
void main()
{
int a[7]={1,2,3,4,2,5,2};
int b[10];
int i,j,count=0;
clrscr();
for(i=0;i<6;i++)
{
for(j=0;j<count;j++)
{
if(a[i]==b[j])
break;
}
if(j==count)
{
b[count] = a[i];
count++;
}
}
for(i=0;i<count;i++)
{
printf("%d",b[i]);
}
getch();
}

Nitin Sir Page 109


Multi-dimensional Arrays

• Multi dimensional arrays are used to store data that requires multiple
references like row number and column number.
• “matrix” is a best example of two dimensional arrays.
• The size of the array will be 3×3, but the indices will be from 0 to 2 in both
the rows and columns.
• Syntax:-

Data_Type array_name[no of rows][no of columns];

e.g :-int a[3][3]; column

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


row
a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]

Initialisation:-

a[3][3]={{1,2,3},{4,5,6},{7,8,9}}

1 2 3
4 5 6
7 8 9

Write a program to accept and display elements in an 2-D array.

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[3][3], i, j, sum=0;
/*Accepts input from the user and stores it in 2-D array*/
printf(“Enter the number of rows and columns\n”)
scanf(“%d %d” ,&m, & n);
printf(“Enter the value for matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&arr[i][j]);

Nitin Sir Page 110


}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d/t”, arr[i][j]);
}
Printf(“/n”);
}
getch();
}
Output :-

Enter the number of rows and columns


3 3
Enter the value for matrix A
1 2 3 4 5 6 7 8 9

1 2 3
4 5 6
7 8 9

Write a Program for addition of two matrices of size m x n.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the First matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix");
Nitin Sir Page 111
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nThe Addition of two matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d",c[i][j]);
}
printf(“\n”);
}
getch();
}

Write a c program to determine whether a matrix is Symmetric or not


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

int n,i,j,temp,a[5][5],flag=0,b[5][5];
clrscr();
printf("Enter the order of the matrix::\n");
scanf("%d",&n);
printf("Enter the elements of the matrix::\n");
for(i=0;i<n;i++)
{

Nitin Sir Page 112


for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<n;i++)
{

for(j=0;j<n;j++)
{
b[i][j]=a[i][j];
}

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

{
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
}
printf("Transpose Matrix is::\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
for(i=0;i<n;i++)
{

for(j=0;j<n;j++)
{
if(a[i][j]!=b[i][j])
{
flag=1;
Nitin Sir Page 113
}
}
}
if(flag==1)
{
printf("The matrix is not symmetric.");
}
else
printf("Matrix is symmetric.");
}

getch();

Write a program to find transpose of a matrix of size m x n.


#include <stdio.h>
int main()
{
int m, n, i, j, matrix[10][10], transpose[10][10];
printf("Enter the number of rows and columns of matrix ");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix \n");
for( i = 0 ; i < m ; i++ )
{
for( j = 0 ; j < n ; j++ )
{
scanf("%d",&matrix[i][j]);
}
}
for( i = 0 ; i < m ; i++ )
{
for( j = 0 ; j < n ; j++ )
{
transpose[j][i] = matrix[i][j];
}
}
printf("Transpose of entered matrix :-\n");
for( i = 0 ; i < n ; i++ )
{
for( j = 0 ; j < m ; j++ )
Nitin Sir Page 114
{
printf("%d\t",transpose[i][j]);
}
printf("\n");
}
return 0;
}

Write a program for multiplication of two matrix of size m x n.


#include <stdio.h>
#inlcude<conio.h>
int main()
{
int m, n, p, q, i, j, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
scanf("%d", &first[i][j]);
}
}
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if ( n != p )
{
printf("Matrices with entered orders can't be multiplied with each
other.\n");
}
else
{
printf("Enter the elements of second matrix\n");
for ( i = 0 ; i < p ; i++ )
{
for ( j = 0 ; j < q ; j++ )
{
Nitin Sir Page 115
scanf("%d", &second[i][j]);
}
}
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < q ; j++ )
{
multiply[i][j]=0;
for ( k = 0 ; k < p ; k++ )
{
multiply[i][j]=multiply[i][j]+ first[i][k]*second[k][j];
}
}
}
printf("Product of entered matrices:-\n");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < q ; j++ )
{
printf("%d\t", multiply[i][j]);
}
printf("\n");
}
}
return 0;
}

Nitin Sir Page 116


Write a program to find transpose of a matrix of size m x n. using a
function transpose.

#include <stdio.h>
void transpose (int [][] ,int ,int );
int main()
{
int m, n, i, j, matrix[10][10];
printf("Enter the number of rows and columns of matrix ");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix \n");
for( i= 0 ; i < m ; i++ )
{
for( j = 0 ; j < n ; j++ )
{
scanf("%d", &matrix[i][j]);
}
}
transpose (matrix,m,n);
return 0;
}

Void transpose (int a[10][10], int m, int n)


{
int b[10][10], i ,j;
for( i= 0 ; i < m ; i++ )
{
for( j = 0 ; j < n ; j++ )
{
b[j][i] = a[i][j];
}
}
printf("Transpose of entered matrix :-\n");
for( i = 0 ; i < n ; i++ )
{
for(j = 0 ; j< m ; j++ )
{
printf("%d\t", b[i][j]);
}
printf("\n");
Nitin Sir Page 117
}
}

Write a program to find transpose of a square matrix. using a function


transpose.
#include <stdio.h>
void transpose (int [][] ,int ,int );
int main()
{
int m, n, i, j, matrix[10][10];
printf("Enter the number of rows and columns of matrix ");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix \n");
for( i= 0 ; i < m ; i++ )
{
for( j = 0 ; j < n ; j++ )
{
scanf("%d", &matrix[i][j]);
}
}
transpose (matrix,m,n);
return 0;
}

void transpose (int a[10][10], int m, int n)


{
int i ,j, temp;
for( i= 0 ; i < m ; i++ )
{
for( j = i ; j < n ; j++ )
{
temp=a[j][i];
a[j][i] = a[i][j];
a[i][j]=temp;
}
}
printf("Transpose of entered matrix :-\n");
for( i = 0 ; i < m ; i++ )
{

Nitin Sir Page 118


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

Write a program to multiply two matrix using a function.


#include <stdio.h>
#include<conio.h>
int main()
{
int m, n, p, q, i, j, k;
int a[10][10], b[10][10];
printf("Enter the number of rows and columns of matrix A\n");
scanf("%d %d", &m, &n);
printf("Enter the elements of matrix A\n");
for ( i = 0 ; i < m ; i++ )
{
for (j = 0 ; j < n ; j++ )
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the number of rows and columns of matrix B\n");
scanf("%d%d", &p, &q);
printf("Enter the elements of matrix B\n");
for ( i = 0 ; i < p ; i++ )
{
for ( j = 0 ; j < q ; j++ )
{
scanf("%d", & b[i][j]);
}
}
if ( n != p )
{

Nitin Sir Page 119


printf("Matrices with entered orders can't be multiplied with each
other.\n");
}
else
{
matmult(a,b, m, n, q);
}
return 0;
}

void matmult (int a[10][10],int b[10][10],int m, int n, int q);


{
Int i, j, k, c[10][10];
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("Product of entered matrices:-\n");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < q ; j++ )
{
printf("%d\t", c[i][j]);
}
printf("\n");
}
}

Nitin Sir Page 120


Questions :-

1. Explain array and what need of an array is [4 M].


2. Write a program to sort given nos in desending order. [Mar-13/May-13]
10 Marks.
3. Write an algorithm to sort set of numbers in ascending order[May-14]10
Marks. For above problem in which cases time complexity is calculated.
[May-13] 6 Marks.
4. Write a program which will accept 2 dimensional square matrix and find
out transpose of it. Program should not make use of another matrix. [Dec-
13] 10 Marks.
5. write a program to calculate matrix multiplication and transpose for a
matrix. [May-13] 8 Marks.
6. Write a program in C to read and display element of a square (2D) matrix
and check whether the entered matrix is symmetric or not. [Dec -14]10
Marks.
7. Write a program which will accepts a 2 dimensional square matrix and
find out transpose of it. Program should not make use of another matrix.
[May-14] 10M

Nitin Sir Page 121


STRINGS
String is defined as collection of characters.

Syntax :

char array_name [size] ;

eg.: Char str [7] = {“Hello”},

H e l l o \0
0 1 2 3 4 5 6

‘/0’ is called as mull value. It is used to indicate end of string.

Initializing String :
String can be initialized in two ways.

eg. :-

1) Char str [ 25 ] = {“Hello”} ,

2) Char str [ 25 ] = {‘H’ , ‘e’ , ‘l’ , ‘ l ‘ , ‘ o’, ‘ lo’}

Three are many string standard library function. These functions are available in
string.h
Some of them can be explained as follows.
1) strlen( )-
Syntax
int strlen(char*)
The strlen ( ) accepts string and calculates and returns the length of the
string which determines number of characters present in the string.
For example,
int n;
n = strlen(“hello”);
will assign value 5 to variable n.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
Nitin Sir Page 122
int len;
char str[100];
printf(“Enter a string\n”);
gets (str);
len=strlen(str);
printf( “The length of string is %d”, len);
getch();
}

2) strcpy( )-
Syntax
char * strcpy(char *d, char *s);
char s1[ ]= “hello”,s2[80];
strcpy(s2,s1);

Due to strcpy( ) string “hello” present in character array s1 will be copied


into character array s2.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[100],d[100];
printf(“Enter a string\n”);
gets (s);
strcpy(d,s);
printf( “The new string is %s”, d);
getch();
}

3) strncpy( ) –
Syntax
char * strncpy(char *destination, char *source, int length)
The strncpy ( ) will copy maximum length number of characters from
source string into destination character array.
For example
char s1[ ]= “welcome”, s2[80];
strncpy (s2,s1, 3);
Due to strncpy( ) string first three character from string s1 i.e. ‘w’,’e’,’l’

Nitin Sir Page 123


are copied into s2[0],s2[1] and s2[2].
The string s2 then become “wel”.

4) stracat()-
Syntax
char * strcat(char *destination, char *source)
The strcat ( )will concatenate (Join) source string into destination
character array.
For e.g.,
Char s1[]= “hello”, s2[80]= “welcome”;
strcat(s2,s1);
Due to strcat () string “hello” present in character array s1 will be
Concatenated onto string present in character array s2 into
“welcomehello” in s2.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[100],d[100];
printf(“Enter two string\n”);
gets (s);
gets (d);
strcat(s,d);
printf( “The concatenated string is %s”, s);
getch();
}

5) strcmp()
Syntax
int strcmp( char *s. char *d);
This function compares the two string variables passed to it.
It returns integer value
• 0 if two strings are equal.
• Negative value, if the first string is smaller than second
string.
• Positive value, if the first string is greater than second
string.

Nitin Sir Page 124


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
Int i;
char s[100],d[100];
printf(“Enter two string\n”);
gets (s);
gets (d);
i=strcmp(s,d);
if(i==0)
{
printf(“The strings are equal\n”);
}
else if(i>0)
{
printf(“%s strings is greater\n”,s);
}
else
{
printf(“%s strings is greater\n”,d);
}
getch();
}

Write a program to accept a string and find its length without using string
header file.
#include<stdio.h>
#include<conio.h>
void main()
{
int len=0;
char str[100];
printf(“Enter a string\n”);
gets (str);
while(str[len]!=’\0’)
{
len++;

Nitin Sir Page 125


}
printf( “The length of string is %d”, len);
getch();
}

Write a program to copy one string to another without using string header
file.

#include<stdio.h>
#inlclude<conio.h>
void main()
{
char tar[20],src[20],*t;
int i=0;
clrscr();
printf("\nEnter first string: ");
gets(tar);
t = tar;
printf("\nEnter second string: ");
gets(src);
while(src[i]!='\0')
{
tar[i] = src[i];
i++;
}
tar[i]= '\0';
printf("\nSecond string after copy::");
puts(t);
getch();
}

Write a program to join one string to another without using string header
file.

#include<stdio.h>
#inlclude<conio.h>
void main()
{
char a[20],b[20];
int i=0,j=0;
Nitin Sir Page 126
clrscr();
printf("\nEnter first string: ");
gets(a);
printf("\nEnter second string: ");
gets(b);
while(a[i]!='\0')
{
i++;
}
while(b[j]!='\0')
{
a[i]=b[j];
i++;
j++;
}
a[i]=’\0’;
printf("\n New string after join::");
puts(a);
getch();
}

Write a C program to check whether the given String Palindrome or not .


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[20];
int flag=0,i,len;
clrscr();
printf("enter any string\n");
gets(st);
len=strlen(st);
for(i=0;i<len/2;i++)
{
if(st[i]!=st[len-1-i])
{
flag=1;
break;
Nitin Sir Page 127
}
}
if(flag==0)
printf("String is Palindrom");
else
printf("String is not palindrom\n");
getch();
}

String - Program which reads month number and displays the same in
words. (Use two dimensional array) */
#include <stdio.h>
#include <conio.h>
void main()
{
int m ;
char x[12][10] = {"January" , "February" , "March" , "April" ,
"May" , "June" , "July" , "August" , "September" , "October",
"November" , "December" } ;
clrscr();
printf("Enter the month number: ") ;
scanf("%d" , &m) ;
printf("Month in words is: %s" , x[m-1]) ;
getch();
}
Output:

Enter the month number: 7

Month in words is: July

String vowel count - Program to count the number of vowels in a given


string

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
void main()
{
char str[50] , c ;
int i , v=0 ;
clrscr() ;
printf("Enter a string: ") ;
Nitin Sir Page 128
gets(str) ;
for(i=0 ; str[i]!='\0' ; i++)
{
c=tolower(str[i]) ;
if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u')
v++ ;
}
printf("Number of vowels in %s is %d" , str , v) ;
getch() ;
}
Output:
Enter a string: Umbrella is nice
Number of vowels in Umbrella is nice is 6

Write a program for performing following operation on strings using


function
i) Copying one string to another
ii) Adding one string to the end of another
#include<stdio.h>
#include<conio.h>
Void main()
{
Int n=0;
Char a[100],b[100];
Printf(“Enter a string”);
gets(a);
while(a[n]!=’\0’)
{
n++;
}
copy(a,b);
printf(“After copy new string is %s”,b);
join(a,b);
printf(“New string after join %s”,a);
getch();
}
void copy( char src [100],char tar [100])
{
int i;

Nitin Sir Page 129


while(src[i]!='\0')
{
tar[i] = src[i];
i++;
}
tar[i]= '\0';
}
void copy( char a[100],char b[100])
{
int i,j;
while(a[i]!='\0')
{
i++;
}
while(b[j]!='\0')
{
a[i]=b[j];
i++;
j++;
}
a[i]=’\0’;
}

Questions : -
Write a user defined function to copy one string to another. 4 Marks.

Write a program to validate whether accepted string is palindrome or not.


[May-13]5Marks

Write a program to check whether given string is palindrome or not. [Dec-13]


10Marks.

Nitin Sir Page 130


Chapter 5 Structure and Union

Structures
• Structure is a collection of multiple data elements that can be of different
data types.
• Array is a collection of data items of same type, while structure can have
data items of different type
• The memory space required to store one variable of structure is equal to
the memory space by all the elements independently.

Syntax of structure declaration:

struct structure_name

data_type variable_name;

data_type variable name;

};

For example a structure to store the some information like name, roll number
and fees of a student in college can be declared as show below.

struct student
{
char name [20];
int roll_no;
float fees;
};
Structure is normally used when a set of data items corresponding to a common
thing are to be stored together.

• To access a member element of a structure variable we use the dot


operator (“.”), also called as the period operator. The syntax of accessing
a structure element is given below:
Structure_variableName. variableName;
e.g s.fees;
Nitin Sir Page 131
//Objetive : Demonstrate simple structure

#include<stdio.h>
struct Student
{
int iRollNo;
char cName[20];
float fMarks;
};
int main()
{
//create var inside main
struct Student s1;
struct Student s2 = {1,"aa",70.6};//create and initialize
float m;
clrscr();

printf("\nroll number is ::");


scanf("%d",&s1.iRollNo);
printf("\nName is ::");
gets(s1.cName);
printf("\nMarks are ::");
scanf("%f",& s1.fMarks);
printf("\n\tRollNo\t\tName\t\tMarks");
printf("\n\t%d\t\t%s\t\t%f",s1.iRollNo,s1.cName,s1.fMarks);
printf("\n\t%d\t\t%s\t\t%f",s2.iRollNo,s2.cName,s2.fMarks);
getch();
return 0;
}

Arrays of structure variable


• To store collection of records we can use array of structure.
• An array of structure can be declared in the same way as declaring array
of any other data type.
• For example, an array of the structure student can be declared as shown
below:
struct student s[100];

This array can now store information of 100 students.


Nitin Sir Page 132
Write a program to declare structure employee having data member
name, age, street and city. Accept data for 5 employee and display it.

#include<stdio,h>
#include<conio.h>
struct employee
{
int age;
char name [40];
char street [40];
char city [40];
};
void main()
{
struct employee e[5];
for(i=0;i<5;i++) /*reading/
{
printf(“Enter employee name”);
gets(e[i].name);
printf(“Enter age”);
scanf(“%d”,&e[i].age);
printf(“Enter street”);
gets(e[i].street);
printf(“Enter city”);
gets(e[i].city);

}
printf(“Employe Name\t Age \t Street\t City\n”);
for(i=0;i<5;i++)
{
printf(“%s\t %d\t %s\t %s\n”, e[i].name, e[i].age, e[i].street,
e[i].city);
}
getch();
}

Write a Program to create an array of structure to store the details of


almost 100 employees and sort it according to employee-ID. Employee
details are as follows.

Nitin Sir Page 133


▪ Employee name
▪ Employee id
▪ Employee salary.

#include<stdio,h>
#include<conio.h>
struct employee
{
int id;
char name [40];
float salary;
};
void main()
{
struct employee e[100],temp;
int n;
printf(“How many elements(not more than 100)=”);
scanf(“%d”,&n);
printf(“Enter information of all\n”)
for(i=0;i<n;i++) /*reading/
{
printf(“ID = ”);
scanf(“%d”,&e[i].id);
printf(“Name =”);
gets(e[i].name);
printf(“Salary=”);
scanf(“%f”,&e[i].salary);
}
for(i = n – 1;i>0;i - -)
{
for(j=0;j < i ; j++)
{
if(e[j].salary < e[j+1].salary) /*descending order*/
{
temp = e[j];
e[j] = e[j+1];
e[j+1] = temp;
}
}

Nitin Sir Page 134


}
printf(“EMPID EMP_Name Emp_Salary\n”);
for(i=0;i<n;i++)
{
printf(“%2d %-40s %10.2f\n”, e[i].id, e[i].name,e[i].salary);
}
getch();
}

Nested Structure
Nested structure in c is nothing but structure within structure.
One structure can be declared inside other structure as we
declare structure member inside other structure.
Syntax
Struct structure_name

Data_type variable_name;

Struct

Data_type variable_name;

Data_type variable_name;

}Internal_structure_name;

Define structure within structure consisting of following elements :

(i) Employee code


(ii) Employee name
(iii) Employee salary and
Nitin Sir Page 135
(iv) Employee date_of_joining
Write a C program to read at least 10 records and display them.
#include<conio.h>
#include<stdio.h>
struct employee
{
char name[20];
int salary, code;
{
int date, month, year;
}
date_joining;
};
void main()
{
struct employee e[100];
int i;
clrscr();
for(i=0;i<=9;i++)
{
printf(“Enter the emplyee’s name, code, salary and date of
joining as date, month and year separately:”);
scanf(“%s %d %d %d %d %d”, e[i].name, &e[i].code,
&e[i].salary, &e[i].date_joining. Date, &e[i].date_joining. month,
&e[i].date_joining. year);
}
printf(“\n employee list\n name\t code\t salary\t date of
joining\n”);
for(i=0;i<=9;i++)
{
printf(“%s\t %d\t %d\t%d\t%d\t%d\n”, e[i].name, e[i].code,
e[i].salary, e[i].date_joining.date, e[i].date_joining.month,
e[i].date_joining.year);
}
getch();
}

Write a program to store the name, runs scored and wickets taken of ‘n’
cricketers using structures. Display the output in tabular form.

#include<conio.h>
#include<stdio.h>
Struct cricketer
Nitin Sir Page 136
{
char name[20];
int runs, wickets;
};
void main ()
{
struct cricketer c[100];
int n, i;
clrscr ();
print(“enter the number of cricketers”);
scanf(“%d”,&n);
for(i=0;i<=n-1;i++)
{
Printf(“enter the cricketer’s name , runs scored and wickets
taken:”);
Scanf(“%s%d%d”,c[i].name , &c[i]. runs, &c[i].wickets);
}
printf (“name/t runs/t wickets/n:”);
printf (“---------------------------------/n”);
for(i=0;<=n-1;++)
{
printf(“%s/t %d/t %d\n”,c[i].runs,c[i].wicket);
}
getch();
}

Write a program to store the name, matches played and runs scored by ‘n’
cricket players using structure. Generate a list with runs scored in
descending order i.e. display the output in tabular form in order of
maximum runs to minimum runs scored.
#include<conio.h>
#include<stdio.h>
struct cricketer
{
char name[20];
int matches , runs;
};
void main()
{
struct cricketers s[100],temp;

Nitin Sir Page 137


int n,i,j;
clrscr();
printf(“enter the number of cricketers:”);
scanf(“%d”,&n);
for(i=0;i<=n-1;i++)
{
printf(“enter the players name, matches played and runs scored:”);
scanf (“%s %d %d”,s[i].name,&s[i].matches, &s[i].matches,
&s[i].runs);
}
for (i=0;i<=n-1;i++)
{
for(j=0;j<=n-2;j++)
{
If (s[i].runs<s[j+1].runs)
{
temp=s[j];
S[j]=s[j+1];
S[j+1]=temp;
}
}
}
printf( “Name\t matches\t goals\n”);
printf(“-----------------------------------/n”);
{
printf(“%s\t %d\t %d\n”, s[i].name, s[i]. matches, s[i].goals);
}
getch();
}

Unions
• Union is a collection of multiple data elements that can be of different
data types. But, only one of these data items can be stored in the union
variable.
• The memory space required to store one variable of union is equal to the
memory space required by the largest element in the union.

Syntax of structure declaration:

Union union_name
{
Data_type variable_name;

Nitin Sir Page 138


Data_type variable_name;
-
};
Union student
{
char name [20];
int roll_no;
float id;
};

Structure Union
Memory allotted for a structure is Memory allotted for a union is equal
equal to the space require collectively to the space required by the largest
by all the members of that structure. member of that union.
Data is more secure in structures Data can be corrupt in union
Structure provides ease of Unions are comparatively difficult for
programming programming
Structures requires more memory Union requires less memory
Structure must be used when Unions must be used when only one
information of all the member of the member elements of the union
elements of a structure are to be is to be stored.
stored

A Hospital needs to maintain details of patients. Details to be maintained are


First name, Middle name, Surname, Date of Birth, Disease. Write a C program
which will print the list of all patients with given disease.

#include<stdio.h>
#include<conio.h>
struct patient
{
char
fname[20], sname[20], mname[20], birthdate[20], disease[20];
};
void main()
{
struct patient s[100];
int n, i, j, k;
char d[20];
printf(“Enter the number of patients\n”);
Nitin Sir Page 139
scanf(“%d”,&n);
for(i=0i<=n-1;i++)
{
printf(“Enter the first name, middle name, surname, date of birth
and disease:”);
scanf(“%s %s %s %s %s, s[i].fname, s[i].mname, s[i].sname,
s[i].birthdate, s[i].disease);
}
printf(“\n Enter the disease whose patients are to be listed :”);
scanf(“%s”, d);
printf(“\n Patients with said disease are:”);

for(j=0;j<=n-1;j++)
{
for(k=0;d[k]!=‘\0’’k++)
{
If(d[k]!=s[j].disease[k])
{
Break;
}
}
if(d[k]==‘\0’)
printf(“%s %s %s \n”, s[j].fname, s[j].mname, s[j].sname);
}
getch();
}

Questions :-

1. A Hospital needs to maintain details of patients. Details to be maintained


are, First name, Middle name, surname, Date of birth ,Disease. Write a C
program which will print the list of all patients with given disease. [May-
14] 10 Marks.
2. What do you mean by struct ? What do mean by nested structure ? A
sport club of cricket need to maintain data about plyers. Description of it
is given below.Club want to maintain players name, age, no of matches
played, no of runs, and average. For above description declare a structure
and comment about size of structure of your declaration. [Dec13]
10Marks.
3. What do you mean by structure [4 M].
4. Explain nested structure with example [4 M].
Nitin Sir Page 140
Chapter 6 : Pointer
What is Pointers

• Pointers are variables used to store the address of anther variable.


• Pointers do not store values. they store the address of another variable.
Syntax :
Data _type *ptr _name;

“Data _type” is the type of the variable to which the pointer is supposed
to point.
If we want a pointer to point to an integer than, we need to have the data
type of the pointer as “int”, for a float type data pointer should also be of
the “float” type and so on.
“ptr _name” is an identifier i.e. the name of the pointer.

Example :

Int *p;

Hence, the pointer name is “p”. Hence, “p” can be used as a pointer to
point to any of the variable of type “int”

1. Address of operator (“&”) :


• It is also called as the referencing operator.
• It returns the address of the variable.
• For e.g.,
if we write “&x”, it will return the address of the variable “x”.
int x=10;
int * P = &x;
• The address of the variable “x” is copied into the pointer variable “p”,
hence the pointer “p” pointing to the variable “x”.

2. Value of operator (“*”) :


• It is also called as the de-referencing operator.
• This operator returns the value stored in the variable pointed by the
specified pointer.

Nitin Sir Page 141


• For e.g.,

if we write “*p”, it will return the value of the variable pointed by


the pointer “p”.

y = *p;
i.e. the value of the variable pointed by the pointer “p” is stored in the
variable “y”.

Explain reference and de – reference operators with example.


The address-of operator (&) is used for referencing and the indirection
operator(*) is used for de-referencing .
Example.
#include<stdio.h>
#include<conio.h>
void main( )
{
int x=7;
int *p;
p = &x;
printf(“%d is stored at address %x\n”,*p, p);
}
The statement, p = &x; In this statement ,the address of x is copied into p.
P will act as reference to x.
In the printf( ) statement we are printing the value of *p. The operator * is
nothing but indirection operator.
The indirection operator operates on address i.e. reference and given value
stored at that address. Since p stores the address of x, the value of *p is nothing
but the value of x.

Passing Pointers to Functions

Write a program to add two numbers using function. Pass the pointers to the
variables as reference to the functions.

#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;

Nitin Sir Page 142


void sum(int *p1, int *p2);
clrscr();
printf(“Enter two numbers:”);
scanf(“%d %d”, &a &b);
sum(&a, &b);
getch();
}
void sum(int *p1, int *p2)
{
int c;
c=*p1+*p2;
printf(“The sum is equal to %d”, c);
}

Output:
Enter two numbers: 4
7
The sum is equal to 11

Pointers to Array
Find output of the following statement.

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

int x=20, y, *ip;


ip= & x;
y=(*ip)++;
printf(“%d\n”, y);
printf(“%d\n”, *ip);
y=++x(*ip);
printf(“%d\n”, y);
printf(“%d\n”, ip);
}

Output:
20
21
22
22

Nitin Sir Page 143


Pass by reference (Call by reference)

Arguments are passed by address while calling a function in C program.

Creating link for the parameter to the original location, since the address is
same, changes to the parameter will refer to the original location and value will
be overwritten.

#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m=10,n=20;
printf(“value before swap m=%d and n=%d”,m,n);
swap (&m.&n);
printf(“value after swap m=%d and n=%d”,*a,*b);
}
void swap(int *a, int *b) // Function Defination
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
O/P
value before swap m=10 and n=20
value after swap m=20 and n=10

Dynamic Memory Allocation:

If we want to change the size of the array during the execution of the program
then we have to use the concept of dynamic memory allocation.

Dynamic memory allocation allows to allocate and deallocate memory


dynamically or during the execution of the program.

This can be done with the help certain library functions of the header file
“stdlib.h”

Nitin Sir Page 144


These functions are explained below:
Malloc()
This function allocates the memory dynamically of specified bytes and returns a
pointer to the same.
Syntax:
Ptr_name=(typecast*)malloc(size_in_bytes);
For example:
Int *p1;
p1=(int*)malloc(10*sizeof(int))
Calloc()
This function does the same task as that of malloc(), except that calloc()
allocates multiple memory blocks and initializes them to zero.
Syntax of using the function calloc:
ptr_name=(typecast*)calloc(n, size_of each_element);
For example:
p1=(int*)calloc(10, sizeof(int));

This statement will allocate space for 10 integers and return the pointer to the
first element of the array.

The initial value of all the elements will be zero.

Free():
This function releases or makes the memory space free which is dynamically
allocated by the function malloc() or calloc()

Syntax of using the function malloc:


free(ptr_name);

For example:
free(p1);

This statement will free the space allocated for the pointer p1.

Realloc():
This function allocates the pointer with a new size of memory block size.

Syntax of using the function malloc:


Nitin Sir Page 145
ptr_name=realloc(ptr_name, new_size);

For example:
p1=realloc(p1, 100);

This statement will now allocate 100 bytes for the array pointed by the pointer
p1.

Nitin Sir Page 146

You might also like