0% found this document useful (0 votes)
43 views124 pages

Sem2 C Notes-24

The document outlines a course on Problem Solving using C, covering fundamental concepts of computer programming, C language features, control statements, data types, functions, pointers, and dynamic memory management. It includes detailed explanations of algorithms, flowcharts, and the differences between machine, assembly, and high-level programming languages. Additionally, it discusses the roles of compilers, interpreters, linkers, and loaders in programming.

Uploaded by

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

Sem2 C Notes-24

The document outlines a course on Problem Solving using C, covering fundamental concepts of computer programming, C language features, control statements, data types, functions, pointers, and dynamic memory management. It includes detailed explanations of algorithms, flowcharts, and the differences between machine, assembly, and high-level programming languages. Additionally, it discusses the roles of compilers, interpreters, linkers, and loaders in programming.

Uploaded by

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

II Semester

Course 3: Problem Solving using C

UNIT-I
Introduction to computer and programming: Introduction, Basic block diagram and
functions of various components of computer, Concepts of Hardware and software,
Types of software, Compiler and interpreter, Concepts of Machine level, Assembly
level and high-level programming, Flowcharts and Algorithms
Fundamentals of C: History of C, Features of C, C Tokens-variables and keywords and
identifiers, constants and Data types, Rules for constructing variable names, Operators,
Structure of C program, Input /output statements in C-Formatted and Unformatted I/O

UNIT-II
Control statements: Decision making statements: if, if else, else if ladder, switch
statements. Loop control statements: while loop, for loop and do-while loop. Jump
Control statements: break, continue and goto.

UNIT-III
Derived data types in C: Arrays: One Dimensional arrays - Declaration, Initialization
and Memory representation; Two Dimensional arrays -Declaration, Initialization and
Memory representation.
Strings: Declaring & Initializing string variables; String handling functions, Character
handling functions

UNIT-IV
Functions: Function Prototype, definition and calling. Return statement. Nesting of
functions. Categories of functions. Recursion, Parameter Passing by address & by value.
Local and Global variables.
Storage classes: automatic, external, static and register.
Pointers: Pointer data type, Pointer declaration, initialization, accessing values using
pointers. Pointer arithmetic. Pointers and arrays, pointers and functions.

UNIT-V
Dynamic Memory Management: Introduction, Functions-malloc, calloc, realloc, free
Structures: Basics of structure, structure members, accessing structure members,
nested structures, array of structures, structure and functions, structures and pointers.
Unions - Union definition; difference between Structures and Unions.

Unit- I
Chapter-1
Introduction to computer and programming
Q) Define Computer?

A computer is an electronic device that accepts data, perform mathematical and


logical operations at high speed and output the result.

The Difference Engine was invented by “Charles Babbage” in the year 1822 to
perform a specific calculation but no storage capacity . The Analytical Machine was a
more advanced machine invented by “Charles Babbage” in the year 1833 to perform
all operations and also had storage capacity. The Analytical Machine was never built
during Babbage’s lifetime due to funding issues and technical difficulties, but it laid
the groundwork for modern computing. That’s the reason, he is also known as
“Father of Computers”.

Q) Explain about Block diagram of a computer?


A computer is an electronic device that performs five major operations.
They are
1. Accepting data or instructions(input).
2. Storing data.
3. Processing data.
4. Displaying results.
5. Controlling.

--------- control
________

1. Input: The processing of entering data and instructions into computer. The data and
instructions can be entered using input devices such as keyboard, mouse, scanner, etc.
input devices convert input data into binary codes.
2. Storage: The process of saving data and instructions permanently in
the computer. Computer has two types of storage areas.
 Primary storage: It is the main memory where data is accessed by CPU directly at
high speed. It is very expensive and had limited storage capacity. It holds the data
until the power is on.
 Secondary storage: It is secondary storage. It stores data permanently. Data is not
directly accessed by the CPU. It is cheap and stores large amount of data.
3. Processing: The process of performing operations on the data specified by the user is
called processing. Data and instructions are taken from main memory and ALU
performs operations on it. When the processing is completed the data (or) result is
transferred to main memory.
4. Output: The process of displaying result of data processed. The results are given
through output devices such as monitor and printer. Output devices convert binary codes
into human readable language.
5. Control: Control unit controls entire computer system. It manages
and controls all components. It also tells which instruction to be executed and
operations to be performed. Entire processing is done in ALU and CU activates
units such as input, output and storage.
The Arithmetic and logic unit (ALU) and Control unit together called as Central
Processing Unit(CPU). The CPU is also called as “Micro processor”.
Arithmetic and logic unit:
The ALU performs Arithmetic and Logical operations. The Arithmetic operations
include addition, subtraction, multiplication and division. The logical operations include
Boolean functions such as AND, OR and NOT.

Q) Hardware:
Computer hardware is the collection of physical parts of a computer system. This
includes the computer case, monitor, keyboard, and mouse. It also includes all the parts
inside the computer case, such as the hard disk drive, motherboard, video card, and
many others. Computer hardware is what you can physically touch.

Q) Software:-
Software, in its most general sense, is a set of instructions or programs instructing a
computer to do specific tasks. Software is a generic term used to describe computer
programs.

Q) Explain about types of Softwares?


System software:
System software is responsible for controlling, integrating, and managing the individual
hardware components of a computer system. System software includes operating
systems (OS).
Application software:
Application software is intended to perform certain tasks. Examples of application
software include office suites, gaming applications, database systems and educational
software. Application software can be a single program or a collection of small
programs.

System software
1. It is a collection of programs that enable the users to efficiently interact with the
hardware components.
2. It controls and manages the hardware.
3. It is machine dependent.
4. The programmer must understand the architecture of the machine and hardware
details to write system software.
5. It directly interacts with the hardware.
6. Writing system software is a complicated task.
7. Example: operating system

Application software
1. It is a collection of programs written for a specific application. Examples are
library system and inventory control system.
2. It uses the services provided by the system software to interact with the hardware
components.
3. It is machine independent.
4. The programmer can ignore the architecture of the machine and hardware details
to write application software.
5. It interacts with the hardware indirectly through system calls provided by the
system software.
6. Writing application software is relatively easy.
7. Example: Microsoft Word, Microsoft Paint

Q) Explain the concepts of Machine Level, Assembly level and high –level
programming?

Machine Language (low level language)

Low-Level language is the only language which can be understood by the computer.
Low-level language is also known as Machine Language. The machine language
contains only two symbols 1 & 0. All the instructions of machine language are written
in the form of binary numbers 1's & 0's. A computer can directly understand the
machine language.

Assembly Language (middle level language)

Middle-level language is a computer language in which the instructions are created


using symbols such as letters, digits and special characters. Assembly language is an
example of middle-level language. In assembly language, we use predefined words
called mnemonics. Binary code instructions in low-level language are replaced with
mnemonics and operands in middle-level language. But the computer cannot understand
mnemonics, so we use a translator called Assembler to translate mnemonics into
machine language.

Assembler is a translator which takes assembly code as input and produces machine
code as output. That means, the computer cannot understand middle-level language, so
it needs to be translated into a low-level language to make it understandable by the
computer. Assembler is used to translate middle-level language into low-level language.

High Level Language

High-level language is a computer language which can be understood by the users. The
high-level language is very similar to human languages and has a set of grammar rules
that are used to make instructions more easily. Every high-level language has a set of
predefined words known as Keywords and a set of rules known as Syntax to create
instructions. The high-level language is easier to understand for the users but the
computer can not understand it. High-level language needs to be converted into the low-
level language to make it understandable by the computer. We
use Compiler or interpreter to convert high-level language to low-level language.

Languages like FORTRAN,C, C++, JAVA, Python, etc., are examples of high-level
languages. All these programming languages use human-understandable language like
English to write program instructions. These instructions are converted to low-level
language by the compiler or interpreter so that it can be understood by the computer.

Q) Compiler
A complier is a special type of program that transforms the source code written in
highlevel programming language into machine language. The code is in 0’s and 1’s is
known as object code. Complier can locate syntax errors in the program.

Q) Interpreter
Interpreter also executes instructions written in high level languages. Interpreter
translates the instructions into an intermediate form, which it then executes. Complied
program executes faster than interpreted program.

Q)Difference between compliers and interpreters

Complier Interpreter

It translates entire program in one go. It interprets and executes one statement
at a time.

It generates errors after translating the It stops translation after getting the first
program. error.

Execution of code is faster. Execution of code is slower.

An object file is generated. No object file is generated.

Code need not to be complied every Code is reinterpreted every time it is


time it is executed. executed.

It requires more memory space. It requires less memory space.

Linker:
A linker is a program that combines object modules to form an executable program.
When the source code is converted into object code, all the modules need to be put
together which is done by linker.

Loader:
A loader is a special type of program that copies programs from a storage device to
the main memory when they can be executed.

Q) Define algorithm and examples


Algorithm:
a sequence of steps to solve a particular problem is called an algorithm.

An algorithm must have the following characteristics.


 Be precise (accurate).
 Be unambiguous (no doubt or leading to one conclusion).
 No instruction must be repeated infinitely.
 After the algorithm is terminated, desired result must be obtained.
Q) What are the key features of algorithm?
1)Input: The algorithm must be able to accept a set of defined input.
2) Output: The algorithm should be able to produce the result as output, preferably
solutions.
3) Finiteness: The algorithm should have a stop after a certain number of steps.
4) Generality: The algorithm must apply to a set of defined inputs.
5) Unambiguous: The algorithm should be clear and unambiguous.
6) Precision: The steps are precisely stated(defined).
7) Easy to grasp: Algorithms are there to help humans to understand the solution.

Control structures used in algorithm:


An algorithm has finite number of steps and may involve decision making and
repetition. An algorithm uses three control structures. They are
1. Sequence
2. Decision
3. Repetition
1. Sequence:
Sequence means that each step of the algorithm is executed in the specified order.
Ex: Algorithm to add two numbers.
Step 1: Start
Step 2: Input the first number as A.
Step 3: Input the second number as B.
Step 4: Set sum=A+B.
Step 5: Print sum.
Step 6: End.

2. Decision:
Decision statements are used when execution of a process depends on some condition.
A condition here may evaluate either a true value or a false value. A decision statement
can be stated in the following way.
if condition
then process1
else
process 2
here if the condition is true, then process1 is executed otherwise process2 is executed.

Ex: Algorithm to check equality of two numbers.


Step 1:Start
Step 2: Input the first number as A.
Step 3: Input the second number as B.
Step 4: if A==B then gotostep5
else gotostep6
Step 5:print “equal” and gotostep7
Step 6:print “ not equal”.
Step 7: End.

3. Repetition:
Repetition involves executing one or more steps for a number of times. They use
constructs such as while, do-while and for loops. Loops execute one or more steps until
the given condition is true.
Ex: Algorithm that prints the first 10 natural numbers.
Step 1:Start
Step 2:[initialize] set I=1, N=10.
Step 3: repeat step 4 and 5 while I<=N otherwise gotostep6
Step 4: Print I.
Step 5: set I=I+1.and gotostep3
Step 6: End.

Some more algorithms:


1. Write an algorithm for interchanging/swapping two values.
Algorithm:
Step 1: Start
Step 2: Input the first number as A.
Step 3: Input the second number as B.
Step 4: Set temp=A.
Step 5: set A=B.
Step 6: set B=temp.
Step 7: Print A, B.
Step 8: End.

2. Write an algorithm to find the larger of two numbers.


Algorithm:
Step 1: Start
Step 2: Input the first number as A.
Step 3: Input the second number as B.
Step 4: if a>bthen gotostep5
else gotostep7
Step 5:print a
Step 6: gotostep8
Step 7: print b
Step 8: End.

3. Write an algorithm to find whether the given number is even or odd.


Algorithm:
Step 1: Start
Step 2: Input the first number as A.
Step 3: if A%2=0 then gotostep4
Else gotostep5
Step 4: write “even” and gotostep6
Step 5: write “odd”
Step 6: End.

4. Write an algorithm to print the grade obtained by a student using the following rules.
marks grade

Above or equal to75 O

60-75 A

50-60 B

40-50 C

Less than 40 D

Algorithm:
Step 1: Start
Step 2: write “Enter the marks obtained”
Step 3: Read M
Step 4: if M>=75 then gotostep5
Else gotostep6
Step 5: write ”O” and gotostep13
Step 6: if M>=60 and M<75 then gotostep7
Else gotostep8
Step 7: write “A” and gotostep13
Step 8: if M>=50 and M<60 then gotostep9
Else gotostep10
Step 9:write ”B” and gotostep13
Step 10: if M>=40 and M<50 then gotostep11
Else gotostep12
Step 11: write ”C” and gotostep13
Step 12: write “D”
Step 13: End

5. Write an algorithm to find the sum of first N natural numbers.


Algorithm:
Step 1: Start
Step 2: Input N.
Step 3: Set I=1, sum=0.
Step 4: Repeat step 5 and 6 while I<=N otherwise gotostep7
Step 5: Set sum=sum+I.
Step 6: Set I=I+1and gotostep4
Step 7: Write sum.
Step 8: End.

Flow charts:
The pictorial representation for solving a problem is called flowchart.

Flowchart consists of different shapes or symbols to represent the data. In flowchart


each and every symbol or shape performs a specific task.

Symbol Symbol name Purpose/task

To start or end the


flowchart
Elliptical

parallelogram To input or output


rectangle Assignment / calculation

Dicision box/diamond Conditions

Hexagon /looping box Looping or repetition

Flow lines /Arrows Flow of lines

Connector To represent continue

1) Draw a flowchart for addition of two numbers

start

Read a, b

Calculate c=a+b

Write c
stop

2) Draw a flowchart for biggest among two numbers

start

Read a, b

No
a>b?

yes

Write “ a is big”

stop

3) Draw a flowchart to display 1 to 10 numbers.

start

Set i=1,n=5

no
i<=n ?
yes

Write i

Set i=i+1
stop

Fundamentals of C

Introduction
The programming language ‘C’ was developed by Dennis Ritchie in 1972 in Bell
Laboratories. ’C’ is one of the most popular programming languages that can be used on
several platforms. It was named ‘C’ as it has many features derived from an earlier
language ‘B’.

Background
In 1960’s ALGOL, the first block structure language was developed. C is derived from
ALGOL. Before C several programming languages are developed. In 1967 Martin
Richards developed BCPL (Basic Combined Programming Language). In 1970 Ken
Thompson developed language called B. B was used to develop the first version of
UNIX. C was developed by Dennis Ritchie in 1972 that took concepts from ALGOL,
BCPL and B.
C language resulted in development of different versions. In 1983, the American
National Standards Institute (ANSI) started working on C. In 1989, C came to be known
as ANSI C. In1990, International Standard Organization (ISO) adopted C. This version
of C is known as C89.In 1995, some changes were made and new version is C95.In
1999, the modified version C99 is introduced.
Characteristics of C
The characteristics of C language are given below.
1. It is a high level programming language that enables users to concentrate on the
problem and not worry about the machine code.
2. It is small in size and has only 32 keywords.
3. It makes extensive use of function calls.
4. It is well suited for structured programming.
5. It is a stable and quick language.
6. It supports pointers, arrays, structures and functions.
7. It is a core language as C++, java, etc are based on C.
8. It is a portable language.
9. It is an extensible language that enables users to add his/her own functions to C
library.
Uses of C
C is a very simple language that is widely used by software professionals.
The uses of C are listed below.
1. C language is used for system programming. The portability, efficiency, the
ability to access specific hard ware makes it a good choice for implementing on
operating systems.
2. Compilers, libraries and interpreters of other programming languages are often
implemented in C.
3. For portability and convenience reasons C is sometimes used as intermediate
language for the implementation of other languages.
4. C is widely used to implement end user application.
Q) Explain about Structure of C program
Documentation section
Linkage section
Definition section
Global declaration section
Function prototypes
Return type main()
{
Declaration part
Executable part
}
Return type subprogram or function
{
Declaration part
Executable part
}
Documentation section:
Documentation section consists of comment lines. Generally it is used to give name of
the program and other details in which the programmer would like to use later.
Ex: /* sum of two numbers */
Linkage section:
Linkagesection provides instructions to the compiler to link the library functions from
library to the main() function. Linking is a process of putting together the library files
and functions that are required by the programmer.
Ex: if the programmer using printf and scanf functions the library file is
#include<stdio.h>
Definition section:
Definition section defines all the symbolic constants ∏ sign such as PI value 3.14 i.e
PI=3.14. whenever a symbolic name is encountered by the compiler substitutes the
values associated with the names automatically.
Ex: #define pi 3.14
Global declaration section:
There are some variables that are used in more than one functions and also can be used
any function in a program. Such variables are called as global variables. Those variables
are declared at the top of main() function. That variables can be used by any function in
our program.
Ex: int a=10;
Function prototypes:
It specifies about the function to the compiler. That is, it gives information about return
type and parameters.
Ex: intcalsum(a,b);
main():
c program is nothing but the collection of one or more functions. The main function is a
special function which is used by the c compiler to instruct computer about the starting
of a program. Every c program consists of a one main() function.
The parenthesis followed after main represents it has no parameters. The main function
contains two parts.
a) Declaration part:
b) Executable part
The declaration part declares all the variables used in the program and
executable part consists of program statements. These two parts must be in between left
and right braces.
subprogram or function:
The sub program section contains all the user defined functions which are to be
called either from main() or from any other function. User-defined functions are
generally placed immediately after the main() function.
Example:
#include<stdio.h>
#include<conio.h>
# define n1 10
void sum(int n2);
voiddisp(int s);
int n3;
void main()
{
int n2;
clrscr();
printf(“Enter n2 and n3 values”);
scanf(“%d%d”,&n2,&n3);
sum(n2);
getch();
}
void sum(int n2)
{
int s;
s=n1+n2+n3;
disp(s);
}
voiddisp(int s)
{
printf(“sum=%d”,s);
}
Q) File used in C Program
Every C program has four kinds of files.
They are 1. Source code file
2. Header file
3. Object file
4. Executable file
1. Source Code File: The source code file contains the source code of the
program. The file extension of C source code file is ‘’.c’’. It defines main
function and other functions.
2. Header File: Some sub routines used in main() may be useful in other program.
But copying from one program to other may be difficult.
So we store such subroutines in different file known as header file. The extension
of headerfile is ’’.h’’ and its name can use letters, digits and underscores.
In C program some standard header files are available.The standard header files
in C are given below.

string.h for string handling functions


stdlib.h for some miscellaneous functions
stdio.h for standard input and output functions
math.h for mathematical functions
alloc.h for dynamic memory allocation
conio.h for clearing the screen
All the header files are referenced at the start of the source code file that uses one
or more functions from that file.
3. Object File: Object files are generated by the complier as a result of processing
the source code file. They contain compact binary code of the function
definitions. Linker uses this object file to produce an executable file. Object files
have a ‘’.o’’ extension.
4. Binary Executable File: The binary executable file is generated by the linker.
The linker links the various object files to produce a binary file that can be
directly executed. The executable files have “.exe” extension.

Q) Writing the first C Program


void main()
{
printf(“welcome to c”);
}
Q) Compiling and Executing C Programs
The following steps are essential in executing a program.
a) Creation of program:
The program should be written in C editor. The file name does not
necessarilyinclude the extension ‘.c’. The default extension is ‘.c’.
b) Compilation and linking a program:
The source program statements should be translated into the object program,
which is suitable for execution by the computer. The translation is done after
correcting each statement. If there is no error, compilation proceeds and the
translation program is stored in another file with same file name with extension
‘.obj’. If errors are there the programmer should correct them. Linking is also an
essential process. It puts together all other program files and functions that are
required by the program.
c) Executing the program:
After the compilation, the executable object code will be loaded in the computer’s
main memory and the program is executed.

Q) Using Comments
Comments are not necessary in the program. However, to understand the flow of the
program, programmer can include comments in the program.
Comments are nothing but some kind of statements which are to be placed
between the delimiters /* and */. The compiler does not execute comments.
Ex: /* sum of 1 to 10 numbers */

Q) Define ‘C’ Character set?

A character denotes any alphabet, digit or special symbol and white spaces used
to represent information.

Alphabets-------------A, B, C, ----------X, Y, Z (or) a,b,c,------------x,y,z


Digits---------------- 0,1,2,3,4,5,6,7,8,9
Special symbols----- ~ , ’, &, *, ( , ) , _ etc
White spaces----------- newline, blank space, horizontal tab, vertical tab .

List of special characters

, Comma ~ Tilde > Greater than

. Period or dot _ Underscore () Parenthesis left


/right

; Semi-colon $ Dollar [] Bracket left / right

: Colon ? Question mark {} Braces left / right

‘ Apostrophe & Ampersand % persent

“ Quatation mark ^ Caret # Number sign or


hash
! Exclamation mark * Asterisk = Equal to

| Vertical bar - Minus @ At the rate

/ Slash + Plus

\ Back slash < Less than

Q) Delimiters

Language pattern of C uses special kind of symbols, which are called as delimiters.

Delimiters Use

: colon Useful for label

; semi-colon Terminates statement

( ) parenthesis Used in expression and function

[ ] square bracket Used for array declaration

{ } curly brace Scope of statement

# Hash Preprocessor directive

, comma Variable separator

Q)Define case sensitivity?


The language which accepts only one case i.e either upper case or lower case letters
then those languages are called case sensitivity.
Example: c ------lower case
FORTRAN ------ uppercase
Q) Why ‘C’ is called middle level language?
All theProgramming languages can be divided into two types.
a) Problem Oriented Languages or High Level Languages:
These languages have been designed to give a better programming
Efficiencyi.e faster program development. Because information is in
English.
Ex: Fortran , Basic, Pascal etc
b) Machine Oriented Languages or Low level Languages:
These languages have been designed to give a better machine efficiency. i.e faster
program execution.
Ex: assembly language and machine language.
C consists of both the features of high level & low level
languages. That’s the reason ‘C’ is called middle level language.

Q) C Tokens

Tokens in C is the most important element to be used in creating a program in C. We


can define the token as the smallest individual element in C. For `example, we cannot
create a sentence without using words; similarly, we cannot create a program in C
without using tokens in C. Therefore, we can say that tokens in C is the building block
or the basic component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

Keywords
Keywords are reserved words by the compiler. All the C keywords have been assigned
fixed meaning. The keywords cannot be used as variable names because they have been
assigned fixed jobs. There are only 32 keywords available in C.

Identifiers

Identifiers are names of variables, function, and arrays. They are user-
defined names, consisting of sequence of letters and digits, with the
letter as the first character. Lower case letters are preferred.
However, the upper case letters are also permitted. The underscore
symbol can be used as an identifier. In general underscore is used as
a link between two words in long identifiers. A special identifier
called a statement label can be used in goto statements.

Constants

A constant is a value assigned to the variable which will remain the same
throughout the program, i.e., the constant value cannot be changed.

There are two ways of declaring constant:

o Using const keyword


o Using #define pre-processor

4.Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in
double quotes. Whereas, a character is enclosed in single quotes.

Examples of String

char string[20] = {‘A’, ’B’, ‘N’, ‘&’, ‘P’, ‘R’, ‘R’, ‘\0’};
char string[20] = “ABNPRR”;
char string [] = “ABNPRR”;

5. Special Symbols
The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose. Some
of these are listed below:
 Brackets[]: Opening and closing brackets are used as array
element references. These indicate single and multidimensional
subscripts.
 Parentheses(): These special symbols are used to indicate
function calls and function parameters.
 Braces{}: These opening and ending curly braces mark the
start and end of a block of code containing more than one
executable statement.
 Comma (, ): It is used to separate more than one statement
like for separating parameters in function calls.
 Colon(:): It is an operator that essentially invokes something
called an initialization list.
 Semicolon(;): It is known as a statement terminator. It
indicates the end of one logical entity. That’s why each
individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the
multiplication of variables.
 Assignment operator(=): It is used to assign values and for
logical operation validation.
 Pre-processor (#): The preprocessor is a macro processor
that is used automatically by the compiler to transform your
program before actual compilation.
 Period (.): Used to access members of a structure or union.

6.Operators
An operator is a symbol that tells the computer to perform certain mathematical and
logical operations. The data items on which operators act are called
operands. Depending on the number of operands that an
operator can act upon, operators can be classified as follows:

 Unary Operators: Those operators that require only a single


operand to act upon are known as unary operators. For
Example increment and decrement operators

 Binary Operators: Those operators that require two operands


to act upon are called binary operators. Binary operators can
further are classified into:

1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator

 Ternary Operator: The operator that requires three operands


to act upon is called the ternary operator. Conditional
Operator(?:) is also called the ternary operator.

Q) Define variable?
A variable is a quantity which is having certain value. The value varies
throughout the execution of the program.
(or)
A variable is a dataname used for storing a data value. Its value may be changed during
the program execution.
Syntax1: datatypevariablename;
Example: int a;
Syntax2: datatypevariablename=value;
Example: int a=10;
Rules:
1) The starting character should be an alphabet.
Valid invalid
Number1 1number
2) Special symbols are not allowed except underscore.
Valid invalid
Roll_no Roll-no
3) Blank spaces are not allowed.
Valid invalid
Roll_no Roll no
4) Keywords should not be used as variable names.
Valid invalid
Int1 int ,float
5) Variable name should be meaningful.
Valid invalid
Mynameabcdef
6) Variable name should not exceed 8 characters.
Valid invalid
Int_rateabcdefghij

Q) Define Keywords?
Keywords are reserved words by the compiler. All the C keywords have been assigned
fixed meaning. The keywords cannot be used as variable names because they have been
assigned fixed jobs. There are only 32 keywords available in C.

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

Q) What are Identifiers?


Identifiers are names of variables, function, and arrays. They are
user-defined names, consisting of sequence of letters and digits, with
the letter as the first character. Lower case letters are preferred.
However, the upper case letters are also permitted. The underscore
symbol can be used as an identifier. In general underscore is used as
a link between two words in long identifiers. A special identifier
called a statement label can be used in goto statements.

Rules for Naming Identifiers

Certain rules should be followed while naming c identifiers which


are as follows:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No
other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31
characters are significant.

Q) What are Datatypes in ‘C’?


Datatype:

Datatypes specify the size and type of values that can be stored in a variable.
C languages supports two different types of datatypes.

1) Primary datatype
2) Derived datatype

1) Primary datatypes:
These are fundamental datatypes in c namely integer, floating point, character
and void.
2) Derived datatypes:
Derived datatypes are nothing but primitive datatype but grouped together
like array, structure, union, pointer.

Primary data types

character integer float void

char float

signed char signed unsigned double

unsigned char int int long double

short int short int

long int long int

void: void type means no value. This is used to specify the type of function which
returns nothing.

Data type Range Size in Format


bytes specifier /Control
string /conversion
char -128 to 127 1 %c

signed char -128 to 127 1 %c

unsigned char 0 to 255 1 %c

int -32768 to 32767 2 %d or %i


signed int -32768 to 32767 2 %d

short int -32768 to 32767 2 %d

signed short int -32768 to 32767 2 %d

unsigned int 0 to 65535 2 %u

unsigned short int 0 to 65535 2 %u

long int -2147483648 to 2147483647 4 %ld

signed long int -2147483648 to 2147483647 4 %ld

unsigned long int 0 to 4294967295 4 %lu

float 3.4E-38 to 3.4E+38 4 %f or %g

double 1.7E-308 to 1.7 E+308 8 %lf

long double 3.4E-4932 to 1.1E+4932 10 %lf

Q) Define constants? Explain about various constants in C?

Constant:

The constants refer to the variables with fixed values. It doesn’t change throughout
the execution of the program.
Syntax:
const datatype variable name = value;
Example:
const int a=10;
There are several types of constants.

C constants

Numeric constants Character constants

Integer constants Single Character constants


Real constants String constants
Numeric constants:

1) Integer constants:
These are the sequence of numbers from 0 to 9 without decimal points or fractional
part or any other symbols. Integer constants could either be positive or negative or
may be zero. The number without a sign is assumed as positive.
a) Decimal:
These numbers are used 0 to 9 digits.
Ex: 10, 20, +30, -25 etc.
b) Octol number:
These numbers are used 0 to 7 digits.
Ex: 045 7, 0256
c) Hexa Decimal number:
These numbers are used 0 to 9 digits and A to F. this means A is equal to 10,
B=11, C=12,D=13,E=14,F=1 5.
Ex: 0xa7, 0x9c
2) Real constants:
Real constants are often known as floating point constants. these numbers have
decimal point. Length, height, prize, distance etc. are measured in real numbers.
Ex: 3.45, 5.345
The real constants can be written in exponential notation, which contains a
fractional part and a exponential part. For example, the value 2456.123 can be
written as 2.456123 X e+3 .

Character constants:
1) Single character constants:
A character constants is a single character. They are also represented in a single
digit or single special symbol or white space enclosed within a pair of single
quote marks.

Ex: ‘a’, ‘8’, ‘&’, ‘ ‘.

Escape sequences are also treated as single character constants.

Ex: ‘\n’, ‘\t’

2) String constants:
String constants are group of characters enclosed within a double quote marks.
The string maybe combination of all kind of symbols.
Ex: “Hello”, “India”,”865”, “a”,”5”.
Q) Explain about I/O statements in C?

Input and Output functions

Formatted I/O functions Unformatted I/o functions


Input Output InputOutput
scanf() printf() getch(), getche(), putch(),putchar(),
getchar(), gets() puts()

Input function:
It takes the data from the keyboard through the input function.

Output function:
It displays the data on the screen through the output function.

Formatted I/O functions:


The formatted I/O functions read and write all types of data values. They require
conversion symbol to identify the data type.
printf():
The printf() function prints all types of data values to the screen. It requires
conversion symbol and variable names to print the data. The conversion symbol and
variable name should be same in number.
Syntax:
printf(“conversion string”, variablename);
Example1:
void main()
{
int a=5;
clrscr();
printf(“%d”,a);
}
Example2:
void main()
{
int a=5;
float b=2.5;
clrscr();
printf(“%d%f”,a,b);
}
scanf():
The scanf()function reads all types of data values. It is used for runtime
assignment of variables. The scanf() statement requires conversion string to
identify the data to be read during the execution of a program. It also requires ‘&’
operator is to indicate the memory location of the variable.
Syntax:
scanf(“conversion string”, &variablename);
Example1:
void main()
{
int a;
clrscr();
scanf(“%d”,&a);
printf(“%d”,a);
}
Example2:
void main()
{
int a;
float b;
char c;
clrscr();
scanf(“%d%f%c”,&a,&b,&c);
printf(“%d%f%c”,a,b,c);
}

Note1: At the time of giving values through the keyboard, values must be separated
by blanks( press SPACEBAR) or tabs or newline (press Enter Key)
Note2: The input and output functions are link between the user and the computer.

Unformatted I/o functions:


The unformatted I/O functions only work with the character datatype. They do not
require conversion symbol for identification of data types because they work only
with character data type. There is no need to convert the data. In case of other data
types are passed to these functions, they are treated as the character datatype.

To read character by using the following functions:-


getch()
getche()
getchar()
To read string by using the below function:-
gets()
To print character by using the following functions:-
putch()
putchar()
To print string by using the below function:-
puts()

Q) Define Operator? Explain about various operators in C?


Operator:
An operator is a symbol that tells the computer to perform certain mathematical and
logical operations.

Types of operators:
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Increment and decrement operators
6) Conditional operators
7) sizeof() ,& (address)operator and comma(,)
8) Bitwise operators
1) Arithmetic operators:
C provides all the basic arithmetic operators. These operators perform Arithmetic
operations on operands.

Operator meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% (remainder) Modular Division
Ex: a+b, a-b
Example:
void main()
{
int a=10,b=20;
clrscr();
printf(“a+b=%d”,(a+b));
printf(“a-b=%d”,(a-b));
printf(“a*b=%d”,(a*b));
printf(“a/b=%d”,(a/b));
printf(“a mod b=%d”,(a%b));
}
2) Relational operators:These operators are used to compare operands. The result
of relational expression is one or zero. If it is one then it is treated as true. If it is
zero then it is treated as false.
Operator meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Ex: a>b,a<b
Example:
void main()
{
int a=10,b=20;
clrscr();
printf(“a<b=%d”,(a<b));
printf(“(a<=b)=%d”,(a<=b));
printf(“(a>b)=%d”,(a>b));
printf(“(a>=b)=%d”,(a>=b));
printf(“(a==b)=%d”,(a==b));
printf(“(a!=b)=%d”,(a!=b));
}
3) Logical operators:
These operators are used to combine two or more than relational expressions.
These are used to test more than one condition. The value of logical operator
expression is either one or zero. Here one is treated as true and zero is treated as
false.
Operator meaning
&& logical AND
|| logical OR
! logical NOT

Truth table
AND OR NOT
A B A&&B A||B !A
1 1 1 1 0
1 0 0 1 0
0 1 0 1 1
0 0 0 0 1
Ex: a<b&&a>c

Example:
void main()
{
int a=10,b=20,c=30;
clrscr();
printf(“(a<b)&&(a<c)=%d”,a<b&&a<c);
printf(“(a<b)||(a<c)=%d”,a<b||a<c);
printf(“!(a<b)=%d”,!(a<b));
}
4) Assignment operators:
Assignment operators are used to assign the value of an expression to a variable.
The usual assignment operator is denoted by ‘=’.
Variable=expression;
C has a set of shorthand assignment operators which are used in the form
V op=exp;
Where v is a variable, op= is the shorthand assignment operator, exp is an
expression.
Example:
void main()
{
int a=10,b=20;
clrscr();
printf(“a+=b =%d”,a+=b);
printf(“a-=b =%d”,a-=b);
printf(“a*=b =%d”,a*=b);
printf(“a/=b =%d”,a/=b);
printf(“a%=b =%d”,a%=b);
}

Statement with simple Statement with shorthand


5)
assignment operator operator
a+=1 a+=1
a-=1 a-=1
a=a*b a*=b
a=a/(n+1) a/=n+1
a=a%b a%=b
Increment or decrement operators:
Increment operator:
This operator increments operand value by 1. This increment operator
Iswritten as ++.
Ex:- i++, ++i
i++ is called post increment
++i is called pre increment
Decrement operator:
This operator decrements operand value by 1. This decrement operator is
written as --.
Ex: i--, --i
i-- is called post decrement
--i is called pre decrement
Example:void main()
{
int i=10;
clrscr();
printf(“i=%d”,i);
printf(“i++ =%d\n”,i++);
printf(“++i =%d\n, ++i);
printf(“i-- =%d\n”, i--);
printf(“--i =%d\n”,--i);
}
6) Conditional operator:
Conditional operator is also called as ternary operator. This is alternative
method to simple if else. This is indicated by “ ? : “ . This is used for three
operands.
Syntax:
Condition ?expression1 : expression2 ;
Here the condition value is evaluated first. If the condition is true then
expression1 is executed. If the condition is false then expression2 is executed.
Ex: x= a>b? a:b;
Example:void main()
{
int a=10,b=20,x;
clrscr();
printf(“%d\n”,a>b?a:b);
x=a>b?a:b;
printf(“x=%d”,x);
}
7) sizeof() ,& operator and comma(,) operator:

The sizeof() operator gives the bytes occupied by a variable. The number of bytes
occupied varies from variable to variable depending upon its data types..
The ‘&’ operator prints address of the variable in the memory.
Comma (,)operator is used to separate two or more expressions.
Ex: int x;
sizeof(x)
&x
Example:void main()
{
int x;
clrscr();
printf(“sizeof(x)=%d”,sizeof(x));
printf(“\n Address of x= %u”, &x);
}
8)Bitwise operator:
C supports a special operator known as Bitwise operators for manipulation
of data at values of bit level. These operators are used for testing the bits, or
shifting them to the right or left. Bitwise operators may not be applied to float or
double.

Operator meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR( EXOR)
~ One’s Complement
<< shift left
>> shift right

Q) Type conversion and type casting

To converting a variable of one data type to another. However there is a basic difference
between type conversion and type casting i.e. type conversion is done “ automatically “
by the compiler whereas, type casting is to be “ explicitly done “ by the programmer.
Type conversion:
To convert a variable from one data type to another data type automatically by
the compiler.

Example:#include<stdio.h>
#include<conio.h>
void main()
{
int a;
float b;
clrscr();
a=10;
b=a;
printf(“b=%f”,b);
}
Type casting:
Forcefully converting a variable from one datatype to another datatype is called
type casting.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
float b;
clrscr();
b=10.5;
a=(int)b;
printf(“a=%d”,a);
}

Decision Control and Looping Statements


Control Structure:
This control structure control the flow of execution of program. By default ‘C’
language statements are executed sequentially. But control structures are used to
alter the sequential execution.

Introduction to Decision Control Statements


In decision control statements (if, if-else and nested if), group of statements are
executed when condition is true. If condition is false, then else part statements are
executed.
There are different types of decision making control statements in C language. They are
1. if statements
2. if else statements
3. nested if statements
4. switch

1. Simple if :
An if statement consists of a condition followed by one or more statements. If the
condition is true, then the 'if' statement will be executed. If the condition is false,
then after the end of the 'if' statement will be executed.
Syntax:
if(condition)
statement;

Flowchart:
false
conditio
n
true

statement

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int age;
clrscr();
printf(“Enter age of a person”);
scanf(“%d”,&age);
if(age>=18)
printf(“\n person is eligible to vote”);
printf(“End program”);
}
2. if- else statements:
An if-else consists of one condition and two statements.If the condition is true, then
statement1 will be executed. If the condition is false, then else part of thestatement2
will be executed.

Syntax:
if(condition)
statement1;
else
statemen2;

flowchart:
no

condition

yes Statement2

Statement1

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inta,b,big;
clrscr();
printf(“enter a,b values”);
scanf(“%d%d”,&a,&b);
if(a>b)
big=a;
else
big=b;
printf(“Big=%d”,big);
}

3) nested if statements:
one if statement contains another if statements is called nested if. Nested contains
simple if or if else.
Syntax:if(condition1)
{
if(condition2)
statement1;
else
statemen2;
}
else
{
if(condition3
statement3;
else
statement4;
}

flowchart:

yes no
Condition1

yes no yes no
Condition2 Condition3

Statement1 Statement2 Statement3 Statement4


yes

In the above flowchart ,


if condition1 is true and condition2 is true then statement1 will be executed.
if condition1 is true and condition2 is false then statement2 will be executed.
if condition1 is false and condition3 is true then statement3 will be executed.
If condition1 is false and condition3 is false then statement4 will be executed.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inta,b,c;
clrscr();
printf(“enter a,b,c values”);
scanf(“%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
printf(“a is big”);
else
printf(“c is big”);
}
else
{
if(b>c)
printf(“b is big”);
else
printf(“c is big”);
}
}

4.else if ladder:
Syntax:
If (condition 1)
Statement 1;
else if (condition 2)
Statement 2;
else if (condition 3)
Statement 3;
.
.
.
.
else if (condition n)
statement n;
else
default-statement;

The conditions are evaluated from the top.If the condition is true the statement
associated with it is executed and the control is transferred to the statement X,
when all the n conditions become false then the final else containing the default
statement will be executed.

Flowchart:

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int code;
printf("Enter any code");
printf("1.RED 2.GREEN 3.WHITE");
scanf(“%d”,&code);
if(code==1)
printf("RED");
else if(code==2)
printf("GREEN");
else if(code==3)
printf("WHITE ");
else
printf("YELLOW");
}

4) switch statement / case control structure

A switch statement is also called multiple if statement. It check whether the


value of expression is equal to any one of the constant values (case values) and
transfer the control accordingly.

Syntax:
switch(integer expression/ character expression)
{
case constant1: statement1;
break;
case constant 2: statement2:
break;
case constant 3: statement3;
break;
.
.
.
.
case constant n: statement n;
break;
default: statement;
}

In the switch statement the expression value is taken first. This value is compared to
every case value. If any case value is equal to expression value then the particular
statement can be executed. If any case value is not equal to constant values then the
default statements can be executed. After every case statement we use break statement.
After execution of any statement then the control come out from switch statement.

Flowchart:

expressio
Expression=case constant1 Statement1
Expression=case constant2
Statement2
Expression=case constant3
Statement3

default
default value
statement
Example:

#include<stdio.h>
#include<conio.h>
void main()
{
intch;
clrscr();
printf(“1-----one\n 2-----two\n 3-----three\n”);
printf(“enter your choice”);
scanf(“%d”,&ch);

switch(ch)
{
case 1: printf(“one”);
break;
case 2: printf(“two”);
break;
case 3: printf(“three”);
break;
default: printf(“invalid choice”);
}

Iterative statements/looping control statements


Introduction to looping control structure

The statements which are used to execute a block of statements with repeated manner is
called iterative statement. There are 3 types. They are

1) for:
Syntax:
for( initialization; condition; increment/decrement)
{
statement ;
}
In this loop structure for is one type. In this for loop initial value is taken first. This
initial value is compared with the condition. If it is true then the statement can be
executed. Next increment value can be incremented then this increment value is
compared with the condition. If it is true then the statement can be executed. Next
increment value can be incremented then this increment value is compared with the
condition. If the condition is false then the control come out from the for loop. Here
Comparison can be stopped when the condition is false up to that time the statement of
loop can be executed.

Flowchart:

Initialization;condition;increment /
false
decrement

true
statements

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inti;
clrscr();
printf(“display 1 to 10 numbers\n”);
for(i=1;i<=10;i++)
printf(“%d\n”,i);
}
2) while :
The while statement is simple statement in all loop statements. This is called entry
control Iterative statement.
Syntax:
initialization;
while(condition)
{
statement;
increment/decrement;
}
In this while loop the initial value is taken first. It is compared with the condition. If it is
true the statements of loop are executed. Next increment value can be incremented and
this value is compared with condition. If it is true the statements of loop are executed.
This increment and comparison process is done until the condition is false. If the
condition is false then the control comes out from the loop.

Flowchart:
initialization

false
conditio

true

statement
s

increment

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inti;
clrscr();
printf(“display 1 to 10 numbers\n”);
i=1;
while(i<=10)
{
printf(“%d\n”,i);
i++;
}
}
3) do-while:
The do while structure is same as while loop. But the condition is used at the
bottom of loop. So this is called exit control iterative statement.

Syntax:
initialization;
do
{
statement;
increment/decrement;
} while(condition);

In this do-while loop the control enters into loop without checking condition and the
statements are executed once. After compilation of single execution the condition will
be compared. If the condition is true then the control enters into loop. The statements
are executed and the increment value can be incremented. Again increment value and
condition can be compared. If the condition is true the loop statements are executed.
The process is continuous up to given condition is false.
Flowchart:
initialization
statements

increment

True false
condition

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
inti;
clrscr();
printf(“display 1 to 10 numbers\n”);
i=1;
do
{
printf(“%d\n”,i);
i++;
}while(i<=10);
}
Nested loops:

One loop statement contains another loop is called nested loops. That is, it may be
while , do- while or for loop.

Example :

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

}
}

start
Flowchart:

i=1; i<10; i++ no

yes
no
j=1;j<=i; j++
yes

Write j

stop
Q) Unconditional statements/Jumping control statements

1) Break:

The break statement is used to terminate the loop immediately without checking
the condition. The keyword for break statement is break. A break is usually
associated with an if and also used in switch statement. Break is used with do-
while, while, or a for loop.

Syntax:break;

Example :

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
break;
printf(“%d\t”,i);
}
}
2) continue:
The continue statement is used to take the control to the beginning of the loop. That is,
continue statement skips the current statement and forces the next iteration of the loop.
The keyword for continue statement is continue. A continue is usually associated with
an if.Continue is used with do-while, while or a for loop.
Syntax: continue;

Example :

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
continue;
printf(“%d\t”,i);
}
}
3) goto:

It takes the control to the specified label. Label name must be starts with character.

After label name : is necessary.

Syntax:
goto label;

-----

-----

label: statement;

Example1:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter two integer numbers\n”);
scanf(“%d%d”, &a,&b);
if(a>b)
goto label1;
else
goto label2;

label1: printf(“\n ais big”);


exit();
label2: printf(“\nb is big”);
}

Example2:

#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
count:
printf(“\n%d”,i);
i++;
if(i<=10)
goto count;
}

Unit-III
Derived data types in C

Arrays

Array:
An array is a group of related data items that share a common name.
(Or)
An array is a collection of same data type elements.
(Or)
Array is a collection of homogeneous elements.
These similar elements could be all integers or all float numbers or all
characters etc. Usually array of characters is called a string. Whereas an array of integer
or float numbers is called simply an array. The elements of array must be of same type.

Types of Arrays:

1) One dimensional array


2) Two dimensional array
3) Multi dimensional array

Q) Explain about one dimensional array?

A list of items can be given one variable name using only one subscript and such
a variable is called a one dimensional array. One dimensional array consists of one row
and several columns. To declare the one dimensional array at first we have to specify
the data type of that array.

Declaration of Array:
Syntax:
datatype arrayname[dimension];

Example:
int a[5];

0 1 2 3 4

[Memory will be allocated sequentially to those 5]

1. Elements of array are stored in the consecutive memory locations.

Example:
int a [4] = {5, 10, 15, 20};

a 5 10 15 20
4052 4054 4056 4058

Initialization of array:
To put values into an array. This process is known as initialization.
In ‘C’ we can initialize an array at the declaration part. The following
represents this fact.

Syntax1:
datatype arrayname[dimension]={list of values};
Example1:
int a[5]={10,20,30,40,50};
or

Syntax2:
datatype arrayname[ ]={list of values};
Example:
int a[]={10,20,30,40,50};
An array is initializing a list of values separated by commas and surrounded
by curly braces.
If no size is given, the compiler allocates enough space for all the elements specified
in the list.
This array initialization is done using the array subscripts as shown below.
Syntax3:
arrayname [subscript]=value;
Example3:
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
In ‘C’ array subscript starting with 0 and ending with a value one less than
the size.
Reading and entering a data :

In ‘C’ the array elements are entering and reading with the help of looping
statements. The following example represents this fact.
Example1: entering a data

for(i=0;i<5;i++)
{
scanf(“%d”, &a[i]);
}
Example2: Reading a data

sum=0;

for(i=0;i<5;i++)
{
sum=sum+a[i];
}

Accessing elements of an array:


Accessing elements of array means displaying values of the array. To access all
elements of the array, we must use for loop.

Example:
for(i=0;i<5;i++)
{
printf(“%d”,a[i]);
}
Program to read and display the elements of an array:
void main()
{
int a[10],n,i;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“display elements from an array\n”);

for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
}
Operations that can be perfomed on Arrays:
1) Traversal:
Traversing the array element means accessing each and every element of the
array for specific purpose.
2) Insertion:
Inserting an element into the array.
3) Deletion:
Deleting an element from the array.
4) Merging:
Merging two arrays means copying two array elements into third array.
5) Searching:
It is used to find out the location of the data item in the array.
6) Sorting:
It is used to arrange the data in some order i.e., ascending or descending order.

Examples:

1) Program on traversing:
void main()
{
int a[10],n,i;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“display elements from an array\n”);

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

2) Program on insertion:
void main()
{
int a[10],n,i,pos,ele;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“\n enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“\n enter which position you want to insert”);
scanf(“%d”, &pos);
printf(“\n enter new element”);
scanf(“%d”,&ele);
for(i=n;i>pos;i--)
{
a[i]=a[i-1];
}

while(pos>n)
{
a[n]=0;
n++;
}
a[pos]=ele;
n++;
printf(“\nAfter inserting array elements are\n”);

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

3) Program on deletion:
void main()
{
int a[10],n,i,pos,ele;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“\nenter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
printf(“\nenterwhich position you want to delete”);
scanf(“%d”,&pos);
if(pos<n)
{
for(i=pos;i<n;i++)
{
a[i]=a[i+1];
}
n--;
}
else
{
printf(“\n invalid choice”);
}
printf(“\nafter deleting array elements are\n”);

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

4) Program on merging:

void main()
{
int a[10],b[10],c[20],n1,n2,i,j,k;
clrscr();
printf(“enter array a of size”);
scanf(“%d”,&n1);
printf(“enter array b of size”);
scanf(“%d”,&n2);
printf(“enter elements into an array ‘a’\n”);
for(i=0;i<n1;i++)
{
scanf(“%d”, &a[i]);
}
printf(“enter elements into an array ‘b’\n”);
for(i=0;i<n2;i++)
{
scanf(“%d”, &b[i]);
}
i=0;
j=0;
k=0;
while(i<n1)
{
c[k]=a[i];
i++;
k++;
}
while(j<n2)
{
c[k]=a[j];
j++;
k++;
}
printf(“\n After merging array elements are\n”);

for(i=0;i<n1+n2;i++)
{
printf(“%d\n”,c[i]);
}
}

5) Programs on sorting:

/* Bubble Sort */
void main()
{
int a[10],n,i,j,t;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf(“\n after sorting \n”);
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
}

/* Selection sort */
void main()
{
int a[10],n,i,j,t,min;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”, &a[i]);
}
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])
{
t=a[min];
a[min]=a[j];
a[j]=t;
}
}
}
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
}

6) Programs on searching:
/* Linear Search */
void main()
{
int a[10],n,i,sv,flag=0;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter search value”);
scanf(“%d”,&sv);
for(i=0;i<n;i++)
{
if(a[i]==sv)
{
printf(“\n search value is found at position %d”,i);
flag=1;
break;
}
}
if(flag==0)
printf(“\n search value is not found”);
}

/* Binary Search */
void main()
{
int a[10],n,i,sv,flag=0,l,u,mid;
clrscr();
printf(“enter array size”);
scanf(“%d”,&n);
printf(“enter elements into an array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter search value”);
scanf(“%d”,&sv);
l=0;
u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(a[mid]==sv)
{
printf(“\n search value is found at position %d”,i);
flag=1;
break;
}
if(a[mid]<sv)
l=mid+1;
else
u=mid-1;
}
if(flag==0)
printf(“\n search value is not found”);
}
Q) One-Dimensional Array for Inter-Function Communication

Like variables of other datatypes, we can pass arrays to functions. We


can either pass individual elements or entire array to functions.

/* passing individual array elements using call by value */


void main()
{
int a[]={1,2,3,4,5};
inti;
clrscr();
for(i=0;i<5;i++)
display(a[i]);
getch();
}
display(int n)
{
printf(“%5d”,n);
}

/* passing individual array elements using call by reference */


void main()
{
int a[]={1,2,3,4,5};
int i;
clrscr();
for(i=0;i<5;i++)
display(&a[i]);
getch();
}
display(int *n)
{
printf(“%5d”,*n);
}

/* passing array using call by value */


void main()
{
int a[5]={1,2,3,4,5};
inti;
clrscr();
display(a, 5);
getch();
}
display(int a[5],int n)
{
int i;
for(i=0;i<n;i++)
printf(“%5d”,a[i]);
}
Q) Explain about two dimensional array?
A list of items can be given one variable name using two subscripts and such a
variable is called a two dimensional array. Two dimensional array consists of more than
one row and columns. First subscript represents rows and second subscript represents
columns. To declare the two dimensional array at first we have to specify the data type
of that array. It is represented in the form of matrix.
Declaration of Array:
Syntax:
datatype arrayname[row-dimension][column-dimension];

Example:
int a[2][3];

00 01 02 10 11 12
Initialization of array:
To put values into an array. This process is known as initialization.
In ‘C’ we can initialize an array at the declaration part. The following
represents this fact.

Syntax1:
datatype arrayname[row-dimension][column-dimension]={list of values};
Example1:int a[2][3]={10,20,30,40,50,60};

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


( or )

Syntax2:
datatype arrayname[row-dimension][column-dimension]={list of values};
Example:
int a[][3]={10,20,30,40,50,60};
row dimension is optional whereas column dimension is compulsory. Because it
represents the size of an array.
An array is initializing a list of values separated by commas and surrounded
by curly braces.
This array initialization is done using the array subscripts as shown below.
Syntax3: arrayname [row][column]=value;

Example3:
a[0][0]=10;
a[0][1]=20;
a[0][2]=30;
a[1][0]=40;
a[1][1]=50;
a[1][2]=60;
Input values into 2D array:

Input values in 2D array, we use nested for loop.

Example1:entering the data

for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
scanf(“%d”, &a[i][j]);
}
Accessing elements of an array:
Accessing elements of array means displaying values of the array. To access all
elements of the array, we must use nested for loop.

Example:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf(“%d”, a[i][j]);
}

Program to read and display the elements of an array:


void main()
{
int a[10][10],r,c,i,j;
clrscr();
printf(“\nenter rows and columns of an array ”);
scanf(“%d%d”,&r,&c);
printf(“\n enter elements into an array\n”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf(“%d”, &a[i][j]);
}
printf(“display elements from an array\n”);

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf(“%d”, a[i][j]);
}
}
Operations that can be performed on two dimensional arrays:

1) Addition/Sum:
Adding two matrices and result is stored in another matrix.
2) Subtraction/Difference :
Subtracting two matrices and result is stored in another matrix.
3) Multiplication/Product:
Multiplication of two matrices and result is stored in another matrix.
4) Transpose:
Transpose of a matrix means changing rows to columns and columns
to rows.
5) Trace:
Sum of all diagonal elements is called trace of a matrix.
Examples:

1) Addition of two matrices

void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf(“enter rows and columns of ‘a’ matrix”);
scanf(“%d%d”,&r1,&c1);
printf(“enter rows and columns of ‘b’ matrix”);
scanf(“%d%d”,&r2,&c2);
if(r1==r2&&c1==c2)
{
printf(“enter elments of ‘a ‘ matrix”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter elments of ‘b ‘ matrix”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“\n addition of two matrices are\n”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
else
printf(“matrix addition is not possible”);
}

2) Subtraction of two matrices


void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf(“enter rows and columns of ‘a’ matrix”);
scanf(“%d%d”,&r1,&c1);
printf(“enter rows and columns of ‘b’ matrix”);
scanf(“%d%d”,&r2,&c2);
if(r1= =r2&&c1= =c2)
{
printf(“enter elments of ‘a ‘ matrix”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter elments of ‘b ‘ matrix”);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]-b[i][j];
}
}
printf(“\n subtraction of two matrices are\n”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
else
printf(“matrix subtraction is not possible”);
}

3) Multiplication of two matrices

void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf(“enter rows and columns of ‘a’ matrix”);
scanf(“%d%d”,&r1,&c1);
printf(“enter rows and columns of ‘b’ matrix”);
scanf(“%d%d”,&r2,&c2);
if(c1= =r2)
{
printf(“enter elments of ‘a ‘ matrix”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter elments of ‘b ‘ matrix”);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=0;
for(k=0;k<r;k++)
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
printf(“\n multiplication of two matrices are\n”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
else
printf(“matrix multiplication is not possible”);
}

4) Transpose of a given matrix

void main()
{
int a[10][10],t[10][10],r,c,i,j;
clrscr();
printf(“enter rows and columns of an array”);
scanf(“%d%d”,&r,&c);
printf(“enter elements into an array\n”);
if(r!=0&&c!=0)
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf(“%d”, &a[i][j]);
}
printf(“\n Transpose of a given matrix is \n”);
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
t[i][j]=a[j][i];
printf(“%d\t”,t[i][j]):
}
printf(“\n”);
}
}
else
printf(“matrix transpose is not possible”);
}

Example:

1 2
3 4

Transpose of above matrix is


1 3
2 4

5) Trace of a matrix

void main()
{
int a[10][10],sum=0,r,c,i,j;
clrscr();
printf(“\n enter rows and columns of an array”);
scanf(“%d%d”,&r,&c);
printf(“\n enter elements into an array\n”);
if(r= =c)
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf(“%d”, &a[i][j]);
}
printf(“\n trace of a given matrix is \n”);
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
if(i= =j)
sum=sum+a[j][i];
}
}
printf(“\n sum of all diagonal elements=%d”,sum);
}
else
printf(“\n trace is not possible”);
}
Q) Two-Dimensional Array for Inter-Function Communication

Like variables of other datatypes, we can pass arrays to functions. We can


either pass individual elements or entire array to functions.
Example:
void main()
{
int a[2][3]={1,2,3,4,5,6};
clrscr();
disp(a);
getch();
}
disp(int a[2][3])
{
inti,j;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
}
Q) Multidimensional Arrays

A multidimensional array is an array of arrays. We have one index in one dimensional


array, two indices in two dimensional arrays and n indices in multidimensional arrays. A
multidimensional array can use as many indices and requirement of memory increases
with number of indices. A multidimensional array is declared and initialized similar to
1D and 2D arrays.

Example:
/*program on multidimensional array*/

#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3][3], i, j,k;
clrscr( );
printf(“\n enter elements into the array”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
scanf(“%d”,&a[i][j][k]);
}
}
}
printf(“\n elements entered in the array are”);
for(i=0;i<2;i++)
{
printf(“\n\n”);
for(j=0;j<2;j++)
{
printf(“\n”);
for(k=0;k<2;k++)
printf(“%d\t”, a[i][j][k]);
}
}
}
Strings

String:-
An array which consists of group of characters is called character array or simply
it is called string. In the character array each and every character occupies one byte of
memory. The character is always ‘\0’. Normally its looks like two characters but, it is
actually only one character. It is also called null character. This null character represents
the terminating point of the string. A string may contain numeric or alphabetic or alpha
numeric or symbols. Single character enclosed in single quote marks. Multiple
characters enclosed in double quote marks.

Declaration:
Syntax:
datatype stringvariablename[size];
Example :
char name[7];
Initialization:
datatype chararrayname[dimension]=”String”;
Example:
char name[7]=”ABNPRR”;

A B N P R R \0
0 1 2 3 4 5 6

NOTE: C compiler inserts null character (‘\0’) automatically.


(or)
Initialization:
datatype chararrayname[dimension]={list of characters};
Example:
char name[7]={‘A’,’B’,’N’,’P’,R’,R’,’\0’};

NOTE: In the above case, inserts null character (‘\0’) by the user.

Example:
char name[ ]={‘A’,’B’,’N’,’P’,R’,R’,’\0’};

An array is initializing a list of values separated by commas and surrounded by curly


braces. If no size is given, the compiler allocates enough space for all the characters
specified in the list.
Input Strings by using two functions:
scanf(): It accepts only single word string.

Syntax: scanf(“format specifier”,&stringcariablename);

Example: scanf(“%s”,&name);

gets(): It also accepts multiword string.

Syntax:gets(stringvariablename);

Example: gets(name);

Output Strings by using two functions:


printf(): It displays only single word string which is input by the user.

Syntax: printf(“format specifier”,stringvariablename);

Example: printf(“%s”,name);

puts(): It also displays multiword string.

Syntax: gets(stringvariablename);

Example: gets(name);

Example:

/* Single word string */


#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
printf(“Enter your name”);
scanf(“%s”,&name);
printf(“My name is %s”,name);
getch();
}
Example:
/* Multi word string */
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
clrscr();
puts(“Enter your name”);
gets(name);
puts(“My name is”);
puts(name);
getch();
}
Examples:
1) /* input and output that string */
void main()
{
char name[ ]=”abnprr”;
clrscr();
printf(“my name is %s”,name);
getch();
}

2) /* Output name using while loop */


void main()
{
char name[6]=”Durga”;
inti;
clrscr();
i=0;
while(name[i]!=’\0’)
{
printf(“%c”,name[i]);
i++;
}
getch();
}
3) /* Display name using pointers */
void main()
{
char name[]=”prabha”;
char *ptr;
clrscr();
ptr=&name;
while(*ptr!=’\0’)
{
printf(“%c”,*ptr);
*ptr++;
}
}
Q) Explain about various string functions in C?

There are several string functions are available in c. They are


1) strlen()
2) strupr()
3) strlwr()
4) strcpy()
5) strcat()
6) strcmp()
7) strrev()

1) strlen():
It returns the number of characters existing in the string.

Syntax:intVar=strlen(str);

Example: l=strlen(name);

/* Using strlen() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[10];
int l;
clrscr();
printf(“Enter your name”);
scanf(“%s”,&name);
l=strlen(name);
printf(“%d”,l);
getch();
}
2) strupr():
It converts lowercase characters to uppercase characters.
Syntax: strupr(lowercasestring);
Example: strupr(name);
/* Using strupr() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[10];
clrscr();
printf(“Enter your name in lowercase”);
scanf(“%s”,&name);
strupr(name);
printf(“Upper case string is %s”,name);
getch();
}
3) strlwr():
It converts uppercase characters to lowercase characters.
Syntax: strlwr(uppercasestring);
Example: strlwr(name);

/* Using strlwr() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[10];
clrscr();
printf(“Enter your name in uppercase”);
scanf(“%s”,&name);
strlwr(name);
printf(“Lower case string is %s”,name);
getch();
}
4) strcpy():
It copies one string to another string.

Syntax: strcpy(target,source);
Example: strcpy(target,source);
/* Using strcpy() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10]=”Computers”;
char t[10];
clrscr();
strcpy(t,s);
printf(“Source string is %s\n”,s);
printf(“Target string is %s\n”,t);
getch();
}
5) strcat():
It combines two strings and stores the combined string in target
string.
Syntax:strcat(target,source);

Example:strcat(t,s);

The target string consists of combined string. The dimension of target


string must be greater than source string.
/* Using strcat() */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20],target[40];
clrscr();
printf(“enter string”);
scanf(“%s”,&name);
printf(“target string string”);
scanf(“%s”,&target);
strcat(target,name);
printf(“target string is %s”,target);
getch();
}
6) strcmp():
It is used to compare two strings character by character and gives ASCII
difference.
Syntax: intVar= strcmp(str1,str2);
Example: D=strcmp(s1,s2);
/* Using strcmp() */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int v;
char s1[20],s2[20];
clrscr();
printf(“enter string1”);
scanf(“%s”,&s1);
printf(“enter string2”);
scanf(“%s”,&s2);
v=strcmp(s1,s2);
if(v==0)
printf(“strings are identical”);
else
printf(“strings are not identical”);
getch();
}
7) strrev():
It is used to reverse the accepted string.
Syntax: strrev(string);
Example: strrev(st);
/* Using strrev() */

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10];
clrscr();
printf(“Enter your name”);
scanf(“%s”,&s);
strrev(s);
printf(“”Reverse string is %s”,s);
getch();
}

Q) Array of Strings

An array which consists of more than one string that is character array. This is called
String array or array of strings.

Syntax: datatype arrayname[row-dimension][column-dimension];

Here row-dimension represents number of strings.

Column dimension represents size of every string.

Example: char name[10][30];

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char n[20][20],t[20];
inti,j,s;
clrscr();
printf("Enterno. of string you want");
scanf("%d",&s);

for(i=0;i<s;i++)
{
printf("Enter String\n");
scanf("%s",&n[i]);
}
for(i=0;i<s;i++)
{
for(j=0;j<s-i-1;j++)
{
if(strcmp(n[j],n[j+1])>0)
{
strcpy(t,n[j]);
strcpy(n[j],n[j+1]);
strcpy(n[j+1],t);
}
}
}
printf(“\nAfter Sorting\n”);
for(i=0;i<s;i++)
puts(n[i]);
getch();
}

Q) Character functions:
getch():Reads a character from the keyboard at that time it does not display
character on the screen.
getche():Reads a character from the keyboard.
getchar():Reads a character from the keyboard. It reads one character at a time
till the user press the enter key.
putch():Writes a character to the screen.
putchar():Writes a character to the screen.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1,s2,s3;
clrscr();
puts("Enterany character using getch()\n");
s1=getch();
putch(s1);

puts("Enter any character getche() \n");


s2=getche();
puts("\n");
putch(s2);

puts("\n Enter any character getchar()\n");


s3=getchar();
puts("\n");
putchar(s3);
}
Unit-4
Chapter 6
Functions

Introduction to Functions
C program is nothing but combination of one or more functions. Every C program
starts with main( ) function. C language supports two types of functions. They are-----
library functions and user defined functions.
Library functions: Library functions are pre-defined set of functions. Their task is
limited. A user cannot understand the internal working of these functions. The user can
only use the functions but can’t modify them. User need not to know about source code.
Ex : sqrt ( )
sqrt (25)-- -- >5
User defined functions: User-defined functions are defined by the user according to the
user requirements are called User-defined functions.

Funtion:
A self-contained block of statements to perform a specific task is called function.

Syntax:
return type function_name(parameter_list)
{
body of the function
}
Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
calsum(a,b);
}
calsum(int a,int b)
{
int s;
s=a+b;
display(s);
}
display(int s)
{
printf(“sum is %d”,s);
}
Advantages:

1) Function using program has clarity about the code.


2) It is very easy to understand.
3) Debugging becomes very easy, because entire task is divided into modules.
Hence if an error occurs at where it occur we uses easily identify.
4) Code redundancy decreases.

Q) Function Prototype?
It specifies about the function to the compiler. That is it gives information about return
type, parameters.
Q) Define function call?
A compiler executes the function when a semi colon(;) is followed by function name. A
function can be called using its name and must be terminated with semi-colon(;).

Q) Define function definition?


Combination function header and function body is called function definition.
Q) Define Actual arguments?
The variables which are using at function call are called actual arguments.
Q) Define formal parameters?
The variables which are using at function header are called formal parameters.
Q) Define return statement?
Return statement is used return certain value to the calling function.That is no need to use
parenthesis for returned variable or value.
Q)Define bug?
An error in a computer program is called bug.
Q)Define debugging?
Finding and correcting error is called debugging.
Q)Define program?
A meaningful collection of instructions which can be understand by the compiler is
called program.
Q) Define call by value?
The function which is called by using the values of variable is called call by value.
Q) Define call by reference?
The function which is called by using the addresses of the variable is called call by
reference.
Q) Difference between call by value and call by reference?
The modifications which are performed by formal parameters will not be effected by
actual arguments in call by value method where as in call by reference actual
arguments are effected formal parameters because both are having same addresses.
Q) Explain different types of functions?

Functions are divided into four types.

1) Without arguments and without return values:


a) In calling function, function call not contains actual arguments. So it doesn’t
send the values to the called function. Called function parameter list is empty.
b) In called function not contains return statement. So it doesn’t return any value
to the calling function.

Example:
void calsum();
void main() ----------- /*calling function*/
{
clrscr();
calsum(); ----------- /*function call*/
}
void calsum() ----------- /* called function*/
{
int a=10,b=20;
printf(“a+b=%d”,a+b);
}
2) With arguments and without return values:
a) In calling function, function call contains actual arguments. So it sends
the values to the called function.
b) In called function, Formal parameters receive the values from actual arguments.
c) In called function not contains return statement. So it doesn’t return any value to
the calling function.

Example:

void calsum(int a, int b);


void main()
{
int a=1,b=2;
clrscr();
calsum(a,b);
}
void calsum(int a, int b)
{
int c;
c=a+b;
printf(“c=%d”,c);
}
3) With arguments and with return values:
a) In calling function, function call contains actual arguments. So it sends
thevalues to the called function.
b) In called function, Formal parameters receive the values from actual
arguments.
c) In called function contains return statement. So it returns certain value to the
calling function

Example:
intcalsum(int a, int b);
void main()
{
int a=1,b=2,c;
clrscr();
c=calsum(a,b);
printf(“c=%d”,c);
}
intcalsum(int a, int b)
{
return (a+b);
}
4) Without arguments but with return values:
a) In calling function, function call not contains actual arguments. So it doesn’t
send the values to the called function. Called function parameter list is
empty.

b) In called function contains return statement. So it returns certain value to the


calling function
Example:

intcalsum();
void main() ----------- /*calling function*/
{
int c;
clrscr();
c=calsum(); ----------- /*function call*/
printf(“c=%d”,c);
}
intcalsum() ----------- /* called function*/
{
int a=10,b=20;
return (a+b);
}

Q) Explain about function calling methods (or) parameter passing techniques in


‘C’?
In ‘c’ functions are calling in two different ways

1) Call by value:
Functions are called by passing the value of variables then such calls are called as
call by value. By using call by value we are passing the values (actual arguments )
to the called function. These arguments are received by the formal parameters to
the called function.

Example:

#include<stdio.h>
#include<conio.h>
void swap(int ,int );
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
swap(a,b);
printf(“\n a=%d\tb=%d”,a,b);
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
printf(“\n x=%d\ty=%d”,x,y);
}
Rules:
1) Both actual arguments and formal parameters have the same data type.
2) Function call contains actual arguments. It sends the values to formal
parameters.
3) Formal parameters receive the values from actual arguments.
4) Variable names actual and formal parameters either same or different.
5) Actual arguments are not effect by the formal parameters.
6) Actual arguments and formal parameters are having different addresses.
7) Finally actual arguments and formal parameters have different values

2) Call by reference:
The function are called by passing the address of variable then such calls are called
call by reference.
Example:

#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y);
void main()
{
int a,b;
clrscr();
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
printf(“\n a=%d\t b=%d”,a,b);
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“\n x=%d\t y=%d”,*x,*y);
}
Rules:
1) Both actual arguments and formal parameters have the same data type.
2) Function call contains & (address) operator prefix the actual arguments. It sends
the addresses of variables to formalparameters.
3) Called function contains pointer variables it stores the addresses of the
variables.
4) Variable names actual and formal parameters either same or different.
5) Actual arguments are effected by the formal parameters.
6) Actual arguments and formal parameters are having same addresses.
7) Finally actual arguments and formal parameters have same values

Q) Define recursion with an example program?


Recursion :
A function can call itself is called recursion or circular definition.

Example:/* factorial value using recursion */


#include<stdio.h>
#include<conio.h>
intfvrec(int x);
void main()
{
int n, fv ;
clrscr();
printf(“Enter n value”);
scanf(“%d”,&n);
fv=fvrec(n);
printf(“\n factorial value of %d is%d “,n,fv);
}
intfvrec(int x)
{
int f;
if(x= =1)
return 1;
else
{
f= x*fvrec(x-1);
return f;
}
}

Q)Types of recursion?

Recursion :
A function can call itself is called recursion or circular definition.

The recursion can be used in two types.

1) Direct recursion
2) Indirect recursion

1)Direct recursion:
The direct recursion function calls itself till the condition is true.
Example:

void main()
{
int i;
clrscr();
f1(i);
}
f1(int i)
{
if(i<5)
{
printf(“\t %d”,i);
i++;
f1(i);
}
}

2)Indirect recursion:
In indirect recursion a function calls another function then the
called function calls the calling function.

Example:

void main()
{
int i;
clrscr();
f1(i);
}

f1(int i)
{
f2(i);
}
f2(int i)
{
if(i<5)
{
printf(“\t %d”,i);
i++;
f1(i);
}
}

Q) Scope of variables
Scope:
The area of the program where the variable is accessible is called its scope.
There are two kinds of variables. 1) local 2)global
1) Local variables:
The variables which are declared and used inside functions are called local
variables. Other functions cannot access these variables.

#include<stdio.h>
#include<conio.h>
void main()
{
int a=10; /*local variables*/
clrscr();
printf(“a=%d”,a);
calsum();
}
calsum()
{
int a=100,b=200,c; /*local variables*/
c=a+b;
printf(“c=%d”,c);
}
2) Global variables:

A variable that is declared outside the main() function is called a Global


Variable. Global variables remain available throughout the program execution.
By default, initial value of the Global variable is 0(zero). Global variable is that
their values can be changed by any function in the program. All functions can
access these variables.
Example:
int a; /*global variables*/
void main()
{
clrscr();
printf(“a=%d\n”,a);
a=10;
printf(“a=%d\n”,a);
calsum();
}
calsum()
{
int b=20,c;
c=a+b;
printf(“c=%d”,c);
}
Q) Explain about storage classes in ‘C’?
Storage class:
Storage class specifies in C language tells the compiler where to store a
variable, how to store the variable, what is the initial value of the variable and life
time of the variable.

(or)

Storage class of a variable tells the compiler for the following four things.
1) Memory: At which memory area is allocated of the variable.
2) Initial value: What is the initial value of variable if not initialized.
3) Scope: What is the scope of the variable in which functions (either main() or user
defined) the variable value will available.
4) Life: What is the life of the variable i.e. how long the variable would be active in
the program.

There are four types of storage classes available in C.


1) Auto
2) Extern
3) Static
4) Register

1)Auto storage class:

Keyword: auto
Memory: Ram
Initial value: Garbage value
Scope: local
Life : within the function /block only

Auto variables are defined inside a function. A variable inside the function
without storage class name, by default it is an auto variable.This is the default storage
class for all the variables declared inside a function or a block. Automatic variables
can also be called local variables.

Example:
void main()
{
auto int i;
printf(“%d”,i);
}

2)Extern storage class:


Keyword: extern
Memory: Ram
Initial value: 0 (zero)
Scope: Global
Life :Till the end of the main program. Variable definition might be
anywhere in the C program.

The extern keyword is used with a variable to inform the compiler that this
variable is declared somewhere else. The extern declaration does not allocate
storage for variables. External variables are also called as global variables.
A variable that is declared outside any function is a Global Variable. Global
variables remain available throughout the program execution. By default, initial
value of the Global variable is 0(zero). Global variable is that their values can be
changed by any function in the program. All functions can access these variables.

Example:
extern int i;
void main()
{
clrscr();
printf(“%d”,i);
i=90;
printf(“%d\n”,i);
}
int i=50;

3) Static Storage class:


Keyword: static
Memory: Ram
Initial value: 0 (zero)
Scope: Local/Global
Life : Retains the value of the variable between different function calls.

1. The static variables may be of an internal or external type, depending upon


where it is declared. If it is declared outside the function of the body it will be
static global.
2. In case it is declared within the function body it will be static local.When a
variable is declared as static its garbage value is removed and initialized to
0(zero).
3. The variables remain available throughout the program execution.
4. The static variable is initialized only once. It is never reinitialized.
5. The value of the static variable save at each call and the change made in the
static variable remains throughout the program execution.

Example:
static int a;
void main()
{
clrscr();
increment();
decrement();
increment();
decrement();
increment();
}
increment()
{
static int b;
printf(“\n %d \t”,a);
printf(“%d”,b);
a++;
b++;
}
decrement()
{
a--;
}

4) Register storage class:


Keyword: register
Memory: CPU registers
Initial value: Garbage value
Scope: Local
Life :Within the function / block only.

The register variable is used as loop variable. We can also keep some
variables in the CPU registers instead of memory. The keyword register tells the
compiler the variable list followed by it is kept on the CPU registers. Since
register access is faster than the memory access.

Example:
void main()
{
register int i;
clrscr();
for(i=1;i<6;i++)
{
printf(“\n%d”,i);
}
}

Pointers
Pointer:
Pointer is a special variable which is used to point to the address of ordinary variable.
The pointer is denoted by ( * ) asterisk symbol.

Or

A pointer is a memory variable that stores a memory address. Pointer can have any
name and it is declared in the same fashion like other variables but it is always denoted
by ‘ * ’ operator.

Normally a pointer variable like any other variable is declared. So that it will work
only with data of given data type. Just like as an integer variable can hold integers, a
character variable can hold only characters. Just like that pointer variables can point to
one specific data type. That means it may be int, char, float and double.

Pointer declaration:

Pointer variable can be declared as follows.

Syntax:
datatype *pointervariablename;

Example:

int *x;
float *y;
char *z;
Here
x is an integer pointer and it tells to the compiler which stores the address of
any integer variable.
y is a float pointer which stores the address of any float variable.
z is a character pointer which stores the address of any character variable.
Indirection operator ( * ) is also called the dereference operator.
& operator is the address operator it represents the address of the variable.
A pointer references a location in memory, and obtaining the value of the
location a pointer refers to as known as dereferencing the pointer.
Initializing a pointer variable:
Syntax: pointervariablename=&variablename;
Example: int a=10,*P;
p=&a;
Accessing pointer variable :
Syntax: *pointervariablename;
Example: *p;

#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, *p;
clrscr();
p=&a;
printf(“address of a variable=%u \n”,&a);
printf(“address of a variable=%u \n”,p);
printf(“value of a variable=%d \n”,*p);
}
Features of pointers:
1) pointers save the memory space.
2) Execution time with pointer is faster because data is manipulated with the
address.
3) The memory is accessed efficiently with the pointers. The pointer assigns the
memory space and it also releases. Dynamically memory is allocated.
4) Pointers are used with data structures. They are useful for representing two-
dimensional and multi dimensional arrays.

Disadvantages of pointers:-
1)we can access the restricted memory area.
2) Pointers require one additional dereference, meaning that the final code must read
the variable’s pointer from memory, then read the variable from the pointed-to
memory. This is slower than reading the value directly from memory.
3). If sufficient memory is not available during runtime for the storage of pointers,
the program may crash
Q)Pointer Expressions
Like other variables pointer variables can be used in expressions. Pointer
deals with the arithmetic, logical and assignment expressions. Pointers are not directly
used in the arithmetic, relational, logical and assignment expression, only pointer
values are used. Some of the arithmetic expressions used with pointer p and q are as
follows.
Example:
void main()
{
int *p,*q,*r,a=10,b=20,c;
clrscr();
p=&a;
q=&b;
*r=(*p)+(*q);
c=(*p)+(*q);
printf(“*r=%d\n”,*r);
printf(“c=%d\n”,c);
printf(“%d\n”,(*p)+(*q));
printf(“%d\n”,(*p)-(*q));
printf(“%d\n”,(*p)*(*q));
printf(“%d\n”,(*p)/(*q));
}
Q)Pointer Arithmetic
Pointer is a variable that points to a memory location. Memory addresses are numeric
value that ranges from zero to maximum memory size in bytes. These addresses can be
manipulated like simple variables. You can increment, decrement, calculate or compare
these addresses manually.

C language provides a set of operators to perform arithmetic and comparison of memory


addresses. Pointer arithmetic and comparison in C is supported by following operators -
Increment and decrement ++ and --
Addition and Subtraction + and -
Comparison <, >, <=, >=, ==, !=

Pointer increment and decrement


Increment operator when used with a pointer variable returns next address pointed by
the pointer. The next address returned is the sum of current pointed address and size of
pointer data type.
i.e new address= current pointed address + size of pointer data type

Similarly, decrement operator returns the previous address pointed by the pointer. The
returned address is the difference of current pointed address and size of pointer data
type.
i.e new address= current pointed address - size of pointer data type

For example, consider the below statements.


int a=5; a
5 value
4052 address

int *p;
p=&a; /* p points to 4052 */
p++; /* now p points to 4054 , since integer size in 2 bytes*/
p--; /* now p points to 4052 */

Example 1:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[4]={1,2,3,4};
int i, *p;
clrscr();
p=a;
for(i=0;i<4;i++)
{
printf("%d\n",*p)
p++;
}
}
Output:
1
2
3
4

Example 2:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[4];
int i, *p;
clrscr();
p=a;
printf(“Enter array elements\n “);
for(i=0;i<4;i++)
{
scanf(“%d",p);
p++;
}
p=a;
printf(“Array elements are\n “);
for(i=0;i<4;i++)
{
printf(“%d\n”,*p);
p++;
}
}
Output:
Enter array elements
1
2
3
4
Array elements are

1
2
3
4
Pointer Addition:
We can add to the pointer variable. The formula of adding value to pointer is given
below.
i.e new address= current pointed address + (number*size of pointer data type)

Example1: int a=5;


a
5 value
4052 address
int *p;
p=&a; (p point to 4052)
p=p+1; (p=4052+1*2 =4052+2 =4054 )

Example2: int a={5,10,15,20};

a 5 10 15 20
4052 4054 4056 4058
int *p;
p=&a;
p=p+1; (p=4052+1*2 =4052+2 = 4054 )

here integer pointer datatype p size is 2


p=p+2; (p=4052+2*2 =4052+4 = 4056 )

Pointer Subtraction:
We can subtract to the pointer variable. The formula of subtracting value to pointer is
given below.
i.e new address= current pointed address - (number*size of pointer data type)
Example: int a=5;
a
5 ---value
4052 --- address
int *p;
p=&a; (p point to 4052)
p=p-1; (p=4052-1*2 =4052-2 =4050 )
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4]={10,20,30,40};
int *p,i;
clrscr();
p=a;
for(i=0;i<4;i++)
{
printf(“%d\n”,*(p+i));
}
}
Output:
10
20
30
40

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4]={10,20,30,40};
int *p,i;
clrscr();
p=&a[3];
for(i=0;i<4;i++)
{
printf(“%d\n”,*(p-i));
}
}
Output:
40
30
20
10

Example :
#include<stdio.h>
#include<conio.h>
#define size 4
void main()
{
int a[size]={10,20,30,40};
int *p,i;
clrscr();
p=a;
printf("\nArray elements are\n");
for(i=0;i<size;i++)
{
printf(“%d\n”,*(p+i));
}
}

Pointer comparison
In C, you can compare two pointers using relational operator. You can perform six
different type of pointer comparison <, >, <=, >=, == and !=.

Note: pointer comparison compares two pointer address to which they point to, instead
of comparing their values.

Pointer comparisons are less used when compared to pointer arithmetic.

Example 1:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[4];
int i, *p;
clrscr();
p=a;
printf("Enter array elements are\n");
while(p<=&a[3])
{
scanf("%d",p);
p++;
}
p=a;
printf("\nArray elements are\n");
while(p<=&a[3])
{
printf("%d\n",*p);
p++;
}
}

Q) Null pointers
A null pointer is a regular pointer of any pointer type which has a special value that
indicates that it is not pointing to any valid reference or memory address. This value is
the result of type casting the integer value zero to any pointer type.
Example:
void main()
{
int *p,*q=NULL;
int a=NULL;
char c=NULL,*ch,d;
clrscr();
p=&a;
printf(“\n%d”,*p);
printf(“\n%d”,*q);
printf(“\n%c”,c);
ch=&c;
printf(“\n%c”,*ch);
printf(“\n%c”,d);
}
Q) Generic pointers (wild pointer)
These are pointers that have not been initialized that is which does not have any address
to it. Pointers that are not specifically initialized may point to random addresses in
memory.
Example:
void main()
{
char *p;
clrscr();
*p=’a’;
printf(“%c\n”,*p);
}
Q) Passing Arguments to Functions using Pointer
In call by reference, the addresses of the variables are passed. When we pass addresses
to a function, the parameters receiving the addresses should be pointers. The process of
calling a function using pointers to pass the addresses of a variable is known as ‘call by
reference’.
Example:

#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y);
void main()
{
inta,b;
clrscr();
printf(“Enter a,b values”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
printf(“\n a=%d\t b=%d”,a,b);
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“\n x=%d\t y=%d”,*x,*y);
}
/* passing individual array elements using call by reference */
void main()
{
int a[]={1,2,3,4,5};
int i;
clrscr();
for(i=0;i<5;i++)
display(&a[i]);
getch();
}
display(int *n)
{
printf(“%5d”,*n);
}
Q) Pointers and Arrays
An array is a collection of similar data type elements. When we declare an array then
consecutive memory locations are allowed to the array elements. The base address of
the array is addresss of 0th element of an array. The name of the array also gives the base
address of the array.
Ex: int a[4]={1,2,3,4};
Here a [4] means that ‘a’ has 4 elements and is of ‘int’ data type.
Following are the two main points to understand the concept of pointers with arrays.

2. Elements of array are stored in the consecutive memory locations.


3. When an array pointer is incremented it refers to the next location of its data type.
Example:
int a [4] = {5, 10, 15, 20};
int *b;

a 5 10 15 20
4052 4054 4056 4058

b=a;
‘b’ is a pointers variable which holds the base address of the array ‘a’.
(Or)
b=&a[0];

When pointer variable is incremented by ‘1’ then it contains the base address +2
because pointer is of type ‘int’. The address of the next element will be also base
address +2 because element of array are stored in consecutive memory location. So, we
can say when an array pointer is incremented it refers to the next immediate location of
the array. Hence
b=&a [0];
b+1=&a[1];
b+2=&a[2];
b+3=&a[3];
The name of the array ‘a’ is the base address of the array. This can also be written as a+0
i.e., &a[0]---> a+0, which gives the base address of the array. To get the value at that
address, we can use *a (or) *(a+0) (or) a[0].
i.e., *a gives the zeroth element of the array.

*(a+1) gives the first element of the array.


*(a+2) gives the second element of the array.
*(a+i) gives the ith element of the array.
This can also be written as *(i+a) (or) i[a].
Example1 :

void main()
{
int a[4]={1,2,3,4};
int i,*p;
clrscr();
p=a;
for(i=0;i<4;i++)
{
printf(“%d\n”,*p);
p++;
}
}
Example2 :
void main()
{
int a[4]={1,2,3,4};
int i;
clrscr();
for(i=0;i<4;i++)
printf(“%d\n”,*(a+i));
}
Example: /* to find the smallest element in the list using pointers*/
void main()
{
int a[4]={1,2,3,4};
int i,*p;
clrscr();
p=&a[0];
for(i=0;i<4;i++)
{
if(*p>a[i])
p=&a[i];
}
printf(“smallest element is %d”,*p);
}

Example:
void main()
{
int a[2][2]={1,2,3,4};
int *p,i,j=0;
clrscr();
p=&a[0][0];
for(i=0;i<4;i++)
{
j++;
printf(“%d\t”,*p);
p++;
if(j==2)
{
printf(“\n”);
j=0;
}
}
}

Q)Passing Array to function


/* passing array using call by reference */
void main()
{
int a[4]={1,2,3,4};
int i;
clrscr();
disp(&a,4);
}
disp(int *p,int n)
{
int i;
for(i=0;i<4;i++)
{
printf("%d\n",*p);
p++;
}
}

Q) Pointers and Strings


An array which consists of group of characters is called character array or simply
it is called string. The null character represents the terminating point of the string. It is
denoted by ‘\0’. The character array name contains address of starting character of the
string.
char name[]=”prabha”;
char *ptr;
ptr=&name;

The pointer variable stores address of name. It represents address of starting character.

/* Display name using pointers */


void main()
{
char name[]=”prabha”;
char *ptr;
clrscr();
ptr=&name;
while(*ptr!=’\0’)
{
printf(“%c”,*ptr);
ptr++;
}
}

Q) Array of pointers
Pointer array contains collection of addresses.

Example:
void main()
{
int a[4]={1,2,3,4},*p[4];
int i;
clrscr();
for(i=0;i<4;i++)
p[i]=a+i;
for(i=0;i<4;i++)
printf(“%d\n”,*p[i]);
}

Q) Pointer to pointer
Pointer is known as a variable containing address of another variable. The pointer
variables also have an address. The pointer variable containing address of another
pointer variable is called as pointer to pointer.

Example:

void main()
{
int *p,**q;
int a=10;
clrscr();
p=&a;
q=&p;
printf(“*p=%d”,*p);
printf(“**q=%d”,**q);
printf(“a=%d”,a);
}

Q) void pointer
Pointers can also be declared as void type. Void pointers cannot be dereferenced
without explicit type conversion. This is because, being void the compiler cannot
determine the size of the object that the pointer points too. However void pointer
declaration is possible, void variables declaration is not allowed.

Example:

void main()
{
int a=10;
float b=2.5;
void *ptr;
clrscr();
ptr=&a;
printf(“%d”,*(int *)ptr);
ptr=&b;
printf(“%f”,*(float *)ptr);

Dynamic Memory Allocation


Q) Dynamic Memory Allocation
"The process of allocating memory at runtime is called dynamic memory
allocation."
There are four library functions known as "memory management functions" that can be
used for allocating and freeing memory during program execution.

MEMORY ALLOCATION FUNCTIONS

1)malloc(): malloc stands for memory allocation. Allocates main memory.

Syntax: (void *)malloc(size);

Size is in bytes. Returns a pointer to the newly allocated block, or NULL if not
enough space exists for the new block. If size= =0, it returns NULL.

Example:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
char *name;
clrscr();
name=(char *)malloc(10);
printf(“enter your name”);
scanf(“%s”,&name);
printf(“my name is %s”,name);
free(name);
}

2)calloc: calloc stands for contiguous memory allocation. Allocates main memory.
Syntax: (void *)calloc(nItems, size);
Allocates space for nItems of size bytes each and stores zero in the area.
Returns a pointer to the newly allocated block or NULL if not enough space exists.
While malloc allocates a single block of storage space, calloc allocates multiple blocks
of storage, each of same size and then sets all bytes to zero.

Example:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
char *name;
clrscr();
name=(char *)calloc(10,sizeof(char));
printf(“enter your name”);
scanf(“%s”,&name);
printf(“my name is %s”,name);
free(name);
}

3) realloc: reallocates main memory.

Syntax: (void *)realloc(void *block, newsize);

Attempts to shrink or expand the previously allocated block to size bytes. Returns the
address of the reallocated block which can be different than the original address. If the
block cannot be reallocated or size==0, realloc returns NULL.

Example:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
char *name;
int l;
clrscr();
name=(char *)malloc(10);
printf(“enter your name”);
scanf(“%d”,name);
printf(“my name is %s”,name);
l=strlen(name);
printf(“Length of the string is %d”,l);
name=(char *)realloc(name,20);
printf(“enter your name”);
scanf(“%d”,name);
printf(“my name is %s”,name);
l=strlen(name);
printf(“Length of the string is %d”,l);
free(name);
}

4) free: deallocates the memory. Frees blocks allocated with malloc or calloc.
Syntax: free(void *block);

Structures, Union and Enumerated Data Types


Structures
Definition:

Structure is a user-defined datatype which consists of dissimilar (different)


datatype elements. The keyword for structure is struct.

Declaration:

Syntax: structstructurename
{
datatype declaration1;
datatype declaration2;
datatype declaration3;
-------
-------
datatype declaration n;
};

Structure variable declaration:

Method1:
structstructurename
{
datatype declaration1;
datatype declaration2;
datatype declaration3;
-------
-------
datatype declaration n;
}structurevariablename ;

Method2:
structstructurename
{
datatype declaration1;
datatype declaration2;
datatype declaration3;
-------
-------
datatype declaration n;
};
struct structurename structurevariablename ;

Example1:

struct student
{
int sno;
char sname[20];
float tmarks;
}s1;

Example2 :

struct student
{
int sno;
char sname[20];
float tmarks;
};
struct student s1;

Initializing structure data member:

structstrudent s1={1,”durga”,987.0};
Accessing structure data member:

Syntax: structurevariablename.structuredatamember

Example: s1.sno

Example program1:

/* local structure */

#include<stdio.h>
#include<conio.h>
void main()
{
struct student
int sno;
char sname[20];
float tmarks;
};
struct student s1={1,”durga”,987};
clrscr();
printf(“sno=%d\n”,s1.sno);
printf(“sname=%s\n”,s1.sname);
printf(“tmarks=%f\n”,s1.tmarks);
}

Note: structure can be declared locally or globally.

Example program2:

/* global structure */

#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
float tmarks;
};
void main()
{
struct student s1={1,”durga”,987};
clrscr();
printf(“sno=%d\n”,s1.sno);
printf(“sname=%s\n”,s1.sname);
printf(“tmarks=%f\n”,s1.tmarks);
}

Example program3:

/* read values from the keyboard */

#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int sno;
char sname[20];
float tmarks;
};
struct student s1;
clrscr();
printf(“Enter sno,sname,tmarks\n”);
scanf(“%d%s%f”,&s1.sno,&s1.sname,&s1.tmarks);
printf(“sno=%d\n”,s1.sno);
printf(“sname=%s\n”,s1.sname);
printf(“tmarks=%f\n”,s1.tmarks);
}

Q) Array of structures

An array is a collection of similar datatypes. In the same way we can also define array
of structures. In such type of array every element is of structure type. Array of structures
can be declared as follow.

Syntax:

structstructurename
{
datatype declaration1;
datatype declaration2;
datatype declaration3;
-------
-------
datatype declaration n;
};
structstructurenamestructureArrayvariablename[size] ;

Example:

struct student
{
intsno;
char sname[20];
float tmarks;
};
struct student s[5];

/* Array of structures */

#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int sno;
char sname[20];
float tmarks;
};
struct student s[5];
int i;
clrscr();
for(i=0;i<5;i++)
{
printf(“Enter sno,sname,tmarks\n”);
scanf(“%d%s%f”, &s[i].sno,&s[i].sname,&s[i].tmarks);
}
for(i=0;i<5;i++)
{
printf(“sno=%d\n”,s[i].sno);
printf(“sname=%s\n”,s[i].sname);
printf(“tmarks=%f\n”,s[i].tmarks);
}
}

Q) Pointer and structures

Structure can be directly handled by its address by using the pointer with structure. We
use pointer with structure through structure variable. Array of structure variable directly
stands for the address of zeroth element.

/* Pointer to structure */

#include<stdio.h>
#include<conio.h>
structemp
{
int eno;
char ename[20];
float sal;
};
void main()
{
structemp *ptr;
structemp e1={1001,”Srinivas”,8000};
clrscr();

ptr=&e1;

printf(“eno=%d\t ename=%s\t sal=%f\n”,e1.eno,e1.ename,e1.sal);

printf(“eno=%d\t ename=%s\t sal=%f\n”,ptr->eno,ptr->ename,ptr->sal);

printf(“eno=%d”,(*ptr).eno);

In the above program, pointer variable ptr can be initialized as

ptr=&e1;

We can directly access the individual member element by using the following valid
way.
(*ptr).eno;

But , we can’t access without the use of parenthesis. To solve this problem, user can use
the arrow operator(->). i.e

ptr->eno;

Q) structures and functions

Structure can be implemented with the function easily.for this process passing of
argument takes place similar to the array and variable.

/*passing structure to a function using call by reference */

#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
float tmarks;
};
void main()
{
struct student s={1,”durga”,987};
clrscr();
disp(&s);

disp(struct student *s)

printf(“sno=%d\n”,s->sno);
printf(“sname=%s\n”,s->sname);
printf(“tmarks=%f\n”,s->tmarks);
}

Q) Nested structure

A structure is declared and processed with in another structure, then it is called Nested
structure or structure within structure.

/* Nested structure*/
#include<stdio.h>
#include<conio.h>
struct address
{
char locname;
long int pin;
};
struct student
{
int sno;
char sname[20];
struct address a;
};
void main()
{
struct student s={1,”durga”,987,”kovvur”,534350};
clrscr();
printf(“sno=%d\n”,s.sno);
printf(“sname=%s\n”,s.sname);
printf(“sname=%s\n”,s.a.locname);
printf(“pin=%ld\n”,s.a.pin);
}

Q) structure copy

/* structure copy */

#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20];
float tmarks;
};
void main()
{
struct student s1={1,”durga”,987};
struct student s2,s3;
clrscr();
s2=s1;
s3.sno=s1.sno;
strcpy(s3.sname,s1.sname);
s3.tmarks=567.0;
printf(“sno=%d\n”,s1.sno);
printf(“sname=%s\n”,s2.sname);
printf(“tmarks=%f\n”,s3.tmarks);
}

Unions
Q) Unions

Definition:

union is a variable, which is similar to the structure. Union is a collection of


different datatype elements. All elements that share the same memory area. The
keyword for union is union.

The size of a union is equal to the size of its largest data type element. Union
declaration has more than one variable declaration, but only one variable can be used at
a time.

Syntax:
union unionname
{

datatype member-element1;

datatype member-element2;

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

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

datatype member-element n;

};

Example:

union st
{
int i;
char ch[2];
};
Union variable declaration:

Method1:

union unionname
{
datatype member-element1;
datatype member-element2;
-- -- -- -- --- --- --- -- - --- - -
- - - - - - - - - - - - - - - -- - - -
datatype member-element n;
}unionvariablename;

Method2:

union unionname
{
datatype member-element1;
datatype member-element2;
-- -- -- -- --- --- --- -- - --- - -
- - - - - - - - - - - - - - - -- - - -
datatype member-element n;
};
union unionnameunionvariablename;

Example1:

union st
{
int i;
char ch[2];
}u;

Example1:

union st
{
int i;
char ch[2];
};
union st u;
union initialization:
syntax:

unionvariablename.memberelement=value;

Example:

u.i=512;

Accessing union member element:

Syntax: unionvariablename.memberelement;

Example: u.i

Example:

void main()
{
union st
{
int i;
char ch[2];
}u;
u.i=512;
printf(“u.i=%d\n”,u.i);
printf(“u.ch[0]=%d\n”,u.ch[0]);
printf(“u.ch[1]=%d\n”,u.ch[1]);
}

Q)Array ofUnions

Similar to structures we have array of union variables. As new data overwrites the
existing data, the program may not display accurate results.

Example:

union point
{
int x,y;
};
void main()
{
int i;
union point p[3];
p[0].x=1;
p[0].y=2;
p[1].x=3;
p[1].y=4;
p[2].x=5;
p[2].y=6;
for(i=0;i<3;i++)
printf(“\n %d \t %d”,p[i].x,p[i].y);
}

Q) unions and pointers

In C programming pointer to union is used to store the addres of unionvariable. Arrow


and dot operators are used for accessing union members.

Example:

union t
{
char *name;
int m;
};
void main()
{
union t u,*p=&u;
clrscr();
u.name=”srinivas”;
printf(“\n%s”,p->name);
u.m=10;
printf(“\n %d”,u.m);
printf(“\n %d”, p->m);
}

Q) Union inside structure

A union is a user-defined type similar to structure in C except for one key difference.
Structures allocate enough space to store all their members, whereas unions can only
hold one member value at a time.
Structure can have union as a datamember.
void main()
{
union result
{
int tmarks;
char grade;
};
struct student
{
int sno;
char sname[20];
union result r;
};
struct student s={1,”durga",512};
clrscr();
printf(“ size of structure=%d\n”,sizeof(s));
printf(“ size of union=%d\n",sizeof(s.r));
printf(“ sno=%d\n",s.sno);
printf(“ sname=%s\n",s.sname);
printf(“ result=%d”s.r.tmarks);
s.r.grade=’A';
printf(“grade=%d",s.r.grade);
}

Enumerated data types


Definition:

An enumeration is a user-defined data type consists of integral constants and each


integral constant is give a name. keyword enum is used to defined enumerated data type.

Syntax: enum identifier{value1,value2,……..valueN};

Here, identifier is the name of the enumerated data type or tag. And value1, value2,
…..valueN are values of type identifier;

By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer
can change the default value.

Example:

void main()
{
enum month{jan,feb,mar=3,apr,may,jun,jul,aug,sep,oct,nov,dec};
clrscr();
printf(“\n%d”,jan);
printf(“\n%d”,feb);
printf(“\n%d”,mar);
}

You might also like