[go: up one dir, main page]

0% found this document useful (0 votes)
67 views155 pages

AIML CPDS Unit-1 - Unit-2

Uploaded by

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

AIML CPDS Unit-1 - Unit-2

Uploaded by

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

Study Material

C Programming &
Data Structures
Unit-1 & Unit-2

Student Name:______________________________
Roll Number :______________________________
Branch :______________________________
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR
B.Tech -CSE – I Sem L T P C
3 0 0 3
(20A05201T) C-PROGRAMMING & DATA STRUCTURES
(Common to All Branches of Engineering)

Course Objectives:

To illustrate the basic concepts of C programming language.


To discuss the concepts of Functions, Arrays, Pointers and Structures.
To familiarize with Stack, Queue and Linked lists data structures.
To explain the concepts of non-linear data structures like graphs and trees.
To learn different types of searching and sorting techniques.

UNIT-1

Introduction to C Language - C language elements, variable declarations and data types, operators
and expressions, decision statements - If and switch statements, loop control statements - while, for,
do-while statements, arrays.

Learning outcomes:

At the end of this unit, the students will be able to


Use C basic concepts to write simple C programs. (L3)
Use iterative statements for writing the C programs (L3)
Use arrays to process multiple homogeneous data. (L3)
Test and execute the programs and correct syntax and logical errors. (L4)
Translate algorithms into programs. (L4)
Implement conditional branching, iteration and recursion. (L2)

UNIT – 2

Functions, types of functions, Recursion and argument passing, pointers, storage allocation, pointers to
functions, expressions involving pointers, Storage classes – auto, register, static, extern, Structures,
Unions, Strings, string handling functions, and Command line arguments.

Learning outcomes:

At the end of this unit, the students will be able to


Writing structured programs using C Functions. (L5)
Writing C programs using various storage classes to control variable access. (L5)
Apply String handling functions and pointers. (L3)
Use arrays, pointers and structures to formulate algorithms and write programs.(L3)
UNIT-3

Data Structures, Overview of data structures, stacks and queues, representation of a stack, stack
related terms, operations on a stack, implementation of a stack, evaluation of arithmetic expressions,
infix, prefix, and postfix notations, evaluation of postfix expression, conversion of expression from
infix to postfix, recursion, queues - various positions of queue, representation of queue, insertion,
deletion, searching operations.

Learning outcomes:

At the end of this unit, the students will be able to


Describe the operations of Stack. (L2)
Explain the different notations of arithmetic expression. (L5)
Develop various operations on Queues. (L6)

UNIT – 4

Linked Lists – Singly linked list, dynamically linked stacks and queues, polynomials using singly
linked lists, using circularly linked lists, insertion, deletion and searching operations, doubly linked
lists and its operations, circular linked lists and its operations.

Learning outcomes:

At the end of this unit, the students will be able to


Analyze various operations on singly linked list. (L4)
Interpret operations of doubly linked lists. (L2)
Apply various operations on Circular linked lists. (L6)

UNIT-5

Trees - Tree terminology, representation, Binary trees, representation, binary tree traversals. binary
tree operations, Graphs - graph terminology, graph representation, elementary graph operations,
Breadth First Search (BFS) and Depth First Search (DFS), connected components, spanning trees.
Searching and Sorting – sequential search, binary search, exchange (bubble) sort, selection sort,
insertion sort.

Learning outcomes:

At the end of this unit, the students will be able to


Develop the representation of Tress. (L3)
Identify the various Binary tree traversals. (L3)
Illustrate different Graph traversals like BFS and DFS. (L2)
Design the different sorting techniques (L6)
Apply programming to solve searching and sorting problems. (L3)
Text Books:
1. The C Programming Language, Brian W Kernighan and Dennis M Ritchie, Second Edition,
Prentice Hall Publication.
2. Fundamentals of Data Structures in C, Ellis Horowitz, SartajSahni, Susan Anderson-Freed,
Computer Science Press.
3. Programming in C and Data Structures, J.R.Hanly, Ashok N. Kamthane and A. AnandaRao,
Pearson Education.
4. B.A. Forouzon and R.F. Gilberg, “COMPUTER SCIENCE: A Structured Programming
Approach Using C”, Third edition, CENGAGE Learning, 2016.
5. Richard F. Gilberg & Behrouz A. Forouzan, “Data Structures: A Pseudocode Approach with
C”, Second Edition, CENGAGE Learning, 2011.

Reference Books:

1. Pradip Dey and Manas Ghosh, Programming in C, Oxford University Press, 2nd Edition
2011.
2. E. Balaguruswamy, “C and Data Structures”, 4th Edition, Tata Mc Graw Hill.
3. A.K. Sharma, Computer Fundamentals and Programming in C, 2nd Edition, University
Press.
4. M.T. Somashekara, “Problem Solving Using C”, PHI, 2nd Edition 2009.

Course Outcomes:

1. Analyse the basicconcepts of C Programming language. (L4)


2. Design applications in C, using functions, arrays, pointers and structures. (L6)
3. Apply the concepts of Stacks and Queues in solving the problems. (L3)
4. Explore various operations on Linked lists. (L5)
5. Demonstrate various tree traversals and graph traversal techniques. (L2)
6. Design searching and sorting methods (L3)
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR
B.Tech-CSE-I Sem L T P C
0 0 3 1.5
(20A05201P) C-PROGRAMMING & DATA STRUCTURES LAB
(Common to All Branches of Engineering)
Course Objectives:

To get familiar with the basic concepts of C programming.


To design programs using arrays, strings, pointers and structures.
To illustrate the use of Stacks and Queues
To apply different operations on linked lists.
To demonstrate Binary search tree traversal techniques.
To design searching and sorting techniques.

Week l

Write C programs that use both recursive and non-recursive functions

i) To find the factorial of a given integer.


ii) To find the GCD (greatest common divisor) of two given integers.
iii) To solve Towers of Hanoi problem.

Week 2

a) Write a C program to find both the largest and smallest number in a list of integers.
b) Write a C program that uses functions to perform the following:
i) Addition of Two Matrices ii) Multiplication of Two Matrices

Week 3
a) Write a C program that uses functions to perform the following operations:
i) To insert a sub-string in to a given main string from a given position.
ii) To delete n characters from a given position in a given string.

Week 4
a) Write a C program that displays the position or index in the string S where the string T
begins, or – 1 if S doesn‘t contain T.

b) Write a C program to count the lines, words and characters in a given text.

Week 5

a) Write a C Program to perform various arithmetic operations on pointer variables.


b) Write a C Program to demonstrate the following parameter passing mechanisms:
i) call-by-value ii) call-by-reference
Week 6
Write a C program that uses functions to perform the following operations:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers

(Note: represent complex number using a structure.)

Week 7

Write C programs that implement stack (its operations) using

i) Arrays
ii) Pointers

Week 8
Write C programs that implement Queue (its operations) using
i) Arrays
ii) Pointers

Week 9

Write a C program that uses Stack operations to perform the following:

i) Converting infix expression into postfix expression


ii) Evaluating the postfix expression

Week 10

Write a C program that uses functions to perform the following operations on singly linked list.

i) Creation ii) Insertion iii) Deletion iv) Traversal

Week 11

Write a C program that uses functions to perform the following operations on Doubly linkedlist.

i) Creation ii) Insertion iii) Deletion iv) Traversal

Week 12

Write a C program that uses functions to perform the following operations on circular linkedlist.

i) Creation ii) Insertion iii) Deletion iv) Traversal


Week 13

Write a C program that uses functions to perform the following:

i) Creating a Binary Tree of integers

ii) Traversing the above binary tree in preorder, inorder and postorder.

Week 14

Write C programs that use both recursive and non-recursive functions to perform the following
searching operations for a key value in a given list of integers:

i) Linear search
ii) Binary search

Week 15

Write a C program that implements the following sorting methods to sort a given list of integers in
ascending order

i) Bubble sort
ii) Selection sort
iii) Insertion sort

Text Books:
1. Programming in C and Data Structures, J.R.Hanly, Ashok N. Kamthane and A. Ananda Rao,
Pearson Education.
2. B.A. Forouzon and R.F. Gilberg, “COMPUTER SCIENCE: A Structured Programming
Approach Using C”, Third edition, CENGAGE Learning, 2016.
3. Richard F. Gilberg & Behrouz A. Forouzan, “Data Structures: A Pseudocode Approach with
C”, Second Edition, CENGAGE Learning, 2011.

Reference Books:
1. PradipDey and ManasGhosh, Programming in C, Oxford University Press, 2nd Edition 2011.
2. E.Balaguruswamy, “C and Data Structures”, 4 th Edition, Tata Mc Graw Hill.
3. A.K.Sharma, Computer Fundamentals and Programming in C, 2nd Edition, University Press.
4. M.T.Somashekara, “Problem Solving Using C”, PHI, 2nd Edition 2009.

Course Outcomes

Demonstrate basic concepts of C programming language. (L2)


Develop C programs using functions, arrays, structures and pointers. (L6)
Illustrate the concepts Stacks and Queues. (L2)
Design operations on Linked lists. (L6)
Apply various Binary tree traversal techniques. (L3)
Develop searching and sorting methods. (L6)
Index
Page No.
Unit-1
1 Introduction to C Language 1.1
2 C language elements 1.7
3 Variable declarations and data types 1.10
4 Operators and expressions 1.15
5 Decision statements - If and switch statements 1.25
6 Loop control statements - while, for, do-while statements 1.36
7 Arrays 1.44
8 2 Marks Questions 1.55

Unit-2
1 Functions 2.1
2 Types of functions 2.5
3 Argument passing 2.8
4 Recursion 2.11
5 Pointers & storage allocation 2.12
6 Expressions involving pointers 2.15
7 Pointers to functions 2.17
8 Storage classes – auto, register, static, extern 2.21
9 Structures 2.25
10 Unions 2.32
11 Strings 2.34
12 String handling functions 2.35
13 Command line arguments 2.37
14 2 Marks Questions 2.40
Index
Lab Programs in C Programming
Page No.
1 Week-1 1– 6
2 Week-2 7 – 14
3 Week-3 15 – 17
4 Week-4 18 – 19
5 Week-5 20 – 22
6 Week-6 23 – 24

Previous Question Papers


1 R20 Regulations 1-2
2 R19 Regulations 3-6
3 R15 Regulations 7-17
C-Programming & Data Structures (20A05201T):: Unit-1

Unit 1
Introduction to C Language
1. Introduction to C Language
2. C language elements
3. Variable declarations and data types
4. Operators and expressions
5. Decision statements - If and switch statements
6. Loop control statements - while, for, do-while statements
7. Arrays

1. Introduction to C Language

Q1.1. Define Computer.


Answer:
The Computer is an electronic device which operates under the control of instructions stored in its
memory and it takes the data from the user (input), process that data (Processing), gives the result (Output)
and stores the result for future use.

Q1.2. Define input and output.


Answer:
Input: Input is a data that is given by the user to computer.
Output: Output is a data that is given by the computer to user.0

Q1.3. Define Software.


Answer:

Prepared By: M. Parthasaradhi, Asst. Prof.


Software is a set of programs that serve a specific application.

Q1.3. Define Program.


Answer:
A program is a set of instructions.

Q1.4. Define Instruction.


Answer:
An instruction is a statement that can form using language character set.
1.1

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q1.5. Define Programming Languages.


Answer:
 Computer Programming languages can communicate and provide instructions to the computers.
 Example: C, Python, C++, Java etc…,

Q1.6. What are the different types of programming languages.


Answer:
There are 3 types of programming languages. They are:
1. Low Level Language (Machine Level language)
2. Middle Level Language (Assembly Level Language)
3. High Level Language

Q1.7. Define machine level language.


Answer:
Low Level Language (Machine Level Language):
Low-Level language is the only language which can be understood by the computer. It contains
only two symbols 1 & 0.

Q1.8. Define Assembly level language. Give example.


Answer:
Middle Level Language (Assembly Level Language)
Middle-level language is a computer language in which the instructions are created using symbols
(mnemonics) such as letters, digits and special characters.
Example:
ADA, NIM, RUST.

Prepared By: M. Parthasaradhi, Asst. Prof.


Q1.9. Define High level language. Give example.
Answer:
High Level Language:
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.
Example:
COBOL, FORTRAN, BASIC, C, C++, JAVA, PYTHON, etc…,

1.2

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q1.10. What is an Assembler.


Answer:
Assembler is software which is used to translate middle-level language program into low-level
language program.

Q1.11. What is a Compiler.


Answer:
Compiler is software which is used to translate an entire high-level language program into low-level
language program.
Q1.11. What is an Interpreter.
Answer:
Interpreter is software which is used to translate line by line high-level language program into low-
level language program.

Q1.12. What is C?
Answer:
C is a computer programming language used to design computer software and applications.

Q1.13 Why do we use C?


Answer:
We use the C programming language to design computer software and applications.

Q1.14. Who invented C?


Answer:
 C Programming Language was invented in the year 1972 by Dennis Ritchie (Dennis MacAlistair Ritchie).

Prepared By: M. Parthasaradhi, Asst. Prof.


 He was an American Computer Scientist worked at Bell Labs as a researcher along with Ken Thompson.
 He was born on 9th September 1941 and lived till 12th October 2011. He is said to be the Father of C.

Q1.15. Why C called as a Structured Programming Language.


Answer:
C is a Structured programming language in which program is divided into various modules. Each
module can be written separately and together it forms a single C program. This structure makes it easy for
testing, maintaining and debugging process.

1.3

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q1.16. Why C called as a Procedural Language.


Answer:
C is a procedural language in which a program is written as a sequence of instructions. User has to
specify “what to do” and “how to do”. These instructions are executed in sequential order.

Q1.17. Why C called as Case Sensitive Language.


Answer:
C is a case sensitive language in which keywords and everything used in C program are case sensitive.

Q1.18. Why is C called the mother of all languages?


Answer:
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of the programming
languages follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are being used in
many languages like C++, Java, C#, etc.

Q1.19. Why C called as Middle Level Language.


C is considered as a middle-level language because it supports the feature of both low-level and high-
level languages.
C language program is converted into assembly code, it supports pointer arithmetic (low-level), but it
is machine independent (a feature of high-level).

Q1.20. Which software used to create C program.


Answer:

Prepared By: M. Parthasaradhi, Asst. Prof.


Following are the applications and software used to create and execute C programs.
 Turbo C
 Turbo C++
 GNU C
 Code Blocks
 Net Beans
 Dev C++ etc…

1.4

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q1.21. Explain in detail about structure of C Program.


Answer:
 C is a structured programming language. Every C program and its statements must be in a particular
structure.
 Every C program has the following general structure.

Documentation Section
1 (Used for Comments)
2 Pre-processing Commends
3 Global Declarations
int main( )
{
Local Declarations
Executable Statements
.
.
4 .
return 0;
}
5 User defined functions
1. Documentation Section:
 This section is used to provide a small description of the program.
 The comment lines are simply ignored by the compiler that means they are not executed.
 In C, there are two types of comments.

1. Single Line Comments: Single line comment begins with // symbol. We can write any
number of single line comments.

2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends with */.

Prepared By: M. Parthasaradhi, Asst. Prof.


We can write any number of multiple lines comments in a program.
 All the comment lines in a C program just provide the guidelines to understand the program and its
code.
2. Pre-processing Commands:
 Pre-processing commands are used to include header files and to define constants.
 Pre-processing commands are beginning with #symbol.
 C Pre-processing commands are: #include, #define, #if, #else etc…,
 #include is used to include header files.
 #define is used to create constants.
1.5

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

3. Global Declarations:
 The global declaration is used to define the global variables, which are common for all the
functions after its declaration.
 We also use the global declaration to declare functions.
4. Main Function:
 Every C program must contain this main function.
 Here, main ( ) is a user-defined function which tells the compiler that this is the starting point of the
program execution.
 The open brace ({ ) indicates the beginning of the main function.
 Local declaration contains local variables which are used within main ( ) function.
 Executable statements perform tasks like reading data, displaying the result, calculations, etc.,
 Closing Brace ( }) indicates the end of the main ( ) function.
 The statement return 0 returns a value zero to the Operating System after completing the main ( )
execution.
 If we don't want to return any value, we can use it as void.
5. User Defined Functions:
 This is the place where we implement the user-defined functions.

Q1.20. Write short note on C Character set.


Answer:
 A program is a set of statements.
 These statements are constructed using words
 And these words are constructed using characters from C character set.
 C language supports 256characters.
 C character set contains the following set of characters...

Prepared By: M. Parthasaradhi, Asst. Prof.


1. Letters
2. Digits
3. Special Symbols
1. Letters:
o C language supports all the alphabets from the English language.
o Lower and upper case letters together support 52 alphabets.
 lower case letters - a to z
 UPPER CASE LETTERS - A to Z

1.6

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

2. Digits:
o Clanguagesupports10digitswhichareusedtoconstructnumericalvalues.
o Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
3. Special Symbols:
o C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
 Example: +, -, *, /, @, #, $, %, etc…,

2. C language elements

Q2.1. Define a C-token. Explain different types of C-tokens?


Answer:
 Every smallest unit of a c program is called token.
 Every instruction in a c program is a collection of tokens.
 Tokens are used to construct c programs and they are said to the basic building blocks of a C program.
 There are 5 types of C-tokens. They are:
1. Keywords

2. Identifiers

3. Special Symbols

4. Constants

5. Strings

6. Operators

Prepared By: M. Parthasaradhi, Asst. Prof.


1. Keywords:
 Keywords are the reserved words with predefined meaning which already known to the
compiler.
 In the C programming language, there are 32keywords.

1.7

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

C- Keywords
User
Condition Looping Storage
Data Types Defined Others
Statements Statements Classes
Data Types
1 int 10 struct 14 if 18 do 23 auto 27 const
2 char 11 union 15 else 19 while 24 static 28 default
3 double 12 enum 16 switch 20 for 25 register 29 goto
4 float 13 typedef 17 case 21 break 26 extern 30 return
5 long 22 continue 31 sizeof
6 short 32 volatile
7 signed
8 unsigned
9 void

2. Identifiers:
 An identifier is a name used to identify a variable, function, structure, etc.
 In C length of identifier is 31characters.

Rules to define Identifiers:


1. Identifiers can be a combination of letters (a to z/ A to Z) or digits (0 to 9) or an underscore ( _ ).
Example: myClass, var_1, print_this_to_screen, _number are valid identifiers.
2. An identifier can start with a letter or an underscore ( _ ), but not with a digit.
Example: 1_variable is invalid
Variable_1 is Valid

Prepared By: M. Parthasaradhi, Asst. Prof.


3. Keywords cannot be used as identifiers.
Example: if is invalid identifier
4. Special symbols like !, @, #, $, % etc. are not allowed in identifiers except one special symbol
underscore ( _).
Example: company#name, $name, email@id are invalid identifiers

1.8

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

3. Special Symbols:
 Some special characters are used in C, and they have a special meaning which cannot be used
for another purpose.
1. Square brackets [ ]: Used in Arrays

2. Simple brackets ( ): Used in Functions

3. Curly braces { }: Used in the opening and closing of the block.

4. Comma (,): It is a separator.

5. Hash/pre-processor (#): It is used for pre-processor directive.

6. Asterisk (*): This symbol is used to represent pointers

7. Period (.): It is used to access a member of a structure or a union.

4. Constants:
 A constant is a value assigned to the variable which will cannot be changed.
 There are two ways of declaring constant:
1. Using const keyword

2. Using #define pre-processor

Types of constants in C:
Constant Example
Integer constant 10, 11, 34, etc.
Floating-point constant 45.6, 67.8, 11.2, etc.
Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Prepared By: M. Parthasaradhi, Asst. Prof.


Character constant 'a', 'b', 'c', etc.
String constant "java", "c++", ".net", etc.
5. Strings:
 Strings in C are always represented as an array of characters having null character '\0' at the
end of the string.
 This null character denotes the end of the string.
 Strings in C are enclosed within double quotes, while characters are enclosed within single
characters.
 The size of a string is a number of characters that the string contains. 1.9

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

6. Operators:
 Operator is a special symbol used to perform the operation.
 The data items on which the operators are applied are known as operands.
 Operators are applied between the operands.
 Depending on the number of operands, operators are classified as follows:

1. Unary Operator:
o A unary operator is an operator applied to the single operand.
o Example: Unary Minus (-), not (!), increment operator (++), decrement operator (--),
sizeof etc…,

2. Binary Operator:
o The binary operator is an operator applied between two operands.
o Example: Addition (+), Subtraction (-), Multiplication (*), etc...,

3. Ternary Operator:
o The ternary operator is an operator applied between three operands.
o Ternary operator in c is conditional operator ( ?:)

3. Variable declarations and data types


Q3.1. Define Data Type. List different Data Types in C.
Answer:
 Adatatypespecifiesthetypeofdatathatavariablecanstoresuchasinteger, floating, character, etc.
 There are the following data types in C language.

Types Data Types

Prepared By: M. Parthasaradhi, Asst. Prof.


Basic Data Type integer, floating point, double and character

(Primitive Data Type)


Derived Data Type array, pointer, structure, union

(User Defined Data Type)


Enumeration Data Type enum
Void Data Type void

1.10

Department of CSE :: ALTS :: ATP


C-Programming (20A05201T):: Unit-1
Programming & Data Structures (20A05201

Q3.2.. Give brief discussion on primitive data types in C.


Answer:
 The primary data types in the C programming language are the basic data types.
 Primary data types are also called as Built
Built-In data types.
 The following are the primary data types in c programming language.

1. Integer:
 The integer data type is a set of whole numbers.
 Every integer value does not have the decimal value.
 We use
se the keyword "int" to represent integer data type in C.
 The following table provides complete details about the integer data type according to the 32-
32
bit architecture.
Range

(For Signed: -2N-1


N to 2N-1
Type Size
– 1, For Unsigned: 0 to 2N
-1, Here N is number of
bits)
int 2 bytes -32,768
32,768 to 32,767

Prepared By: M. Parthasaradhi, Asst. Prof.


unsigned int 2 bytes 0 to 65,535
short 2 bytes -32,768
32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -232-1 to 232-1 -1
unsigned long 4 bytes 0 to 232 -1

1.11

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

2. Floating Point:
 Floating-point data types are a set of numbers with the decimal value.
 We use the keyword "float" to represent floating-point data type and "double" to represent
double data type in C.
 The following table provides complete details about floating-point data types.
Range
Type Size Precision
(-2N-1 to 2N-1 – 1,

Here N is number of
bits)
float 4 byte -232-1 to 232-1 -1 6 decimal places

double 8 byte -264-1 to 264-1 -1 15 decimal places

long double 10 byte -280-1 to 280-1 -1 19 decimal places

3. Character:

 The character data type is a set of characters enclosed in single quotations.

 The following table provides complete details about the character data type.

Range

(For Signed: -2N-1 to 2N-1


Type Size
– 1, For Unsigned: 0 to 2N
-1, Here N is number of
bits)

Prepared By: M. Parthasaradhi, Asst. Prof.


char 1 byte -128 to 127

(signed char)
unsigned char 1 byte 0 to 255

Q3.3. Write short note on format specifiers in C.


Answer:
 The format specifiers are used in C for input and output purposes.
 Using this concept the compiler can understand that what type of data will be taking input using the
scanf() function and printing using printf() function.
1.12

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

 Here is a list of format specifiers.


Format Specifier Type
%c Character
%d Signed Integer
%e or %E Scientific notation of floats
%f Float values
%g or %G Similar as %e or %E
%hi Signed integer(short)
%hu Unsigned Integer(short)
%i Unsigned Integer
%l or %ld or %li Long
%lf Double
%Lf Long Double
%lu Unsigned int or unsigned long
%lli or %lld Long Long
%llu Unsigned long long
%o Octal representation
%p Pointer
%s String
%u Unsigned int
%x or %X Hexadecimal representation
%n Prints nothing
%% Prints % character

Q3.4. Define variable. Explain how to declare and initialize a variable in C.

Prepared By: M. Parthasaradhi, Asst. Prof.


Answer:
Variable:

A variable is a name of the memory location which can store a value.

Declaration:

Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified data type values into that memory location.
We can declare a variable using below syntax.

1.13

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Syntax:

Datatype Variable_name;

Example:
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the name number and
allows only integer values into that memory location.
Initialization:
Initialization of a variable means assigning a value to the variable. We can initialize a variable with a
value using below syntax.
Syntax:

Variable_name = Value

Example:

int number;
number = 10;
In the above example, value 10 is assigned to the variable number.

Q3.5. What are the rules to define a variable.


Answer:
Rules to define Identifiers:

1. Variables can be a combination of letters (a to z/ A to Z) or digits (0 to 9) or an underscore ( _).


Example: myClass, var_1, print_this_to_screen, _number are valid variables.

2. A variable can start with a letter or an underscore ( _ ), but not with a digit.

Prepared By: M. Parthasaradhi, Asst. Prof.


Example: 1_variable is invalid

Variable_1 is Valid

3. Keywords cannot be used as variables.


Example: if is invalid variable

4. Special symbols like !, @, #, $, % etc. are not allowed in variables except one special symbol
underscore ( _ ).
Example: company#name, $name, email@id are invalid variables

1.14

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q3.6. What is the use of void data type.


Answer:
Void data type:

 The void data type means nothing or no value.


 Generally, the void is used to specify a function which does not return any value.
 We also use the void data type to specify empty parameters of a function.

4. Operators and expressions


Q4.1. Define Operator. Explain different operators in C.
Answer:
Operator:

Operator is symbol is used perform operation in between operands.


Different types of Operators:

C operators are classified as:

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operator

5. Increment & Decrement Operators

6. Conditional Operator

Prepared By: M. Parthasaradhi, Asst. Prof.


7. Bitwise Operators

8. Special Operators

1.15

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

1. Arithmetic Operators:

 The arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, division and percentage modulo.
 The following table provides information about arithmetic operators:
Operator Name Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Modulo Division 5%2 1
(Gives the Remainder for
integer division)

2. Relational Operators:
 The relational operators are used to check the relationship between two values.
 Every relational operator has two results TRUE or FALSE.
 In simple words, the relational operators are used to define conditions in a program.
 The following table provides information about relational operators.
Operator Name Example Result

< Less than 10 < 5 False

> Greater than 10 > 5 True

<= Less than or equal to 10 <= 5 False

Prepared By: M. Parthasaradhi, Asst. Prof.


>= Greater than equal to 10 >= 5 True

== Equal to 10 == 5 False

!= Not Equal to 10 != 5 True

1.16

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

3. Logical Operators:

 The logical operators are used to check logical relationship between two conditions.
 The following table provides information about logical operators.
Operator Name Meaning Example Result

Returns True, if both conditions are


&& Logical AND True. Otherwise False 10 < 5 && 12 > 10 False

Return False, If both conditions are


|| Logical OR False Otherwise True 10 < 5 || 12 > 10 True

Return False, if condition is True


!(10 < 5 && 12 >
! Logical NOT and vice versa True
10)

4. Assignment Operator:

 Assignment operator is used to assigning values to the variables.


Example:
a= 5
Shorthand Assignment Operators:

 The following table illustrates different types of shorthand operators.

Example Equivalent Resultant


Operator (A = 10) equation value of A

+= A += 5 A=A+5 15

Prepared By: M. Parthasaradhi, Asst. Prof.


-= A -= 5 A=A-5 5

*= A *= 5 A=A*5 50

/= A /= 5 A=A/5 2

%= A %= 5 A=A%5 0

1.17

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

5. Increment & Decrement Operators:


 Increment operator is used to increase the value of variable by one.
 Decrement operator is used to decrease the value of variable byo ne.
 We can use these operators before or after variable name.
 The below table illustrates the different increment and decrement operators.
Resultant
Example
Operator Meaning value of
A=5
A
A++ Post Increment A++ 6

++A Pre Increment ++A 6

A-- Post Decrement A-- 4

--A Pre Decrement --A 4

6. Conditional Operator:
 The conditional operator is also called a ternary operator because it requires three operands.
 This operator is used for decision making.
Syntax:

Condition ? TRUE Part : FALSE Part;

If the condition is TRUE the TRUE Part is performed, if the condition is FALSE the FALSE Part
is performed.

Prepared By: M. Parthasaradhi, Asst. Prof.


Example:

A = (10<15) ? 100 : 200;

⇒ A value is 100

7. Bitwise Operators
 The bitwise operators are used to perform bit-level operations in the C.
 When we use the bitwise operators, the operations are performed based on the binary values.
 The following table describes all the bitwise operators in the C.

1.18

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example (A = 25,
Operator Name Meaning B = 20 ) Result

Bitwise Return 1 if both the bits


& AND are 1 otherwise it is 0 A&B 16

Return 0 if both bits are 0


Bitwise
| otherwise it is 1 A|B 29
OR

Bitwise Return 0 if all the bits are


^ XOR same otherwise it is 1 A^B 13

Bitwise Returns Once Complement


~ NOT of a number. ~A -26
~A = -(A+1)
Shifts all the bits to the left
by the specified number of
<< Left shift A << 2 100
positions
A << n = A * 2n
Shifts all the bits to the
>> Right shift right by the specified A >> 2 6
number of positions
A >> n = A / 2n

Prepared By: M. Parthasaradhi, Asst. Prof.


8. Special Operators
 The following are the special operators in C.

1. sizeof operator:
 This operator is used to find the size of the memory (in bytes) allocated for a variable.
Syntax:
sizeof(variableName)

1.19

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example:

int a;

sizeof(a); ⇒ the result is 2

2. Pointer operator(*):
 This operator is used to define pointer variables.

3. Comma operator(,):
 This operator is used to separate variables while they are declaring, separate the
expressions in function calls, etc.

4. Dot operator (.) and Member operator(->):


 This operator is used to access members of structure or union.

Q4.2. What is an expression? Explain different types of Expressions?


Answer:
Expression:

An expression is a collection of operators and operands that represents a specific value.


Example:

C=A+B
Expression Types:

There are 3 types of expressions.

1. Infix Expression

2. Postfix Expression

Prepared By: M. Parthasaradhi, Asst. Prof.


3. Prefix Expression

1. Infix Expression:

In Infix expression the operator is used between operands.


Example:
A+B
2. Postfix Expression:

In Postfix expression the operator is used after operands.


Example:
AB+ 1.20

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

3. Pre fix Expression:

In Infix expression the operator is used before operands.


Example:
+AB

Q4.3. What is Operator Precedence?


Answer:

Operator precedence is used to determine the order of operators evaluated in an expression. In c


programming language every operator has precedence (priority).

When there is more than one operator in an expression the operator with higher precedence is evaluated
first and the operator with the least precedence is evaluated last.

Q4.4. What is Operator Associativity?


Answer:

Operator associativity is used to determine the order of operators with equal precedence evaluated in an
expression.

When an expression contains multiple operators with equal precedence, we use associativity to determine
the order of evaluation of those operators.

Prepared By: M. Parthasaradhi, Asst. Prof.

1.21

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q4.5. Draw the table of operator precedence and associativity.


Answer:
Precedence Operator Operator Meaning Associativity

()
function call
[] array reference
-> structure member access
1 Left to Right
structure member access
.

!
~
negation
+ Bitwise Not
- Unary plus
Unary minus
++ increment operator
-- decrement operator
address of operator
& pointer
2 * returns size of a variable Right to Left
type conversion
sizeof
(type)

*
multiplication
/ division
3 remainder Left to Right
%

Prepared By: M. Parthasaradhi, Asst. Prof.


addition
4 - subtraction Left to Right

<< left shift


5 >> right shift Left to Right

< less than


<= less than or equal to
6 > greater than Left to Right

>= greater than or equal to

1.22

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

==
equal to not equalto
7 != Left to Right

8 & bitwise AND Left to Right

9 ^ bitwise EXCLUSIVE OR Left to Right

10 | bitwise OR Left to Right

11 && logical AND Left to Right

12 || logical OR Left to Right

13 ?: conditional operator Left to Right


= Assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign addition
14 -= assign subtraction Right to Left
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift

15 , separator Left to Right

Q4.6. How the expression is evaluated.

Prepared By: M. Parthasaradhi, Asst. Prof.


Answer:

An expression is evaluated based on the precedence and associativity of the operators in that expression.

Example:

10 + 4 * 3 / 2

In the above expression, there are three operators +, * and /. Among these three operators, both
multiplication and division have the same higher precedence and addition has lower precedence. So,
according to the operator precedence both multiplication and division are evaluated first and then the addition
is evaluated.
1.23

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

As multiplication and division have the same precedence they are evaluated based on the associativity.
Here, the associativity of multiplication and division is left to right. So, multiplication is performed first, then
division and finally addition. So, the above expression is evaluated in the order of * / and +. It is evaluated as
follows...

4 * 3 ====> 12

12 / 2 ===> 6

10 + 6 ===> 16

The expression is evaluated to 16.

Q4.7. Write short note Type Casting and Conversion in C.


Answer:

In a c programming language, the data conversion is performed in two different methods as follows...

1. Type Conversion

2. Type Casting
1. Type Conversion:

The type conversion is the process of converting a data value from one data type to another
data type automatically by the compiler.

Sometimes type conversion is also called implicit type conversion. The implicit type
conversion is automatically performed by the compiler.
Example:
int i = 10 ;
float x = 15.5 ;

Prepared By: M. Parthasaradhi, Asst. Prof.


char ch = 'A' ;
i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i
x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; =======> Here the ASCII value of A (65) is assigned to i

2. Type Casting:

Typecasting is also called an explicit type conversion. Compiler converts data from one data
type to another data type implicitly. When compiler converts implicitly, there may be a data loss.

1.24

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

In such a case, we convert the data from one data type to another data type using explicit type
conversion. To perform this, we use the unary cast operator.

To convert data from one type to another type we specify the target data type in parenthesis as a
prefix to the data value that has to be converted.

The general syntax of typecasting is as follows.


(TargetDatatype) DataValue

Example:
int totalMarks = 450, maxMarks = 600 ;
float average ;
average = (float) totalMarks / maxMarks * 100 ;

In the above example code, both totalMarks and maxMarks are integer data values. When we
perform totalMarks / maxMarks the result is a float value, but the destination (average) datatype is a
float. So we use type casting to convert totalMarks and maxMarks into float data type.

5. Decision statements - If and switch statements


Q5.1. Define a statement. What are the different types of statements?
Answer:

A Statement is an instruction in a program that can form using C-Tokens. There are 3 types of statements.

1. Sequential Statements

2. Conditional Statements (Decision Statements)

3. Looping Statements.

Prepared By: M. Parthasaradhi, Asst. Prof.


 In Sequential, each and every statement is executed one by one without skipping.

 In Conditional, particular block of statements is executed based on condition. Conditional


statements in C are: if and switch

 In Looping, a block of statements is executed up to number of times based on condition. Looping


statements in C are: do-while, while and for.

1.25

Department of CSE :: ALTS :: ATP


C-Programming (20A05201T):: Unit-1
Programming & Data Structures (20A05201

Q5.2.
.2. Define null statement. What is the importance of it?
Answer:

Null statement means it executes nothing in the program that means it performs no operation.
Example:
;  it is a null statement
Importance:
It is useful when the syntax of the language calls for a statement but no expression evaluation.

Q5.3. Explain in detail about if statement with example.


Answer:

There are 3 types of if statement. They are:

1. Simple if

2. if-else statement

3. if-else-if
if statement (else
(else-if ladder)

1. Simple if:

In simple if, if the condition is true, then True block statemen


statements
ts are executed. Simple if does not
concentrate on the False condition.

Prepared By: M. Parthasaradhi, Asst. Prof.

1.26

Department of CSE :: ALTS :: ATP


C-Programming (20A05201T):: Unit-1
Programming & Data Structures (20A05201

Example Program | Test whether given number is divisible by 5.


#include<stdio.h>
int main()
{
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
{
printf("Given number is divisible by 5") ;
}
return 0;
}
Output:
Enter any integer number: 50
Given number is divisible by 5

2. if-else statement:

In if-else-if
if statement, if the condition is true then True block statements are executed otherwise False
block statements are executed.

Prepared By: M. Parthasaradhi, Asst. Prof.

1.27

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example Program | Test whether given number is even or odd.


#include<stdio.h>
int main()
{
int n ;
printf("Enter any integer number: ") ; scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ; return 0;
}
Output:
Enter any integer number: 65
Given number is ODD

3. if-else-if statement (else-if ladder):

It is used in the scenario where there are multiple cases to be performed for different conditions.

In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be
executed, otherwise if some other condition is true then the statements defined in the else-if block will be
executed, at the last if none of the condition is true then the statements defined in the else block will be
executed.

Syntax:

Prepared By: M. Parthasaradhi, Asst. Prof.

1.28

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Flowchart:

Example Program | Find the largest of three numbers using else-if ladder.
#include<stdio.h>
int main()
{
int a, b, c ;

Prepared By: M. Parthasaradhi, Asst. Prof.


printf("Enter any three integer numbers: ");
scanf("%d%d%d", &a, &b, &c);
if( a>=b && a>=c)
printf("%d is the largest number", a);
else if (b>=a && b>=c)
printf("%d is the largest number", b);
else
printf("%d is the largest number", c);
return 0;
} 1.29

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Output:
Enter any three integer numbers: 35
65

41

65 is the largest number

Q5.4. Write short note on nested-if statement.


Answer:

Writing one if statement inside another if statement is called nested if statement.

Example Program | Write a program to find a largest number among 3 numbers using
nested if.

#include<stdio.h>

int main()

Prepared By: M. Parthasaradhi, Asst. Prof.


int a, b, c ;

printf("Enter 3 numbers: ") ;

scanf("%d%d%d", &a, &b, &c) ;

if (a > b)

if(a > c)

printf("%d is big", a) ;
1.30

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

else

printf("%d is big", c) ;

else

if(b > c)

printf("%d is big", b) ;

else

printf("%d is big", c) ;

return 0;

}
Output:
Enter 3 numbers:

25 20 14

25 is big

Q5.5. Explain in detail about switch statement.


Answer:

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple

Prepared By: M. Parthasaradhi, Asst. Prof.


operations for the different possible values of a single variable called switch variable.

Here, we can define various statements in the multiple cases for the different values of a single variable.

The syntax of switch statement is given below

Syntax:

1.31

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Flowchart:

Prepared By: M. Parthasaradhi, Asst. Prof.

1.32

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example Program | Display pressed digit in words.


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

printf("Enter any digit: ") ;

scanf("%d", &n) ;

switch( n )

case 0:

printf("ZERO") ;

break;

case1:

printf("ONE") ;

break;

case 2:

printf("TWO") ;

break;

case 3:

printf("THREE") ;

Prepared By: M. Parthasaradhi, Asst. Prof.


break;

case 4:

printf("FOUR") ;

break;

case 5:

printf("FIVE") ;

break;
1.33

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

case 6:

printf("SIX") ;

break;

case 7:

printf("SEVEN") ;

break ;

case 8:

printf("EIGHT") ;

break ;

case 9:

printf("NINE") ;

break ;

default:

printf("Not a Digit") ;

return 0;

Output:

Enter any digit: 5

Prepared By: M. Parthasaradhi, Asst. Prof.


FIVE

1.34

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q5.5. Distinguish between if-else-if statement and switch statement.

Answer:
if-else switch
Definition Depending on the condition in the 'if' The user will decide which statement is to
statement, 'if' and 'else' blocks are be executed.
executed.
Expression It contains either logical or equality It contains a single expression which can be
expression. either a character or integer variable.
Evaluation It evaluates all types of data, such as It evaluates either an integer, or character.
integer, floating-point, character or
Boolean.
Sequence of First, the condition is checked. If the It executes one case after another till the
execution condition is true then 'if' block is executed break keyword is not found, or the default
otherwise 'else' block statement is executed.
Default If the condition is not true, then by default, If the value does not match with any case,
execution else block will be executed. then by default, default statement is
executed.
Editing Editing is not easy in the 'if-else' statement. Cases in a switch statement are easy to
maintain and modify. Therefore, we can say
that the removal or editing of any case will
not interrupt the execution of other cases.
Speed If there are multiple choices implemented If we have multiple choices then the switch
through 'if-else', then the speed of the statement is the best option as the speed of
execution will be slow. the execution will be much higher than 'if-
else'.

Prepared By: M. Parthasaradhi, Asst. Prof.

1.35

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

6. Loop control statements - while, for, do-while statements:


Q6.1. Explain in detail about looping statements.
Answer:

The looping statements are used to execute a single statement or block of statements repeatedly until the
given condition is FALSE.

C has 3 looping statements:

1. do-while

2. while

3. for

1. do-while statement:

 The do-while statement is used to execute a single statement or block of


statements repeatedly until given condition is False.
 The do-while statement is also known as the Exit control looping statement.

 In do-while, the block of statements is executed at least once.

Prepared By: M. Parthasaradhi, Asst. Prof.

1.36

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example Program | Program to display even numbers upto 10 using do-while.

#include<stdio.h>

int main()

int n = 0;

printf("Even numbers upto 10\n");

do

if( n%2 == 0)

printf("%d\t", n) ;

n++ ;

}while( n <= 10 ) ;

Output:

Even numbers upto 10

0 2 4 6 8 10

2. while statement:

Prepared By: M. Parthasaradhi, Asst. Prof.


 The while statement is used to execute a single statement or block of statements
repeatedly until given condition is False.
 The while statement is also known as the Entry control looping statement.

1.37

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example Program | Program to display even numbers upto 10 using while.

#include<stdio.h>

int main()

int n = 0;

printf("Even numbers upto 10\n");

while( n <= 10 )

if( n%2 == 0)

printf("%d\t", n) ;

n++ ; Prepared By: M. Parthasaradhi, Asst. Prof.

Output:

Even numbers upto 10

0 2 4 6 8 10
1.38

Department of CSE :: ALTS :: ATP


C-Programming (20A05201T):: Unit-1
Programming & Data Structures (20A05201

3. for statement:
 The for statement is used to execute a single statement or block of statements repeatedly
until given condition is False.

Prepared By: M. Parthasaradhi, Asst. Prof.

1.39

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example Program | Program to display even numbers upto 10 using for.

#include<stdio.h>

int main()

int n ;

printf("Even numbers upto 10\n");

for( n = 0 ; n <= 10 ; n++ )

if( n%2 == 0)

printf("%d\t", n) ;

return 0;

Output:

Even numbers upto 10

0 2 4 6 8 10

Q6.2. Write the difference between do-while and while.


Answer:

Prepared By: M. Parthasaradhi, Asst. Prof.


S.NO while do-while

Condition is checked first then statement(s) Statement(s) is executed atleast once,


1
is executed. thereafter condition is checked.

It might occur statement(s) is executed zero At least once the statement(s) is


2
times, If condition is false. executed.

No semicolon at the end of while. Semicolon at the end of while.


3
while(condition) while(condition);

1.40

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

If there is a single statement, brackets are not


4
required. Brackets are always required.

Variable in condition is initialized before the variable may be initialized before or


5
execution of loop. within the loop.

6 while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) { do {

7 statement(s);
statement(s);
}while(condition);
}

Q6.3. Write short note on break statement.


Answer:

 In C, the break statement is used to perform the following two things:

1. break statement is used to terminate the switch case statement

2. break statement is also used to terminate looping statements like while, do- while and for.

 The break statement execution is as shown in the following figure.

Prepared By: M. Parthasaradhi, Asst. Prof.

1.41

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example Program | Program break statement.

#include<stdio.h>

int main()

int i;

for( i = 0; i <= 10; i++)

if( i == 5)

break;

printf("%d\t",i);

return 0;

Output:

0 1 2 3 4

Q6.4. Write short note on continue statement.


Answer:

 The continue statement is used to move the program execution control to the beginning of the looping
statement.

Prepared By: M. Parthasaradhi, Asst. Prof.


 The continue statement can be used with looping statements like while, do-while and for.

 When we use continue statement with while and do-while statements the execution control directly
jumps to the condition.

 When we use continue statement with for statement the execution control directly jumps to the
modification portion (increment/decrement/any modification) of the for loop.

 The continue statement execution is as shown in the following figure.

1.42

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Example Program | Program on continue statement


#include<stdio.h>
int main()
{
int i;
for( i = 0; i <= 10; i++)
{
if( i == 5)
continue;
printf("%d\t",i);
}
return 0;

Prepared By: M. Parthasaradhi, Asst. Prof.


}
Output:
0 1 2 3 4 6 7 8 9 10

1.43

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q6.5. Write the difference between break and continue.


Answer:
Break Continue
Break is used to terminate the execution of Continue is not used to terminate the
the loop. execution of loop.
It breaks the iteration. It skips the iteration.
When this statement is executed, control When this statement is executed, it will not
will come out from the loop and executes come out of the loop but jumps to the next
the statement immediate after the loop. iteration.
Break is used with loops and switch case. Continue is only used in loops, it is not
used in switch case.

7. Arrays

Q7.1. Define an Array. Explain how to declare and initialize an array.


Answer:
Array:

 An array is a variable which can store more than one value of same datatype.

 The elements of array stored in continue memory locations.


Declaration of Array:

 When we want to create an array we must know the data type of values to be stored in that array and
also the number of values to be stored in that array.

 We use the following general syntax to create an array...

Prepared By: M. Parthasaradhi, Asst. Prof.


datatype arrayName [ size ] ;

 In the above syntax, the datatype specifies the type of values we store in that array and size specifies
the maximum number of values that can be stored in that array.
Example
int a [3] ;

 Here, the compiler allocates 6 bytes of memory locations with a single name 'a' and tells the compiler
to store three different integer values (each in 2 bytes of memory).

1.44

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

 For the above declaration, the memory is organized as follows...

Initialization of Array:

 Syntax for creating an array with size and initial values.

datatype arrayName [ size ] = {value1, value2, ...} ;

Example

int a[5] = {1, 2, 3, 4, 5};

Here, an array ‘a’ stores 5 values.

 Syntax for creating an array without size and with initial values:

datatype arrayName [ ] = {value1, value2, ...} ;

Example

int a[ ] = {1, 2, 3, 4, 5};

Here, an array ‘a’ stores 5 values.

Q7.2. Explain how to access elements of an array?


Answer:

 An element is accessed by indexing the array name. This is done by placing the indexof the element

Prepared By: M. Parthasaradhi, Asst. Prof.


ithin square brackets after the name of thearray.

 Syntax:

arrayName [ indexValue ] ;

Example:

int a[5] = {1, 2, 3}

For the above example the individual elements can be denoted as follows:

1.45

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

1. We can access the elements asf ollows:

printf(“%d”, a[2]);

Output of the above statement is: 3

2. We can change the individual elements of array as follows:

a[1] = 100;

3. Then array elements are:

Q7.3. Explain the different types of arrays.


Answer:

 Arrays are classified into two types. They are asfollows...

Prepared By: M. Parthasaradhi, Asst. Prof.


o Single Dimensional Array / One Dimensional Array

o Multi-Dimensional Array

1. Single Dimensional Array (One Dimensional Array):

 An array contains one subscript is known as One or Single Dimensional Array.

 Single dimensional arrays are used to store list of values of same data type.

 Single dimensional arrays are also called as one-dimensional arrays, Linear Arrays or simply
1-DArrays.
1.46

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

 Declaration of Single Dimensional Array:

o We use the following general syntax for declaring a single dimensional array.

datatype arrayName [ size ] ;

o Example

int rollNumbers [60];

The above declaration of single dimensional array reserves 60 continuous


memory locations of 2 bytes each with the name rollNumbers and tells the compiler
to allow only integer values into those memory locations.

 Initialization of Single Dimensional Array:

Case-1:

o We use the following general syntax for declaring and initializing a single dimensional
array with size and initial values.

datatype arrayName [ size ] = {value1, value2, ...} ;

o Example

int marks [6] = { 89, 90, 76, 78, 98, 86 } ;

The above declaration of single dimensional array reserves 6 contiguous


memory locations of 2 bytes each with the name marks and initializes with value 89
in first memory location, 90 in second memory location, 76 in third memory
location, 78 in fourth memory location, 98 in fifth memory location and 86 in sixth

Prepared By: M. Parthasaradhi, Asst. Prof.


memory location.

Case-2:

o We can also use the following general syntax to initialize a single dimensional array
without specifying size and with initial values.

datatype arrayName [ ] = {value1, value2, ...} ;

o The array must be initialized if it is created without specifying any size. In this case, the
size of the array is decided based on the number of values initialized.
1.47

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

o Example:

int marks [ ] = { 89, 90, 76, 78, 98, 86 } ;

In the above example declaration, size of the array 'marks' is 6.

 Accessing Elements of Single Dimensional Array

o To access the elements of single dimensional array we use array name followed by index
value of the element that to be accessed.

o The index value of single dimensional array starts with zero (0) for first element and
incremented by one for each element.

o The index value in an array is also called as subscript or indices.

o We use the following general syntax to access individual elements of single


dimensional array.

arrayName [ indexValue ]

o Example

marks [2] = 99 ;

In the above statement, the third element of 'marks' array is assinged with
value '99'.

2. Multi-Dimensional Array:

 If an array contains more than one subscript is known as multi-dimensional array.

 Multi-dimensional array can be of two dimensional array or three dimensional array or four
dimensional array or more.

Prepared By: M. Parthasaradhi, Asst. Prof.


 Most popular and commonly used multi-dimensional array is two dimensional arrays.

 The 2-D arrays are used to store data in the form of table.

 We also use 2-D arrays to create mathematical matrices.

 Declaration of Two Dimensional Array:

o We use the following general syntax for declaring a two dimensional array:

datatype arrayName [ rowSize ] [ columnSize ] ;

1.48

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

o Example

int matrix_A [2][3] ;

The above declaration of two dimensional array reserves 6 continuous


memory locations of 2 bytes each in the form of 2 rows and 3 columns.

 Initialization of Two Dimensional Array:

o We use the following general syntax for declaring and initializing a two dimensional
array with specific number of rows and columns with initial values.

datatype arrayName [rows][columns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;

o Example
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;

The above declaration of two-dimensional array reserves 6 contiguous


memory locations of 2 bytes each in the form of 2 rows and 3 columns. And the
first row is initialized with values 1, 2 & 3 and second row is initialized with values
4, 5 & 6.

o We can also initialize as follows:


int matrix_A [2][3] ={

{1, 2, 3},

{4, 5, 6}
};

 Accessing Individual Elements of Two Dimensional Array:

Prepared By: M. Parthasaradhi, Asst. Prof.


o To access elements of a two-dimensional array we use array name followed by row
index value and column index value of the element that to be accessed.

o Here the row and column index values must be enclosed in separate square braces.

o We use the following general syntax to access the individual elements of a two-
dimensional array...

arrayName [ rowIndex ] [ columnIndex ]

1.49

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

o Example
matrix_A [0][1] = 10 ;

In the above statement, the element with row index 0 and column index 1 of
matrix_A array is assigned with value 10.

Q7.4. Explain how memory is allocated for 1-D arrays, and how can we address of ith element.
Answer:

 Whenever an array is declared in the program, contiguous memory to it elements are allocated.

 Initial address or base address of the array – address of the first element of the array is called base
address of the array.

 Each element will occupy the memory space required to accommodate the values for its type, i.e.;
depending on elements data type, 1, 2 or 4 bytes of memory is allocated for each elements.

 Below diagram shows how memory is allocated to an integer array of N elements. Its base address –
address of its first element is10000.

 Since it is an integer array, each of its element will occupy 2 bytes of space. Hence first element
occupies memory from 10000 to 10001. Second element of the array occupies immediate next
memory address in the memory, i.e.; 10002 to10003.

Prepared By: M. Parthasaradhi, Asst. Prof.


 In this way all the N elements of the array occupies the memory space.

 We can calculate ith element address as follows:

Address of Arr[ i ] = Base_Address + i * datatype_size

 Example:

o If an array ‘P’ is created with 50 elements of integer type. The base address is 5050, then
calculate 28th element address.

1.50

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Address of P[28] = base_address + 28 * datatype_size


Address of P[28] = 5050 + 28 * 2
Address of P[28] = 5106

Q7.5. Explain about memory allocation of 2D-Arrays.


Answer:

 Whenever an array is declared in the program, contiguous memory to it elements are allocated, but the
elements assigned to the memory location depend on the two different methods

1. Row Major Order

2. Column Major Order

1. Row Major Order:

o In 2D array, its elements are considered as rows and columns of a table.

o When we store the array elements in row major order, first we will store the elements of first
row followed by second row and so on as shown in below figure.

o Hence in the memory we can find the elements of first row followed by second row and soon.

o Example:

Int intArr[3][3] = {{10,20,30,}, {40,50,60},{70,80,90}

Prepared By: M. Parthasaradhi, Asst. Prof.


Matrix representation is:

10 20 30
40 50 60
70 80 90
Row major order allocation as follows:

1.51

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

o We can find an element address of an array of size M*N as follows:

Address of a[i][j] = Base_address + datatype_ size * (total_coloumns * i +j)

o Example:

Address of intarr[1][2] = 10000 + 2 * (3 * 1 +2)

Address of intarr[1][2] = 10000 + 2 * (3 + 2)

Address of intarr[1][2] = 10000 + 2 * 5


Address of intarr[1][2] = 10000 + 10
Address of intarr[1][2] = 10010

2. Column Major Order:

o In this method all the first column elements are stored first, followed by second column

Prepared By: M. Parthasaradhi, Asst. Prof.


elements and so on as shown in below figure.

1.52

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

o Example:

int intArr[3][3] = {{10,20,30,}, {40,50,60},{70,80,90}

Matrix representation is:

10 40 70
20 50 80
30 60 90

Column major order allocation as follows:

o We can find an element address of an array of size M*N as follows:

Address of a[i][j] = Base_address + datatype_ size * ( total_rows * j +i)

o Example:

Address of intarr[1][2] = 10000 + 2 * (3 * 2 + 1)

Prepared By: M. Parthasaradhi, Asst. Prof.


Address of intarr[1][2] = 10000 + 2 * (6 + 1)
Address of intarr[1][2] = 10000 + 2 * 7
Address of intarr[1][2] = 10000 + 14
Address of intarr[1][2] = 10014

1.53

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Q7.6. What are the advantages and disadvantages of arrays.


Answer:
Advantages of Arrays:

1. Arrays represent multiple data items of the same type using a single name.

2. In arrays, the elements can be accessed randomly by using the index number.

3. Arrays allocate memory in contiguous memory locations for all its elements. Hence there is no chance
of extra memory being allocated in case of arrays. This avoids memory overflow or shortage of
memory in arrays.

Disadvantages of Arrays:

1. The number of elements to be stored in an array should be known in advance.

2. An array is a static structure (which means the array is of fixed size). Once declared the size of the
array cannot be modified. The memory which is allocated to it cannot be increased or decreased.

3. Insertion and deletion are quite difficult in an array as the elements are stored in consecutive memory
locations and the shifting operation is costly.

4. Allocating more memory than the requirement leads to wastage of memory space and less allocation
of memory also leads to a problem.

Q7.7. What are the applications of arrays.


Answer:
Applications of Arrays:

1. Array stores data elements of the same data type.

Prepared By: M. Parthasaradhi, Asst. Prof.


2. Maintains multiple variable names using a single name. Arrays help to maintain large data under a
single variable name. This avoids the confusion of using multiple variables.

3. Arrays can be used for sorting data elements.

4. Arrays can be used for performing matrix operations.

5. Arrays can be used for CPU scheduling.

6. Arrays are also used to implement other data structures like Stacks, Queues, Heaps, Hash tables etc.

1.54

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

2 Marks Questions
1. Introduction to C Language
1. Define computer hardware.
2. Why is C called the mother of all languages?
3. What is the use of the pre-processor directives?
(OR)
Discuss pre-processor directives in C.
(OR)
4. What is a pre-processor?
5. Define header file.
Answer:

The header files contain declarations relating to standard library functions and macros that are
available with C.
2. C language elements
6. What is a token? List out the C- Tokens
7. What is a keyword?
8. What is an identifier? What are the rules to define an identifier?
9. What is a constant?
3. Variable declarations and data types
10. What will be the output of the following program?
(a) #include <stdio.h>
int main()
{
int a=010;
printf("\n a=%d",a);
return0;

Prepared By: M. Parthasaradhi, Asst. Prof.


}
Output: a = 8
(b) #include<stdio.h>
int main()
{
int a=010;
printf("\n a=%o",a);
return0;
}
Output: a = 10
1.55

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Explanation:

In (a), the integer constant 010 is taken to be octal as it is preceded by a zero (0). Here the
variable 'a' is printed with %d specifier. The decimal equivalent of the octal value 10, which is
8, will be printed. Whereas in (b) the same variable is printed with %o format specifier, so 10 is
printed on the screen.
(c) #include <stdi.h>
int main()
{
int a=010;
printf("\n a=%x",a);
return 0;
}
Output: a = 8

Explanation: In (c), the octal value 10 is printed with %x format specifi er. That is
hexadecimal equivalent of 10 which is 8 will be printed. Basics of C.
(d) #include<stdio.h>
int main()
{
inta=53;
printf("\n a=%o",a);
return0;
}
Output: a = 65

Explanation: In (d), an integer constant 53 is stored in the variable 'a' but is printed with
%o. The octal equivalent of 53, which is 65, will be printed.
(e) #include<stio.h>

Prepared By: M. Parthasaradhi, Asst. Prof.


int main()
{
inta=53;
printf("\n a=%X",a);
return0;
}
Output: a = 35

Explanation: In (e), an integer constant 53 is stored in the variable 'a' but is printed with
%X. The hexadecimal equivalent of 53, which is 35, will be printed.
1.56

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

11. What are the basic data types supported in C programming language?
12. List the data types and their sizes of C language.
13. What is the size of integer data type?
14. Write a sample C program to demonstrate the control string of scanf() function.
15. What is the main difference between variable and constant? List any two constants used in C.
Answer:

Variables Constants

It is a variable that stores data type value in a It is similar to a variable and cannot be
program. changed during program execution.

It is a variable that can be changed after defining It is a fixed variable that cannot be
the variable in a program changed after defining the variable in a
program.

The value of a variable can change depending on In constants, the value cannot be
the conditions. changed.

Typically, it uses int, float, char, string, double, It can be express in two ways: #define
etc. data types in a program. pre-processor and the const keyword.

Example: int a = 5; Example:


float radius = 5.2; const int Len = 5;
char c = 'A'; #define PI 3.14

4. Operators and expressions


16. Define operator. List out different operators in C.

Prepared By: M. Parthasaradhi, Asst. Prof.


17. Define ternary operator.
18. What are the bitwise operators in C?
19. Predict the result of following code.
Const int i = 5;
i++;
printf(“I value = %d”, i);
Answer:
The above code gives compilation error at i++. Because ‘i’ is a constant and it could not be
modified in the program.
1.57

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

20. Write a sample program for ternary operator.


Answer:
#include<stdio.h>
int main()
{
int a, b, max;
printf("Enter 2 Numbers: ");
scanf("%d%d", &a, &b);
max = a>b?a:b;
printf("Max = %d", max);
return 0;
}
Output:
Enter 2 Numbers: 15 20
Max = 20
21. Find and remove the error in the following C statement.
a >b ? g = a : g = b;
Answer:
In the statement an assignment is wrong. The correct statement is:
g = a >b ? a : b;

22. Evaluate the following expressions:


i. 4-768/(6*2^2).
ii. 8^2*2-100+50/5(25-5)
23. Define precedence and order of evaluation.

Prepared By: M. Parthasaradhi, Asst. Prof.


24. Illustrate in which order any mathematical expression is evaluated.
25. Justify the significance of operator precedence with an example.
26. Evaluate the following expressions:
i. a*(3+b)/2-c++ *b where a=3,b=4 and c=5
ii. !(4+5*0>=6-4)
27. What is the output of the following expression?

10+20+16-3*10/6-4
28. What is the output of the following expression?

8 >> 3
1.58

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

29. What is the output of the following expression?

16<<3
30. Define null statement.
31. Define expression. List out its types.

5. Decision statements - If and switch statements


32. Write syntax of If-else statements.
33. Write the differences between switch and if-else-if statement.
6. Loop control statements - while, for, do-while statements
34. Give an example of iteration statements in C.
35. What is the use of continue key word?
36. Define break and continue statements along with their syntax.
37. Distinguish between continue and break statements.
38. Write differences between while and do-while.
7. Arrays
39. Define an Array.
40. Define one dimensional array with suitable example.
41. How one Dimensional array is initialized?
42. What is the size required to store any array of 25 integers?
43. Illustrate with an example, the declaration and initialization of an array.
44. How to declare and initialize two dimensional array.
45. What are the applications of array?
46. Consider the following declaration of 2D-array in C:
char a[R][C];
Assume that char type require one bytes of memory and that array is stored starting from memory

Prepared By: M. Parthasaradhi, Asst. Prof.


address 2015, find the address of a[i][j]
Answer:
Address of a[i][j] = Base_address + datatype_ size * ( total_rows * j + i)
Address of a[i][j] = 2015 + 1 * (R * j + i)
47. What is the condition to multiply two matrices
Answer:
Number of Columns in First matrix is equal to Number of Rows in Second matrix
48. Write a program in C to find the sum of numbers present in an array.
49. Explain how address of an element in array is calculated.
1.59

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-1

Prepared By: M. Parthasaradhi, Asst. Prof.

1.60

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2

Unit 2
1. Functions
2. Types of functions
3. Argument passing
4. Recursion
5. Pointers & storage allocation
6. Expressions involving pointers
7. Pointers to functions
8. Storage classes – auto, register, static, extern
9. Structures
10. Unions
11. Strings
12. String handling functions
13. Command line arguments

1. Functions
Q1.1. Define a function. How to define and call a function in C.
Answer:
 A function is a block of statements which perform specific task.
 Every function in C has the following:
1. Function Definition
2. Function Call
3. Function Declaration (Function Prototype)
1. Function Definition:
The function definition is also known as the body of the function.
Syntax Prepared By: M. Parthasaradhi, Asst. Prof.

Return_Type function_Name(parameters_List)
{
Actual code...
}
In the above syntax,
Return_Type specifies the value return by a function
function_Name is a user-defined name used to identify the function uniquely
parameters_List is the data values that are sent to the function definition
2.1

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Example:
Void add(int a, int b)
{
printf(“Addition of a and b = %d”, a+b);
}
In this example,
The function name is add, it is taking two integer variables as parameters and it is not
returning any value.
2. Function Call:
The function call tells the compiler when to execute the function definition. When a function call
is executed, the execution control jumps to the function definition where the actual code gets executed
and returns to the same functions call once the execution completes.
The function call is performed inside the main function or any other function or inside the
function itself.
Syntax
Function_Name(parameters);

Example:
add(15, 20)
3. Function Declaration (Function Prototype):
The function declaration tells the compiler about function name, the data type of the return
value and parameters. The function declaration is also called a function prototype.
The function declaration is performed before the main function or inside the main function or
any other function.
Syntax:
Return_Type function_Name(parameters_List);
Example:
void add( int , int );
Prepared By: M. Parthasaradhi, Asst. Prof.

Q1.2. define parameter. What are its types?


Answer:
 Parameters are the data values that are passed from calling function to called function.
 Parameters are also called as arguments.
 In C, there are two types of parameters and they are as follows...
1. Actual Parameters
2. Formal Parameters

2.2

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
 The actual parameters are the parameters that are specified in calling function.
 The formal parameters are the parameters that are declared at called function.
 When a function gets executed, the copy of actual parameter values is copied into formal parameters.
Example:

Q1.3. Write the differences between actual parameters and formal parameters.
Answer:
Actual Parameters Formal Parameters
These are specified in function calling. These are declared in function definition.
It may be variable or constant. It must be variable.
Example: Example:
void main( ) void sum(int x, int y)
{ {
int a=2;
sum(a, 40)
} }
Here a, 40 are actual parameters. Here x and y are formal parameters.

Q1.4. Define local and global variables.


Answer:
Local Variable: Prepared By: M. Parthasaradhi, Asst. Prof.

 Local variable is declared inside a function.


 Local variables are created when the function has started execution and are lost when the function
terminates.
 If a value of local variable is updated, it will effect within that function only.
Global Variable:
 Global variable is declared outside the function.
 Global variable is created as execution starts and is lost when the program ends.
 If a value of global variable updated, it will effect on entire program.
2.3

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Example:
Example Program
#include<stdio.h>
int a = 10; // Global Variable
int main( )
{
int x = 20; // Local Variable
printf("a = %d, x = %d", a, x);
return 0;
}
Output:
a = 10, x = 20

Q1.5. Write short note on return statement.


Answer:
retrun statement will return a value to the calling function and control is transfers from called to
calling function.
Syntax:
return <value>;
Example:
return 10;

Q1.6. What are the advantages of functions?


Answer:
1. Avoids repetition of the code.
2. Increases reusability i.e., existing code can be used rather than trying to develop new code. Also,
the function can be used by many other programs.
3. The length of the source code (ie., the program size) is reduced.
4. Easy to debug.
Prepared By: M. Parthasaradhi, Asst. Prof.

5. Increases readability.
6. Program development time, effort and cost can be reduced.

2.4

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
2. Types of Functions
Q2.1. What are the different types of functions? Explain.
Answer:
Bases on function definition, functions are divided into two types:
1. Pre-Defined Functions
2. User Defined Functions
1. Pre-Defined Functions:
The function whose definition is defined by the developers of language is called as system defined
function.
The pre-defined functions are also called as Library Functions or Standard Functions or system
Functions.
In C, all the system defined functions are defined inside the header files like stdio.h,
conio.h, math.h, string.h, stdlib,hetc.,
For example, the functions printf( ) and scanf( ) are defined in the header file called stdio.h.

2. User Defined Functions:


The function whose definition is defined by the user is called as user defined function.
Example Program
#include<stdio.h>
int addition(int, int) ; // function declaration
int main( )
{
int num1, num2, result ;
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("SUM = %d", result);
return 0;
}
Prepared By: M. Parthasaradhi, Asst. Prof.

int addition(int a, int b) // function definition


{
return a+b ;
}
Output:
Enter any two integer numbers : 23 54
SUM = 77
In the above example addition ( ) is user defined function.
2.5

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Q2.2.What is different types of functions based on parameters and return values? Explain.
Answer:
Based on parameters and return types, functions are classified into 4 types:
1. Function without parameters and without return values
2. Function with parameters and without return values
3. Function without parameters and with return values
4. Function with parameters and with return values
1. Function without parameters and without return values:
 This type of functions doesn’t contain parameters and return values.
Example Program
#include<stdio.h>
void addition( ) ; // function declaration

int main( )
{
addition( ) ; // function call
}
void addition( ) // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50

2. Function with parameters and without return values:


Prepared By: M. Parthasaradhi, Asst. Prof.

This type of functions having the parameters and doesn’t have the return values.
Example Program
#include<stdio.h>
void addition(int, int) ; // function declaration
int main( )
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
2.6

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
return 0;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50

3. Function without parameters and with return values:


These type of functions doesn’t have any parameters and contains return values.
Example Program
#include<stdio.h>
int addition( ) ; // function declaration
int main( )
{
int result ;
result = addition( ) ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition( ) // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
Prepared By: M. Parthasaradhi, Asst. Prof.

scanf("%d%d", &num1, &num2);


return (num1+num2) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50

2.7

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
4. Function with parameters and with return values:
These type of functions contain both parameters and return values.
Example Program
#include<stdio.h>
int addition(int, int) ; // function declaration
int main( )
{
int num1, num2, result ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
return 0;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
Output:
Enter any two integer numbers : 20 30
Sum = 50

3. Argument passing
Q3.1. Explain in detail about parameter passing techniques.
(Or)
Explain call by value and call by reference with example.
Answer:
There are two methods to pass parameters from calling function to called function and they are:
1. Call by Value
Prepared By: M. Parthasaradhi, Asst. Prof.

2. Call by Reference
1. Call by Value
In call by value parameter passing method, the copy of actual parameter values are copied
to formal parameters and these formal parameters are used in called function.
The changes made on the formal parameters do not affect the values of actual
parameters.

2.8

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Example Program
#include<stdio.h>
void swap(int, int) ; // function declaration
int main( )
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("Before swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}

void swap(int a, int b) // called function


{
int temp ;
temp = a ;
a=b;
b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 10, num2 = 20

2. Call by reference:
In Call by Reference parameter passing method, the memory address of the actual
parameters is copied to formal parameters.
Prepared By: M. Parthasaradhi, Asst. Prof.

This address is used to access the memory locations of the actual parameters in called
function. In this method, the formal parameters must be pointer variables.
Any changes made on the formal parameters effects the values of actual parameters.

Example Program:

2.9

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Example Program
#include<stdio.h>
void swap(int*, int*) ; // function declaration
int main( )
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("Before swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}

Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10

Prepared By: M. Parthasaradhi, Asst. Prof.

2.10

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
4. Recursion
Q4.1. Explain recursive function with an example.
Answer:
A function called by itself is called recursive function.
Syntax:
Return_type Function_name(Parameter_list)
{
…..
…..
Function_name(Parameter_list);
}
Example Program--Factorail Using Recursive Function
#include<stdio.h>
int factorial( int ) ;
int main( )
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("Factorial of %d is %d\n", n, fact) ;
return 0;
}
int factorial( int n )
{
int temp ;
if( n == 0 || n == 1)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
Prepared By: M. Parthasaradhi, Asst. Prof.

}
Output:
Enter any positive integer: 5
Factorial of 5 is 120

In the above example program, the factorial( ) function call is initiated from main( ) function with
the value 3. Inside the factorial( ) function, the function calls factorial(2), factorial(1) and factorial(0) are
called recursively.
The complete execution process of the above program is shown in the following figure: 2.11

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2

Factorial (3)

6 3 * Factorial (2)

2 2 * Factorial (1)

Factorial (1) 1
1

5. Pointers & storage allocation


Q5.1. How to access address of a variable?
Answer:
 In c language, we use the reference operator "&" to access the address of variable.
 For example, to access the address of a variable "marks" we use "&marks".
 We use the following printf statement to display memory location address of variable "marks".
Example:
printf("Address : %u", &marks) ;
 In the above example statement %u is used to display address of marks variable.
 Address of any memory location is unsigned integer value.

Q5.2. Define a pointer. Explain how to declare and initialize a pointer.


Answer:
Pointer:
A pointer is a variable which holds memory address of another variable.
Declaring Pointer:
Declaration of pointer variable is similar to the creation of normal variable but the name is
Prepared By: M. Parthasaradhi, Asst. Prof.

prefixed with * symbol.


Syntax:
datatype *pointerName ;

Example:
int *ptr ;
In the above example declaration, the variable "ptr" is a pointer variable that can be used to store
any integer variable address.
2.12

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Initializing a Pointer:
To assign address to a pointer variable we use assignment operator with the following syntax.
Pointer_Variable_Name = &variable_Name ;
Example:
int a = 50, *ptr ;
ptr = &a ;
Diagrammatic representation of above example is:

a ptr

50 2020

2020 3510

Accessing Variable Value Using Pointer


Pointer variables are used to store the address of other variables. We can use this address to access
the value of the variable through its pointer.
We use the symbol "*" in front of pointer variable name to access the value of variable to which
the pointer is pointing.
Syntax:
*pointer_Variable_Name

Example Code
#include<stdio.h>
int main( )
{
int a = 10, *ptr ;
ptr = &a ;
printf("Address of variable a = %u\n", ptr) ;
printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
return 0;
Prepared By: M. Parthasaradhi, Asst. Prof.

}
Output:
Address of variable a = 6487580
Value of variable a = 10
Address of variable ptr = 6487568

2.13

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Q5.3. How many bytes of memory allocated for pointer variable.
Answer:
Every pointer variable is used to store the address of another variable. In computer memory address
of any memory location is an unsigned long integer value.
In c programming language, unsigned long integer requires 4 bytes of memory. So, irrespective of
pointer datatype every pointer variable is allocated with 4 bytes of memory in 32-bit architecture.
Q5.4. Define pointer to pointer.
Answer:
 A pointer variable to store the address of another pointer variable is called a pointer to pointer
variable. Sometimes we also call it a double pointer.
Syntax:
Data_type **pointer_Name ;
Example:
int a;
int *p1, **p2, ***p3;
p1 = &a;
p2 = &p1;
p3 = &p2
Note:
1. To store the address of normal variable we use single pointer variable
2. To store the address of single pointer variable we use double pointer variable
3. To store the address of double pointer variable we use triple pointer variable
4. Similarly, the same for remaining pointer variables also…
Q5.5. Define void pointer with example.

Answer:
A void pointer is a pointer variable used to store the address of a variable of any datatype.
That means single void pointer can be used to store the address of integer variable, float variable,
character variable, double variable or any structure variable. Prepared By: M. Parthasaradhi, Asst. Prof.
We use the keyword "void" to create void pointer.
Syntax:
void *pointerName ;
Example:
int a;
float b;
void *p1, *p2;
p1 = &a;
p2 = &b;
2.14

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Q5.6. What are the advantages with pointers.
Answer:
1. By using pointers we can get multiple values from the function, as we know a function can return
only one value but by passing arguments as pointers we can get more than one values from the
pointer.
2. By using pointers dynamic memory can be created according to the program use. We can save
memory from static (compile time) declarations.
3. By using pointers we can design and develop complex data structures like STACK, QUEUE, and
LINKED LIST etc.
4. Amazing feature of pointes: Pointers provide direct memory access.

Q5.7. What are the disadvantages with pointers?


(OR)
What are the problems with pointes?
Answer:
1. Failed to protect memory addresses (locations) - Since pointer can access direct memory so
memory cannot be protected.
2. Uninitialized pointers can cause of segmentation fault.
3. Pointers variables are slower than normal variables.
4. Pointers always required Free Memory for Dynamically Allocated Memory.

6. Expressions involving pointers


Q6.1. What are the operations performed on pointers? Explain.
Answer:
Pointer variables are used to store the address of variables. Address of any variable is an unsigned
integer value i.e., it is a numerical value. So we can perform following arithmetic operations on pointer
values:
1. Addition
Prepared By: M. Parthasaradhi, Asst. Prof.

2. Subtraction
3. Increment
4. Decrement
5. Comparison

2.15

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
1. Addition:
The addition operation on pointer variables is calculated using the following formula:
Address_At_Pointer + ( Number_To_Be_Add * Data_type_size )
Example 1:
int a, *iPtr ;
iPtr = &a ; // Asume address of a is 1000
iPtr = iPtr + 3 ; // iPtr = 1000 + ( 3 * 2 ) 1006
Example 2:
float b, *fPtr ;
fPtr = &b ; // Asume address of b is 2000
fPtr = fPtr + 2 ; // fPtr = 2000 + ( 2 * 4 )2008
2. Subtraction:
The subtraction operation on pointer variables is calculated using the following formula:
Address_At_Pointer - ( Number_To_Be_Add * Data_type_Size )
Example1:
int a, *iPtr ;
iPtr = &a ; // Asume address of a is 1000
iPtr = iPtr - 3 ; // iPtr = 1000 - ( 3 * 2 ) 994
Example2:
float b, *fPtr ;
fPtr = &b ; // Asume address of b is 2000
fPtr = fPtr - 2 ; // fPtr = 2000 - ( 2 * 4 ) 1992

3. Increment:
The increment operation on pointer variable is calculated as follows:
Address_At_Pointer + Data_type_size
Example1:
int a, *iPtr ;
iPtr = &a ; // Asume address of a is 1000
Prepared By: M. Parthasaradhi, Asst. Prof.

iPtr++ ; // iPtr = 1000 + 21002


Example2:
float b, *fPtr ;
fPtr = &b ; // Asume address of b is 2000
fPtr++ ; // fPtr = 2000 + 42004

2.16

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
4. Decrement:
The decrement operation on pointer variable is calculated as follows:
Address_At_Pointer – Data_type_size
Example1:
int a, *iPtr ;
iPtr = &a ; // Asume address of a is 1000
iPtr-- ; // iPtr = 1000 – 2 998
Example2:
float b, *fPtr ;
fPtr = &b ; // Asume address of b is 2000
fPtr-- ; // fPtr = 2000 – 41996

5. Comparison:
The comparison operation is performing between the pointers of same data type only. In c
programming language, we can use all comparison operators (relational operators) with pointers.
Note:
 We can't perform multiplication and division operations on pointers.

7. Pointers to functions
Q7.1. Explain about pointers to arrays?
Answer:
 In c, when we declare an array the compiler allocates the required amount of memory and also
creates a constant pointer with array name and stores the base address of that pointer in it.
 The address of the first element of an array is called as base address of that array.
 The array name itself acts as a pointer to the first element of that array.
 Consider the following example of array declaration...
int marks[6] ;
 For the above declaration, the compiler allocates 12 bytes of memory and the address of first
memory location (i.e., marks[0]) is stored in a constant pointer called marks. That means in the
Prepared By: M. Parthasaradhi, Asst. Prof.

above example, marks is a pointer to marks[0].


 An array name is a constant pointer.
Note:
1. marks is same as &marks[0]
2. marks + 1 is same as &marks[1]
3. marks + 2 is same as &marks[2]
4. marks + 3 is same as &marks[3]
5. marks + 4 is same as &marks[4]
2.17

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
6. marks + 5 is same as &marks[5]
7. *marks is same as marks[0]
8. *(marks + 1) is same as marks[1]
9. *(marks + 2) is same as marks[2]
10. *(marks + 3) is same as marks[3]
11. *(marks + 4) is same as marks[4]
12. *(marks + 5) is same as marks[5]
13. marks[1][2] is same as *(*(marks + 1) + 2)

Q7.2. Explain about pointers to functions (Call by reference).


Answer:
 We can pass address of a variable to the functions as a parameter.
 In Call by Reference parameter passing method, the memory address of the actual parameters is
copied to formal parameters.
 This address is used to access the memory locations of the actual parameters in called function. In
this method, the formal parameters must be pointer variables.
 Any changes made on the formal parameters effects the values of actual parameters.
Example Program
#include<stdio.h>
void swap(int*, int*) ; // function declaration
int main( )
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("Before swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
Prepared By: M. Parthasaradhi, Asst. Prof.

}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
2.18

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10

Q7.3. Define static memory allocation. What are its limitations?


Answer:
 Allocation of memory during compile time is called static memory allocation.
 When we declare variables memory is allocated in space called stack. The memory allocated in the
stack is fixed at the time of compilation and remains until the end of the program execution.
Limitations:
o When we create an array, we must specify the size at the time of the declaration itself and it
cannot be changed during the program execution. This is a major problem when we do not
know the number of values to be stored in an array.

Q7.4. Explain about dynamic memory allocation in C.


Answer:
 Allocation of memory during the program execution is called dynamic memory allocation.
 We use pre-defined functions to allocate memory dynamically.
 There are FOUR pre-defined functions that are defined in the header file known as "stdlib.h".
 They are as follows:
1. malloc( )
2. calloc( )
3. realloc( )
4. free( )
1. malloc( ):
o malloc( ) is the pre-defined function used to allocate a memory block of specified number
of bytes and returns void pointer.
o The void pointer can be casted to any datatype.
Prepared By: M. Parthasaradhi, Asst. Prof.

o If malloc( ) function unable to allocate memory due to any reason it returns NULL pointer.
Syntax:
void* malloc(size_in_bytes)
Example:
char *title;
title = (char *) malloc(15);

2.19

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
2. calloc( ):
o calloc( ) is the pre-defined function used to allocate multiple memory blocks of the specified
number of bytes and initializes them to ZERO.
o calloc( ) function returns void pointer.
o If calloc( ) function unable to allocate memory due to any reason it returns a NULL pointer.
o Generally, calloc( ) is used to allocate memory for array and structure.
o calloc( ) function takes two arguments and they are
1. The number of blocks to be allocated
2. Size of each block in bytes
Syntax:
void* calloc(number_of_blocks, size_of_each_block_in_bytes)
Example:
int *ptr;
ptr = (int*)calloc(5, sizeof(int));

3. realloc( ):
o realloc( ) is the pre-defined function used to modify the size of memory blocks that were
previously allocated using malloc( ) or calloc( ).
o realloc( ) function returns void pointer.
o If realloc( ) function unable to allocate memory due to any reason it returns NULL pointer.
Syntax
void* realloc(*pointer, new_size_of_each_block_in_bytes)
Example:
char *title;
title = (char *) malloc(15);
title = (char*) realloc(title, 30);

4. free( ):
o free( ) is the pre-defined function used to deallocate memory block that was previously
Prepared By: M. Parthasaradhi, Asst. Prof.

allocated using malloc( ) or calloc( ).


Syntax
void free(*pointer)

Example:
char *title;
title = (char *) malloc(15);
free(title);
2.20

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2

8. Storage classes – auto, register, static, extern


Q8.1. Define storage class. What are the storage classes in C. Explain with example?
Answer:
Storage classes are used to define storage location (whether RAM or Register), scope, lifetime and
the default value of a variable.
In C language, there are FOUR storage classes and they are as follows:
1. auto storage class
2. static storage class
3. register storage class
4. extern storage class
1. auto storage class:
The default storage class of all local variables (variables declared inside block or function) is
auto storage class.
Variable of auto storage class has the following properties:

Property Description

Keyword auto

Storage Computer Memory (RAM)

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains Within a block of function in which variable is
defined.
Example Code
#include<stdio.h>
void fun( )
{
auto int a = 1;
printf("%d", a);
Prepared By: M. Parthasaradhi, Asst. Prof.

}
int main( )
{
fun( );
fun( );
fun( );
}
Output:
1
1
1 2.21

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
2. static storage class:
The static storage class is used to create variables that hold value beyond its scope until the end
of the program.
The static variable allows initializing only once and can be modified any number of times.
Variable of static storage class has the following properties:

Property Description

Keyword static

Storage Computer Memory (RAM)

Default Value Zero

Scope Local to the block in which the variable is defined

Life time The value persists between different function calls (i.e., Initialization
is done only once)

Example Code
#include<stdio.h>
void fun( )
{
static int a;
printf("%d\n",a);
a++;
}
int main( )
{
fun( );
fun( );
fun( ); Prepared By: M. Parthasaradhi, Asst. Prof.

}
Output:
0
1
2

2.22

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
3. register storage class:
The register storage class is used to specify the memory of the variable that has to be allocated in
CPU Registers.
The register variables enable faster accessibility compared to other storage class variables.
As the number of registers inside the CPU is very less we can use very less number of register
variables.
Variable of register storage class has the following properties:

Property Description

Keyword register

Storage CPU Register

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is defined

Example Code
#include<stdio.h>
void fun( )
{
register int a = 1;
printf("%d\n",a);
a++;
}
int main( )
{
fun( );
fun( );
fun( ); Prepared By: M. Parthasaradhi, Asst. Prof.

}
Output:
1
1
1

2.23

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
4. extern storage class:
The default storage class of all global variables (variables declared outside function) is external
storage class.
Variable of external storage class has the following properties:

Property Description

Keyword extern

Storage Computer Memory (RAM)

Default Value Zero

Scope Global to the program (i.e., Throughout the program)

Life time As long as the program’s execution does not comes to end

Example:
Extern.c Main.c
#include<stdio.h> #include<stdio.h>
extern int a =10; #include "Extern.c"
int main( )
{
printf("%d", a);
return 0;
}
Output:
10

Prepared By: M. Parthasaradhi, Asst. Prof.

2.24

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
9. Structures
Q9.1. Define a structure. How to declare a structure in C?
Answer:
Structure:
Structure is a collection of different data type elements which can be referred under a single name.
Creating Structure:
To create structure, we use the keyword called "struct".
Syntax:
struct structure_name
{
// Structure members
data_type member1;
data_type member2, member3;
….
};
struct structure_name structure_varaibles;

Example:
struct Student
{
// structure members
char stud_name[30];
int roll_number;
float percentage;
};
// structure variables
struct Student s1, s2;
Accessing Structure Members:
We use structure variables to access structure members with dot(.) operator.
Prepared By: M. Parthasaradhi, Asst. Prof.

Syntax:
Structure_varaible . structure_member
Example:
s1.stud_name
s1.roll_number

2.25

Department of CSE :: ALTS :: ATP


C-Programming (20A05201 :: Unit-2
Programming & Data Structures (20A05201T)
Example Program:
#include<stdio.h>
struct employee
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
e1.name = "Ajay");
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Ajay

Q9.2. How much memory is allocated for a structure?


Answer:
The memory does not allocate on defining a structu
structure.
re. The memory is allocated when we create
the variable of a particular structure.
The size of memory allocated is equal to the sum of memory required by individual members of
that structure.
Example:
Prepared By: M. Parthasaradhi, Asst. Prof.

2.26
C-Programming & Data Structures (20A05201T):: Unit-2
Q9.3. Explain in detail about structure with arrays with example.
Answer:
An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities.
The arrays of structures in C are used to store information about multiple entities of different data
types.
The array of structures is also known as the collection of structures.
Example:
#include<stdio.h>
struct student
{
int rollno;
char name[10];
};
int main( )
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnterRollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
Prepared By: M. Parthasaradhi, Asst. Prof.

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
2.27

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

Q9.4. Explain in detail about structure with functions with example.


Answer:
We can pass a structure a variable to a function and also a function returns structure variable.
Example:
#include <stdio.h>
// function prototype
void display(struct student s);
struct student
{
char name[50];
int age;
};
int main( )
Prepared By: M. Parthasaradhi, Asst. Prof.

{
struct student s1;
printf("Enter name: ");
scanf("%s", s1.name);
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
return 0;
} 2.28

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
void display(struct student s)
{
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}

Output
Enter name: Bond
Enter age: 13

Displaying information
Name: Bond
Age: 13

Q9.5. Explain in detail about structure with pointer with example.


Answer:
We can create pointers to the structure variable.
struct name
{
member1;
member2;
.
.
};
struct name *ptr, Harry;
Here, ptr is a pointer to struct.
We can Access pointers to structure we use -> (membership) operator.
Prepared By: M. Parthasaradhi, Asst. Prof.

Example:
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main( )
{
struct person *personPtr, person1;
2.29

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age);
printf("Enter weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
Output:
Enter age: 18
Enter weight: 52
Displaying:
Age: 18
weight: 52.000000

Q9.6. Write short note on structure with in structure.


Answer:
C provides us the feature of nesting one structure within another structure by using which,
complex data types are created.
For example, we may need to store the address of an entity employee in a structure. The attribute
address may also have the subparts as street number, city, state, and pin code. Hence, to store the address
of the employee, we need to store the address of the employee into a separate structure and nest the
structure address into the structure employee.
Consider the following program.
Example
#include<stdio.h>
struct address
Prepared By: M. Parthasaradhi, Asst. Prof.

{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
2.30

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
struct address add;
};
int main ( )
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone:%s", emp.name, emp.add.city,
emp.add.pin, emp.add.phone) ;

return 0;
}
Output

Enter employee information?


Arun
Delhi
110001
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890

Q9.7. Define self-referential structure.


Answer:
Self-Referential structures are those structures that have one or more pointers which point to the
Prepared By: M. Parthasaradhi, Asst. Prof.

same type of structure, as their member.


Example:

struct node

int data1;

struct node* link;

};
2.31

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
10. Unions
Q 10.1. Define union. Explain creation of union and accessing union members.
Answer:
Union:
Union is a collection of different data type elements which can be referred under a single name.
Creating Union:
To create union, we use the keyword called "union".
Syntax:
union union_name
{
// Union members
data_type member1;
data_type member2, member3;
….
};
union union_name union_varaibles;

Example:
union Student
{
// union members
char stud_name[30];
int roll_number;
float percentage;
};
// union variables
union Student s1,s2;
Accessing Union Members:
We use union variables to access structure members with dot(.) operator.
Syntax: Prepared By: M. Parthasaradhi, Asst. Prof.
Union_varaible . Union_member
Example:
s1.stud_name
s1.roll_number
s1.percentage

2.32

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Q10.2 How much memory is allocated for a structure?
Answer:
The memory is allocated when we create the variable of a particular union. The size of memory
allocated is equal to the maximum memory required by an individual member among all members of that
union.
Example:

Q10.3. Write the differences between structure and union.


Answer:
Structure Union

Keyword The keyword struct is used to define a The keyword union is used to define a
structure. union.
The size of the structure is greater than
Size The size of the union is equal to the
or equal to the sum of size of its
size of largest member.
members.
Memory Each member in a structure is assigned Memory allocated is shared by
unique storage location. individual member of a union.
Value Altering value of a member will not Altering value of a member will alter
Altering affect other members of a structure. other members of a union.
Accessing Individual member can be accessed at a Only one member can be accessed at a
members time. time.
Initialization Several members of a structure can Only the first members of a union can
of Members initialize at once. be initialized.
Prepared By: M. Parthasaradhi, Asst. Prof.

2.33

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
11. Strings
Q11.1. Define a string. Explain how to create and initialize strings in C.
Answer:
String:
String is a set of characters enclosed in double quotation marks.
In C programming, the string is a character array of single dimension.
Creating a String:
Syntax:
char string_name[size];
Example:
char str1[30];
Initialization:
Syntax:
string_name[size] = String
Example:
1. char str1[30] = “Hello”
2. char str2[20];
str = “Hello Hai”
Note:
‘\0’ represents end of the string.
Q11.2. Explain about gets and puts functions.
Answer:
gets( ) function is used to read a string from standard input device and puts is used to display a
string on standard output device.
gets( ) and puts( ) functions are defined in stdio.h header file.
Example:
Example:
#include<stdio.h>
int main( )
{
Prepared By: M. Parthasaradhi, Asst. Prof.

char s[20];
printf("Enter a String: ");
gets(s);
printf("Your String is: ");
puts(s);
return 0;
}
Output:
Enter a String: hello
Your String is: hello 2.34

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
12. String handling functions
Q.13. Explain about string handling functions.
Answer:
 C programming language provides a set of pre-defined functions called string handling functions to
work with string values.
 The string handling functions are defined in a header file called string.h.
 Whenever we want to use any string handling function we must include the header file called string.h.
 The following table provides most commonly used string handling function and their use:
Function Syntax Description & Example
Copies string2 value into string1
Example:
char str1[] = “Hello”

strcpy() strcpy(string1, string2) char str2[] = “Good Morning”


strcpy(str1, str2)
printf(“%s”, str1)
Output:
Good Morning
returns total number of characters in string1
Example:
strlen() strlen(string1) char str2[] = “Good Morning”
printf(“%d”, strlen(str2))
Output:
12
Appends string2 to string1
Example:
char str1[] = “Hello”

strcat() strcat(string1,string2) char str2[] = “Good Morning”


strcat(str1, str2)
printf(“%s”, str1)
Output:
Prepared By: M. Parthasaradhi, Asst. Prof.
Hello Good Morning
Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2;
greater than 0 if string1>string2
Example:
strcmp() strcmp(string1, string2)
char str1[] = “Hello”
char str2[] = “Hello”
printf(“%d”, strcat(str1, str2))
Output:
0 2.35

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Converts all the characters of string1 to lower case.
Example:
strlwr() strlwr(string1) char str1[] = “HELLO”
printf(“%s”, strlwr(str1))
Output:
hello
Converts all the characters of string1 to upper case.
Example:
strupr() strupr(string1) char str1[] = “hello”
printf(“%s”, strupr(str1))
Output:
HELLO
It reverses the value of string1
Example:
strrev() strrev(string1) char str1[] = “hello”
printf(“%s”, strrev(str1))
Output:
olleh
Sets all the characters of string1 to given character 'B'.
Example:
strset() strset(string1, 'B') char str1[]= “Hello";
printf("%s", strset(str1,’a’));
Output:
aaaaa
Returns a pointer to the first occurrence of character 'b' in
strchr() strchr(string1, 'b')
string1
Returns a pointer to the last occurrence of character 'b' in
strrchr() strrchr(string1, 'b')
string1
Returns a pointer to the first occurrence of string2 in
strstr() strstr(string1, string2)
string1
Prepared By: M. Parthasaradhi, Asst. Prof.

2.36

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
13. Command line arguments
Q13.1. What are the command line arguments? Explain with an example.
Answer:
 Command line arguments are the parameters passing to main( ) method from the command line.
 When command line arguments are passed main( ) method receives them with the help of two
formal parameters and they are,
1. int argc
2. char *argv[ ]
 int argc - It is an integer argument used to store the count of command line arguments are passed
from the command line.
 char *argv[ ] - It is a character pointer array used to store the actual values of command line
arguments are passed from the command line.
Example Program to illustrate command line arguments in C.
Program name: main.c
#include<stdio.h>
int main(intargc, char *argv[])
{
int i;
if(argc == 1)
printf("Please provide command line arguments!!!");
else
{
printf("Total number of arguments are - %d and they are\n\n", argc);
for(i=0; i<argc ; i++)
{
printf("%d -- %s \n", i+1, argv[i]);
}
}
return 0;
} Prepared By: M. Parthasaradhi, Asst. Prof.

Output:
D:\C Programs>main.exe hello welcome to GATESIT
Total number of arguments are - 5 and they are
1 -- main.exe
2 -- hello
3 -- welcome
4 -- to
5 – GATESIT
2.37

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Q13.2. Write short note on enumeration in C with an example.
Answer:
 Enumeration is the process of creating user defined datatype by assigning names to integral
constants
 We use the keyword enum to create enumerated datatype.
Syntax:
enumenum_name{name1, name2, name3, ... }

 In the above syntax, integral constant '0' is assigned to name1, integral constant '1' is assigned to
name2 and so on.
 We can also assign our own integral constants as follows:
enumenum_name{name1 = 10, name2 = 30, name3 = 15, ... }
 In the above syntax, integral constant '10' is assigned to name1, integral constant '30' is assigned to
name2 and so on.
Example Program for enum with default values
#include<stdio.h>
enum day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} ;
int main( )
{
printf("\nSunday = %d ", Sunday) ;
printf("\nMonday = %d ", Monday) ;
printf("\nTuesday = %d ", Tuesday) ;
printf("\nWednesday = %d ", Wednesday) ;
printf("\nThursday = %d ", Thursday) ;
printf("\nFriday = %d ", Friday) ;
printf("\nsaturday = %d ", Saturday) ;
return 0;
}
Output:
Prepared By: M. Parthasaradhi, Asst. Prof.

Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
saturday = 6

2.38

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
Q13.3. Write a short note on typedef.
Answer:
 In C programming language, typedef is a keyword used to create alias name for the existing
datatypes.
Syntax:
typedef <existing-datatype> <alias-name>
Example:
Example Program to illustrate typedef in C.
#include<stdio.h>
typedef int Number;
int main( )
{
Number a,b,c; // Here a,b,&c are integer type of variables.
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &a,&b) ;
c = a + b;
printf("Sum = %d", c) ;
return 0;
}
Output:
Enter any two integer numbers: 5 3
Sum = 8

Q13.4. Write short note on bit fields.


Answer:
 In C, we can specify size (in bits) of structure and union members.
 The idea is to use memory efficiently when we know that the value of a field or group of fields
will never exceed a limit or is within a small range.
Example:
#include <stdio.h>
struct date
{ Prepared By: M. Parthasaradhi, Asst. Prof.
int d : 5;
int m : 4;
int y;
};
int main( )
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
return 0;
}
Output:
Size of date is 4 bytes 2.39

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
2 Marks Questions
1. Functions &
2. Types of functions
1. Define a function. Write the syntax to define a function.
2. List the advantages of functions.
3. Define function prototype. Give the general syntax of function prototype.
4. In what way actual arguments differ from formal arguments.
(OR)
Differentiate between actual parameters and formal parameters.
5. Illustrate with a suitable example the use of return statement.
6. How many maximum arguments can be passes by return ( )?
Answer:
return statements returns maximum one value at a time.
7. List the basic console I/O functions.
Answer:
The below table illustrates 4 console I/O functions :
Functions Description
This function returns the character that was typed last or was typed most recently.
getch() It does not display (echo) the character on the screen. It is defined in the header
file conio.h
putch() This function prints a single character on the console
It takes a string input (single-word or multi-word) from the user. It terminates
gets()
when the Enter key is pressed.
puts() It is used to print the string to the console.

3. Argument passing
8. Explain call by reference.
9. Distinguish between Call by value and Call by reference.
Prepared By: M. Parthasaradhi, Asst. Prof.

10. Write a function to swap two integer elements


11. Write a C program for call by reference.
4. Recursion
12. Illustrate recursion with an example.
13. Define recursion.
5. Pointers & storage allocation
14. Give syntax to create a pointer to function.
15. What is a pointer? Give its general form.
2.40

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
16. Write the syntax of dynamic allocation functions in C language.
17. Explain malloc( ) function.
18. Discuss the problems associated with pointers.
(OR)
What are the problems with pointers?
6. Pointers to functions
19. Explain pointer to an array with an example.
(OR)
What is a pointer array? Give example.
7. Expressions involving pointers
20. Recall the possible arithmetic operations on pointers in C language?
21. What does this statement indicate p = **a; where p and a are variables?
Answer:
The variable ‘p’ stores a value pointed by the double pointer ‘a’.
8. Storage classes – auto, register, static, extern
22. What is mean by storage class of variable?
23. Discuss any two storage class specifiers.
24. Write a note on static and extern storage classes.
25. Write a note on register and auto storage classes.
26. How to define a global constant?
Answer:
In C we can declare global constants in 2 ways:
1. Using const keyword
2. Using #define
1. Using const Keyword:
Example:
#include<stdio.h>
const pi = 3.14
int main( )
{
Prepared By: M. Parthasaradhi, Asst. Prof.

printf(“%d”, pi);
return 0;
}
2. Using #define:
#include<stdio.h>
#define pi = 3.14
int main( )
{
2.41

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
printf(“%d”, pi);
return 0;
}

27. What are static variables and functions?


Answer:
Static Variable:
When a variable is declared with a static keyword, then it is known as a static variable. The
static variable value persists between different function calls (i.e., Initialization is done only once)
Static Function:
When a function is declared with a static keyword known as a static function. Its lifetime is
throughout the program.
Example:
static void func( )
{
printf("Hello javaTpoint");
}

28. Define type qualifiers.


Answer:
Using type qualifiers, we can change the properties of variables. The c programming
language provides two type qualifiers and they are as follows...
1. const
2. volatile
1. const type qualifier:
The const type qualifier is used to create constant variables. When a variable is
created with const keyword, the value of that variable can't be changed once it is defined.
2. volatile type qualifier in C
The volatile type qualifier is used to create variables whose values can't be changed
Prepared By: M. Parthasaradhi, Asst. Prof.

in the program explicitly but can be changed by any external device or hardware.
For example, the variable which is used to store system clock is defined as a
volatile variable. The value of this variable is not changed explicitly in the program but is
changed by the clock routine of the operating system.
9. Structures
29. Define structure. Write syntax to declare a structure.
30. What are self-referential structures?

2.42

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
31. Declare a struct name containing field’s first_name, middle_name, last_name within a struct student.
32. How much memory is allocated for a structure?
33. Illustrate the need of structures with an example.
Answer:
Structure is a user-defined data type in C language which allows us to combine data of
different types together. Structure helps to construct a complex data type which is more meaningful.
10. Unions
34. Define union. Write syntax to declare a structure.
35. Differentiate between structure and union types.
36. How much memory is allocated for a union?
11. Strings &
12. String handling functions
37. Define a string. How to declare a string?
38. What is the problem with getchar ( )?
Answer:
getchar() function terminates only after when a “enter” key is pressed. This causes an
additional ‘\n’ character along with the single character you entered.
39. List the string functions in C.
40. Write the syntax to read string from key board. Give example.
Answer:
To read a string in C using scanf( ), we use %s format specifier.
Syntax:
scanf(“%s”, string_variable);
Example:
#include<stdio.h>
int main( )
{
char str1[30];
printf(“Enter a String: ”);
scanf(“%s”, str1);
Prepared By: M. Parthasaradhi, Asst. Prof.

printf(“The given String is: %s”, str1);


return 0;
}
Output:
Enter a String: Hello
The given String is: Hello

2.43

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures (20A05201T):: Unit-2
41. How can we read the character and set of characters? Give examples for each one.
Answer:
Reading Characters:
To read a character in C using scanf( ), we use %c format specifier.
#include<stdio.h>
int main( )
{
char ch;
printf(“Enter a Character: ”);
scanf(“%c”, &ch);
printf(“The given Character is: %c”, ch);
return 0;
}
Output:
Enter a String: H
The given String is: H
Reading set of Characters (String):
To read a string in C using scanf( ), we use %s format specifier.
Syntax:
scanf(“%s”, string_variable);
Example:
#include<stdio.h>
int main( )
{
char str1[30];
printf(“Enter a String: ”);
scanf(“%s”, str1);
printf(“The given String is: %s”, str1);
return 0;
}
Output:
Prepared By: M. Parthasaradhi, Asst. Prof.

Enter a String: Hello


The given String is: Hello
13. Command line arguments
42. Why to use typedef?
(OR)
What is the use of typedef in C?
43. Define command line arguments.
44. Write short note on enum.
45. Write a short note on bit fields.
2.44

Department of CSE :: ALTS :: ATP


C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

C-Programming & Data Structures Lab (20A05201P)


Week 1
Write C programs that use both recursive and non-recursive functions
i) To find the factorial of a given integer.
ii) To find the GCD (greatest common divisor) of two given integers.
iii) To solve Towers of Hanoi problem.

1.i.A. Write C program that use non-recursive function, to find the factorial of a given integer.
#include<stdio.h>
int factorial(int);
int main()
{
int n;
printf("Enter a Number: ");
scanf("%d", &n);
printf("The Factorial of %d is %d", n, factorial(n));
return 0;
}
int factorial(int n)
{
int i, fact = 1;
for( i = 1; i <= n; i++)
fact = fact * i;

Prepared By: M. Parthasaradhi, Asst. Prof.


return fact;
}
Output:
Enter a Number: 5
The Factorial of 5 is 120

1
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

1.i.B. Write C program that use recursive function, to find the factorial of a given integer.
#include<stdio.h>
int factorial(int);
int main()
{
int n;
printf("Enter a Number: ");
scanf("%d", &n);
printf("The Factorial of %d is %d", n, factorial(n));
return 0;
}
int factorial(int n)
{
if( n == 0 || n == 1)
return 1;

return n * factorial(n-1);
}
Output:
Enter a Number: 5
The Factorial of 5 is 120

Prepared By: M. Parthasaradhi, Asst. Prof.

2
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

1.ii.A. Write C program that use non-recursive function, to find the GCD of a given two
integers.
#include<stdio.h>
int gcd(int , int);
int main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
printf("The GCD of %d and %d is %d", a, b, gcd(a,b));

return 0;
}
int gcd(int a, int b)
{
while( a != b)
{
if( a > b)
a = a - b;
else
b = b - a;
}
return a;
}

Prepared By: M. Parthasaradhi, Asst. Prof.


Output:
Enter two numbers: 16 30
The GCD of 16 and 30 is 2

3
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

1.ii.B. Write C program that use recursive function, to find the GCD of a given two integers.
#include<stdio.h>
int gcd(int , int);
int main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
printf("The GCD of %d and %d is %d", a, b, gcd(a,b));

return 0;
}
int gcd(int a, int b)
{
if( b == 0)
return a;
return gcd(b, a % b);
}
Output:
Enter two numbers: 16 30
The GCD of 16 and 30 is 2

Prepared By: M. Parthasaradhi, Asst. Prof.

4
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

1.iii.A.Write C program that use non-recursive function, to solve Towers of Hanoi problem.
#include<stdio.h>
void TOH(int n)
{
int i, source, dest;
for( i = 1; i < (1 << n); i++)
{
source = (i & (i-1)) % 3;
dest = (((i | (i - 1))) + 1) % 3;
printf("\nMove one disk from %c to %c", source+65, dest+65);
}
}
int main()
{
int number;
printf("Enter number of Disks: ");
scanf("%d", &number);
TOH(number);
return 0;
}
Output:
Enter number of Disks: 3

Move one disk from A to C

Prepared By: M. Parthasaradhi, Asst. Prof.


Move one disk from A to B
Move one disk from C to B
Move one disk from A to C
Move one disk from B to A
Move one disk from B to C
Move one disk from A to C

5
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

1.iii.B. Write C program that use recursive function, to solve Towers of Hanoi problem.
#include<stdio.h>
void TOH(int n, char a, char b, char c)
{
if(n > 0)
{
TOH(n-1,a,c,b);
printf("\nMove Disk-%d from %c to %c", n, a,b);
TOH(n-1,c,b,a);
}
}
int main()
{
int number;
printf("Enter number of Disks: ");
scanf("%d", &number);
// Tower C is Destination
TOH(number, 'A', 'C', 'B');
return 0;
}
Output:
Enter number of Disks: 3

Move Disk-1 from A to C

Prepared By: M. Parthasaradhi, Asst. Prof.


Move Disk-2 from A to B
Move Disk-1 from C to B
Move Disk-3 from A to C
Move Disk-1 from B to A
Move Disk-2 from B to C
Move Disk-1 from A to C

6
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

Week 2
a) Write a C program to find both the largest and smallest number in a list of integers.
b) Write a C program that uses functions to perform the following:
i) Addition of Two Matrices ii) Multiplication of Two Matrices

2.A. Write a C program that uses functions to performs Multiplication of Two Matrices
#include<stdio.h>
void Enter_Elements(int a[10][10], int m, int n)
{
int i, j;
for( i=0; i<m; i++)
for( j=0; j<n; j++)
scanf("%d", &a[i][j]);
}
void Display_Elements(int a[10][10], int m, int n)
{
int i, j;
for( i=0; i<m; i++)
{
for( j=0; j<n; j++)
printf("%d\t", a[i][j]);

printf("\n");
}
}
void Multiplication(int a[10][10], int b[10][10], int c[10][10], int m, int n, int q)

Prepared By: M. Parthasaradhi, Asst. Prof.


{
int i, j, k;
for( i=0; i<m; i++)
for( j=0; j<q; j++)
{
c[i][j] = 0;
for( k=0; k<n; k++)
c[i][j] += a[i][k] * b[k][j];
}
}
7
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

int main()
{
int a[10][10], b[10][10], c[10][10];
int m, n, p, q;
printf("Enter The Size of Matrix A: ");
scanf("%d%d", &m, &n);
printf("Enter The Size of Matrix B: ");
scanf("%d%d", &p, &q);
if( n != p)
{
printf("Matrix Multiplication is not possible!");
printf("Number of Columns First Matrix is eualto number of Rows in Second Matrix");
return 0;
}
printf("Matrix Multiplication is Possible\n");

printf("Enter %d Integers into Matrix A:\n", m*n);


Enter_Elements(a, m, n);

printf("Enter %d Integers into Matrix B:\n", p*q);


Enter_Elements(b, p, q);

printf("Matrix A Elements are:\n");


Display_Elements(a, m, n);

Prepared By: M. Parthasaradhi, Asst. Prof.


printf("Matrix B Elements are:\n");
Display_Elements(b, p, q);

Multiplication(a, b, c, m, n, q);

printf("Multiplication of Matrix A and Matrix B is:\n");


Display_Elements(c, m, q);

return 0;
} 8
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

Output:
Enter The Size of Matrix A: 2 2
Enter The Size of Matrix B: 2 2
Matrix Multiplication is Possible
Enter 4 Integers into Matrix A:
12
34
Enter 4 Integers into Matrix B:
10
01
Matrix A Elements are:
1 2
3 4
Matrix B Elements are:
1 0
0 1
Multiplication of Matrix A and Matrix B is:
1 2
3 4

Prepared By: M. Parthasaradhi, Asst. Prof.

9
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

2.B.i. Write a C program that uses functions to performs Addition of Two Matrices

#include<stdio.h>
void Enter_Elements(int a[10][10], int m, int n)
{
int i, j;
for( i=0; i<m; i++)
for( j=0; j<n; j++)
scanf("%d", &a[i][j]);
}
void Display_Elements(int a[10][10], int m, int n)
{
int i, j;
for( i=0; i<m; i++)
{
for( j=0; j<n; j++)
printf("%d\t", a[i][j]);

printf("\n");
}
}
void Addition(int a[10][10], int b[10][10], int c[10][10], int m, int n)
{
int i, j;

Prepared By: M. Parthasaradhi, Asst. Prof.


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

int main()
{
int a[10][10], b[10][10], c[10][10];
int m, n;
printf("Enter Matrix Size: "); 10
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

scanf("%d%d", &m, &n);


printf("Enter %d Integers into Matrix A: ", m*n);
Enter_Elements(a, m, n);
printf("Enter %d Integers into Matrix B: ", m*n);
Enter_Elements(b, m, n);
printf("Matrix A Elements are:\n");
Display_Elements(a, m, n);

printf("Matrix B Elements are:\n");


Display_Elements(b, m, n);

Addition(a, b, c, m, n);

printf("Addition of Matrix A and Matrix B is:\n");


Display_Elements(c, m, n);

return 0;
}
Output:
Enter Matrix Size: 3
2
Enter 6 Integers into Matrix A: 1 2 3 4 5 6
Enter 6 Integers into Matrix B: 7 8 9 1 2 3
Matrix A Elements are:
1 2

Prepared By: M. Parthasaradhi, Asst. Prof.


3 4
5 6
Matrix B Elements are:
7 8
9 1
2 3
Addition of Matrix A and Matrix B is:
8 10
12 5
7 9 11
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

2.B.ii. Write a C program that uses functions to performs Multiplication of Two Matrices

#include<stdio.h>

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


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

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


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

printf("\n");
}
}
void Multiplication(int a[10][10], int b[10][10], int c[10][10], int m, int n, int q)

Prepared By: M. Parthasaradhi, Asst. Prof.


{
int i, j, k;
for( i=0; i<m; i++)
for( j=0; j<q; j++)
{
c[i][j] = 0;
for( k=0; k<n; k++)
c[i][j] += a[i][k] * b[k][j];
}
} 12
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

int main()
{
int a[10][10], b[10][10], c[10][10];
int m, n, p, q;
printf("Enter The Size of Matrix A: ");
scanf("%d%d", &m, &n);
printf("Enter The Size of Matrix B: ");
scanf("%d%d", &p, &q);
if( n != p)
{
printf("Matrix Multiplication is not possible!");
printf("Number of Columns First Matrix is eualto number of Rows in Second Matrix");
return 0;
}
printf("Matrix Multiplication is Possible\n");

printf("Enter %d Integers into Matrix A:\n", m*n);


Enter_Elements(a, m, n);

printf("Enter %d Integers into Matrix B:\n", p*q);


Enter_Elements(b, p, q);

printf("Matrix A Elements are:\n");


Display_Elements(a, m, n);

Prepared By: M. Parthasaradhi, Asst. Prof.


printf("Matrix B Elements are:\n");
Display_Elements(b, p, q);

Multiplication(a, b, c, m, n, q);

printf("Multiplication of Matrix A and Matrix B is:\n");


Display_Elements(c, m, q);

return 0;
} 13
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

Output:
Enter The Size of Matrix A: 2 2
Enter The Size of Matrix B: 2 2
Matrix Multiplication is Possible
Enter 4 Integers into Matrix A:
12
34
Enter 4 Integers into Matrix B:
10
01
Matrix A Elements are:
1 2
3 4
Matrix B Elements are:
1 0
0 1
Multiplication of Matrix A and Matrix B is:
1 2
3 4

Prepared By: M. Parthasaradhi, Asst. Prof.

14
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

Week 3
Write a C program that uses functions to perform the following operations:
i) To insert a sub-string in to a given main string from a given position.
ii) To delete n characters from a given position in a given string.
3.i. Write a C program that uses functions to insert a sub-string in to a given main string from a
given position.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void insert_substring(char str1[], char str2[], int p)


{
int l1, l2, i, j;
char str3[50];
l1 = strlen(str1);
l2 = strlen(str2);

for(i=0, j=0; j<p-1; j++, i++)


str3[i] = str1[j];

for(j=0; j<l2; j++,i++)


str3[i] = str2[j];

Prepared By: M. Parthasaradhi, Asst. Prof.


for(j = p-1; j<l1; j++, i++)
str3[i] = str1[j];

str3[i] = '\0';

strcpy(str1, str3);
}

15
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

int main()
{
char str1[20], str2[20];
int p;
printf("Enter the string1: ");
gets(str1);
printf("Enter the string2: ");
fflush(stdin);
gets(str2);
printf("Enter the position where the sub-string is to be inserted: ");
scanf("%d", &p);
insert_substring(str1, str2, p);
printf("After inserting the string is %s", str1);
}
Output:
Enter the string1: Good Morning
Enter the string2: Hello
Enter the position where the sub-string is to be inserted1
After inserting the string is HelloGood Morning

Prepared By: M. Parthasaradhi, Asst. Prof.

16
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

3.ii. Write a C program that uses functions to delete n characters from a given position in a given
string.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void Delete_Chars(char str1[], int p, int n)
{
int i,j;
for(i=0,j=0;str1[i]!='\0';i++,j++){
if(i==(p-1)){
i=i+n;
}
str1[j]=str1[i];
}
str1[j]='\0';
}
int main()
{
char str1[20];
int p, n;
printf("Enter the string1: ");
gets(str1);
printf("Enter the number of characters you want to delete: ");
fflush(stdin);
scanf("%d", &n);

Prepared By: M. Parthasaradhi, Asst. Prof.


printf("Enter the position where the sub-string is to be inserted: ");
scanf("%d", &p);
Delete_Chars(str1, p, n);
printf("The string after deletion of characters: %s", str1);
return 0;
}
Output:
Enter the string1: Good Morning
Enter the number of characters you want to delete: 6
Enter the position where the sub-string is to be inserted: 2
The string after deletion of characters: Grning
17
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

Week 4
a) Write a C program that displays the position or index in the string S where the
string T
begins, or – 1 if S doesn‘t contain T.
b) Write a C program to count the lines, words and characters in a given text.
4.A. Write a C program that displays the position or index in the string S where the string T begins,
or – 1 if S doesn‘t contain T.
#include<stdio.h>
#include<string.h>
int main()
{
char s[30], t[20];
char *found;
puts("Enter the first string: ");
gets(s);
puts("Enter the string to be searched: ");
gets(t);
found = strstr(s, t);
if(found)
printf("Second String is found in the First String at %d position.\n", found - s);
else
printf("-1");
return 0;
}

Prepared By: M. Parthasaradhi, Asst. Prof.


Output:
Enter the first string:
nagaraju
Enter the string to be searched:
raju
Second String is found in the First String at 4 position.

18
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

4.B. Write a C program to count the lines, words and characters in a given text.
#include<stdio.h>
int main()
{
char str[200];
int i, line = 1, word = 0, ch = 0;
printf("Enter string terminated with ~ :\n");
scanf("%[^~]", str);
for(i=0; str[i]!='\0'; i++)
{
if(str[i]=='\n')
{
line++;
word++;
}
else
{
if(str[i]==' '||str[i]=='\t')
{
word++;
ch++;
}
else {
ch++;
}
}
}

Prepared By: M. Parthasaradhi, Asst. Prof.


printf("\nCharacter counts = %d\n", ch);
printf("Word counts = %d\n", word);
printf("Line counts = %d\n", line);
return 0;
}
Output:
Enter string terminated with ~ :
Hello, how are you?
Welcome to the programming world.
Programming is fun.~

Character counts = 71
Word counts = 11
Line counts = 3
19
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

Week 5
a) Write a C Program to perform various arithmetic operations on pointer variables.
b) Write a C Program to demonstrate the following parameter passing mechanisms:
i) call-by-value ii) call-by-reference
5.A. Write a C Program to perform various arithmetic operations on pointer variables.
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Size of int = %d bytes \n", sizeof(int));
printf("Address of p variable is %u \n",p);
printf("p+2 = %u \n",p+2);
printf("p-2 = %u \n",p-2);
printf("p++ = %u \n",p++);
printf("p-- = %u \n",p--);
return 0;
}
Output:
Size of int = 4 bytes
Address of p variable is 6487704
p+2 = 6487712
p-2 = 6487696

Prepared By: M. Parthasaradhi, Asst. Prof.


p++ = 6487704
p-- = 6487708

20
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

5.B.i. Write a C Program to demonstrate call-by-value


#include<stdio.h>
void swap(int, int) ;
int main( )
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("Before swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ;
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}

void swap(int a, int b)


{
int temp ;
temp = a ;
a=b;
b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20

Prepared By: M. Parthasaradhi, Asst. Prof.


After swap: num1 = 10, num2 = 20

21
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

5.B.ii. Write a C Program to demonstrate call-by-reference


#include<stdio.h>
void swap(int*, int*) ;
int main( )
{
int num1, num2 ;
printf("Enter two numbers: ");
scanf("%d%d",&num1,&num2);
printf("Before swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ;
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
return 0;
}
void swap(int *a, int *b)
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Enter two numbers: 10 20
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10

Prepared By: M. Parthasaradhi, Asst. Prof.

22
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

Week 6
Write a C program that uses functions to perform the following operations:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers
(Note: represent complex number using a structure.)
6. Write a C program that uses functions to perform the following operations:
i) Reading a complex number
ii) Writing a complex number
iii) Addition of two complex numbers
iv) Multiplication of two complex numbers

#include <stdio.h>
#include <stdlib.h>
struct complex
{
int real, img;
};

int main()
{
int choice, x, y, z;
struct complex a, b, c;

Prepared By: M. Parthasaradhi, Asst. Prof.


printf("Enter a and b where a + ib is the first complex number:");
scanf("%d%d", &a.real, &a.img);
printf("Enter c and d where c + id is the second complex number:");
scanf("%d%d", &b.real, &b.img);

//Addition
c.real = a.real + b.real;
c.img = a.img + b.img;
printf("\nSum of the complex numbers = %d + %di", c.real, c.img);
23
Department of CSE :: ALTS :: ATP
C-Programming & Data Structures Lab (20A05201P):: Week l - Week 6

//Multiplication
c.real = a.real*b.real - a.img*b.img;
c.img = a.img*b.real + a.real*b.img;
printf("\nMultiplication of the complex numbers = %d + %di", c.real, c.img);
return 0;
}
Output:
Enter a and b where a + ib is the first complex number:2 5
Enter c and d where c + id is the second complex number:3 4

Sum of the complex numbers = 5 + 9i


Multiplication of the complex numbers = -14 + 23i

Prepared By: M. Parthasaradhi, Asst. Prof.

24
Department of CSE :: ALTS :: ATP
Code: 20A05201T R20
B.Tech I Year I Semester (R20) Regular Examinations August/September 2021
C-PROGRAMMING & DATA STRUCTURES
(Common to IT, ME, FT, CSE, AI&ML, DS, IoF, AI and AI&DS)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) What are the basic data types supported in C programming language?
(b) Why is C called the mother of all languages?
(c) What are static variables and functions?
(d) Differentiate between actual parameters and formal parameters.
(e) What are the operations that can be performed on stack?
(f) Write the applications of stack.
(g) What is singly linked list?
(h) What is a circular linked list? Give an example.
(i) Define BFS with an example.
(j) What is a spanning tree?

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 (a) Explain different decision statements in C language.
(b) What is an array? What are the advantages of arrays over ordinary variables?
OR
3 (a) Explain how arrays are declared and initialized with suitable example.
(b) Write a c program to shift input data by two bits right.
UNIT – II
4 (a) Explain about defining the structure and accessing the structure members with examples.
(b) Explain various dynamic memory allocation functions with examples.
OR
5 (a) Explain the concept of pointer to functions with examples.
(b) Explain any five string handling functions with examples.
UNIT – III
6 (a) Explain the procedure to evaluate postfix expression:
623+-382/+*243+
(b) Explain the procedure to convert infix to postfix using stack.
OR
7 (a) Explain the various operations on a stack.
(b) Explain the basic operations of queue with pseudo code.
UNIT – IV
8 (a) List various operations of linked list and explain how to insert a node anywhere in the list.
(b) Write an algorithm to push and pop an element from linked stack.
OR
9 (a) Explain basic operations of circularly linked lists with suitable example.
(b) Describe how a node can be deleted at a user specified position in a doubly linked list.
UNIT – V
10 (a) Explain the inorder and preorder traversals of a binary tree with suitable example.
(b) Explain about depth first search with suitable examples.
OR
11 (a) Write a short note on connected components.
(b) Sort the elements using selection sort: 52, 38, 81, 22, 48, 13, 69, 93, 14, 45, 58, 79, 72.

***** Page 1
Code: 20A05201T R20
B.Tech I Year I Semester (R20) Regular Examinations November 2021
C-PROGRAMMING & DATA STRUCTURES
(Common to CE, EEE, ECE)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) Define one-dimensional array with suitable example.
(b) Define polynomial ADT?
(c) Explain command line arguments.
(d) Define functions.
(e) What are the disadvantages of representing a stack or queue by linked list?
(f) Convert the following expression into postfix A-B*C+D-E+F/G-H.
(g) What are the limitations of doubly linked lists?
(h) Write the advantages and disadvantages of double linked lists.
(i) Define a full binary tree.
(j) How do you find the degree of a graph?

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 What are the different types of arrays? Give example of each array type and how two-dimension
arrays are represented in memory.
OR
3 Explain in detail about elements of C language

UNIT – II
4 (a) What is recursion? Explain about argument passing techniques.
(b) List and explain string handling functions.
OR
5 (a) Explain different storage classes in detail.
(b) Define pointers. How to declare and initialize pointers, explain with example?
UNIT – III
6 (a) Explain about array representation of stack

OR
7 (a) Write a C program to implement multiple stacks using single array.
(b) Convert the infix expression a / b – c +d * e – a * c into postfix expression and trace that
postfix expression for given data a = 6, b = 3, c = 1, d = 2, e = 4.
UNIT – IV
8 With C-statements, explain how do you create a node, add and delete on a singly linked
list with proper message where each node is containing the details of employee in the form
of Empid, EmpName, Empaddr, and Empsalary as data fields.
OR
9 (a) W hat is a linked list? Explain the different types of linked list with neat diagram.
(b) Explain Circular linked list with example.
UNIT – V
10 With example, explain BFS and DFS.

OR
11 What is a binary tree? State its properties? How it is represented using array and linked
list give example

*****
Page 2
Code: 19A05101T R19
B.Tech I Year I Semester (R19) Supplementary Examinations August/September 2021
PROBLEM SOLVING & PROGRAMMING
(Common to all branches)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) Compare and contrast flowchart and algorithm.
(b) Write the pseudo code to find the given year is a leap year or not.
(c) What will happen if an algorithm does not stop after a finite number of steps?
(d) What is top-down design of problem solving?
(e) What is the difference between a constant and variable?
(f) Write a sample program for ternary operator.
(g) Distinguish between Call by value and Call by reference.
(h) Recall the possible arithmetic operations on pointers in C language?
(i) List some miscellaneous functions in C.
(j) What is the use of typedef?

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 Explain the fundamental units of a computer with a block diagram.
OR
3 (a) Discuss about the classification of computers.
(b) List out the way how algorithm may be represented.
UNIT – II
4 Write algorithm for.
(a) Generation of the Fibonacci sequence.
(b) Reversing the digits of an integer.
OR
5 (a) Illustrate the steps involved in problem solving techniques with neat sketch.
(b) Justify, why C program is called as top-down approach?
(c) Why is verification of an algorithm is important step in problem solving?
UNIT – III
6 (a) What are storage classes? Explain each with an example.
(b) What is recursion? Give an example program.
OR
7 (a) Explain in detail about the formatted and unformatted I/O functions in C.
(b) Compare: (i) Break and continue. (ii) While and Do while.
Contd. in page 2

Page 1 of 2 Page 3
Code: 19A05101T R19
UNIT – IV
8 (a) Write a C program to remove the duplicate elements from an order array.
(b) What are command line arguments? Explain with an example program.
OR
9 (a) Write C program to print the prime numbers less than 500.
(b) What is the output of the following program? Illustrate important steps in your answer.
main ()
{ int a=8, b=4, c;
*p1=&a, *p2=&b;
c=*p1**p2-*p1/ *p2+9;
printf (“%d”,c); }
UNIT – V
10 (a) Write a C program to search an element in a sorted array using binary search.
(b) How will you declare variable-length arguments in C? Explain with an example.
OR
11 (a) Write a C program to store the employee information using structure and search a particular
employee using employee number.
(b) Differentiate between structures and unions.

*****

Page 2 of 2 Page 4
Code: 19A05101T R19
B.Tech I Year I Semester (R19) Regular Examinations January 2020
PROBLEM SOLVING & PROGRAMMING
(Common to all branches)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) What is a compiler? Give example.
(b) Write the algorithm for finding the area of a given square.
(c) List the important steps in solving a problem.
(d) Give an example showing how redundant computations make an algorithm inefficient.
(e) What is type conversion? Give an example.
(f) Illustrate the use of break in loop statements with an example.
(g) What is a command line argument? How do you pass a command line arguments to a C-
program?
(h) Let int a[5] = { 1, 3, 5, 7, 9}. What is the value output of: printf("%d", *(a+2)). Justify your
answer.
(i) What is the use of typedef in C? Give an example.
(j) What are bit-fields? Give an example.

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 (a) Explain in detail about the working of a computer.
(b) Write an algorithm to compute the roots of given quadratic equation.
OR
3 (a) Explain in detail about the strategy designing algorithms with suitable examples wherever for
necessary.

UNIT – II
4 (a) Explain the top-down approach for problem solving.
(b) How do you measure the efficiency of an algorithm9 Explain with an example.
OR
5 (a) Design an algorithm that reads a set of numbers from the user and makes a count of the
number of negative and the number of non-negative members in the set.
(b) Write an algorithm for computing the sum of all even numbers in the range 1 to n (including
both 1 an n). Trace you algorithm for n = 10.
UNIT – III
6 (a) Explain in detail about the arithmetic, relational and logical operators in C with suitable
examples.
OR
7 (a) What is function? What are the advantages of using functions in a C-program? Write C-
function for exchanging the values of two given variables.
(b) Write a C-program for computing the sum of first n terms of the following series using for loop.
S = 1 -3+7-9+11 -13+ …….. 'n' terms.
Contd. in page 2

Page 1 of 2 Page 5
Code: 19A05101T R19
UNIT – IV
8 Design and write algorithm for finding the square root of a given integer. Trace your
algorithm for input value 16.
OR
9 (a) What is a pointer and pointer to a pointer? Illustrate the declaration and use of pointers
and pointer to a pointer in C with suitable example program.
(b) Write an algorithm for reversing the array elements. Trace your algorithm for the
following array of size 10.
a[10] = { 12, 3, 4, 48 87, 54, 67, 43, 78, 19 }

UNIT – V
10 Design and write an algorithm to sort a given set of randomly ordered integers into non-descending
order using insertion method. Trace your algorithm for the following list of integers.
78 43 9 2 12 45 98 22
OR
11 (a) Explain the difference between structures and unions with the help of a C-program.

(b) Illustrate the passing of structures to functions through an example.

*****

Page 2 of 2 Page 6
Code: 15A05101

B.Tech I Year I Semester (R15) Regular & Supplementary Examinations December 2016
COMPUTER PROGRAMMING
(Common to CE, EEE, CSE, ECE, ME, EIE and IT)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) Define precedence and order of evaluation.
(b) List the importance of Flowchart.
(c) Write syntax of If-else statements.
(d) How one Dimensional array is initialized?
(e) Discuss the problems associated with pointers.
(f) Define type qualifiers.
(g) Define function prototype. Give the general syntax of function prototype.
(h) Why do we need structures?
(i) What is the problem with getchar ()?
(j) Define Stream. List different types of Streams.

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 (a) Write an algorithm to find the distance between two points in plane.
(b) With an example, explain the structure of C program.
OR
3 (a) Explain the bitwise operators and relation operators available in C program.
(b) Evaluate the following expressions:
(i) a*(3+b)/2-c++ *b where a=3,b=4 and c=5
(ii) !(4+5*0>=6-4)
UNIT – II
4 (a) Explain switch case statement with an example program.
(b) Write a C program to check whether a given number is Palindrome or not.
OR
5 (a) Explain for loop statement with syntax with an example.
(b) Define an array. Write a program to find the largest and smallest element in a given array.
UNIT – III
6 (a) Define Pointer. Write a C program to find the sum of the all elements in given array using pointers.
(b) Define scope. Briefly explain the scope, life time and visibility of Identifier.
OR
7 (a) List the different storage classes in C and explain each one of them.
(b) Write a C program to exchange the value of two integers using call by reference.

Contd. in page 2

Page 1 of 2 Page 7
Code: 15A05101 R15

UNIT – IV
8 (a) Define structures. Write a C program using functions to return the sum of two complex numbers
passed as parameters.
(b) Explain enumerated data types with an example.
OR
9 (a) Define union. Differentiate between union and structures.
(b) With an example program, explain structure within structure.
UNIT – V
10 (a) Explain fprintf() and fscanf() functions with an example program.
(b) Define Preprocessor directives. Discuss Marco replacement with an example.
OR
11 (a) Write a C program that reads characters from the keyboard and writes them to a disk file until the
user types a dollar sign.
(b) What is Flushing a Stream? Discuss function like Macro With an example.

*****

Page 2 of 2 Page 8
Code: 15A05101 R15
B.Tech I Year I Semester (R15) Regular Examinations December/January 2015/2016
COMPUTER PROGRAMMING
(Common to CE, EEE, CSE, ECE, ME, EIE and IT)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) Find and remove the error in the following C statement.
a >b ? g = a : g = b;
(b) Define algorithm.
(c) What is the use of continue key word?
(d) Consider the following declaration of 2D-array in C:
char a[R][C];
Assume that char type require one bytes of memory and that array is stored starting from memory
address 2015, find the address of a[i][j].
(e) Write the syntax of dynamic allocation functions in C language.
(f) Give syntax to create a pointer to function.
(g) What is the role of stack in recursion?
(h) Why to use typedef?
(i) Define a file.
(j) What is the use of the preprocessor directives?

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 (a) List and explain the various symbols used in flowchart with figures.
(b) Write a C Program to find maximum number among three numbers using conditional operator.
OR
3 (a) Write an algorithm to find product of two integers using repetitive addition.
(b) Evaluate the following expressions:
(i) 4-768/(6*^2).
(ii) 8^2*2-100+50/5(25-5).
UNIT – II
4 (a) There are four coins a, b, c, d out of which three coins are of equal weight and one coin is heavier.
Write a C program to find the heavier coin.
(b) Explain the ways in which we can pass a one dimension array to functions.
OR
5 (a) Give a note on iteration statements in C language.
(b) A program P reads in 500 integers in the range (0,100) representing the scores of 500 students. It
then prints the frequency of each score above 50. Implement program P in C language.
UNIT – III
6 Give a detailed note on pointer expressions.
OR
7 List and explain the storage classes with examples.
Contd. in page 2

Page 1 of 2 Page 9
Code: 15A05101 R15
UNIT – III

8 (a) Write a recursive function in C to find the sum of array elements.


(b) Explain the following:
(i) Structure with in structure.
(ii) Self reference structure.
OR
9 (a) . Write the recursive function to compute f(n).
(b) How to pass the structures to functions as an argument? Explain with a suitable example.
UNIT – V
10 Describe the following file functions.
(a) fopen().
(b) fclose().
(c) getc().
(d) putc().
(e) feof().
OR
11 (a) How to use fseek() for random access of the file content?
(b) Explain about Macros with an example.

*****

Page 2 of 2

Page 10
Code: 15A05101 R15
B.Tech I Year I Semester (R15) Supplementary Examinations June 2016
COMPUTER PROGRAMMING
(Common to CE, EEE, CSE, ECE, ME, EIE and IT)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) What is the size of integer data type?
(b) Illustrate in which order any mathematical expression is evaluated.
(c) What is the size required to store any array of 25 integers?
(d) Explain call by reference.
(e) What does this statement indicate p = **a; where p and a are variables?
(f) How many maximum arguments can be passes by return ( )?
(g) Define command line arguments.
(h) Declare a struct name containing field’s first_name, middle_name, last_name within a struct
student.
(i) How to define a global constant?
(j) Write a statement to open a file in reading mode.

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 Write an algorithm to add a list of n elements and display them in ascending order.
OR
3 Write a program in ‘C’ language to print the Fibonacci series.
Fibonacci series is 0, 0, 1, 1, 2, 3, 5, 8, 13, 21
UNIT – II
4 What is the condition to multiply two matrices? Write a ‘C’ program to multiply two matrices.
OR
5 Write a program to print an array in reverse order.
UNIT – III
6 Write a function to swap two integer elements.
OR
7 Explain pointers and arrays with some example programs.
UNIT – IV
8 Differentiate between structure and unions.
OR
9 Write a program using command line to print the statement “I am proud of my country”.
UNIT – V
10 Explain FILE structure in detail.
OR
11 Describe formatted input output statements.

*****

Page 11
Code: 15A05101 R15
B.Tech I Year I Semester (R15) Regular & Supplementary Examinations December 2016
COMPUTER PROGRAMMING
(Common to CE, EEE, CSE, ECE, ME, EIE and IT)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) Define precedence and order of evaluation.
(b) List the importance of Flowchart.
(c) Write syntax of If-else statements.
(d) How one Dimensional array is initialized?
(e) Discuss the problems associated with pointers.
(f) Define type qualifiers.
(g) Define function prototype. Give the general syntax of function prototype.
(h) Why do we need structures?
(i) What is the problem with getchar ()?
(j) Define Stream. List different types of Streams.

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 (a) Write an algorithm to find the distance between two points in plane.
(b) With an example, explain the structure of C program.

3 (a) Explain the bitwise operators and relation operators available in C program.
(b) Evaluate the following expressions:
(i) a*(3+b)/2-c++ *b where a=3,b=4 and c=5
(ii) !(4+5*0>=6-4)
UNIT – II
4 (a) Explain switch case statement with an example program.
(b) Write a C program to check whether a given number is Palindrome or not.
OR
5 (a) Explain for loop statement with syntax with an example.
(b) Define an array. Write a program to find the largest and smallest element in a given array.
UNIT – III
6 (a) Define Pointer. Write a C program to find the sum of the all elements in given array using pointers.
(b) Define scope. Briefly explain the scope, life time and visibility of Identifier.
OR
7 (a) List the different storage classes in C and explain each one of them.
(b) Write a C program to exchange the value of two integers using call by reference.

Contd. in page 2

Page 1 of 2

Page 12
Code: 15A05101 R15

UNIT – IV
8 (a) Define structures. Write a C program using functions to return the sum of two complex numbers
passed as parameters.
(b) Explain enumerated data types with an example.
OR
9 (a) Define union. Differentiate between union and structures.
(b) With an example program, explain structure within structure.
UNIT – V
10 (a) Explain fprintf() and fscanf() functions with an example program.
(b) Define Preprocessor directives. Discuss Marco replacement with an example.
OR
11 (a) Write a C program that reads characters from the keyboard and writes them to a disk file until the
user types a dollar sign.
(b) What is Flushing a Stream? Discuss function like Macro With an example.

*****

Page 2 of 2

Page 13
Code: 15A05101
R15
B.Tech I Year I Semester (R15) Supplementary Examinations June 2017
COMPUTER PROGRAMMING
(Common to CE, EEE, CSE, ECE, ME, EIE and IT)

Time: 3 hours Max. Marks: 70


PART - A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) Define computer hardware.
(b) List the data types and their sizes of C language.
(c) Give an example of iteration statements in C.
(d) Illustrate with an example, the declaration and initialization of an array.
(e) Discuss any two storage class specifiers.
(f) What are the problems with pointers?
(g) Illustrate the need of structures with an example.
(h) Differentiate between structure and union types.
(i) Write a sample C program to demonstrate the control string of scanf() function.
(j) Discuss the types of streams.

PART - B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT - I
2 (a) Write an algorithm to find the roots of a quadratic equation.
(b) List and explain the various symbols used in flowchart with figures.
OR
3 (a) Write an algorithm to check the given number is perfect number or not.
(b) Explain the bitwise operators and relation operators available in C program.

UNIT - II
4 Discuss selection statements with a suitable example for each.
OR
5 Write a C program for matrix multiplication.
UNIT - III
6 Explain dynamic memory allocation functions of C with a suitable example.
OR
7 Compare call by value with call by reference and explain using a suitable example.

UNIT - IV
8 Write a C program to demonstrate the use of array of structures.
OR
9 What is union? Write a C program to store information in a union and display it.

UNIT - V
10 Write a C program to read name and marks of N number of students from user and store them in a file.
OR
11 Write a C program to demonstrate the use of fscanf and fprintf functions.

Page 14
Code: 15A05101 R15

B.Tech I Year I Semester (R15) Regular & Supplementary Examinations December 2017
COMPUTER PROGRAMMING
(Common to CE, EEE, CSE, ECE, ME, EIE and IT)
Time: 3 hours Max. Marks: 70
PART - A
(Compulsory Question)

1 Answer the following: (10 X 02 = 20 Marks)


(a) Differentiate between algorithm and program.
(b) What is the main difference between variable and constant? List any two constants
used in C.
(c) Explain pointer to an array with an example.
(d) Define break and continue statements along with their syntax.
(e) What is meant by storage class of variable?
(f) What is pointer? Give its General form.
(g) Write any two differences between union and structure.
(h) What is the use of typedef?
(i) What is a pre-processor?
(j) What role does the fseek() plays and how many arguments does it Have?

PART - B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT - I
2 What is an Algorithm? Write an algorithm to compute factorial of a number n where n>= 0.
OR
3 Explain the following operators: (i) Arithmetic operator. (ii) Relational operator. (iii)
Logical operator. (iv) Increment & decrement operator. (v) Conditional operator.
UNIT- II
4 What do you mean by a loop? Explain the difference between the do loop, while loop, and for
loop with the help of an example.
OR
5 (a) Write a C function for searching an element in an array of size N. Assume that elements
in array are stored in ascending order.
(b) Explain the declaration int (*p (char `a))(10].
UNIT - III
6 What is meant by the scope of variables and summarize types of storage class in C?
OR
7 Write a program to assign any number at random to an integer variable k and display the
same through pointer.
UNIT- IV
8 What is the difference between a structure declaration and a structure initialization?
OR
9 Define a function & explain why function prototype is essential.
UNIT- V
10 Write different built-in (library) functions provided by 'C' language for handling I/O
operations on files.
OR
11What are the features of C preprocessor? Give the differences between macros and functions.
Page 15
Code: 15A05101 R15
B.Tech I Year I Semester (R15) Supplementary Examinations June 2018
COMPUTER PROGRAMMING
(Common to all branches)
Time: 3 hours Max. Marks: 70
PART – A
(Compulsory Question)
*****
1 Answer the following: (10 X 02 = 20 Marks)
(a) What are the bitwise operators in C?
(b) Justify the significance of operator precedence with an example.
(c) List the string functions in C.
(d) Write a C program for call by reference.
(e) Illustrate with a suitable example the use of return statement.
(f) Explain malloc() function.
(g) Illustrate recursion with an example.
(h) What is the use of typedef in C?
(i) Discuss pre-processor directives in C.
(j) List the basic console I/O functions.

PART – B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT – I
2 (a) Discuss about procedural oriented languages.
(b) Explain in detail about the software development method.
OR
3 (a) Write an algorithm to find the distance between two points in plane.
(b) Explain the bitwise operators and relation operators available in C
UNIT – II
4 What are the different types of arrays in C? Explain with a suitable example, array
declaration,initialization and accessing of the elements for these different types.
OR
5 Write a C program to calculate the sum of all elements of an array using pointers as arguments.
UNIT – III
6 What is a pointer? Write a program in C to reflect the concept of pointers to functions.
OR
7 Illustrate with an example, the significance of argc and argv arguments passed to the main function.
UNIT – IV
8 Explain all the function prototypes with examples.
OR
9 Demonstrate with a suitable example, the use of structure within a structure.
UNIT – V
10 Write a program in C to illustrate the use of rewind and fseek functions.
OR
11 Write a program in C that reads files and displays them on the screen.

*****

Page 16
Code: 15A05101
R15
B.Tech I Year I Semester (R15) Regular & Supplementary Examinations November/December 2018
COMPUTER PROGRAMMING
(Common to all branches)
Time: 3 hours Max. Marks: 70
PART - A
(Compulsory Question)
1 Answer the following: (10 X 02 = 20 Marks)
(a) What is software? Give at least two examples for system software and application software.
(b) Write an a:gorithm to find the largest number among three numbers.
(c) Distinguish between continue and break statements.
(d) Write a program in C to find the sum of numbers present in an array.
(e) Li st the advant ages of functi on s.
(f) Predict the result for the fo: owing code
const int i = 5:
i++:
printf("i value = `Yod",i):
(g) D e f i n e r e c u r s i o n .
(h) In what way actual arguments differ from formal arguments.
(i) Write the syntax to read string from the keyboard. Give example.
(j) How can we read the character and set of characters? Give examples for each one .
PART - B
(Answer all five units, 5 X 10 = 50 Marks)
UNIT -1
2 (a) Using conditional operator write a C program to find the largest number from two numbers.
(b) Draw the typical b ock diagram for a computer. Explain it in detail.
OR
3 (a) What is a flow chart? List and explain the different notations used to represent a flowchart.
(b) Write a C program to find the sum of first six natural numbers.
UNIT - II
4 (a) How arrays differ from normal variables? Write a C program to find the largest number present
in an array.
(b) In what way if statements differ from switch case statements.
OR
5 Write a program in C language to perform the matrix multiplication.
UNIT - III
6 (a) Describe the pointer to pointer mechanism.
(b) Illustrate the mechanism of passing the pointer variables as arguments to the functions.
OR
7 How can we define the scope of a function? List the rules for defining the scope of a variable. Give
brief description about the differ storage specifiers.
UNIT – IV
8 (a) Distinguish between structures and unions.
(b) Explain with example structures within structures.
OR
9 (a) List the advantages of using functions. In what way a built - in function differs from user defined
(b) Write short notes on command line arguments.
UNIT - V
10 (a) Write and explain the different types of files.
(b) Describe the macros with suitable example.
OR
11 (a) Give brief description about the various modes of a file.
(b) Explain the role of files in C programming.
Page 17

You might also like