Cracking The C Interview PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 320

Cracking the C Interview

Praveen Kumar D | Hari Krishna B | Farooq S


Copyright
c 2017 authors

P UBLISHED BY S KILL S UBSIST I MPELS LTD

Licensed under Skill Subsist Impels Ltd - Non Commercial 3.0 Unported License (the “License”).
You may not use this file except in compliance with the License. You may obtain a copy of the
License at http://skillsubsist.in. Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an “AS IS ” BASIS , WITHOUT WARRANTIES
OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.

First printing, Jan 2017


About Company

Skill Subsist Impels ltd is a Tirupati based company Deft in Training,IT and HR services
started by two enthusiastic Entrepreneurs Mr Kiran Kumar Dasari and Lakshmi Prasad Reddy T.
Skill Subsist is gate way for career and professional development. Right person for Right job is the
main motto of our company. SSIL has proven excellence in IT,ITES, Training to enhance the better
platform to job aspirants as well as employees. It’s a multi benefit usher for both companies and
employees.

More: http://skillsubsist.in
Free Online Exams: http://skillsubsist.in/exams
About Authors
D PRAVEEN KUMAR, Currently working as Ph. D Research scholar (Full-Time) in Yogi Vemana
University from the Department of Computer Science & Engineering under the guidance of Dr. C.
Naga Raju, Associate professor and Head Department of Computer Science and Engineering. He is
Former Assistant professor and placement coordinator at Bapatla Engineering College, Bapatla, AP
& Sree Venkateswara College of Engineering, Nellore, AP and also Worked as Assistant Professor
in Sri Venkatesa Perumal College of Engineering and Technology, Puttur, AP. He completed Master
in Technology and Bachelor in Technology at JNTUA, Ananthapuramu with Distinction. He had
certificates like PGDCA from Ministry of HRD recognized institute, Technical Teacher Training
from NITTTR, Chennai , Basics of Computer from NIIT, Big Data Analytics With Hadoop and
RHadoop from Skill Subsist Impels Ltd. He Published one International journal and three Inter-
national conference proceedings in IEEE, ACM and Springer. Given FDP and seminars on Big
data analytics in various colleges in AP. He is a member of SWIDC, CSTA, UACEE, IAENG,
IJCSIT, CSI and Swecha. Interested subjects are Programming in C, C++, JAVA, Python, PHP &
R, Operating Systems, Algorithms, Storage Area Networks and Big Data. Research areas are Big
Data Analytics.

BOMMALA HARIKRISHNA, Currently working as Full Time Ph.D Research scholar in Y.S.R
E.C of Yogi Vemana University, Proddatur from the department of Computer Science & Engineering
under the guidance of Dr. S. Kiran, Assistant Professor, department of CSE. He is Former Lecturer
and In-Charge coordinator of QEEE at JNTUA College of Engineering Pulivendula, Pulivendula,
Kadapa, AP and also Worked as Assistant Professor in A1 GLobal Institute of Engineering and
Technology, Markapuram, AP. He completed Master in Technology at Acharya Nagarjuna Uni-
versity, Guntur and Bachelor in Technology at JNTU Kakinada. He had received Best QEEE
In-Charge through out India by MHRD with IIT Chennai. He published eighteen international
journals and conference, four International conference proceedings published in IEEE explore
and one international conference proceeding published in SCIENCE Directory with Elsevier. He
published five National journals and conference. He is a member of SWIDC, ISTE, ISTE, UACEE,
IAENG, IJCSE, IJCSA and ITHISTORY. He published two text books one is the fundamental of C
- language and other one is Data Structures lab. Interested subjects are Programming in C, C++,
JAVA, Python, PHP & R, Operating Systems, Algorithms, Data Structures and Big Data. Research
areas are cloud computing and data security in cloud computing.

S M FAROOQ, Currently working as Full time PhD Research scholar in Y.S.R Engineering Col-
lege of Yogi Vemana University from the department of Computer Science & Engineering under
the guidance of Dr. S. Kiran, Assistant Professor, department of CSE. He completed Master in
Technology at School of Information Technology (SIT), JNTU Hyderabad and Bachelor in Technol-
ogy at Madina Engineering College, Kadapa affiliated to JNTU Hyderabad. He had certificates on
Database Programming using SQL from Oracle Academy and problem solving in C, Introduction
Modern Application Development form NPTEL. He published three international journals and one
International conference proceedings published in IEEE explore. He is a member of IEEE, IEI and
ISTE. His research areas are theoretical cryptography, cryptanalysis on block ciphers, and hash
functions.
Contents

1 Technical Preparation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 How to Prepare for Technical Questions 1
1.2 General Advice for Technical Questions 1
1.3 Five Steps to a Technical Questions 2
1.4 Top Ten Mistakes Candidates Make 3
1.5 Errors and debugging 5
1.5.1 Compiler Trappable Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5.2 Errors not trappable by a compiler (run time errors) . . . . . . . . . . . . . . . . . . . . . . 5
1.5.3 Tracing Errors/ Locating a problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5.4 Pathological Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5.5 Porting Programs between computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Introduction to C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1 Introduction 7
2.1.1 Computer Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Program Development Steps 9
2.3 History & Evolution of C 9
2.4 Basic Structure of C Program 10
2.5 Multiple Choice Questions 11

3 C Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.1 Character Set 13
3.2 C Tokens 13
3.2.1 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2.2 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2.3 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2.4 Variables : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2.5 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.3 Multiple Choice Questions 18

4 Operators & Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23


4.1 Arithmetic Operators 23
4.2 Assignment Operators 24
4.3 Relational operators 25
4.4 Unary Operator 25
4.4.1 Unary minus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.4.2 Increment and Decrement operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.5 Bitwise operators 26
4.6 Logical operators 27
4.7 Conditional operator 28
4.8 Special operators 28
4.9 Operator Precedence 29
4.10 Expressions 30
4.11 Expression Evaluation 30
4.11.1 Rules for Expression Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.12 Type Conversion 31
4.12.1 Implicit Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.13 Multiple Choice Questions 32

5 Basic Input and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41


5.1 Unformatted IO 41
5.1.1 getch() & getche() . . ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.1.2 getchar() . . . . . . . . . . ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.1.3 putchar() and putch() .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.1.4 gets() & puts() . . . . . . ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.2 Formatted IO 43
5.2.1 printf() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
5.3 scanf Function 46
5.3.1 Reading Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.3.2 Reading Float . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.3.3 Reading single character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.3.4 Reading String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.3.5 Search sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.4 Blocks 48
5.5 Multiple Choice Questions 49
5.6 Example Programs 52
6 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
6.1 if statement 57
6.1.1 Simple if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
6.1.2 if..else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
6.1.3 Nested if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
6.1.4 else..if Ladder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
6.2 Conditional Operator 62
6.3 switch statement 63
6.4 goto 65
6.5 Example Programs 66
6.6 Multiple Choice Questions 68

7 Looping Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
7.1 while loop 75
7.2 do-while loop 76
7.3 for loop 77
7.3.1 Comma operator : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.3.2 break & continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.3.3 exit() : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7.4 Example Programs 79
7.5 Multiple Choice Questions 103

8 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
8.1 Introduction 111
8.1.1 Importance of functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
8.2 User-Define function 111
8.3 Type of Functions 113
8.4 Storage Classes 116
8.4.1 Types of Storage Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.4.2 Scope of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.5 Standard Library Functions 120
8.5.1 Commonly used Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.6 Recursion 120
8.7 Header file 123
8.8 C Preprocessor 123
8.8.1 Simple string replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.8.2 Macro expansion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
8.8.3 File Inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
8.8.4 Conditional Inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
8.9 Example Programs 125
8.10 Multiple Choice Questions 126
9 Arrays & Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
9.1 Introduction 137
9.2 One-Dimensional Arrays 137
9.2.1 Array declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.2.2 Array Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.2.3 Storage and Accessing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.2.4 Size of an array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
9.3 Two-Dimensional Arrays 139
9.3.1 Array declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.3.2 Array Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.4 Multi-Dimensional Arrays 140
9.5 Strings 140
9.5.1 Declaration and Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.5.2 Reading a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
9.5.3 Writing a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
9.6 String Operations 142
9.7 String Handling Functions 142
9.8 Example Programs 143
9.9 Multiple Choice Questions 157

10 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
10.1 Introduction 163
10.1.1 Pointer Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
10.1.2 Pointer Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.2 Types Of Pointers 165
10.2.1 Null Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
10.2.2 Dangling Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
10.2.3 Generic Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
10.2.4 Wild Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
10.2.5 Complex Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
10.2.6 Near Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
10.2.7 Far Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
10.2.8 Huge Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
10.3 Pointer Arithmetic 169
10.3.1 Adding integer value with Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
10.3.2 Incrementing Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
10.3.3 subtracting integer value from pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
10.3.4 Decrementing pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
10.3.5 Subtracting pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
10.3.6 Comparing two pointer variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
10.4 Pointers & Functions 178
10.5 Pointers and Arrays 180
10.5.1 Passing an entire array to a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
10.5.2 Passing array elements to functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
10.5.3 Accessing array element in different ways . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
10.6 Character pointers and Functions 182
10.7 Array of Pointers 184
10.8 Pointer to Functions 184
10.9 Pointer to Pointers 185
10.10 Pointers and Multi dimentional Arrays 187
10.11 Dynamic Memory Allocation 187
10.11.1 malloc() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
10.11.2 calloc() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
10.11.3 realloc() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
10.11.4 free() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
10.12 Example Programs 190
10.13 Multiple Choice Questions 191

11 Structures & Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205


11.1 Declaration of Structure 205
11.2 Definition of Structure 205
11.3 Structure Initialization 206
11.4 Accessing Elements in Structure 207
11.4.1 Comparision of Structure Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
11.5 Array of Structures 208
11.6 Array With in Structure 210
11.7 Nested Structures 210
11.8 Structures and Functions 210
11.9 Structure and pointers 212
11.10 Self-Referential Structures 212
11.11 Union 213
11.11.1 Accessing Union elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
11.12 Multiple Choice Questions 214

12 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
12.1 Types of Files 219
12.2 Streams 219
12.3 Standard IO 220
12.3.1 I/O Functions : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
12.3.2 Character oriented I/O functions: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
12.3.3 Formatted I/O Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
12.4 File Operations 221
12.4.1 Closing a file . . . . . . . . . . . . . . . . .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
12.4.2 Character I/O on files . . . . . . . . . .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
12.4.3 getw AND putw FUNCTIONS . . . . .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
12.4.4 THE fprintf AND fscanf FUNCTIONS ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
12.5 Error Handling 225
12.6 Example Programs 226
12.7 Multiple Choice Questions 229

A Interview Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

B Coding Interview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249


B.1 Coding Interview Questions 249
B.2 List of Basic Programs 270

C GATE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273

D Mock Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287


D.1 Mock Test 1 287
D.2 Mock Test 2 295
D.3 Mock Test-3 301
1. Technical Preparation

1.1 How to Prepare for Technical Questions


That said, there are better and worse ways to prepare. Many candidates just read through problems
and solutions. Don’t do that! Memorizing or trying to learn specific questions won’t help you!
Rather, do this:
1. Try to solve the problem on your own. I mean, really try to solve it. Many questions are
designed to be tough - that’s ok! When you’re solving a problem, make sure to think about
the space and time efficiency. Ask yourself if you could improve the time efficiency by
reducing the space efficiency, or vice versa.
2. Write the code for the algorithm on paper. You’ve been coding all your life on a computer,
and you’ve gotten used to the many nice things about it. But, in your interview, you won’t
have the luxury of syntax highlighting, code completion, or compiling. Mimic this situation
by coding on paper.
3. Type your paper code as-is into a computer. You’ll probably have made a bunch of mistakes.
Start a list of all the mistakes you made, so that you can keep these in mind in the real
interview.
4. Do a mock interview.

1.2 General Advice for Technical Questions


Interviews are supposed to be difficult. If you don’t get every - or any - answer immediately, that’s
ok! In fact, in my experience, maybe only 10 people out of the 120+ that I’ve interviewed have
gotten the question right instantly.
So when you get a hard question, don’t panic. Just start talking aloud about how you would
solve it.
And, one more thing: you’re not done until the interviewer says that you’re done! What I mean
here is that when you come up with an algorithm, start thinking about the problems accompanying
it. When you write code, start trying to find bugs. If you’re anything like the other 110 candidates
that I’ve interviewed, you probably made some mistakes.
2 Chapter 1. Technical Preparation

1.3 Five Steps to a Technical Questions


A technical interview question can be solved utilizing a five step approach:
1. Ask your interviewer questions to resolve ambiguity.
2. Design an Algorithm
3. Write pseudo-code first, but make sure to tell your interviewer that you’re writing pseudo-
code! Otherwise, he/she may think that you’re never planning to write "real"’ code, and
many interviewers will hold that against you.
4. Write your code, not too slow and not too fast.
5. Test your code and carefully fix any mistakes.

Step 1: Ask Questions


Technical problems are more ambiguous than they might appear, so make sure to ask questions
to resolve anything that might be unclear or ambiguous. You may eventually wind up with a very
different - or much easier - problem than you had initially thought. In fact, many interviewers
(especially at Microsoft) will specifically test to see if you ask good questions.
Good questions might be things like: What are the data types? How much data is there? What
assumptions do you need to solve the problem? Who is the user?
Example: "Design an algorithm to sort a list."
• Question: What sort of list? An array? A linked list?
Answer: An array.
• Question: What does the array hold? Numbers? Characters? Strings?
Answer: Numbers.
• Question: And are the numbers integers?
Answer: Yes.
• Question: Where did the numbers come from? Are they IDs? Values of something?
Answer: They are the ages of customers.
• Question: And how many customers are there?
Answer: About a million.
We now have a pretty different problem: sort an array containing a million integers between 0 and
130. How do we solve this? Just create an array with 130 elements and count the number of ages at
each value.

Step 2: Design an Algorithm


While you’re designing your algorithm, don’t forget to think about:
1. What are the space and time complexities?
2. What happens if there is a lot of data?
3. Does your design cause other issues? (i.e., if you’re creating a modified version of a binary
search tree, did your design impact the time for insert / find / delete?)
4. If there are other issues, did you make the right trade-offs?
5. If they gave you specific data (e.g., mentioned that the data is ages, or in sorted order), have
you leveraged that information? There’s probably a reason that you’re given it.

Pseudo-Code
Writing pseudo-code first can help you outline your thoughts clearly and reduce the number of
mistakes you commit. But, make sure to tell your interviewer that you’re writing pseudo-code first
and that you’ll follow it up with "real" code. Many candidates will write pseudo-code in order to
’escape’ writing real code, and you certainly don’t want to be confused with those candidates.
1.4 Top Ten Mistakes Candidates Make 3

Code
You don’t need to rush through your code; in fact, this will most likely hurt you. Just go at a nice,
slow methodical pace. Also, remember this advice:
• Use Data Structures Generously: Where relevant, use a good data structure or define your
own. For example, if you’re asked a problem involving finding the minimum age for a
group of people, consider defining a data structure to represent a Person. This shows your
interviewer that you care about good object oriented design.
• Don’t Crowd Your Coding: This is a minor thing, but it can really help. When you’re writing
code on a whiteboard, start in the upper left hand corner - not in the middle. This will give
you plenty of space to write your answer.
Test
Yes, you need to test your code! Consider testing for:
• Extreme cases: 0, negative, null, maximums, etc
• User error: What happens if the user passes in null or a negative value?
• General cases: Test the normal case.
If the algorithm is complicated or highly numerical (bit shifting, arithmetic, etc), consider testing
while you’re writing the code rather than just at the end.
Also, when you find mistakes (which you will), carefully think through why the bug is occuring.
One of the worst things I saw while interviewing was candidates who recognized a mistake and
tried making "random" changes to fix the error.
For example, imagine a candidate writes a function that returns a number. When he tests his
code with the number ’5’ he notices that it returns 0 when it should be returning 1. So, he changes
the last line from "return ans" to "return ans+1," without thinking through why this would resolve
the issue. Not only does this look bad, but it also sends the candidate on an endless string of bugs
and bug fixes.
When you notice problems in your code, really think deeply about why your code failed before
fixing the mistake.

1.4 Top Ten Mistakes Candidates Make


#1 |Practicing on a Computer
If you were training for a serious bike race in the mountains, would you practice only by biking on
the streets? I hope not. The air is different. The terrain is different. Yeah, I bet you’d practice in the
mountains.
Using a compiler to practice interview questions is like this - and you’ve basically been biking on
the streets your entire life. Put away the compiler and get out the old pen and paper. Use a compiler
only to verify your solutions.
#2 | Not Rehearsing Behavioral Questions
Many candidates spend all their time prepping for technical questions and overlook the behavioral
questions. Guess what? Your interviewer is judging those too! And, not only that - your performance
on behavioral questions might bias your interviewer’s perception of your technical performance.
Behavioral prep is relatively easy and well-worth your time. Looking over your projects and
positions and think of the key stories. Rehearse the stories.
#3 | Not Doing a Mock Interview
Imagine you’re preparing for a big speech. Your whole school, or company, or whatever will be
there. Your future depends on this. And all you do to prepare is read the speech to yourself. Silently.
In your head. Crazy, right?
Not doing a mock interview to prepare for your real interview is just like this. If you’re an engineer,
4 Chapter 1. Technical Preparation

you must know other engineers. Grab a buddy and ask him/her to do a mock interview for you. You
can even return the favor!

#4 | Trying to Memorize Solutions


Quality beats quantity. Try to struggle through and solve questions yourself; don’t flip directly to
the solutions when you get stuck. Memorizing how to solve specific problem isn’t going to help
you much in an interview. Real preparation is about learning how to approach new problems.

#5 | Talking Too Much


I can’t tell you how many times I’ve asked candidates a simple question like "what was the hardest
bug on Project Pod?", only to have them ramble on and on about things I don’t understand. Five
minutes later, when they finally come up for air, I’ve learned nothing - except that they’re a poor
communicator. When asked a question, break your answer into three parts (Situation / Action /
Response, Issue 1 / Issue 2 / Issue 3, etc) and speak for just a couple sentences about each. If I want
more details, I’ll ask!

#6 | Talking Too Little


Psst - let me tell you a secret: I don’t know what’s going on in your head. So if you aren’t talking,
I don’t know what you’re thinking. If you don’t talk for a long time, I’ll assume that you aren’t
making any progress. Speak up often, and try to talk your way through a solution. This shows your
interviewer that you’re tackling the problem and aren’t stuck. And it lets them guide you when you
get off-track, helping you get to the answer faster. And it shows your awesome communication
skills. What’s not to love?

#7 | Rushing
Coding is not a race, and neither is interviewing. Take your time in a coding problem - don’t rush!
Rushing leads to mistakes, and reveals you to be careless. Go slowly and methodically, testing
often and thinking through the problem thoroughly. You’ll finish the problem in less time in the
end, and with fewer mistakes.

#8 | Not Debugging
Would you ever write code and not run it or test it? I would hope not! So why do that in an
interview? When you finish writing code in an interview, "run" (or walk through) the code to test it.
Or, on more complicated problems, test the code while writing it.

#9 |Sloppy Coding
Did you know that you can write bug-free code while still doing horribly on a coding question? It’s
true! Duplicated code, messy data structures (i.e., lack of object oriented design), etc. Bad, bad,
bad! When you write code, imagine you’re writing for real-world maintainability. Break code into
sub-routines, and design data structures to link appropriate data.

#10 | Giving Up
Have you ever taken a computer adaptive test? These are tests that give you harder questions the
better you do. Take it from me - they’re not fun. Regardless of how well you’re actually doing, you
suddenly find yourself stumbling through problems. Yikes!
Interviewing is sort of like this. If you whiz through the easy problems, you’re going to get
more and harder problems. Or, the questions might have just started out hard to begin with! Either
way, struggling on a question does not mean that you’re doing badly. So don’t give up or get
discouraged. You’re doing great!
1.5 Errors and debugging 5

1.5 Errors and debugging

Debugging can be a difficult process. In many cases compiler errors are not generated because the
actual error which was present but because the compiler got out of step. Often the error messages
give a completely misleading impression of what has gone wrong.

1.5.1 Compiler Trappable Errors


• Missing semicolon;
• Missing brace
• Mistyping Upper Lower Case
• Missing inv comma
• Variable not declared or scope wrong
• Using a function or assignment inside a macro
• Forgetting to declare a function which is not type int
• Type mismatch in expressions

1.5.2 Errors not trappable by a compiler (run time errors)


• Confusion of = and ==
• Missing & in scanf
• Confusing C++ and ++C
• Unwarranted assumptions about storage of arrays/structures
• Number of actual and formal parameters does not match
• Conversion string in scanf or printf wrong
• Accidental confusion of int short and char
• Arrays out of bounds
• Mathematical Error
• Uncoordinated Output using put/get I/O
• Global Variables and Recursion

1.5.3 Tracing Errors/ Locating a problem


Complex bugs can be difficult to locate. Here are some tips for fault finding:
• Try to use local variables, in preference to global ones for local duties. Never rely on global
variables for passing messages between functions.
• Check variable declarations and missing parameters.
• Check that a program has not run out of private memory. (If it repeatedly crashes for no
apparent reason, this could be a cause.) Make the program stack size bigger if that is possible.
• Use statements like printf("program is now here") to map out the progress of a program and
to check that all function calls are made correctly.
• Use statements like ch = getchar() to halt a program in certain places and to find out the
exact location at which things go wrong.
• Try "commenting out" lines of suspect code. In other words: put comment markers around
lines that you would like to eliminate temporarily and then recompile to pinpoint errors.
• Check that the compiler disk has not been corrupted (make a new copy) - getting desperate
now!
• Try retyping the program, or using a filter which strips out any illegal characters which might
have found their way into a program.
• Get some sleep! Hope the problem has gone away in the morning.
6 Chapter 1. Technical Preparation

1.5.4 Pathological Problems


Problems which defy reasonable explanations are called pathological or ‘sick’. Sometimes these
will be the result of misconceptions about C functions, but occasionally they may be the result of
compiler bugs, or operating system design peculiarities. Consider the following example which
was encountered while writing the simple example in the chapter on Files and Devices, subsection
‘Low Level File Handling’: in that program a seemingly innocent macro defined by

#define CLRSCRN() putchar('\f');

1.5.5 Porting Programs between computers


Programs written according to the style guidelines described in this book should be highly portable.
Nevertheless, there are almost inevitably problems in porting programs from one computer to
another. The most likely area of incompatibility between compilers regards filing operations, espe-
cially scanf(). Programmers attempting to transfer programs between machines are recommended
to look at all the scanf() statements first and to check all the conversion specifiers with a local
compiler manual. scanf() is capable of producing a full spectrum of weird effects which have
nothing to do with I/O. Here are some more potential problems to look out for:
• Assumptions about the size of data objects such as int and float can be risky.
• Check conversion characters in printf() and scanf() as some compilers choose slightly
different conventions for these.
• The stack size for (memory available to) a program is likely to vary between systems. This
can cause errors at run time if a program runs out of space, even though there is nothing
wrong with the code.
• Check for functions which rely on the speed of a particular computer. For example, pause()
or wait loops. Some computers may scarcely notice counting to 50000, whereas others may
labour at it for some time!
• Check for assumptions made about file names. e.g. limited/unlimited size, valid characters
etc..
2. Introduction to C

2.1 Introduction
Definition 2.1.1 — Computer. It is an electronic machine which accepts data as its input,
process to it by doing some kind of manipulations and produce the output in a desired format.
Technically a computer is a high speed electronic data processing machine.

2.1.1 Computer Programming Languages


Computer programming means giving instructions to a computer, in the language which computer
understands. Instructions can be written in two different languages. They are 1. Low Level
Language, 2. High Level Language.
Low Level Language
These are basically two types, they are : 1. Machine Language, 2. Assembly Language.
1. Machine Language : A computer is an electronic machine which can understand any
instruction given to it in a coded form. Since its memory can store only 0s and 1s, the
instruction must be given to computer in binary code. A program written in binary coded
form (or any other coded form like Hexa, Octal, etc.,) that can be directly fed into the
computer for execution is known as machine Language. Machine language differs from
processor to processor. Writing a program in machine language is a very difficult and
cumbersome process. Machine language contains instructions written in very long numerical
chains and it is very difficult to remember the code.
2. Assembly Language : It is a symbolical language to reduce the programmers burden, de-
veloped in 1950s. This language permits the use of alphanumeric symbols (numbers and
letters) instead of numeric operations. An assembly language program contains mnemonics
because it is also called mnemonical language. Mnemonic means that the information can be
memorized easily and is generally in the form of abbreviations. Assembly language is not
cumbersome to use as the machine language. It is machine oriented.

Machine language (Vs) Assembly language :


8 Chapter 2. Introduction to C

(a) Execution of machine language program is faster than the assembly language program,
because there is no conversion in machine language.
(b) Reading and writing the assembly language programs are easy for programmers, it is
difficult in machine language.
(c) Machine instructions are difficult to remember, where as mnemonics are easy to re-
member.
(d) Introduction of data to program is easier in Assembly language, while it is difficult in
machine language.

High-Level Languages :

A set of languages developed which are very close to our native languages, are called High-
Level languages. High level languages were designed to provide high level control structures,
Input/Output facilities, hardware independents and so on. A single instruction or statement in a
high level language produces a number of machine language instructions. High level languages can
be put into four general categories.
They are : (i) Scientific languages (ii) Commercial languages (iii) Special purpose languages
(iv) Multipurpose languages. Ex. : BASIC, COBOL, FORTRAN, PASCAL and C.
Advantages:
1. Easy to learn and easy to understand than machine or assembly languages.
2. Takes less time to write.
3. Easy to maintain.
4. Better documentation
Definition 2.1.2 — Algorithm. An algorithm is the step-by-step logical procedure for solving
a problem. Each step is called an instruction. An algorithm can be written in English like
sentences or in any standard representation. The algorithm written in English like language is
called ‘pseudo code’. All algorithms must satisfy the following properties.
1. Input: Zero or more inputs.
2. Output: At least one quantity is produced.
3. Definiteness: Each instruction is clear and unambiguous.
4. Finiteness: The algorithm should terminate after a finite number of steps. It should not
enter into an infinite loop.
5. Effectiveness: Each operation must be simple and should complete in a finite time.

A problem can have several algorithms. Each algorithm represents a different way of solving the
given problem. For example, there are several different algorithms for sorting the n numbers. In
such a situation we would like to pick up the best or most efficient algorithm for the given problem.
Therefore we need a way of characterizing the efficiency of an algorithm. Time complexity is one
way of characterizing the efficiency or work to be done by an algorithm.
Definition 2.1.3 — Flowchart. A flowchart is a pictorial representation of an algorithm. It
shows the flow of operations in pictorial form and any error in the logic of the problem can be
detected very easily.

A flowchart uses different shapes of boxes and symbols to denote different types of instructions.
These symbols are connected by solid lines with arrow marks to indicate the operation flow.
Normally an algorithm is represented in the form of a flowchart and the flowchart is then expressed
in some programming language to prepare a computer program.
2.2 Program Development Steps 9

2.2 Program Development Steps


Generally programmers can be broadly categorized as two types such as successful and nonsuc-
cessful programmer. The second category programmers rush to their keyboards and begin coding,
i.e. the actual writing of instructions. But its is the last stages task for the successful programmers.
There are many more important steps to consider first.
Understand the problem : Unless the problem is clearly understood, you cannot even begin to
solve it. This seems like a truism until you appreciate that a program specification seldom
gives all the facts required by the programmer. The professional programmer is a pessimist,
because from past experience there is always some importance information which is omitted.
This needs to be identified first.
Examine the data : Programs are written to work on data. Unless one knows exactly how the
data is organized, what it ’looks’ like, etc., the program which processes it cannot be written.
This fact becomes clearer the more one writes programs, but it is a fact all too frequently
overlooked by the novice.
Plan the output : The output should be planned next. Not only does this help to ensure that
nothing is omitted from the program, but it helps to get a clear picture of what the program is
trying to achieve and whether the programmer really does understand the problem.
Designing the solution : There are many ways of designing solution, so much so that entire books
are devoted to this subject alone. Computer scientists frequently say that programming is
like any engineering task in that the program has to be designed and constructed in much
the same way as any engineering project. A motorway is not built by starting at point A and
steadfastly pushing on to point X. Rather, months are spent in planning; charts designed;
sub-tasks identified as well as those which cannot begin until others have been completed;
broad designs are developed and later more detailed designs constructed. It is only after a
long planning period and the most effective order of the sub-tasks is agreed upon that the
construction crew actually begins the work. Programming requires the same painstaking
processes, with the end result standing or falling by the amount of care and attention invested
in the planning stage.
Selecting test data : How can one ensure that once a program is eventually working the results it
produces are ’correct’? The answer is simple common sense. Try the program out on some
data to which the answers have been worked out in advance. If they match, the program
should be all right. Selecting effective test data is a serious exercise and the more significant
the program, the more care needs to be taken in the selection.
The actual coding : At this stage, one can begin to code the detailed program designs into program
instructions of a given language. If all the previous steps have been completed with due
diligence, this coding should be almost ’automatic’. The chances are high that a fairly
successful program will result first time around. Although it may still contain bugs (errors),
these should be fewer and relatively easy to identify and correct.
Testing : The program can be tested with the test data, results checked and any errors amended.
When all is correct, the program can be released and set to work on live data.

2.3 History & Evolution of C


’C’ seems a strange name for a programming language, but it is one of the most popular pro-
gramming languages today. ’C’ was originally developed in the 1970’s by Dennis Ritchie at Bell
Telephone Laboratories Inc. ’C’ was an offspring of the BCPL (Basic Combined Programming
Language) called B. The C language is often described as a "Middle-level" language, because it
combines the best features of high level languages with the control and flexibility of assembly
language. C is a general purpose structured programming language that has much in common with
10 Chapter 2. Introduction to C

the best of the high-level language.

Features and Applications of ’C’ language :


1. ’C’ is general purpose structured programming language.
2. ’C’ is powerful efficient, compact and flexible.
3. ’C’ is highly portable.
4. ’C’ is a robust language, whose rich set of built-in functions and operators can be used to
write any program.
5. ’C’ is well suited for writing system software, as well as application programming.
6. ’C’ has the ability to extend itself. We can continuously add our own functions to the existing
’C’ library functions.
7. ’C’ programs can be run on any of the different computers with little or no alteration.
8. ’C’ is widely available Commercial. ’C’ compilers are available on most personal computers,
mini and mainframes.
9. ’C’ language allows reference to a memory location with the help of pointer which holds the
address of the memory location.
10. ’C’ language allows dynamic allocation of memory i.e. a program can request the operating
system to allocate/release memory.
11. ’C’ language allows manipulations of data at the lowest level i.e. bit level manipulation. This
feature is extensively useful in writing system software programs.
12. C is a case sensitive language

2.4 Basic Structure of C Program


A ’C’ program is a group of building blocks called functions. A function is a subroutine that may
include one or more statements designed to perform a specific task. To write a C program, we first
create functions and then put them together. Any C program may contain one or more sections as
shown in the below.

Figure 2.1: Basic Structure of a C Program


2.5 Multiple Choice Questions 11

Document Section: This section consisting of comments specifies the name of the program, author
and other details. These comments beginning with the two characters /* and ending with the
characters */. No space can be included between these pairs of characters (delimiters), any
characters may be included in either uppercase or lowercase.
Link Section: This section provides the compiler to link functions from the system library (Ex:
stdio.h, math.h etc.,).
Definition Section: This section defines all symbolic constants.
Global Declaration Section: Some variables are used in one or more function; such variables are
called Global variables and are declared in this section i.e. outside of all the functions.
Main function section: Every C program must have atleast one function i.e. main() function. This
main section have two parts (1) declaration part and (2) execution part. The declaration part
declares all the variables that are used in the executable part. There is at least one statement
in the executable part. These two parts can appear between the opening and closing braces.
In all C programs execution begins at this opening brace and ends at this closing brace. The
closing brace of this function section is the logical end of the program. All the declaration
and executable statements end with a semicolon.
Subprogram section: This section contains user defined functions that are mentioned in the main
function. User defined functions are generally placed immediately after the main function.
All sections, except the main function section may be absent when they are not required.

Example
This is a example program to print a string.

1. /* A sample C program */
2. main()
3. {
4. /* prints the string */
5. printf("Welcome to C world \n");
6. }

In the above program first and fourth lines are commented lines. These are used in a program
to enhance its readability and understanding. Comment lines are not executable statements i.e.
anything between /* and */ is ignored by the compiler. These comment lines can be inserted
wherever we want them in the program.
The second line informs the system that the name of the function is main and the execution
begins at this line. The main() is a special function used in the C language to tell the computer
where the program starts. The empty pair of parentheses immediately following main indicates that
the function has no arguments.
In the third line the opening brace ’{’ indicates the beginning of the function main and in the
last line the closing brace ’}’ indicates the end of the function. All the statements between these
two braces is the function body. Here the function body consists of two statements, one is comment
line and another one is printf line is an executable statement. The printf is a predefined function to
print the characters which appear in between quotation marks, here the output will be "Welcome to
C World".

2.5 Multiple Choice Questions


1. Who developed the C language? [ C ]
(A) Ken Thompson (B) Bjarne Stroustrup (C) Dennis Ritchie (D) Kernighan
2. When was the C language developed? [ B ]
12 Chapter 2. Introduction to C

(A) 1970 (B) 1972 (C) 1975 (D) 1976


3. Algorithm written in English like language is called ____ [ B ]
(A) Object Code (B) Pseudo Code (C) Source Code (D) None
4. ____ is a pictorial representation of an algorithm. [ C ]
(A) Program (B) Language (C) Flow chart (D) None
5. Flow chart symbols are standardized by ____ [ B ]
(A) ASCII (B) ANSI (C) IBM (D) None
6. ____ symbol is used to indicate a pause < HALT > [ A ]
(A) Oval (B) Parallelogram (C) Rectangle (D) Circle
7. ____ symbol is used to represent arithmetic operation [ C ]
(A) Oval (B) Parallelogram (C) Rectangle (D) Circle
8. The logical processing of moving data from one location of the main memory to another is
denoted by ____ symbol. [ C ]
(A) Oval (B) Parallelogram (C) Rectangle (D) Circle
9. Double sided rectangle is used to represent ____ [ A ]
(A) Predefined process(B) Input/Output (C) Computing (D) None
10. ____ symbol is used to represent the comments [ A ]
(A) Bracket with broken line (B) Parallelogram
(C) Rectangle (D) Circle
11. A compiler compiles the source code [ B ]
(A) One line at a time (B) Complete program in one stroke
(C) Two lines at a time (D) Five lines at a time
12. An interpreter reads the source code of a program [ A ]
(A) One line at a time (B) Complete program in one stroke
(C) Two lines at a time (D) Five lines at a time
13. The C language is closely associated with ____ operating system [ B ]
(A) MS-DOS (B) Unix (C) MS-Windows (D) Linux
14. The extension for C program files by default is [ D ]
(A) ’cpp’ (B) ’exe’ (C) ’obj’ (D) ’.c’
15. C program should be written in [ B ]
(A) Uppercase (B) Lowercase (C) Titlecase (D) None of the above
16. C is a [ B ]
(A) High-level language (B) Middle-level language
(C) Low-level language (D) Machine language
17. Each statement in a C program is terminated with [ C ]
(A) Period(.) (B) Slash(/) (C) Semicolon(;) (D) Hash(#)
3. C Basics

3.1 Character Set


The characters that can be used to form words, numbers, expressions, data types, constants, variables
and keywords, etc., The characters in C are grouped into four categories.
Alphabets (Letters) : A,B,C,D . . . X,Y,Z, a,b,c,d. . . . x,y,z
Digits : 0,1,2,3,4,5,6,7,8,9
Symbols : $, & , *, ( , )
White Spaces : Blank space, horizontal tab, vertical lab, carriage return, new line, form feed

3.2 C Tokens
The smallest individual unit in a program is called token.
The C tokens are classified as Keywords, Identifiers, Constants, Operators, Strings and Special
symbols.

3.2.1 Keywords
In ’C’ every word is classified into either a keyword or an identifier. Keywords have fixed meaning
and it cannot be changed and it must be written in lowercase. These words serve as basic building
blocks for program statements. There are 32 keywords in ANSI C.

auto break case char


continue default do double
else enum extern float
for goto if int
long register return short
signed sizeof static struct
switch typedef union unsigned
void volatile while
14 Chapter 3. C Basics

3.2.2 Identifiers
Identifiers are user defined names consisting of a sequence of letters and digits, used to refer the
names of the variable, functions, arrays, etc., It must begin with an alphabet or underscore and
should not contain white space. Both uppercase and lowercase letters are permitted; an uppercase
is not equivalent to the corresponding lowercase letter, although lowercase letters are commonly
used. It cannot be a keyword. It can be of any length, most of the C compiles will recognize only
first eight characters.

3.2.3 Constants
Constants are fixed values that do not change during the execution of a program. For example in
the equation 5X+2Y=45 since 5, 2 and 45 cannot change, these are called Constants, whereas the
quantities X & Y can vary or change and hence these are called Variables.

Figure 3.1: Clasification of Constants

Numeric Constants :
Numeric constants are classified into 1. Integer constants and 2. Real constants.
1. Integer Constant : An integer constant is a sequence of digits without a decimal point; no
commas, no blank spaces are allowed. It could be either positive or negative; if no sign
precedes it is assumed to be positive. It ranges from -32768 to 32767. It may be specified in
Decimal, Octal or Hexa Decimal notation.
(a) Decimal Integer constant : It consists of a sequence of one or more decimal digits 0
through 9 preceded by an optional sign, the first digit of the sequence cannot be 0 unless
the decimal integer constant is 0.
Ex : 0 276 3412 31467 -7123
(b) An Octal Integer constants : It consists of the digit 0 followed by a sequence of one or
more Octal digits. 0 through 7.
Ex : 012 07134 07777
(c) A Hexa Decimal integer constant : It consists of the digit 0, followed by one of the
letter x or X, followed by a sequence of one or more Hexadecimal digits 0 through 9 or
letter a through f or A through F.
Ex : 0X1F 0XABC 0X9a2F 0XFFFF
2. Real Constant : A real constant is to be a sequence of digits with a decimal point, no commas,
blank spaces are allowed. It could be either positive or negative, if no sign precedes it is
assumed to be positive. The Scientific notation is often used to express numbers that are very
small or very large. Thus 0.000000011 is written as 1.1X10−8 and 20000000000as2X1010 .
C provide an exponential form for such numbers that are related to the scientific notation. In
exponential form of representation the real value will be represented in two parts. The part
appearing before ’e’ is called mantissa, where as the part following ’e’ is called exponent.
(coe f f icient)e(Integer) = (coe f f icient)X10(integer)

Character Constants :
Character constants are classified into 1. Single character constants and 2. String constants.
3.2 C Tokens 15

1. Single Character Constants : Any character written within single quotes is called Charac-
ter Constant. A character constant represents an integer value equal to the numerical value of
the character in the machine’s character code is known as ASCII value. Since each character
constant represents an integer value it is also possible to perform arithmetic operations on
character constants.
Example : ‘x’, ‘k’, ‘6’, ‘:’, ‘!’, ‘?’, ‘ ‘, ‘*’, ‘+’, ‘”’
2. String constant : A String constant is a sequence of characters enclosed within a pair of
double quotes. The characters may be letters, numbers, special characters and blank space
and etc., A string constant is also known as a String Literal.
Example : "hello" "1999" "5+4+6" "Good Bye"
The compiler automatically places a special character NULL at the end of the string constant. The
NULL character at the end of the string is known as the delimiter of the string. The difference
between a character constant and string constant is : ‘p’ character constant gives the ASCII value
of the character p whereas the string constant “p” contains the character p and NULL.

3.2.4 Variables :
A variable is a data name which can be used to store data and a variable may take different values
at different times, during execution.
For example in the equation 5X+2Y=45 since 5, 2 and 45 cannot change, these are called
Constants, whereas the quantities X & Y can vary or change; hence these are called Variables.

Rules for Constructing Variable Names :


1. A variable name is any combination of 1 to 8 alphabets, digits or underscore. Some compilers
allow variables names whose length could be upto 40 characters. Still it would be safe to
stick to its rule of 8 characters.
2. The first character in the variable name must be an alphabet.
3. No commas or blank spaces are allowed.
4. No special symbol other than an underscore can be used.
Valid Examples: Bas_pay, Net_sal, month , __a, num1, INT
Invalid Examples: $123, 1num, int, a1%

3.2.5 Data Types


Data is represented using numbers or characters. All compilers support a variety of data types.
Every programming language has its own data types. Each data type has predetermined memory
requirement and an associated range of legal values. C supports four different classes of data types
namely (1) Basic or Primary Data types (2) Derived Data types (3) User-defined Data types and (4)
Pointer Data types.

Figure 3.2: Clasification of Constants


16 Chapter 3. C Basics

Primary Data types


The following are the Primary C data types
Integer Data type : C offers three different integer data types they are : int, short int and long
int. The difference between these three integers is the number of bytes to occupy and the range of
values.

Figure 3.3: Clasification of integers

Float Data type : Like integers floats are divided into three types. They are float, double and
long double. The difference between these three floats are the number of bytes to occupy and the
range of values.

Figure 3.4: Clasification of float

Characters Data type : A char data type can store an element of machine’s character set and
will occupy 1 Byte. It is of two types, they are signed char and unsigned char. The difference
between these two types is the range of values.

Figure 3.5: Clasification of characters


3.2 C Tokens 17

Declaration of Variables
In any programming language any variable used in the program must be declared before it is used.
This declaration tells the compiler what the variable name and what type of data it holds. In C
language the declaration of a variable should be done in the declaration part of the program. The
type declaration statement is usually written at the beginning of the C program. Syntax :

<Data_type> <var1>, <var2>, . . ., <varn>;

Example :
int i, count;
float price, salary;
char c;
Scope of variables : Scope of variables implies to the availability within a program. Variables
have two types of scopes, Local and Global. A variable with a global scope is accessible to all
statements in a program but the one with local scope is restricted to be accessed only by certain
selected statements in the program, in which it is defined. The global variables are declared outside
all functions where as local variables are defined inside a function.
User define Data Types
The user defined data types are two types, they are :
1. Type definition : The users can define an identifier that represents an existing data type by a
feature known as "‘type definition"’. The user defined data type identifier can later be used to
declare variables.
General Form :
typedef type identifier;
Here type refers to an existing data type and identifier refers to the new name given to the
data type.
Ex :
typedef int sno;
typedef float salary;
Here sno symbolizes int, and salary symbolizes float. These can be used to declare variables
as follows.
sno c1, c2;
salary e1, e2;
2. Enumerated data type : Another user-defined data type is enumerated data type. The
user-defined enumerated data type can be used to declare variables that can have one of the
values out of many enumeration constants. After that we can declare variables to be of this
new type
General Form :
enum identifier {value1, value2, . . . , valueN};
Here the identifier is a user-defined enumerated data type which can be used to declare
variables that can have one of the values enclosed within the braces (known as enumeration
constants).
enum identifier v1, v2, . . , vn;
18 Chapter 3. C Basics

The enumerated variables v1, v2, . . , vn can only have one of the values value1, value2, . . ,
valueN.
Example:

enum month {January, February, . . , December};


enum month month_st, month_end;
(or)
enum month {January, February, . . , December} month_st, month_end;
Here the definition and declaration of enumerated variables can be combined in one statement.
Assigning Values to Variables
Values can be assigned to variables by using the assignment operator. An assignment statement
implies that the value of the variable on the left of the equal sign is equal to the value of the quantity
on the right.
Syntax :

variable_name = constant
’C’ permits multiple assignments in one line like a=10; b=20; c=30;
Variables declared can be assigned or initialized using an assignment operator ’=’. C permits the
initialization of more than one variable in one statement by using multiple assignment operators.

int x = y = 10;
x = y = z = 10;
a = b = c = temp;
Defining Symbolic Constants
Some constants may appear repeatedly in a number of places in the program. For example the
mathematical constant “pi” with the value 3.142. In any case if you want to change the value of pi
we have to search throughout the program, if any value is left, the program may produce wrong
result. To avoid this disadvantage C provides to define symbolic constants. General form :

#define symbolic-name value of constant


Example :

#define PI 3.142
#define MAX 100

3.3 Multiple Choice Questions


1. Which is not a character of C? [ A ]
(A) $ (B) ∧ (C) e (D) |
2. Which is not a C keyword? [ B ]
(A) const (B) main (C) sizeof (D) void
3. Identify the scalar datatype: [ A ]
(A) double (B) union (C) function (D) array
4. The qualifier that may precede float is : [ D ]
(A) signed (B) unsigned (C) long (D) none of the above
5. Identify the Octal constant: [ C ]
3.3 Multiple Choice Questions 19

(A) 637 (B) 0x25 (C) -0756 (D) 06.25


6. Identify the invalid constant: [ C ]
(A) "" (B) ’ ’ (C) ’in’ (D) ’\b’
7. Symbolic constants are defined as: [ A ]
(A) #define s1 s2 (B) #define s1=s2 (C) #define s1 s2; (D) #define s1=s2;
8. Identify the C token(s): [ D ]
(A) keywords (B) constants (C) operators (D) all above
9. Statement terminator in ’C’ is represented by: [ C ]
(A) : (B) blank (C) ; (D) \n
10. Which is an invalid variable name: [ C ]
(A) Ints (B) Xx (C) net-salary (D) floating
11. Identify invalid identifier [ A ]
(A) NET _$ (B) BINGO (C) _account (D) _4
12. Identify the wrong statement: [ D ]
(A) unsigned long int a,b; (B) long float f1;
(C) long double ld; (D) signed a;
13. A block is enclosed with pair of : [ A ]
(A) { } (B) ( ) (C) <>
14. The declaration of C variables can be done [ C ]
(A) anywhere in the program (B) in executable part
(C) in declaration part (D) at the end of the program
15. A short integer variable occupies memory [ B ]
(A) 1 byte (B) 2 bytes (C) 4 bytes (D) 8 bytes
16. A character variable can store only [ A ]
(A) 1 character (B) 10 characters
(C) 100 characters (D) none of the above
17. A variable name can be starts with [ C ]
(A) asterisk symbol (*) (B) hash symbol (#)
(C) underscore symbol (_) (D) none of the above
18. The variables are initialized using [ B ]
(A) greater than (>) (B) equal to (=)
(C) double equal to (==) (D) none of the above
19. C variable can start with [ A ]
(A) an alphabet (B) a number (C) dot (.) (D) none of the above
20. Identifiers are [ D ]
(A) C statements (B) user-defined names(C) reserved words (D) none of the above
21. The valid octal constants from the following [ D ]
(i) 0245 (ii) 0387 (iii) 04.32 (iv) –0467
20 Chapter 3. C Basics

(A) (i) and (ii) (B) (iii) and (iv) (C) (ii) and (iii) (D) (i) and (iv)
22. Find the invalid identifiers from the following:- [ C ]
(i) nA (ii) 2nd (iii) ROLL NO (iv) case
(A) (i), (ii) and (iv) (B) (i) and (iii) (C) (ii), (iii) and (iv) (D) (ii), (i) and (iii)
23. Which of the following is not an escape sequence? [ D ]
(A) \n (B) \r (C) \’ (D) \p
24. Determine which of the following is an invalid character constant. [ D ]
(A) ’\a’ (B) ’T’ (C) ’\0’ (D) ’/n’
25. Literal means [ B ]
(A) a string (B) a string constant (C) a character (D) an alphabet
26. If an integer needs two bytes of storage, then the maximum value of a signed integer is [ B
]
(A) 216 -1 (B) 215 -1 (C) 216 (D) 215
27. The first digit of a decimal constant must be [ D ]
(A) a zero (B) a non zero number (C) a negative number (D) an integer
28. Choose the correct answer [ C ]
(A) enum variable can not be assigned new values
(B) enum variable can be compared
(C) enumeration feature increase the power of C
(D) None of the above
29. What can be said of the following program ? [ B ]
main()
{
enum Months {JAN =1,FEB,MAR,APR};
Months X = JAN;
if(X==1)
{
printf("Jan is the first month");
}
}
(A) Does not print anything
(B) Prints : Jan is the first month
(C) Generates compilation error
(D) Results in runtime error
30. What is the output of following source code? [ C ]
main()
{
extern int i;
i=20;
printf("%d",i);
}
3.3 Multiple Choice Questions 21

(A) 20 (B) Compiler Error


(C) Linking Error (D) None of the above
31. What is the output of following source code? [ C ]

enum colors {BLACK,BLUE,GREEN}


main()
{
printf("%d..%d..%d",BLACK,BLUE,GREEN);
return(1);
}
(A) 1..2..3 (B) 2..2..3
(C) 0..1..2 (D) None of the above
32. Given the following statement enum day = jan = 1 ,feb=4, april, may What is the value of
may? [ C ]
(A) 4 (B) 5 (C) 6 (D) 11
33. What is th output of the following program?[ C ]

int x= 0x65;
main()
{
char x;
printf("%d\n",x)
}
(A) compilation error (B) ’A’ (C) 65 (D) unidentified
34. what is the value of e ?[ A ]

enum number { a=-1, b= 4,c,d,e}


(A) 7 (B) 4 (C) 5 (D) 15
35. Observe the below code

main()
{
float f=5,g=10;
enum{i=10,j=20,k=50};
printf("%d\n",++k);
printf("%f\n",f<<2);
printf("%lf\n",f%g);
printf("%lf\n",fmod(f,g));
}
Answer:
Line no 5: Error: Lvalue required
Line no 6: Cannot apply leftshift to float
Line no 7: Cannot apply mod to float
4. Operators & Expressions

Definition 4.0.1 — Operators. An operator is a symbol which represents a particular operation


that can be performed on data.

The data itself (which can be either a variable or a constant) is called the ’operand’.
C is rich in use of different operators are as follows.
1. Arithmetic
2. Assignment
3. Relational
4. Increment / Decrement
5. Bitwise
6. logical or Boolean
7. Conditional operator
8. Special

4.1 Arithmetic Operators


The following are the Arithmetic operators:

Operator Meaning Example


+ ADDITION a+b
− SUBSTRACTION a−b
* MULTIPLICATION a*b
/ DIVISION a/b
% MODULO DIVISION a%b

These operators are called ’binary’ operators as they operate on two operands at a time. Each
operand can be int, float or char.
If both operands are integers, then the expression is called an integer expression and the
operation is called integer arithmetic. Integer arithmetic always yields an integer value.
Examples: If a=14 and b=3 the
24 Chapter 4. Operators & Expressions

a + b is 17
a - b is 11
a * b is 42
a / b is 4
a % b is 2

In case of -ve numbers in modulo division operation, the sign of the result is only depends on the
sign of first operand.
Examples:

-14 % 3 = -4
-14 % -3 = -4
14 % -3 = 4
14 % 3 = 4

If both operands are real, then the expression is called an real expression and the operation
is called real arithmetic. A real operand may be either in decimal or exponential notation. Real
arithmetic always yields an real value. The modulus (%) operator cannot be used for
real operands. Examples: If a=14.8 and b=3.0 the

a + b is 17.800000
a - b is 11.800000
a * b is 44.400000
a / b is 4.9333333
a % b is INVALID OPERATION (ERROR)

If one of the operand is real and the other is integer then the expression is called mixed-mode
arithmetic expression. Here only the real operation is performed and the result is always in real
form.

15.0/10 is 1.500000
15/10.0 is 1.500000
15/10 is 1 (one)

4.2 Assignment Operators


Assignment operators are used to assign the result of an expression to a variable, Usual assignment
operator is ’=’.
Syntax :

variable = Expresion (or) Constant (or) Variable;

Example:

c = a + b;
c = 5;
c = a;

In addition C has a set of ’shorthand’ assignment operators. If the expression is


4.3 Relational operators 25

variable = variable operator Expression;


then, We can write as follows
variable operator= Expression;

The operator operator= is known as the shorthand assignment operator. The shorthand assignment
operators are ’+=’ is called add assignment operator, ’-=’ is called minus assignment operator, ’*=’
is called multiply assignment operator, ’/=’ is called divide assignment operator and ’%=’ is called
modulus assignment operator. Example:

a = a + 1; then we can write a += 1;

x += y is equivalent to x = x + y
x -= y is equivalent to x = x  y
x *= y is equivalent to x = x * y
x /= y is equivalent to x = x / y
x %= y is equivalent to x = x % y

4.3 Relational operators


The relational and equality operators are used to test or compare the values between two operands.
The relational and equality operators produce an integer result to express the condition of the
comparison. If the condition is false then the integer result is 0 (zero) otherwise the integer result is
non zero. The relational operators are as follows: The output of the relational operator is either

Operator Meaning Example


< LESSTHAN a<b
> GREATERTHAN a>b
<= LESSTHAN or EQUALS TO a <= b
>= GREATERTHAN or EQUALS TO a=>b
== EQUALS TO a == b
!= NOT EQUALS TO a!=b

0 (FALSE) or 1 (TRUE). All the relational operators are Binary operators because of taking two
input operands. Example: If a = 5 & b=10 then

a > b is 0
a < b is 1
a <= b is 0
a >= b is 1
a == b is 0
a != b is 1

4.4 Unary Operator


‘C’ includes a class of operator that acts upon a single operand to produce a new value, such
operators are known as Unary operators. Unary operators usually preceded their single operand.
Most commonly used unary operators are 1) Unary minus operator and 2) Increment and Decrement
operators.
26 Chapter 4. Operators & Expressions

4.4.1 Unary minus


Where a minus sign precedes a numerical constants, variables or an expressions. Where as the
unary minus operator is different from the arithmetic minus operator. Thus a negative number is
actually an expression consisting of unary minus operator.
Ex : x = -y;

4.4.2 Increment and Decrement operators


The increment (++) and decrement (–) operators are add one and subtract one. These operators
operate on only one operand and the operand has to be a variable. The add one or subtract one of
the value either before or after the value of the variable is used. If the operator appears before the
variable, it is called a prefix operator. If the operator appears after the variable, it is called a postfix
operator.
a++ and ++a is the same when the statements are independent. For example if a = 5 then a++
and ++a are same the value will be 6.
When the prefix ++ (or –) is used in an expression, the variable is incremented (or decremented)
first and then the expression is evaluated using the new value of the variable. Where as the postfix
++ (or –) is used in an expression, the expression is evaluated first using with the original values of
the variables and then the variable is incremented (or decremented) by one.
Consider the following :

a = 5;
b = a++;

In this case the value of a would be 6 and b would be 5. If we write the above statement as

a = 5;
b = ++a;

then the value of a would be 6 and b would be 6.

4.5 Bitwise operators


The smallest element in the memory on which we are able to operate is a bit. C supports several
Bitwise operators. These permit the programmer to access and manipulate individual bits within a
piece of data. The ‘C’ Bitwise operators can operate on ints and chars but not on float.

Operator Meaning Example


& Bitwise AND a&b
| Bitwise OR a|b
>> right shift a >> b
<< left shift a << b
˜ one’s complement ˜a
ˆ Bitwise XOR (exclusive OR) aˆb

1. Bit wise and operator : The operator is represented as & and operates on two operands.
While operating upon these two operands they are compared on a bit-by-bit basis. (Both the
operands must be of same type either chars or ints). The truth table and Examples for & is as
follows:
Examples:
4.6 Logical operators 27

X = 0000 0111 ( = 7)
Y = 0000 1000 ( = 8)
Z = X & Y = 0000 0000 ( = 0)

& 0 1
0 0 0
1 0 1

2. Bit wise or operator : The operator is represented as | and operates on two operands.
While operating upon these two operands they are compared on a bit-by-bit basis. (Both the
operands must be of same type either chars or ints). The truth table and examples for | is :
Example:

| 0 1
0 0 1
1 1 1

X = 0000 0111 ( = 7)
Y = 0000 1000 ( = 8)
Z = X | Y = 0000 1111 ( = 15)

3. One’s complement : The operator is represented as˜and operates on one operand. For a
binary number if we take one’s complement all zero’s become 1 and one’s become 0’s
Example:

X = 0001
~X = 1110
n
4. Right Shift : (>>) This operation will divide the given number by 2s i.e. x = 2s , where n is
the input number and s is the number of shifts.
Example :

x = 16
x = x>>3 After execution x will be 2.

5. Left Shift (<<) : This operation multiplies the given number by 2s i.e. x = n * 2s , where n
is the input number and s is the number of shifts.
Example :

x = 4
x = x<<2 After execution x will be 16.

In the case of -ve numbers insert 1 in the place of 0.


Except compliment all bitwise operators are Binary operator because they are taken two
operands rather complement requires only one operand.

4.6 Logical operators


Logical operators are used to combine two or more relations. The logical operators are called
Boolean operators. Because the tests between values are reduced to either true or false, with zero
28 Chapter 4. Operators & Expressions

Operator Meaning Example


&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a

being false and one being true. Except Logical NOT all logical operators are Binary operator
because they are taken two operands rather Not requires only one operand.
Following are the list of Logical operators:
The expressions can be connected like the following

(expression1) &&/|| (expression2)

Logical AND and Logical OR Works as follows:

Exp1 Exp2 Exp1&&Exp2 Exp1||Exp2


0 0 0 0
0 Non zero 0 1
Non zero 0 0 1
Non zero Non zero 1 1

4.7 Conditional operator


The conditional operator ? and : are sometimes called ternary operator since it operates on three
operands, and it is a condensed form of an if-then- else ’C’ statement. The general form is:

exp1 ? exp2 : exp3

Example:

y = (x > 5 ? 3 : 4) is equivalent to
if (x>5)
then
y = 3;
else
y = 4;

4.8 Special operators


Some commonly used special operators are
1. Comma operator : The comma(,) operator permits two different expressions, appears in a
situation where only one expression would ordinarily be used. The expressions are separated
by comma operator.

Ex: c = (a=10, b=20, a+b);

Here first the value 10 is assigned to a, followed by 20 is assigned to b and then calculate
a+b and result is assigned to c.
2. Size of operator : The size of operator returns the number of bytes the operand occupies in
memory. The operand may be a variable, a constant or a data type.

Ex : sizeof(int) is going to return 2


4.9 Operator Precedence 29

3. Address of operator : The address of’ operator (&) returns the address of the variable. The
operand may be a variable, a constant.

Ex : m = &n;
Here address of n is assigned to m. This m is not a ordinary variable, it is a variable which
holds the address of the other variable.
4. value at address operator : The value at address operator (*) returns the value stored at a
particular address. The ’value at address’ operator is also called ’indirection’ operator.

Ex : x = *m;
Here the value at address of m is assigned to x, and m is going to hold the address.

4.9 Operator Precedence


All arithmetic expressions may contain two or more operators, then we may have some problem
about how to get it exactly executed. To answer these questions one has to understand the precedence
of operators. The order of priority in which the operations are performed in an expression is called
precedence. The precedence of all operators is shown below.

Operator Meaning of operator Associativity


() Functional call Left to right
[] Array element reference
−> Indirect member selection
. Direct member selection
! Logical negation Right to left
Bitwise(1 ’s) complement
+ Unary plus
- Unary minus
++ Increment
– Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
* Multiply Left to right
/ Divide
% Remainder
+ Binary plus(Addition) Left to right
- Binary minus(subtraction)
<< Left shift Left to right
>> Right shift
< Less than Left to right
<= Less than or equals to
> Greater than
>= Greater than or equals to
== Equals to Left to right
!= Not equals to
& Bitwise AND Left to right
∧ Bitwise exclusive OR Left to right
30 Chapter 4. Operators & Expressions

| Bitwise OR Left to right


&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Left to right
= Simple assignment Right to left
*= Assign product
/= Assign quotient
%= Assign remainder
-= Assign difference
+= Assign sum
&= Assign bitwise AND
∧= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
, Separator of expressions Left to right

4.10 Expressions
An expression is a combination of variables, constants and operators arranged as per the syntax of
the language.

Algebraic Expression C Expression


(a – b)(c + d)e (a – b) * (c + d) * e
4x2+8y+10 4 * x * x + 8 * y + 10
a
b +c (a/b) + c
ab
c +d ((a * b) / c) + d

4.11 Expression Evaluation


Expressions are evaluated by using an assignment statement. The expressions is evaluated first and
then the result replaces the previous value of the variable on the left hand side. All variables used
in the expression must be assigned with values before evaluation is attempted.
Example of evaluation statement are :
x = b / c * a;
y = a – b / c + d;
z = a + b – c;

4.11.1 Rules for Expression Evaluation


• First parenthesized sub expressions from left to right are evaluated.
• If parentheses are nested, the evaluation begins with the innermost sub-expression i.e. the
innermost parenthesis will be solved first, followed by the second and so on.
• When parentheses are used, the expressions within parentheses assume highest priority.
• The precedence rule is applied for evaluating sub-expressions.
• The associativity rule is applied when two or more operators of the same precedence level
appear in a sub-expression. i.e. When two operators of the same priority are found in the
expression, precedence is given to the extreme left operator.
4.12 Type Conversion 31

4.12 Type Conversion


When an operator has different data types of operands it is in Mixed mode. C supports the use of
mixed mode operations in arithmetic expressions. Normally, before performing any operation we
have to see that both operands must have the same data type. C conversion one or both the operands
to the appropriate data types is called Type Conversion.
Type Conversion can be achieved by two methods, they are Implicit type Conversion and
Explicit Type Conversion.

4.12.1 Implicit Type Conversion


In this case one data type is automatically converted into another data type as per the rules described.
There are two types of implicit type conversion viz., automatic type conversion and assignment
type conversion.

Automatic Type Conversion :


In automatic type conversion, the data type with lower rank is converted automatically into higher
rank data before the operation proceeds. The rules are as follows:
All the short and char data types are convert into int
1. If one of the operand is long double then other is converted to long double and result will be
long double.
2. If one of the operand is double then other is converted to double and result will be double.
3. If one of the operand is float then other is converted to float and result will be float.
4. If one of the operand is unsigned long int then other is converted to unsigned long int and
result will be unsigned long int.
5. If one of the operand is long double then other is converted to long double and result will be
long double.
6. If one of the operand is long int then other is converted to unsigned int:
(a) unsigned int is converted into long int , result is long int
(b) Both operands are converted into unsigned long int and result is unsigned long int.
7. If one of the operand is long int then other is converted to long int and result will be long int.
8. If one of the operand is unsigned int then other is converted to unsigned int and result will be
unsigned int.
It should be noted that final result of the expression is converted to type of the variable on left side
of assignment operator before assigning value to it. Also, Conversion of float to int causes loss of
fractional part, conversion of double to float causes rounding of digits and conversion of long int to
int cause dropping of higher excess bits.

Explicit Type Conversion


The type conversion performed by the programmer b forcing the data type of expression of specific
type is known as explicit type conversion.It is also called as Type casting.
General form of type casting is :

(datatype)Expression

Where datatype is any valid C data type and Expression is any valid C variable or constant or
Expression.
Example:
a=(int)b+c*d;
The following rules have to be followed while converting the expression from one type to
another to avoid loss of information.
• All int type convert to float.
32 Chapter 4. Operators & Expressions

• All float type convert to double


• All char type convert to int

4.13 Multiple Choice Questions


1. What will be the output of the following program? [ A ]
void main()
{
int a, b, c, d;
a = 3;
b = 5;
c = a, b;
d = (a, b);
printf("c=%d d=%d", c, d);
}
(A) c=3 d=5 (B) c=3 d=3 (C) c=5 d=3 (D) c=5 d=5
2. What is the output of this C code? [ C ]
#include <stdio.h>
int main()
{
int i = -3;
int k = i % 2;
printf("%d\n", k);
}
(A) Error (B) 2 (C) -1 (D) 1
3. In an expression involving || operator, evaluation [ D ]
I. Will be stopped if one of its components evaluates to false
II. Will be stopped if one of its components evaluates to true
III. Takes place from right to left
IV. Takes place from left to right
(A) I and III (B) I and II (C) II and III (D) II and IV
4. Which of the following is invalid operation in C? [ C ]
(A) 10*10 (B) 10.5%2 (C) 10/5 (D) 10.5/5
5. In C programming language, which of the following type of operators have the highest
precedence? [ C ]
(A) Logical (B) Equality (C) Arithmetic (D) Relational
6. Which of the following is invalid operation in C? [ D ]
(A) 12.56/12 (B) 12.56%11 (C) 12%11 (D) 12%-11
7. What number will z in the sample code given below? [ A ]
int z, x=5, y= -10, a=4, b=2;
z = x++ - --y*b/a;
(A) 10 (B) 6 (C) 11 (D) 9
8. What is the output of following code? [ C ]
4.13 Multiple Choice Questions 33

int i=0;
printf(%d%d%d,i++,i++,i++);
(A) 3 2 1 (B) 0 1 2 (C) 2 1 0 (D) 1 2 3
9. Determine output: [ A ]

void main()
{
int i=0, j=1, k=2, m;
m = i++ || j++ || k++;
printf("%d %d %d %d", m, i, j, k);
}
(A) 1 1 2 2 (B) 1 2 1 2 (C) 1 2 3 4 (D) 1 1 2 3
10. Determine output: [ A ]

void main()
{
int c = - -2;
printf("c=%d", c);
}
(A) 2 (B) -2 (C) 1 (D) -1
11. What is the result of 5/4 [ B ]
(A) 0 (B) 1 (C) 5 (D) None
12. What is the result of 5%4 [ B ]
(A) 0 (B) 1 (C) 5 (D) None
13. What is the result of 32>>3 [ A ]
(A) 4 (B) 9 (C) 0 (D) None
14. What is the result of 3<<3 [ C ]
(A) 0 (B) 9 (C) 24 (D) None
15. Multiplication of two numbers is performed using [ C ]
(A) unary operator (B) logical operator
(C) arithmetic operator (D) assignment operator
16. The ’&’ operator displays [ B ]
(A) Value of the variable (B) Address of the variable
(C) Both a and b (D) None of the above
17. What is the value of !1? [ A ]
(A) 0 (B) 1 (C) -1 (D) None
18. Number of binary arithmetic operators in C is: [ A ]
(A) 5 (B) 4 (C) 6 (D) 7
19. Which is not a valid expression? [ C ]
(A) +0XAB5 (B) -0525 (C) 15- (D) +a
20. Which is not a valid expression? [ C ]
34 Chapter 4. Operators & Expressions

(A) -p++ (B) ++p– (C) ++6 (D) ++x++


21. Which is not a valid expression? [ A ]
(A) ++(a+b) (B) y– (C) -x- (D) ++p+q
22. The equality operator is represent by: [ D ]
(A) := (B) .EQ. (C) = (D) ==
23. Identify the logical operator: [ A ]
(A) (B) = (C) e (D) ==
24. Identify the relational operator: [ B ]
(A) && (B) > (C) ||
(D)
25. The symbol for exclusive OR operator is: [ A ]
(A) b (B) e (C) & (D) |
26. The symbol for one’s complement operator is: [ C ]
(A) & (B) b (C) e (D) |
27. The symbol for bitwise AND operator is: [ D ]
(A) << (B) &= (C) && (D) &
28. The symbol for left shift operator is: [ B ]
(A) < (B) << (C) <= (D) <<<
29. Structural programming approach makes use of: [ D ]
(A) modules (B) control structures
(C) used defined data types (D) all above
30. A statement is differentiated from an expression [ A ]
(A) by terminating it by a semicolon
(B) by terminating it by a newline character
(C) by terminating it by a NULL
(D) by terminating it by a blank space
31. Consider the following statements:-
int x = 6, y=8, z, w;
y = x++;
z = ++x;
The value of x,y,z by calculating the above expressions are___ [ B ]
(A) y=8, z=8, x=6 (B) y=6, x=8, z=8
(C) y=9, z=7, x=8 (D) y=7, x=8, z=7
32. Consider the following statement
int j, k, p;
float q, r, a;
a = j/k;
p=q/r;
If q=7.2, r=20, j=3, k=2
4.13 Multiple Choice Questions 35

The value of a and p is [ C ]


(A) a=1.5, p=3.6 (B) a=2, p=3 (C) a=1.5, p=4 (D) a=1, p=3
33. Which amongst the following expression uses bitwise operator? [ C ]
(A) a++
(B) a>5
(C) a|b (D) a!=b
34. In the following code fragment [ A ]

int x, y = 2, z, a;
x=(y*=2) + (z=a=y);
printf (`%d',x);
(A) prints 8
(B) prints 6
(C) prints 6 or 8 depending on the compiler
(D) is syntactically wrong
35. If ’y’ is of integer type then the expressions [ C ]
3* (y - 8)/9 and (y - 8)/9 * 3
(A) must yield the same value.
(B) must yield different values.
(C) may or may not yield the same value.
(D) none of the above.
36. If the variables i, j and k are assigned the values 5,3 and 2 respectively, then the expression i
=j+(k++=6)+7 [ A ]
(A) gives an error message (B) assigns a value 16 to i
(C) assigns a value 18 to i (D) assigns a value 19 to i
37. If a, b and c are integer variables with the values a=8, b=3 and c=-5. Then what is thevalue
of the arithmetic expression: [ A ]
2 * b + 3 * (a-c)
(A) 45 (B) 6 (C) -16 (D) -1
38. Which of the following is the odd one out? [ A ]
(A) j = j + 1; (B) j =+ 1; (C) j++; (D) j += 1;
39. The second expression (j - k) in the following expression will be evaluated [ A ]

(i + 5) && (j  k)
(A) if expression (i + 5) is true.
(B) if expression (i + 5) is false.
(C) irrespective of whether (i + 5) is true or false.
(D) will not be evaluated in any case.
40. What is the output of following code: [ A ]
36 Chapter 4. Operators & Expressions

void main()
{c
har *s="\12345s\n";
printf("%d",sizeof(s));
}
(A) 6 (B) 5 (C) 4 (D) Error
41. What is the output of the below code: [ A ]

main()
{
int i=10;
i=!i>14;
printf ("i=%d",i);
}
(A) 0 (B) 10 (C) 1 (D) Syntax Error
42. What is the output of the below code: [ A ]

main()
{ int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
(A) -1 -1 (B) 1 1 (C) 1 -1 (D) -1 1
43. What is the output of the below code: [ D ]

main()
{ int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}
(A) -1 -1 (B) 1 1 (C) 1 -1 (D) -1 1
44. What is the output of the below code: [ A ]

main()
{
int i=0;
while(+(+i--)!=0)
i- =i++;
printf("%d",i);
}
(A) -1 (B) 1 (C) Error (D) None
45. What is the output of the below code: [ A ]

int a ,b=7
a=b<4?b<<1:b>4?7>>1:a
(A) 3 (B) 0 (C) Error (D) None
4.13 Multiple Choice Questions 37

46. What is the value assigned to the variable a if b is 7 [ A ]

a=b>8?b<<2:b>4?b>>1:b;
(A) 3 (B) 7 (C) Error (D) None
47. What is the output of the following program [ D ]

main()
{
int a=10;
int b=6;
if(a=3)
b++;
printf("%d %d\n",a,b++);
}
(A) 10,6 (B) 10,7 (C) 3,6 (D) 3,7
48. What is the output of the following program [ D ]

main()
{ int x,j,k;
j=k=6;x=2;
x=j*k;
printf("%d", x);
}
(A) 12 (B) 0 (C) 1 (D) 36
49. Which is the output produced by the following program [ B ]

main()
{
int n=2;
printf("%d %d\n", ++n, n*n);
}
(A) 3,6 (B) 3,4 (C) 2,4 (D) cannot determine
50. given two statements [ B ]
a=(10,15);
b=10,15;
if they are executed what is the output if

printf("%d%d",a,b);
(A) 10,15 (B) 15,10 (C) 10,10 (D) 15,15
51. Which is the output produced by the following program [ D ]

main()
{
int x=10,y=15,z=16;
x=y==z;
printf("%d",x);
}
38 Chapter 4. Operators & Expressions

(A) 1 (B) 15 (C) 10 (D) 0


52. What is the value assigned to the variable X if b is 7 ?[ D ]
X = b>8 ? b <<3 : b>4 ? b>>1:b;
(A) 13 (B) 15 (C) 10 (D) 14
53. Evaluate(1 &&(0 || 1)).
Answer is 1 (TRUE)
54. Which header file do you need to include to use typecasting?[ D ]
(A) stdio.h (B) ctype.h (C) math.h (D) None
55. Why can typecasting be dangerous?[ C ]
(A) Some conversions (B) You might perma- (C) You might temporar- (D) There are no dangers.
are not defined, such nently change the ily lose part of the
as char to int. value of the variable. data - such as trun-
cating a float when
typecasting to an
int.
56. What is the output of the following problem ? [ D ]
main()
{
printf("%x",-1<<4);
}
(A) 0 (B) 1 (C) ffff (D) fff0
57. What is the output of the following problem ? [ B ]
void main()
{ int i=7;
printf("%d",i++*i++);
}
(A) 49 (B) 56 (C) 64 (D) Error
58. What is the output of the following problem ? [ B ]
int i;
i=1;
i=i+2*i++;
printf(%d,i);
(A) 4 (B) 5 (C) 6 (D) Error
59. What is the output of the following problem ? [ D ]
int i=10;
printf("%d %d %d",i,++i,i++);
(A) 10 11 11 (B) 12 11 10 (C) 12 12 10 (D) Compiler Dependent
60. What is the output of the following problem ? [ A ]
int x=2;
x=x<<2;
printf("%d ",x);
4.13 Multiple Choice Questions 39

(A) 8 (B) 7 (C) 6 (D) Error


61. What is the output of the following problem ? [ B ]

main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}
(A) 1 0 1 3 1 (B) 0 0 1 3 1 (C) 0 0 1 3 2 (D) Error
62. What is the output of the following problem ? [ B ]

main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
(A) 45544 (B) 45545 (C) 55545 (D) Error
63. What is the output of the following problem ? [ D ]

void main()
{
int i=5;
printf("%d",i+++++i);
}
(A) 11 (B) 12 (C) 13 (D) Error
64. What is the output of the following problem ? [ A ]

main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}
(A) 11 (B) 12 (C) 13 (D) Error
5. Basic Input and Outputs

’C’ language does not have any built-in input/output statements. All input/output operations can
be performed through function calls such as printf and scanf. These functions are known as the
standard I/O library. A program using these functions must include the standard input-output header
file < stdio.h >line :

#include <stdio.h>
The input/output functions are classified into three categories.
1. Console I/O functions: Functions to receive input from keyboard and write output to VDU
2. Disk I/O functions : Functions to perform I/O operations on a floppy or Hard Disk.
3. Port I/O functions : Functions to perform I/O operations on various ports (serial and
parallel).
An input/output functions can be accessed from any where within a program by simply writing the
function name followed by a list of arguments enclosed in parentheses.
Console I/O Functions : Console I/O functions are mainly classified into two categories
1. Unformatted console I/O functions
2. Formatted console I/O functions
Both types of functions are performed the standard input (usually the keyboard) and a standard
output (usually the monitor).

5.1 Unformatted Console I/O functions


Functions that accept a single argument (the argument must be data item representing a string or a
character) are concerned with unformatted I/O. Here the programmer need not specified either IO
format of the data.
Char type String type
Input : getch(), getche(), getchar() gets()
Output : putch(), putchar() puts()
42 Chapter 5. Basic Input and Outputs

5.1.1 getch() & getche()


These functions will read a single character the instant it is typed without waiting for the enter key
to be hit.
Program:

/* PROGRAM TO DEMONSTRATE getch() AND getche() FUNCTIONS */


#include<stdio.h>
main()
{
char ch;
printf(" Hit any key ! : ");
getch(); /* character input without echo */
printf(" Hit any key ! : ");
getche();
/* character will be echoed on the screen */
}

Explanation : The above program will explain the difference between getch() and getche()
functions. The main difference is getche function will echo a character but it is not in getch function.

5.1.2 getchar()
It is very similar to the getche() and getch() functions echoing the character you type on the screen,
but requires enter key to hit following the character you typed.

5.1.3 putchar() and putch()


These functions are used to write a character one at a time to the terminal.
Program:

/* PROGRAM TO DEMONSTRATE getchar() AND putch() FUNCTIONS */


#include<stdio.h>
main()
{
char ch;
printf(" Hit any key ! : ");
ch=getchar();
putch(ch);
}

Explanation: In the above program character ch will be read through getchar() function and
character will print through putchar() function.

5.1.4 gets() & puts()


gets() receives a string which is an array of characters from the keyboard, puts() function works
exactly opposite to gets() function i.e. prints the string on console.
Program:

/* PROGRAM TO DEMONSTRATE gets() AND puts() FUNCTIONS */


#include<stdio.h>
main()
{
5.2 Formatted IO 43

char name[100];
puts("Enter a string : ");
gets(name);
puts(name);
}
OUTPUT : Enter a string :
I am a Software Engineer
I am a Software Engineer
Explanation : In the above program a string will read through the gets function and will ptint it by
puts function.

5.2 Formatted Console I/O


Functions that accept strings as well as variable number of arguments to be displayed and read in a
specified format is formatted I/O.
Type : char, int, float, string
Input : scanf()
Output : printf()
The above two functions are used to supply input from keyboard in a fixed format and obtain output
in a specified format on the screen.

5.2.1 printf() function


Output data can be written from the computer on to a standard output device using this library
function. This function can be used to output any combination of numerical values, single character
and strings.
The general format is :

printf("control string", arg1, arg2, arg3...);


where the control string refers to a string contains formatting information. When printf() is called it
opens the format string and reads a character at a time. If the character reads % or \ it does not
print it but reads the next character, have a special meaning to printf.
Format Descriptors :

Descripter Use
%d for int and short int
%ld for long int
%u for unsigned int and unsigned short int
%lu for long unsigned int
%f for float
%lf for double
%Lf for long double
%c for char
%s for string.
%o for octal
%x for hexa decimal

Escape sequence: An escape sequence is a sequence of characters that does not represent itself
when used inside a character or string literal, but is translated into another character or a sequence
of characters that may be difficult or impossible to represent directly.
44 Chapter 5. Basic Input and Outputs

Backslash Char Use


\n new line
\t horizontal tab
\v vertical tabulator
\a to beep the speaker
\’ single quote
\" double quotes
\? question mark
\\ back slash
\0 NULL.

Output of Integer Number


The format specification for printing an integer numbers is %wd. Here w specifies the minimum
field width for the output. If a number is greater than the specified field width the number will be
printed fully. d specifies that the value to be printed, is an integer. The following example program
illustrates the output of an integer in different formats.
Program

/* OUTPUT OF INTEGER NUMBERS UNDER VARIOUS FORMATS */


#include <stdio.h>
main()
{
int i=3214;
clrscr();
printf(" i = %d\n",i);
printf(" i (%%3d) = %3d\n",i);
printf(" i (%%7d) = %7d\n",i);
printf(" i (%%-7d) = %-7d\n",i);
printf(" i (%%010d) = %010d\n",i);
printf(" i (%%.10d) = %.10d\n",i);
printf(" i (%%o) = %o\n",i);
printf(" i (%%x) = %x\n",i);
printf(" i (%%#o) = %#o\n",i);
printf(" i (%%#x) = %#x\n",i);
printf(" i (%%6d) = %6d\n",-i);
}

Output :
5.2 Formatted IO 45

Explanation : In the above program integer i is initialized with 3214, it is printed with various
formats.

Output of Real Numbers


The real numbers may be displayed in decimal notation using the format specification of %w.p f.
Here w indicates the minimum number of positions that are to be used for display the value and
p indicates the number of digits to be displayed after the decimal point (precision). The value is
rounded to p decimal places and printed. The default precision is 6 decimal places.
We can also display a real number in exponential notation by using the specification %w.p e. The
following Example program illustrates the output of a real number in different formats;
Program:

/* OUTPUT OF REAL NUMBERS IN VARIOUS FORMATS */


#include <stdio.h>
main()
{
float i=2500.321;
clrscr();
printf(" i (%%f) = %f\n",i);
printf(" i (%%f) = %f\n",-i);
printf(" i (%%+.0f) = %+.0f\n",i);
printf(" i (%%-.0f) = %-.0f\n",i);
printf(" i (%%8.2f) = %8.2f\n",i);
printf(" i (%%6.8f) = %6.8f\n",i);
printf(" i (%%2.2f) = %2.2f\n",i);
printf(" i (%%10.2e) = %10.2e\n",i);
printf(" i (%%09.2f) = %09.2f\n",i);
printf(" i (%%9.2f) = %9.2f\n",i);
printf(" i (%%012.2f) = %012.2f\n",i);
printf(" i (%%12.2f) = %12.2f\n",i);
printf(" i (%%8.2f) = %8.2f\n",i);
printf(" i (%%#10.0f) = %#10.0f\n",i);
printf(" i (%%e) = %e\n",i);
printf(" i (%%*.*f 8 2) = %*.*f",8,2,i);
}

Output:
Explanation : In the above program float i is initialized with 2500.321, it is printed with
various formats.

Output of Characters and Strings


The Characters and Strings may be displayed by using the format specification of %w.p f. Here
w specifies the field for display and p instructs that the first p characters of the string are to be
displayed. The display is right-justified. The following Example program illustrates the output of
Characters and Strings in different formats;
Program

/* PRINTING OF CHARACTERS & STRINGS IN VARIOUS FORMATS */


#include<stdio.h>
main()
{
46 Chapter 5. Basic Input and Outputs

char name[50]="PRAVEEN Kumar", ch='P';


clrscr();
printf(" ch = %c\n",ch);
printf(" ch = %3c\n",ch);
printf(" ch = %6c\n",ch);
printf(" name = %s\n",name);
printf(" name = %12s\n",name);
printf(" name = %*s\n",2,name);
printf(" name = %20.7s\n",name);
printf(" name = %-20.7s\n",name);
printf(" name = %.5s\n",name);
}
Output:

5.3 scanf Function


This function can be used to read any combination of numerical values, single character and string.
The general format is :
scanf("control string", arg1, arg2, arg3...)
Where the control string refers to a string certain required formatting information, arg1, arg2, . . . .,
argn are arguments that represent the individual data items.
5.3 scanf Function 47

Here the scanf() function gets the value from user and store the value in the address(memory
location) of the variable ’n’. Which is represented as &n. Hence, when we use ’&’ symbol we
refers to the address of the variable. scanf() has got its own limitations. Though both scanf() &
gets() are used for inputting a string, scanf() will not allow to input a string with blank spaces.

argument Description
* This is an optional starting asterisk indicates that the data is to be read from the stream but ignored, i.e.
width This specifies the maximum number of characters to be read in the current reading operation.
modifiers Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or fl
type A character specifying the type of data to be read and how it is expected to be read. See next table.

If successful, the total number of characters written is returned, otherwise a negative number is
returned.

5.3.1 Reading Integers


For reading the integers, the control string format is %wd where w indicates maximum width and
d indicates reading integers. w is optional here. Example is as follows:

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

since the width is not specified for input number, whatever the value entered is absorbed as ’n’
value. One more example is as follows:

int n;
scanf("%4d",&n);

Here ’n’ is a value with the length of four digits. If n=25 there is no problem, in case if n=34521,
the last digit ’1’ can be loss and a value is absorbed as 3452.

5.3.2 Reading Float


Control string here is %f. Example is as follows:

float n;
scanf("%f",&n);

5.3.3 Reading single character


Control string here is %c. Example is as follows:

char n;
scanf("%c",&n);

5.3.4 Reading String


Control string here is %ws. Where w is the maximum length of the string. Example is as follows:

char str;
scanf("%s",str);

There is no address operator for str variable here The default delimiter of a string is white space.
Another Example is as follows:
48 Chapter 5. Basic Input and Outputs

char str;
scanf("%10s",str);
Here it take up to 10 characters, if there is no space up to 10 characters.
Program:

#include <stdio.h>
int main()
{
char str1[20], str2[30];
printf("Enter name: ");
scanf("%s", str1);
printf("Enter your website name: ");
scanf("%s", str2);
printf("Entered Name: %s\n", str1);
printf("Entered Website:%s", str2);
return(0);
}
OUTPUT:
Enter name: welcome
Enter your website name: www.welcome.com

Entered Name: welcome


Entered Website: www.welcome.com
Take care about the number, type and order of the control string as well as arguments, in the case of
reading mixed data types at a time.

5.3.5 Search sets


It is used to represent the combination if characters to be read. General form is %[..]. Example is
as follows:
%[abcd]
It will read any string, it may be combination of a, b, c and d characters. If any other characters it
will terminate.
%[0-9] is read a numbered string contain only digits.

5.4 Blocks
A group of declarations and statements surrounded by the opening and closing braces ( { } ) is
called a Compound statement or a Block. A block may hold variables, statements, structures,
expressions, control structures, etc., which are necessary for a program. Any variables declared
inside a block are not available outside of block, declaration should be done at the beginning of the
block. The variables declared inside any block are called block variables. A block is syntactically
equivalent to a single statement no semicolon is placed after the closing brace that ends a block.
A program can hold any no. of blocks, also it is possible to insert a block within another block.
General format of blocks :

{ // initiation of a block
variables;
expressions;
} // termination of a block
5.5 Multiple Choice Questions 49

{ // initiation of block1
------------
{ // initiation of block2
-----------
} // termination of block2
-------------
} // termination of block 1
Ex :
{
int x, y=5;
x=y*y*y;
printf("%d \t %d \n", y, x);
}

5.5 Multiple Choice Questions


1. What is the output of the below code snippet? [ D ]

#include<stdio.h>
main()
{
int a = 1;
float b = 1.3;
double c;

c = a + b;
printf("%.2lf", c);
}
(A) -2.3 (B) -2.00 (C) Compiler error (D) -2.30

2. What will output when you compile and run the below code? [ C ]

#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=6,c=11;
clrscr();
printf("%d %d %d");
getch();
}
(A) Error (B) 5 6 11 (C) 11 6 5 (D) Garbage values

3. What is the output of the below program? [ B ]

#include<stdio.h>
int main()
50 Chapter 5. Basic Input and Outputs

{
int n=5;
printf("n=%*d\n", n, n);
return 0;
}
(A) Error (B) 5 (C) 6 (D) None

4. If the required output is abcdefghijklmnopqrstuvwxyz then xxx should be ?[ A ]


char c='a';
while(c++ <= 'z') {
putchar(xxx);
}
(A) c-1 (B) c– (C) c (D) c++

5. The below mentioned program fragment will __________.[ D ]


int i = 263;
putchar(i);
(A) Prints ascii of 263 (B) Garbage (C) Error (D) rings the bell

6. The below mentioned program fragment will __________.[ D ]


for(i=3;i<15;i+=3);
printf("%d",i);
(A) 12 (B) Garbage (C) Error (D) 15

7. The code
printf("%d",printf("tim"));
What will be the output?[ D ]
(A) tim (B) Error (C) 3 (D) tim3

8. What will output when you compile and run the above code?[ D ]
(A) 5 (B) 51 (C) c (D) d

9. If abc is the input then the following program fragment results in __________ ? [ A ]
char x,y,z
printf("%d",scanf("%c%c%c",&x,&y,&z));
(A) 3 (B) 3abc (C) abc3 (D) Error

10. To scan a (float) and b (double), which scanf() statement do you use? [ D ]
(A) scanf("%f%f",&a,&b); (B) scanf("%Lf%Lf",&a,&b)
(C) scanf("%f%Lf",&a,&b); (D) scanf("%f%lf",&a,&b);
5.5 Multiple Choice Questions 51

11. To printout a (float a=5.43) and b (double b=2.14), which printf() statement do you use? [
A ]
(A) printf("%f%f",a,b); (B) printf("%Lf%f",a,b)
(C) printf("%f%Lf",a,b); (D) printf("%Lf%Lf",a,b);
12. What is the output of the following code [ B ]

main()
{
printf("\n%%%%");
}
(A) % (B) %% (C) %%% (D) %%%%
13. The output of the following is [ C ]

x = 'a';
printf(%d, x);
(A) ’a’ (B) a (C) 97 (D) None of the above
14. Which header file is used for screen handling function:- [ D ]
(A) IO.H (B) STDLIB.H (C) CONIO.H (D) STDIO.H
15. The output of the following program is [ C ]

main( )
{ float y;
y=198.7361;
printf(%7.2f, y);
}
(Assume _ means single whitespace)
(A) 198.736 (B) _198.73 (C) _198.74 (D) 198.74_
16. printf("%-10s"', "ABDUL"); displays (Assume _ means single whitespace) [ A ]
(A) ABDUL_____ (B) _____ABDUL (C) ABDUL__________
(D) __________ABDUL
17. A single character input from the keyboard can be obtained by using the function. [ D ]
(A) printf ( ) (B) scanf ( ) (C) putchar ( ) (D) getchar ( )
18. What is the output of the following statement: [ C ]

printf ("%-3d",12345);
(A) 123 (B) -123 (C) 12345 (D) 12
19. What is the output of the following statement: [ C ]

main()
{ int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
(A) 10 (B) 2 (C) 1 (D) Compiler Error
20. What is the output of the following statement: [ A ]
52 Chapter 5. Basic Input and Outputs

main()
{
100;
printf("%d\n",100);
}

(A) 100 (B) 2 (C) 1 (D) Compiler Error


21. What is the output of the following problem ?

void main()
{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}

Answer: Ok here
22. What is the output of the following problem ?

void main()
{
unsigned giveit=-1;
int gotit;
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}

Answer: 0 65535
23. What is the output of the following code?

main()
{
float value=10.00;
printf("%g %0.2g %0.4g %f",value,value,value,value)
}

Answer: 10,10,10,10.000000

5.6 Example Programs


1. PROGRAM TO DEMONSTRATE sizeof OPERATOR

#include<stdio.h>
main()
{
short int a;
int b;
long int c;
float d;
5.6 Example Programs 53

double e;
long double f;
char g;
printf("short int a\t int b\t long int c\t float d\n");
printf("double e\t long double f\t char g\n\n");
printf("Bytes occupied by a is : %d\n",sizeof(a));
printf("Bytes occupied by b is : %d\n",sizeof(b));
printf("Bytes occupied by c is : %d\n",sizeof(c));
printf("Bytes occupied by d is : %d\n",sizeof(d));
printf("Bytes occupied by e is : %d\n",sizeof(e));
printf("Bytes occupied by f is : %d\n",sizeof(f));
printf("Bytes occupied by g is : %d\n",sizeof(g));
printf("short int occupies %d bytes \n",sizeof(short int));
printf("int occupies %d bytes \n",sizeof(int));
printf("long int occupies %d bytes \n",sizeof(long int));
printf("float occupies %d bytes \n",sizeof(float));
printf("double occupies %d bytes \n",sizeof(double));
printf("long double occupies %d bytes \n",sizeof(long double));
printf("char occupies %d bytes \n",sizeof(char));
printf("Bytes occupied by '5' is : %d\n",sizeof('5'));
printf("Bytes occupied by 5 is : %d\n",sizeof(5));
printf("Bytes occupied by 5.0 is : %d\n",sizeof(5.0));
}

OUTPUT :
short int a int b long int c float d
double e long double f char g
Bytes occupied by a is : 2
Bytes occupied by b is : 2
Bytes occupied by c is : 4
Bytes occupied by d is : 4
Bytes occupied by e is : 8
Bytes occupied by f is : 10
Bytes occupied by g is : 1
short int occupies 2 bytes
int occupies 2 bytes
long int occupies 4 bytes
float occupies 4 bytes
double occupies 8 bytes
long double occupies 10 bytes
char occupies 1 bytes
Bytes occupied by 'c' is : 2
Bytes occupied by 5 is : 2
Bytes occupied by 5.0 is : 8

Explanation : The above program will specify the number of bytes occupied for each data
type, the numbers 5, 5.0 and character ’C’.
2. PROGRAM TO PRINT PREFIX AND SUFIX CHARACTERS
#include<stdio.h>
54 Chapter 5. Basic Input and Outputs

main()
{
char c;
clrscr();
printf("\nEnter any single character : ");
c=getchar();
printf("\nThe character prefix to character %c is : ",c);
putchar(c-1);
printf("\nThe character suffix to character %c is : ",c);
putchar(c+1);
}

OUTPUT :
Enter any single character : e
the character prefix to character e is : d
the character suffix to character e is : f
Explanation : The above accepts a character through getchar function as c, it is printing its
prefix and suffix characters. Here c is incremented and decremented by 1, it is showing that
chacters also performing addition and subtractions.
3. PROGRAM TO ACCEPT THREE SIDES OF TRIANGLE AND CALCULATE THE AREA
AND CIRCUMFERENCE OF IT
#include<stdio.h>
#include<math.h>
main()
{
float a,b,c,cir;
float s,area;
printf("Enter first side of a triangle : ");
scanf("%f",&a);
printf("Enter second side of a triangle : ");
scanf("%f",&b);
printf("Enter third side of a triangle : ");
scanf("%f",&c);
cir=a+b+c;
s=(a+b+c)/2;
area=sqrt((double)(s*(s-a)*(s-b)*(s-c)));
printf(" \nThe area of the given triangle is : %f\n",area);
printf(" \nThe circumference of the given triangle is : %f\n",cir);
getchar();
}
OUTPUT:
Enter first side of a triangle : 4
Enter second side of a triangle : 5
Enter third side of a triangle : 6
The area of the given triangle is : 9.921567
The circumference of the given triangle is : 15.000000
Explanation : The above accepts three float values from the user as sides of triangle. Area
and circumference will be calculated by the formula.
5.6 Example Programs 55

4. PROGRAM TO ACCEPT TWO VARIABLES AND INTERCHANGE IT BY WITHOUT


USING TEMPORARY VARIABLE

#include<stdio.h>
main()
{
int a,b,t;
printf("Enter the first number : ");
scanf("%d",&a);
printf("Enter the second number : ");
scanf("%d",&b);
printf("Before interchanging A = %d\t B = %d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After interchanging A = %d\t B = %d\n",a,b);
}
OUTPUT:
Enter the first number : 13
Enter the second number : 51
Before interchanging A = 13 B = 51
After interchanging A = 51 B = 13
Explanation : The above program accepts two integers as a and b. These values are
interchanged by formula and printed.
6. Conditional Statements

The ability to control the flow of your program, letting it make decisions on what code to execute,
is valuable to the programmer. In these statement few part may skip from execution. Following are
the selection statements:

6.1 if statement
The if statement is used to specify conditional execution of program statements or a group of
statements enclosed in braces.

6.1.1 Simple if
It is used of make the single way decision or one way decision. The general syntax is:
if(Expression){
Statements;
}
58 Chapter 6. Conditional Statements

The flow of execution is as follows:

Here first the condition is evaluated and based on the result (Non-zero) only it executes the
Statements. Otherwise it simply skip the execution of the statements. From the syntax:
• if is a keyword
• The Expression is any valid arithmetic or relational or logical expression.
• The braces are optional, if the body of the if contain only one statement, otherwise necessary.
Example1:

int a=8;
if(a>=8){
printf("a is greater than or equal to 8");
}

Example1:PROGRAM TO PRINT ABSOLUTE VALUE OF THE GIVEN INTEGER

#include<stdio.h>
main()
{
int x;
printf(" Enter any integer number : ");
scanf("%d",&x);
if(x<0)
x=-x;
printf("Absolute value of the given number is : %d\n",x);
}
OUTPUT:
Enter any integer number : -10
Absolute value of the given number is : 10

Explanation : This program accepts an integer number as x from user. The entered number is
checked by if statement. If it is less than zero it will be multiplied by -1. Finally it prints the
absolute value of the given integer.
6.1 if statement 59

6.1.2 if..else
There are situations when there are two groups of statements and it is desired that one of them
be executed if some condition is true and the other be executed if the condition is false. In such
situations we make use of if - else statement. The general syntax is:

if (Expression)}
statement 1;
}else{
statement 2;
}

The flow of execution is as follows: If the Expression is TRUE (Non-Zero) the Statement 1 block is

executed otherwise statement2 block will be executed. Here the if and else are the keywords.
Example:PROGRAM TO FINDOUT THE ACCEPTED NUMBER IS POSITIVE OR NEGATIVE

#include<stdio.h>
main()
{
int x;
printf(" Enter any integer number : ");
scanf("%d",&x);
if(x<0)
printf(" The given number is negative \n");
else
printf(" The given number is positive \n");
}
OUTPUT:
Enter any integer number : -12
The given number is negative

Explanation : This program accepts an integer number as x from user. The entered number is
checked by if statement. If it is less than zero, it will be print "The given number is negative"
otherwise it will prints "The given number is positive".

6.1.3 Nested if
When a series of decisions are involved, we may have to use more than one if-else statements in
nested form as follows:
60 Chapter 6. Conditional Statements

If (Condition 1)
{
if (Condition 2)
{
Statement 1;
}
else
{
Statements 2;
}
}
else
{
if (Condition 3)
{
Statements 3;
}
else
{
Statements 4;
}
}
Statement 5;

Example: PROGRAM TO FINDOUT THE HIGHEST NUMBER FROM THE GIVEN


THREE NUMBERS

#include<stdio.h>
main()
{
int x,y,z,max;
printf(" Enter first number : ");
scanf("%d",&x);
printf(" Enter second number : ");
scanf("%d",&y);
6.1 if statement 61

printf(" Enter third number : ");


scanf("%d",&z);
if(x<y)
{
if(y<z)
max=z;
else
max=y;
}
else
{
if(x<z)
max=z;
else
max=x;
}
printf(" max number of %d %d %d is : %d\n",x,y,z,max);
}
OUTPUT:
Enter first number : 8
Enter second number : 23
Enter third number : 9
Max number of 8 23 9 is : 23
Explanation : This program accepts three integer numbers as x, y and z from user. The entered
numbers are checked one another and the highest number will be saved in max variable. Finally, it
wil print the max value i.e. max value of the given three numbers.

6.1.4 else..if Ladder


Here the conditions are evaluated from the top (of the ladder) to downwards. As soon as a true
condition is found, the statements associated with it is executed and the rest of the ladder is bypassed.
The last else is handles the default case.

if (condition)
statement 1;
62 Chapter 6. Conditional Statements

else if (condition)
statement 2;
else if (condition)
statement 3;
else
statement 4;
Example:PROGRAM TO IDENTIFYING WHICH CHARACTER IS ENTERED

#include<stdio.h>
main()
{
int c;
printf("Enter any character : ");
c=getchar();
if (c>='a' && c<='z')
printf("The given character is LOWERCASE character\n");
else if (c>='A' && c<='Z')
printf("The given character is UPPERCASE character\n");
else if (c>='0' && c<='9')
printf("The given character is DIGIT\n");
else
printf("The given character is SPECIAL character\n");
}
OUTPUT:
Enter any character : 7
The given character is DIGIT
Explanation : The above program to accept a character from the input and identify the character
type by using else – if ladder. Each if statement is checking two conditions combining with &&
operator.

6.2 Conditional Operator


It is also called as ternary operator. C provides condition evaluation operator called the ternary
operator in the form of the ? symbol.

(condition) ? exp1 : exp2


The ? operator evaluates the condition that precedes it. it is true, it returns exp1 and returns exp2
otherwise.
Example:

if(n>0)
n+=10; (Or) n=n>0?n+10:-n;
else
n=-n;
Example2: PROGRAM TO FIND OUT THE MAXIMUM NUMBER FROM THE GIVEN
TWO NUMBERS BY USING TERNARY OPERATOR

#include<stdio.h>
main()
6.3 switch statement 63

{
int x,y,max;
printf(" Enter first number : ");
scanf("%d",&x);
printf(" Enter second number : ");
scanf("%d",&y);
max=x>y?x:y;
printf(" max number of %d %d is : %d\n",x,y,max);
}
OUTPUT:
Enter first number : 43
Enter second number : 12
Max number of 43 12 is : 43

Explanation : The above program to accepts two integers as x & y. Both variables checked by
ternery operator and highest value will be stored max variable.

6.3 switch statement


’switch’ statement works in the same way as ’if-else-if’, but it is more elegant. The switch statement
is a special multi-way decision maker that tests whether an expression matches one of a number of
constancy values, and branches accordingly. Switch differs from if-else-if because switch can test
for only equality, whether if can evaluate logical expression. The ’switch’ statement is often used to
process key board commands like menu options.

The general format :

switch(expression)
{
case var1:
statement 1;
break;
case var2:
64 Chapter 6. Conditional Statements

statement 2;
break;
case var3:
statement 3;
break;
.
default:
statement n;
break;
}
Note that in the above structure switch, case, break and default are C keywords. Example:

PROGRAM TO DEMO ON SWITCH STATEMENT

#include<stdio.h>
main()
{
int x,y,rst;
char opt;
printf(" Enter first number : ");
scanf("%d",&x);
6.4 goto 65

printf(" Enter second number : ");


scanf("%d",&y);
getchar();
printf(" Enter your option + - X / %% : ");
scanf("%c",&opt);
switch(opt)
{
case '+':
printf(" %d + %d = %d\n",x,y,x+y);
break;
case '-':
printf(" %d - %d = %d\n",x,y,x-y);
break;
case 'X':
printf(" %d X %d = %d\n",x,y,x*y);
break;
case '/':
printf(" %d / %d = %d\n",x,y,x/y);
break;
case '%':
printf(" %d %% %d = %d\n",x,y,x%y);
break;
default:
printf("No operation\n");
break;
}
}
OUTPUT:
Enter first number : 12
Enter second number : 8
Enter your option + - X / % : +
12 + 8 = 20
Explanation : The above program to accepts two integers as x & y along with an arithmetic
operation symbol. Based on the operator it perfers operation, the result will be displayed.

6.4 goto
C supports the goto statement to branch unconditionally from one point to another in the program.
Although it may not be essential to use the goto statement in a highly structured language like C,
there may be occasions when the use of goto might be desirable.
The goto requires a label in order to identify the place where the branch is to be made. A label
is any valid variable name, and must be followed by a colon. The label is placed immediately
before the statement where the control is to be transferred.
The general format :
goto label;
------------------
------------------
label:
------------------
66 Chapter 6. Conditional Statements

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

label :
------------------
------------------
------------------
goto label ;

The label: It can be anywhere in the program either before or after the goto label statement. If the
label is before the statement goto label a loop will be formed and some statements will be executed
repeatedly. Such a jump is known as backward jump. On the other hand if the label is placed after
the goto label some statements will be skipped and the jump is known as a forward jump.

6.5 Example Programs


1. Write a program to check whether a box is cube, rectangle or semi-rectangle.

#include<stdio.h>
#include<conio.h>
void main()
{
float length, width, height;
clrscr();
printf("enter the dimension of box\n");
printf("Length= ");
scanf("%f",&length);
printf("width= ");
scanf("%f",&width);
printf("height= ");
scanf("%f",&height);
if(length==width)
{ if(length==height)
printf("\nThe box is a cube\n");
else
printf("\nThe box is a rectangle\n");
}
if(width==(0.5*length))
printf("\nThe box is a semirectangle\n");
getch();
}

2. PROGRAM TO ACCEPT A NUMBER AND FIND OUT IS IT EVEN OR ODD

#include<stdio.h>
main()
{
int n;
printf("Enter any number : ");
scanf("%d",&n);
if(n%2==0)
6.5 Example Programs 67

printf(" \nThe given number is EVEN \n");


else
printf(" \nThe given number is ODD\n");
}
OUTPUT:
Enter any number : 45
The given number is ODD

Explanation : The above program to accepts an integer numer. It is checked, whether is it


divided by 2 or not, based on that it will print EVEN or ODD.
3. PROGRAM TO ACCEPT THREE SIDES (POSITIVE INTEGERS) OF A TRIAN-
GLE DETERMINE WHETHER THEY FORM A VALID TRIANGLE

#include<stdio.h>
main()
{
int a,b,c;
printf("Enter first side of a triangle : ");
scanf("%d",&a);
printf("Enter second side of a triangle : ");
scanf("%d",&b);
printf("Enter third side of a triangle : ");
scanf("%d",&c);
if (a+b>c || a+c>b || b+c>a)
printf(" It will form a valid triangle \n");
else
printf(" It will not form a valid triangle \n");
}
OUTPUT:
Enter first side of a triangle : 4
Enter second side of a triangle : 1
Enter third side of a triangle : 6
It will form a valid triangle

Explanation : The above program accepts three integer numers. By using if condition it is
checking three conditions. If any one condition is satisfied, it will form a valid triangle.
4. PROGRAM TO ACCEPT A CHARACTER AND FINDOUT IS IT UPPERCASE OR
LOWERCASE CHARACTER

#include<stdio.h>
main()
{
int c;
printf("Enter any character : ");
c=getchar();
if(c>97)
printf("The given character is LOWERCASE character \n");
else
printf("The given character is UPPERCASE character \n");
}
OUTPUT:
68 Chapter 6. Conditional Statements

Enter any character : r


The given character is LOWERCASE character
Explanation : The above program accepts an alphabet. This c value is checked by if codition.
If it is greaterthan 97 it is Lowercase letter otherwise it is Uppercase. Lowercase alphabets
ASCII value is greaterthn 97, uppercase alphabets ASCII value is lessthan 97 only.
5. PROGRAM TO FIND THE GIVEN CHARACTER IS VOWEL OR CONSONANT

#include<stdio.h>
main()
{
char c;
printf("Enter any character : ");
c=getchar();
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
printf(" The given character is VOWEL \n");
else
printf(" The given character is CONSONENT \n");
}
OUTPUT:
Enter any character : u
the given character is VOWEL
Explanation : The above program accepts an alphabet. This c value is checked by compound
conditions to identify the given alphabet is vowel or consonant.

6.6 Multiple Choice Questions


1. The switch statement is used to [ B ]
(A) switch from one variable to another
(B) choose from multiple possibilities which may arise due to different values of a single
variable
(C) switch between functions in a program
(D) None of the above
2. The break statement is used in [ C ]
(A) selective control structures only
(B) loop control structures only
(C) options a and b
(D) switch-case control structures only
3. Each case statement in switch() is separated by [ C ]
(A) continue (B) goto (C) break (D) None
4. Identify the wrong statement: [ B ]
(A) if (a<b); (B) if a<b;
(C) if (a<b) ; (D) options b and c
5. which is syntactically correct: [ B ]
6.6 Multiple Choice Questions 69

(A) if (a:=10) {..} else if (a<10) {..}


(B) if (a==10){..} else if (a<10) {..}
(C) if (a eq 10) { .. } else if (a<10) {..}
(D) if (a.eq. 10) {..} else if (a<10) {..}
6. Which is correct statement: [ D ]
(A) printf("Maximum=%d",(x.y)?x:y);
(B) printf("%s",(marks >=60)? "first class" : "Not firstclass";
(C) printf("%s","pass");
(D) all the above
7. Identify the unconditional control structure: [ C ]
(A) do-while (B) switch-case (C) goto (D) if
8. What is the output of the following program? [ A ]
main( )
{
int i=4, z=12;
if(i=5 || z>50)
printf(hello);
else
printf(hye);
}
(A) hello (B) hye (C) syntax error (D) hellohye
9. Consider the following statements [ A ]
x = 5;
y = x >3 ? 10 : 20;
The value of y is
(A) 10 (B) 20 (C) 5 (D) 3
10. The output of the following code segment will be [ D ]
char x = `B';
switch (x) {
case `A': printf(a);
case `B': printf(b);
case `C': printf(c);
}
(A) B (B) b (C) BC (D) bc
11. What is the output of the following program? [ B ]
main()
{
int l=6;
switch(l)
{ default : l+=2;
70 Chapter 6. Conditional Statements

case 4: l=4;
case 5: l++;
break;
}
printf("%d",l);
}
(A) 8 (B) 6 (C) 5 (D) 4
12. What is the output of the following program?
main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}
Ans: three
13. What is the output of the following program?
#include<stdio.h>
main()
{ int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}
Answer: Compiler Error: Constant expression required in function main.
Explanation: The case statement can have only constant expressions (this implies that we
cannot use variable names directly so an error).
Note: Enumerated types can be used in case statements
14. Output of the following program is [ D ]
main()
{
int i=0;
for(i=0;i<20;i++)
{
switch(i)
6.6 Multiple Choice Questions 71

case 0:i+=5;
case 1:i+=2;
case 5:i+=5;
default i+=4;
break;
}
printf("%d,",i);
}
}
(A) 0,5,9,13,17 (B) 5,9,13,17 (C) 12,17,22 (D) 16,21
15. Output of the following program is

main()
{
int i;
for(i=0;i<3;i++)
switch(i)
{
case 1: printf("%d",i);
case 2 : printf("%d",i);
default: printf("%d"i);
}
}
Answer: 011122
16. What is the output of given program if input is 2000

main()
{ int y;
scanf("%d",&y);
if( (y%4==0 && y%100 != 0) || y%100 == 0 )
printf("%d is a leap year");
else
printf("%d is not a leap year");
}
Answer: 2000 is a leap year
17. What is the output of given program?

main()
{
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}
Answer: hello
Explanation: The comma operator has associativity from left to right. Only the rightmost
value is returned and the other values are evaluated and ignored. Thus the value of last
variable y is returned to check in if. Since it is a non zero value if becomes true so, "hello"
will be printed.
72 Chapter 6. Conditional Statements

18. Output of the below code is:

main()
{
int i=10,j=20;
j = i, j?(i,j)?i:j:j;
printf("%d %d",i,j);
}

Answer: 10 10
19. Find the output for the following C program [ B ]

main()
{
int Y=10;
if( Y++>9 && Y++!=10 && Y++>10)
printf("%d", Y);
else
printf("%d", Y);
}

(A) 14 (B) 13 (C) 20 (D) None of these


20. What is the output in the following program? [ C ]

main()
{char c=-64;
int i=-32
unsigned int u =-16;
if(c>i)
{
printf("pass1,");
if(c<u)
printf("pass2");
else
printf("Fail2");
}else
printf("Fail1);
if(i<u)
printf("pass2");
else
printf("Fail2")
}

(A) Pass1,Pass2 (B) Pass1,Fail2 (C) Fail1,Pass2 (D) Fail1,Fail2


21. Output value from the source code is [ C ]

int zap(int n)
{
if(n<=1)then zap=1;
else zap=zap(n-3)+zap(n-1);
}
6.6 Multiple Choice Questions 73

then the call zap(6) gives the values of zap


(A) 4 (B) 5 (C) 6 (D) 7
22. What is the output of the below code [ B ]
void main()
{
int i;
for(i=1;i<4,i++)
switch(i)
case 1: printf("%d",i);break;
{c
ase 2:printf("%d",i);break;
case 3:printf("%d",i);break;
}
switch(i) case 4:printf("%d",i);
}
(A) Error (B) 1 2 3 4 (C) 4 3 2 1 (D) None of the Above
23. What is the output of the given code? [ C ]
void main()
{
unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(i<j)
printf("less");
else
if(i>j)
printf("greater");
else
www.csetf.blogspot.com
if(i==j)
printf("equal");
}
Answer: less
24. What is the output of the given number?
main()
{
int i, j, k = 0;
char c1 = 'a', c2 = 'b';
if ( k == 0 )
printf("K is zero");
else
-----
-----
if ( c1 != 'a' )
printf("c2 == b");
else if ( c2 == 'a' )
74 Chapter 6. Conditional Statements

printf("c1 == a");
else
printf("Hello");
}
(A) K is zero c1 == a (B) K is zero c2 == (C) K is zero Hello (D) error
b
25. What is the output of the below code? Ans: 20

int a = 0, b = 2;
if (a = 0)
b = 0;
else
b *= 10;
26. if the input is "1a1b1c" then what is the output?

main ()
{
int ones, twos, threes, others;
int c;
ones = twos = threes = others = 0;
while ((c = getchar ()) != EOF)
{
switch (c)
{
case '1': ++ones;
case '2': ++twos;
case '3': ++threes;
break;
default: ++others;
break;
}
}
printf ("%d %d", ones, others);
}
7. Looping Statements

7.1 while loop


The while loop in the C starts with while keyword, followed by a parenthesized boolean condition,
and has a set of statements which constitute the body of the loop.

The general format :


while(expression)
{
statement 1;
statement 2;
statement 3;
.
76 Chapter 7. Looping Statements

statement n;
}

As soon as execution reaches the while loop, the specified condition is tested. If it is found to
be true, it will enter into the body of the loop. Once it reaches the closing brace of the body
automatically loop back to the top and test the condition freshly now, and if it is true re-enter the
body and so on, till the controlling condition of the while loop becomes false.
Example:FACTORIAL OF THE GIVEN NUMBER BY USING WHILE LOOP

#include<stdio.h>
main()
{
int x,i=1,rst=1;
printf("Enter any integer number : ");
scanf("%d",&x);
while(i<=x)
{
rst=rst*i;
i++;
}
printf("Factorial of %d is : %d",x,rst);
}
OUTPUT:
Enter any integer number : 5
Factorial of 5 is : 120

Explanation : The above program to accepts an integer numer to calculate the factorial. The
variable i is initialized with 1, till this I value becomes to given number the body of the while loop
will execute. The factorial of the given number will saved in the variable rst and printed it.

7.2 do-while loop


The do-while loop performs the test at the bottom rather than at the top. The do-while loop start
with the keyword do, followed by the body of the loop.
The general format :

do
{
statement 1;
statement 2;
statement 3;
.
.
statement n;
}while(expression);

After executing the body of the loop it reaches the while, the expression specified is evaluated. If it
is found to be true, automatically loop back to the top and re-enter the body of the loop. If at the
time of testing, the condition evaluates as false, you break out the do-while loop.
Example: FACTORIAL OF THE GIVEN NUMBER BY USING DO_WHILE LOOP
7.3 for loop 77

#include<stdio.h>
main()
{
int x,i=1,rst=1;
printf("Enter any integer number : ");
scanf("%d",&x);
do
{
rst=rst*i;
i++;
}while(i<=x);
printf("Factorial of %d is : %d",x,rst);
}
OUTPUT:
Enter any integer number : 5
Factorial of 5 is : 120

Explanation : The above program to accepts an integer numer to calculate the factorial. The
variable i is initialized with 1, till this I value becomes to given number the body of the do-while
loop will executes. The factorial of the given number will saved in the variable rst and printed it.

7.3 for loop


This is used when the statements are to be executed more than once. This is the most widely used
iteration construct. The for loop supported by C is much more powerful than its counterpart in
78 Chapter 7. Looping Statements

other high level languages.

The general format:


for(initialization; expression; increment)
{
statement 1;
statement 2;
.
.
statement n;
}
The for loop starts with for keyword. The keyword for is followed by a parenthesized with a header.
This is followed by the body of the loop which typically is a set of statements enclosed between
braces. The header of the for loop consists of 3 portions; first portion consists of a set of statements
to be executed initially, second portion is an expression that will act as the controlling condition of
the loop and final portion consists of incrementing or decrementing.
Ex: FACTORIAL OF THE GIVEN NUMBER BY USING FOR LOOP
#include<stdio.h>
main()
{
int x,i,rst=1;
printf("Enter any integer number : ");
scanf("%d",&x);
for(i=1;i<=x;i++)
rst=rst*i;
printf("Factorial of %d is : %d",x,rst);
}
OUTPUT:
Enter any integer number : 5
Factorial of 5 is : 120
7.4 Example Programs 79

Explanation : The above program to accepts an integer numer to calculate the factorial. Within
the for loop the variable i is initialized with 1, till this I value becomes to given number the body of
the for loop will execute, with increments of 1. The factorial of the given number will saved in the
variable rst and printed it.

7.3.1 Comma operator :


Comma operators are basically used in for loops to have more than one initialization and increment
statements.
The general format :
for(exp1,exp2;exp3;exp4,exp5)
{
statements;
}

7.3.2 break & continue


C provides two statements - break and continue using which the normal behavior of a loop can be
altered. We already have used the break statement in switch statement. It can also be used inside
a while loop, a for loop and do-while loop. It causes control to break out the innermost control
structure. C does not provide any mechanism to break out of an outer enclosing loop. Because of
its nature a break will always be conditional (attached to an if).
The general format :
while(1)
{
/* do something */
if(some condition)
break;
/* do something */
}
The continue statement whenever executed causes the rest of current iteration to be skipped and
causes the next iteration to begin, subjecting of course to the truth of the controlling condition.
The general format :
while(exp)
{
/* do something */
if(some condition)
continue;
/* do something */
}

7.3.3 exit() :
It is a standard library function used to terminate the program execution.
The general format : exit(argument);

7.4 Example Programs


1. PROGRAM TO ACCEPT TWO NUMBERS AND CALCULATE THE PRODUCT
OF IT BY USING THE SUCCESSIVE ADDITION METHOD
80 Chapter 7. Looping Statements

#include<stdio.h>
main()
{
int i,a,b,rst=0;
printf("Enter the first number i.e A : ");
scanf("%d",&a);
printf("Enter the second number i.e B : ");
scanf("%d",&b);
for(i=1;i<=b;i++)
rst+=a;
printf("%d X %d = %d\n",a,b,rst);
}
OUTPUT:
Enter the first number i.e A : 8
Enter the second number i.e B : 9
8 X 9 = 72
Explanation : The above program accepts two integers numbers as a and b. The rst variable
is initialized with zero. Variable a value will be added to rst variable b number of times.
2. PROGRAM TO ACCEPT TWO NUMBERS AND CALCULATE THE PRODUCT
OF IT BY USING RUSSIAN TECHNIC METHOD
#include<stdio.h>
main()
{
int x,y,i,a,b,rst=0;
printf("Enter the first number i.e A : ");
scanf("%d",&a);
printf("Enter the second number i.e B : ");
scanf("%d",&b);
x=a;
y=b;
printf("\n\n\n\t A B \n\n");
while (a>0)
{
if (a%2!=0)
{
printf("\t %3d %3d +\n",a,b);
rst+=b;
}
else
printf("\t %3d %3d \n",a,b);
a=a/2;
b=b*2;
}
printf("\n\n\t %d X %d = %d\n",x,y,rst);
}
OUTPUT:
Enter the first number i.e A : 23
Enter the second number i.e B : 10
A B
7.4 Example Programs 81

23 10+
11 20+
5 40+
2 80
1 160+
23 X 10 = 230
Explanation : The above program accepts two integers numbers as a and b. The rst variable
is initialized with zero. If variable a value is odd value then b value will be added to rst.
Variable a value will be divided by 2 and b value will be multiplied by 2. Till a value becomes
zero it will repeat.
3. PROGRAM TO ACCEPT X AND Y VALUES AND CALCULATE THE X Y VALUE
#include<stdio.h>
main()
{
int i,x,y,rst=1;
printf("Enter the base value i.e X : ");
scanf("%d",&x);
printf("Enter the power value i.e Y : ");
scanf("%d",&y);
for(i=1;i<=y;i++)
rst*=x;
printf("\n\n\t The %d power %d value is\t = %d\n",x,y,rst);
}
OUTPUT:
Enter the base value i.e X : 3
Enter the power value i.e Y : 3
the 3 power 3 value is = 27
Explanation : The above program accepts two integers numbers as x and y. The rst variable
is initialized with 1. Now rst will multiplied with x, y number of times.
4. PROGRAM TO ACCEPT A NUMBER AND PRINT ITS REVERSE NUMBER
#include<stdio.h>
main()
{
int t,n,r=0;
printf("Enter any number : ");
scanf("%d",&n);
t=n;
while (n>0)
{
r=r*10+n%10;
n=n/10;
}
printf("The reverse of the %d number %d\n",t,r);
}

OUTPUT:
Enter any number : 4567
The reverse of the 4567 number 7654
82 Chapter 7. Looping Statements

Explanation : The above program accepts an integer number as n. The variable r is


initialized with 1. This r will be multiplied with 10 and add the right most digit of the given
number (n%10). Now n will n/10, i.e. right ost digit will be deleted. This process will
continue till n becomes zero. Now r will be the reverse of the given number.
5. PROGRAM TO ACCEPT A NUMBER AND FIND OUT IS IT ARMSTRONG NUM-
BER OR NOT
#include<stdio.h>
main()
{
int t,n,r=0;
printf("Enter any number : ");
scanf("%d",&n);
t=n;
while (n>0)
{
r=r+(n%10*n%10*n%10);
n=n/10;
}
if (t==r)
printf(" The number %d is ARMSTRONG number\n",t);
else
printf(" The number %d is NOT ARMSTRONG number\n",t);
}
OUTPUT:
Enter any number : 432
The number 432 is NOT ARMSTRONG number
Explanation : The above program accepts an integer number as n. The variable r is
initialized with zero. This r will be added to the right most digit of the given number (n%10).
Now n will n/10, i.e. right ost digit will be deleted. This process will continue till n becomes
zero. This r value will copared with the given number, if both are same it is Armstrong
number otherwise not Armstrong number.
6. PROGRAM TO ACCEPT A NUMBER AND FIND OUT WHETHER IS IT POLIN-
DROME OR NOT
#include<stdio.h>
main()
{
int t,n,r=0;
printf("Enter any number : ");
scanf("%d",&n);
t=n;
while (n>0)
{
r=r*10+n%10;
n=n/10;
}
if(r==t)
printf("The number %d is PALINDROME\n",t);
else
7.4 Example Programs 83

printf("The number %d is NOT PALINDROME\n",t);


}
OUTPUT:
Enter any number : 6556
The number 6556 is PALINDROME

Explanation : The above program accepts an integer number as n. The variable r is


initialized with 1. This r will be multiplied with 10 and add the right most digit of the given
number (n%10). Now n will n/10, i.e. right ost digit will be deleted. This process will
continue till n becomes zero. Now r will be the reverse of the given number. This reverse
number r will be compared with the given number. If both are same then the given number is
Palindrome otherwise not Palindrome.
7. PROGRAM TO ACCEPT TWO NUMBERS AND CALCULATE THE GCD OF IT

#include<stdio.h>
main()
{
int x,y,i,a,b;
printf("Enter the first number i.e A : ");
scanf("%d",&a);
printf("Enter the second number i.e B : ");
scanf("%d",&b);
x=a;
y=b;
while(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
}
printf("GCD of %d & %d is : %d\n",x,y,a);
}
OUTPUT:
Enter the first number i.e A : 45
Enter the second number i.e B : 60
GCD of 45 & 60 is : 15

Explanation : The above program accepts two integer numbers as a and b. If both values
are not equal, the lowest value will be subtracted form highest value. This process will repeat
till both values becomes equal. Finally it will prints either a or b value i.e. GCD of given two
numbers.
8. PROGRAM TO ACCEPT TWO NUMBERS AND CALCULATE THE LCM OF IT

#include<stdio.h>
main()
{
int x,y,i,a,b,l;
printf("Enter the first number i.e A : ");
scanf("%d",&a);
printf("Enter the second number i.e B : ");
84 Chapter 7. Looping Statements

scanf("%d",&b);
x=a;
y=b;
while(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
}
l=(x*y)/a;
printf("LCM of %d & %d is : %d\n",x,y,l);
}
OUTPUT:
Enter the first number i.e A : 25
Enter the second number i.e B : 20
LCM of 25 & 20 is : 100
Explanation : The above program accepts two integer numbers as a and b. If both values are
not equal, the lowest value will be subtracted form highest value. This process will repeat till
both values become equal. Now the product of given two numbers will be divided by either a
or b and stored in the variable l. The value of the l is LCM of given two numbers.
9. PROGRAM TO ACCEPT A NUMBER AND FIND OUT WHETHER IS IT PRIME
OR NOT
#include<stdio.h>
main()
{
int i,n,c=0;
printf("Enter any number : ");
scanf("%d",&n);
i=1;
while(i<=n)
{
if (n%i==0)
c++;
i++;
}
if(c>2)
printf(" The number %d is NOT PRIME NUMBER\n",n);
else
printf(" The number %d is PRIME NUMBER\n",n);
}
OUTPUT:
Enter any number : 11
The number 11 is PRIME NUMBER
Explanation : The above program accepts two integer numbers as a and b. If both values
are not equal, the lowest value will be subtracted form highest value. This process will repeat
till both values become equal. Finally it will prints either a or b value i.e. GCD of given two
numbers.
7.4 Example Programs 85

10. PROGRAM TO PRINT MULTIPLICATION TABLE OF THE SPECIFIED NUM-


BER
#include<stdio.h>
main()
{
int i,n,c=0;
printf("Enter any number : ");
scanf("%d",&n);
i=1;
while(i<=10)
{
printf(" %d X %d = %d\n",n,i,n*i);
i++;
}
}
OUTPUT:
Enter any number : 12
12 X 1 = 12
12 X 2 = 24
12 X 3 = 36
12 X 4 = 48
12 X 5 = 60
12 X 6 = 72
12 X 7 = 84
12 X 8 = 96
12 X 9 = 108
12 X 10 = 120
Explanation : The above program accepts an integer number as n. It prints the multiplication
table of the given number by using while loop.
11. PROGRAM TO PRINT ALL LOWER CASE LETTERS FROM THE SPECIFIED
CHARACTER TO SPECIFIED CHARACTER
#include<stdio.h>
main()
{
int n;
char f,l;
clrscr();
printf(" Enter a character from where you start : ");
f=getchar();
getchar();
printf(" Enter a character where to stop : ");
l=getchar();
puts(" The letters are :");
for(n=f;n<=l;n++)
printf(" %c ",n);
}

OUTPUT:
86 Chapter 7. Looping Statements

Enter a character from where you start : d


Enter a character where to stop : l
The letters are :
d e f g h i j k l

Explanation : The above program accepts two characters i.e. starting and ending charac-
ters. In the for loop n is initialized with the starting character, prints value of n and it is
incrementing by 1 till the ending character.
12. PROGRAM TO GENERATE THE FIBONACY NUMBERS TILL THE SPECIFIED
NUMBER

#include<stdio.h>
main()
{
int a=0,b=1,n,c;
printf("Enter any number : ");
scanf("%d",&n);
printf("The fibonacy numbers are . . . .:");
printf("\n%d %d ",a,b);
c=a+b;
while (c<=n)
{
printf("%d ",c);
a=b;
b=c;
c=a+b;
}
printf("\n");
}
OUTPUT:
Enter any number : 100
The fibonacy numbers are . . . . :
1 1 2 3 5 8 13 21 34 55 89

Explanation : The above program accepts an integer number n. The variables a and b is
initialized with the 0 and 1 and prints. Next number will be identified as addition of a and b
will stored in c. Till c value becomes greater than or equal to n, it will prints c and next c can
be calculated.
13. PROGRAM TO ACCEPT A NUMBER N, FINDS AND DISPLAYS THE SUM OF
INTEGERS 1 TO 2, 1 TO 3, 1 TO 4, . . . , 1 TO N

#include<stdio.h>
main()
{
int i,m,t,n,sum;
printf("Enter any number : ");
scanf("%d",&m);
for(i=2;i<=m;i++)
{
sum=0;
t=i;
7.4 Example Programs 87

do
{
sum+=i;
i--;
}while(i>=1);
printf("%d ",sum);
i=t;
}
}
OUTPUT:
Enter any number : 5
3 6 10 15

Explanation : The above program accepts an integer number m. By using nested loops,
here within the for loop we are using do-while loop to perform the above operation.
14. PROGRAM TO PRINT 1!,2!,3!,4!,. . . ,N!

#include<stdio.h>
main()
{
int i,j,n,fact;
printf("Enter any number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=1;
for(j=1;j<=i;j++)
fact*=j;
printf("%d, ",fact);
}
}
OUTPUT:
Enter any number : 5
1, 2, 6, 24, 120

Explanation : The above program accepts an integer number m. By using nested loops,
here within the for loop we are using another for loop to perform the above operation.
15. PROGRAM TO GENERATE PRIME NUMBERS TILL THE SPECIFIED NUM-
BER

#include<stdio.h>
main()
{
int j,i,n,c;
printf("Enter any number : ");
scanf("%d",&n);
for(j=1;j<=n;j++)
{
c=0;
i=1;
while(i<=j)
88 Chapter 7. Looping Statements

{
if (j%i==0)
c++;
i++;
}
if(c<=2)
printf("%d ",j);
}
}
OUTPUT:
Enter any number : 10
1 2 3 5 7

Explanation : The above program accepts an integer number n. By using nested loops, here
within the for loop we are using while loop to perform the above operation.
16. PRINT THE FOLLOWING FORMAT

/* PRINT THE FOLLOWING FORMAT


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
. . . . . . . . .
*/
#include<stdio.h>
main()
{
int n,i,j;
clrscr();
printf("Enter an Integer number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf("%d ",j);
printf("\n");
}
}

Explanation : The above program accepts an integer number n. By using nested loops, here
within the for loop we are using another for loop to print the above format.
17. PRINT THE FOLLOWING FORMAT

/* PRINT THE FOLLOWING FORMAT


1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
. . . . . . . . .
7.4 Example Programs 89

*/
#include<stdio.h>
main()
{
int n,i,j;
clrscr();
printf("Enter an Integer number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=i;j>=1;j--)
printf("%2d ",j);
printf("\n");
}
}

Explanation : The above program accepts an integer number n. By using nested loops, here
within the for loop we are using another for loop to print the above format.
18. PRINT THE FOLLOWING FORMAT

/* PRINT THE FOLLOWING FORMAT


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
. . . . .
*/

#include<stdio.h>
main()
{
int n,i,k,j;
clrscr();
printf("Enter an Integer number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(k=1;k<=40-4*i/2;k++)
printf(" ");
for(j=i;j>=1;j--)
printf("%4d",i);
printf("\n");
}
}

Explanation : The above program accepts an integer number n. By using nested loops, here
within the for loops we are using another for loop to print the above format.
19. PRINT THE FOLLOWING FORMAT

/* PRINT THE FOLLOWING FORMAT


90 Chapter 7. Looping Statements

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
. . . . .
*/
#include<stdio.h>
main()
{
int n,i,k,j;
clrscr();
printf("Enter an Integer number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)

{
for(k=1;k<=40-3*i;k++)
printf(" ");
for(j=i;j>=1;j--)
printf("%3d",i);
printf("\n");
}
}
Explanation : The above program accepts an integer number n. By using nested loops, here
within the for loops we are using another for loop to print the above format.
20. PRINTS THE GIVEN THREE NUMBERS IN ASCENDING ORDER
#include<stdio.h>
#include<conio.h>
/* Main program begins */
main()
{
int a,b,c;
clrscr();
/* Accepting inputs from user */
printf("\n Enter 'a' value : ");
scanf ("%d",&a);
printf("\n Enter 'b' value : ");
scanf("%d",&b);
printf("\n Enter 'c' value : ");
scanf("%d",&c);
/* Evaluation and print in ascending order */
if(a<=b&&a<=c)
{
if(b<c)
printf(" The given numbers in ascending order is: %d, %d, %d \n",a,b,c);
else
printf("The given numbers in ascending order is:%d,%d,%d \n",a,c,b);
}
7.4 Example Programs 91

if(b<=a&&b<=c)
{
if(a<c)
printf("The given numbers in ascending order is : %d, %d, %d \n",b,a,c);
else
printf("The given numbers in ascending order is: %d, %d, %d \n",b,c,a);
}
if(c<=a&&c<=b)
{
if(a<b)
printf("The given numbers in ascending order is: %d, %d, %d \n",c,a,b);
else
printf("The given numbers in ascending order is: %d, %d, %d \n",c,b,a);
}
}
OUTPUT:
Enter 'a' value : 12
Enter 'b' value : 10
Enter 'c' value : 2
The given numbers in ascending order is : 2, 10, 12
Explanation : The above program accepts three integer numbers. By using compound if -
else statements we can print the given three numbers in ascending order.
21. C PROGRAMS TO PRINT THE FOLLOWING OUTPUTS USING FOR LOOP.
1 1
2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5

i) Program :
#include<stdio.h>
main()
{
int n,i,j;
clrscr();
printf("Enter an Integer number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf("%d ",i);
printf("\n");
}
}

ii) Program :
#include<stdio.h>
main()
{
92 Chapter 7. Looping Statements

int n,i,k,j;
clrscr();
printf("Enter an Integer number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(k=1;k<=40-4*i/2;k++)
printf(" ");
for(j=i;j>=1;j--)
printf("%4d",i);
printf("\n");
}
}
PROGRAM TO GENERATE SPECIFIED NUMBER OF FIBONACY NUMBERS
#include<stdio.h>
main()
{
int a=0,b=1,n,c,i=2;
printf("Enter how many Fibonaci numbers do you want : ");
scanf("%d",&n);
printf("The fibonacy numbers are . . . .:");
printf("\n%d %d ",a,b);
c=a+b;
do
{
printf("%d ",c);
i++;
a=b;
b=c;
c=a+b;
}while(i<=n);
printf("\n");
getchar();
}
OUTPUT:
Enter any number : 10
The fibonacy numbers are . . . . :
1 1 2 3 5 8 13 21 34 55

22. A cloth show room has announced the following seasonal discounts on purchase of
items.
PURCHASE Discount (percentage)
AMOUNT Mill Cloth Handloom Items
1-100 — 5.0
101-200 5.0 7.5
201-300 7.5 10.0
Above 300 10.0 15.0
Write a C program using switch and if statements to complete the net amount to be
7.4 Example Programs 93

paid by a customer.

#include<stdio.h>
#include<conio.h>
#include<math.h>
/* Main program begins */
main()
{
int amt, cho, item=0;
float finalamt, dis=0.0;
clrscr();
/* Accepting inputs from user */
printf("\n Enter amount : ");
scanf ("%d",&amt);
printf(" Enter item number 1-Mill cloth and 2-Handloom cloth: ");
scanf("%d",&item);
/* Discount Evaluation */
switch(item)
{
case 1:
if (amt>=1 && amt<=100)
dis=0.0;
else if(amt>=101 && amt<=200)
dis=5.0;
else if(amt>=201 && amt<=300)
dis=7.5;
else
dis=10.0;
break;
case 2:
if (amt>=1 && amt<=100)
dis=5.0;
else if(amt>=101 && amt<=200)
dis=7.5;
else if(amt>=201 && amt<=300)
dis=10.0;
else
dis=15.0;
break;
default:
printf(" Invalid Cloth Selection \n");
exit(0);
}
finalamt=amt-(dis/100.0)*amt;
/* Print the Result */
printf(" Discount is : %f ",dis);
printf(" Total amount is : %f ",finalamt);
getch();
}
OUTPUT:
94 Chapter 7. Looping Statements

Enter amount : 200


Enter item number 1 - Mill cloth and 2 - Handloom cloth : 1
Discount is : 5.000000
Total amount is : 190.000000
23. PROGRAM TO PERFORM COMPLEX NUMBER OPERATIONS
#include<stdio.h>
#include<conio.h>
/* Main program begins */
float ans1,ans2;
void main()
{
/* functions declaration */
void sum(int a, int b, int c, int d);
void sub(int a, int b, int c, int d);
void mul(int a, int b, int c, int d);
void div(int a, int b, int c, int d) ;
int a,b,c,d,cho;
char sign;
do
{
clrscr();
/* Displaying the Menu */
printf("\n\t 1 - Addition of complex Numbers");
printf("\n\t 2 - Subtraction of complex Numbers");
printf("\n\t 3 - Multiplication of Complex Numbers");
printf("\n\t 4 - Division of Complex Numbers");
printf("\n\t 5 - Exit");
printf("\n\t\t\t Enter your Choice : ");
scanf("%d",&cho);
if(cho>=5||cho<1)
{
printf("\n\t No operation performed \n");
getch();
exit(0);
}
/* Accepting values from the user */
printf("\n Enter first complex number values (a+ib) : \n");
printf("\n Enter 'a' value : ");
scanf(" %d",&a);
printf("\n Enter 'b' value : ");
scanf("%d",&b) ;
printf("\n Enter second complex number values (c+id):\n");
printf("\n Enter 'c' value : ");
scanf("%d",&c) ;
printf("\n Enter 'd' value : ");
scanf("%d",&d) ;
/* Perform the specified operation */
switch(cho)
{
7.4 Example Programs 95

case 1:
sum(a,b,c,d);
sign='+';
break;
case 2:
sub(a,b,c,d);
sign='-';
break;
case 3:
mul(a,b,c,d);
sign='*';
break;
case 4:
div(a,b,c,d);
sign='/';
break;
default:
printf("No complex operation \n");
break;
}
/* Print the result */
printf("\n\t(%d+i(%d)) %c (%d+i(%d))= (%f+i(%f))",a,b,sign,c,d,ans1,ans2);
getch();
}while(cho!=5);
}
/* Function to addition of two complex numbers */
void sum(int a, int b,int c,int d)
{
ans1=a+c;
ans2=b+d;
}
/* Function to subtraction of two complex numbers */
void sub(int a, int b,int c,int d)
{
ans1=a-c;
ans2=b-d;
}
/* Function to multiply the two complex numbers */
void mul(int a, int b, int c, int d)
{
ans1=(a*c-(b*d));
ans2=(a*d)+(b*c);
}
/* Function to division of two complex numbers */
void div(int a, int b,int c,int d)
{
ans1=((a*c)+(b*d))/((a*a)+(b*b));
ans2=((a*d)+(b*c))/((a*a)+(b*b));;
}
96 Chapter 7. Looping Statements

OUTPUT:
1 - Addition of complex Numbers");
2 - Subtraction of complex Numbers");
3 - Multiplication of Complex Numbers");
4 - Division of Complex Numbers");
5 - Exit");
Enter your Choice : 1
Enter first complex number values (a+ib) :
Enter 'a' value : 1
Enter 'b' value : 2
Enter second complex number values (c+id) :
Enter 'c' value : 4
Enter 'd' value : 5
(1+i (2)) + (4+i(5)) = (5.000000 + i(7.000000));

24. Write C program using FOR statement to find the following from a given set of 20
integers
(a) Total number of even integers
(b) Total number of odd integers
(c) Sum of all even integers
(d) Sum of all odd integers
#include<stdio.h>
#include<conio.h>
/* Main program begins */
main()
{
int n, e=0, o=0, es=0, os=0, i, m;
clrscr();
printf(" Enter how many numbers do you want : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf(" Enter the %dth number : ");
scanf("%d",&m);
if(m%2==0)
{
e++;
es=es+m;
}
else
{
o++;
os=os+m;
}
}
/* Print the specified values */
printf("\n\n The no of even numbers are : %d",e);
printf("\n\n The no of odd numbers are : %d",o);
printf("\n\n The sum of even numbers are : %d",es);
7.4 Example Programs 97

printf("\n\n The sum of odd numbers are : %d",os);


getch();
}
OUTPUT:
Enter how many numbers do you want : 10
Enter the 1th number : 5
Enter the 2th number : 6
Enter the 3th number : 7
Enter the 4th number : 8
Enter the 5th number : 9
Enter the 6th number : 10
Enter the 7th number : 11
Enter the 8th number : 12
Enter the 9th number : 13
Enter the 10th number : 14
The no of even numbers are : 5
The no of odd numbers are : 5
The sum of even numbers are : 50
The sum of odd numbers are : 45
25. Program that will read the value of the following function :
1 for x >0
y = ? 0 for x = 0
-1 for x < 0
using (i) if statements
(ii) else if statements
(iii) conditional operator. */
i) if statements
#include<stdio.h>
#include<conio.h>
/* Main program begins */
main()
{
int y;
float x;
clrscr();
/* Accepting inputs from user */
printf("\n Enter 'x' value : ");
scanf ("%f",&x);
if (x>0.0)
y=1;
if (x<0.0)
y=-1;
if (x==0)
y=0;
/* Print the Result */
printf ("\n\t The value of y is : %d\n",y);
getch();
}
OUTPUT:
98 Chapter 7. Looping Statements

Enter 'x' value : 0.0


The value of y : 0

ii) else-if statements


#include<stdio.h>
#include<conio.h>
/* Main program begins */
main()
{
int y;
float x;
clrscr();
/* Accepting inputs from user */
printf("\n Enter 'x' value : ");
scanf ("%f",&x);
if (x>0.0)
y=1;
else if (x<0.0)
y=-1;
else
y=0;
/* Print the Result */
printf ("\n\t The value of y is : %d\n",y);
getch();
}
OUTPUT:
Enter 'x' value : -45.5
The value of y : -1

iii) Conditional operator


#include<stdio.h>
#include<conio.h>
/* Main program begins */
main()
{
int y;
float x;
clrscr();
/* Accepting inputs from user */
printf("\n Enter 'x' value : ");
scanf ("%f",&x);
y=x>0.0?1(x<0.0?-1:0);
/* Print the Result */
printf ("\n\t The value of y is : %d\n",y);
getch();
}
OUTPUT:
Enter 'x' value : 45.5
The value of y : 1
7.4 Example Programs 99

Program 6.43 :
26. PROGRAM TO FIND THE SUM OF 1 + 2 + 3 + . . . + N USING WHILE LOOP
#include<stdio.h>
#include<conio.h>
main()
{
int sum=0,n,I=1;
clrscr();
/* Accepting inputs from user */
printf("\nEnter number of terms do you want : ");
scanf ("%d",&n);
/* Calculating sum of first n numbers */
while(i<=n)
{
sum=sum+i;
i++;
}
/* Printing of answer */
printf("\n\n sum of the first %d numbers is : %d\n",n,sum);
getch();
}
OUTPUT:
Enter number of terms do you want : 10
sum of first 10 numbers is : 55
27. PROGRAM TO EVALUATE THE SERIES 1+X2/2!+X4/4!+. . . . . UPTO 10 TERMS,
ASSUME SUITABLE VALUE OF X
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int x, f=1, i, j, p=0;
float y=0.0;
clrscr();
/* Accepting inputs from user */
printf("\n Enter 'x' value : ");
scanf ("%d",&x);
/* Evaluation of series */
for(i=0;i<10;i++)
{
for(j=1;j<=p;j++)
fact=fact*j;
y=y+pow(x,p)/fact;
p=p+2;
}
/* Print the Result */
printf("\n\n The value of Y is : %f\n",y);
getch();
100 Chapter 7. Looping Statements

}
OUTPUT:
Enter 'x' value : 4
The value of Y is : 12.201101

28. PROGRAM TO EVALUATE THE SERIES (SIN X) X-X3/3!+X5/5!+. . . . . UPTO 7


TERMS, ASSUME SUITABLE VALUE OF X.

#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int d,n;
float x,y,term,sinx,acc=0.0000001;
clrscr();
/* Accepting inputs from user */
printf("\nEnter 'x' value (in degrees) : ");
scanf ("%f",&x);
/* conversion of degrees into radians */
y=x*3.1415/180;
term=y;
sinx=term;
n=1;
/* Evaluation the expression */
do
{
d=2*n*(2*n+l);
term=-term*y*y/d;
sinx=sinx+term;
n=n+l;
}while(acc<=abs(sinx));
/* Print the result */
printf('\n\n Sin(%f) is : %f", x, sinx);
getch();
}
OUTPUT:
Enter 'x' value (in degrees) : 45
Sin(45.000000) is : 0.707090

29. Write a C program to compute the sum of first n terms (n ≥ 1) of the following series using
’for’ loop. 1 – 3 + 5 – 7 + 9 - . . . . . .

main()
{
int start=1,i=1,no=0,sum=0;
clrscr();
printf ("\nEnter number of terms to be added:-> ");
scanf("%d",&no);
for (i=1;i<=no;i++)
{
7.4 Example Programs 101

if (i%2!=0)
{
sum+=start;
if (i==1)
printf ("%d",start);
else
printf ("+%d",start);
}
else
{
sum-=start;
printf ("-%d",start);
}
start+=2;
}
printf ("=%d",sum);
getch();
}
30. Write a C program to convert a binary number to its corresponding octal number.
main()
{
long int bin_no,no;
int oct_no,oct_p,i,rem,pow2,pow8,inter_oct;
clrscr();
printf ("\nEnter the Binary number: -> ");
scanf("%ld",&bin_no);
no=bin_no;
pow8=1;
oct_no=0;
while (no>0)
{
i=0;
inter_oct=0;
pow2=1;
while (i<=2)
{
if (no==0)break;
rem=no%10;
inter_oct+=rem*pow2;
i++;
pow2*=2;
no/=10;
}
oct_no+=inter_oct*pow8;
pow8*=10;
}
printf ("\nOctal Equivalent for %ld = %d",bin_no,oct_no);
getch();
}
102 Chapter 7. Looping Statements

31. Write a C program to print out n values of the following sequence.


1 –1 1 –1 1 . . .

#include<stdio.h>
#include<conio.h>
main()
{
int i,j,n,k;
clrscr();
printf("\n enter number \n");
scanf("%d",&n);
k=1;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf("%d",k);
printf("\t");
}
getch();
}

32. Write a C program to test whether a given pair of numbers are amicable numbers.
(Amicable number are pairs of numbers each of whose divisors add to the other num-
ber)

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,j,n,sum_i=0,sum_j=0;
clrscr();
printf("enter any two numbers >");
scanf("%d%d",&i,&j);
for(n=1;n<i;n++)
{
if (i%n==0)
sum_i+=n;
}
for (n=1;n<j;n++)
{
if (j%n==0)
sum_j+=n;
}
if ((sum_j==i) && (sum_i==j))
printf ("\nAmicable");
else
printf ("\nNot Amicable");
getch();
}
7.5 Multiple Choice Questions 103

7.5 Multiple Choice Questions


1. Identify the loop construct: [ D ]
(A) if-else (B) switch-case (C) goto (D) while
2. The number of loop constructs in C is: [ B ]
(A) 2 (B) 3 (C) 4 (D) 5
3. The minimum number of times the while loop is executed is [ A ]
(A) 0 (B) 1 (C) 2 (D) cannot be predicted
4. The minimum number of times the for loop is executed is [ A ]
(A) 0 (B) 1 (C) 2 (D) cannot be predicted
5. The minimum number of times the do-while loop is executed is [ B ]
(A) 0 (B) 1 (C) 2 (D) cannot be predicted
6. Continue statement is used to [ A ]
(A) continue the next iteration of a loop construct

(B) exit the block where is exists and continues further

(C) exit the outermost block even if it occurs inside the innermost

(D) continue the compilation even an error occurs in a program

7. What will be the value of x after execution of the program [ B ]

#include<stdio.h>
main()
{
int x=5,y=0;
while(y<10)
{
printf("%d%d",y++,x++);
}
}

(A) 5 (B) 14 (C) 15 (D) 16


8. In the following code point out the error, if any in the for loop [ D ]

#include<stdio.h>
main()
{
int i=1;
for( ; ; )
{
printf("%d",i++);
if (i>5)
break;
}
}
104 Chapter 7. Looping Statements

(A) condition in the for loop is must


(B) two semicolons should be dropped
(C) for loop should be replace with other loop
(D) No error
9. In the following code point out the error, if any in the while loop [ D ]

#include<stdio.h>
main()
{
int i=1;
while( )
{
printf("%d",i++);
if (i>5)
break;
}
}
(A) condition in the while loop is must
(B) there should be at least one semicolon
(C) while loop should be replace with other loop
(D) No error
10. In the following code, if c is a variable initialized to 2, the lowing loop executes. . . . . . . . . ..
number of times [ B ]

while((c>0)&&(c<10))
{
body of the loop
c++;
}
(A) 10 (B) 8 (C) 9 (D) 0
11. What is the functionality of the following program ? [ D ]

main( )
{
int c=0;
do{
printf("%d\n",c++);
}while(c <= 9);
}
(A) adding 9 integers (B) adding integers from 1 to 9
(C) display any 9 integers (D) display integers from 0 to 9
12. How many times the following code prints the string "hello". [ A ]

for(i=1; i<=1000; i++);


printf("hello");
7.5 Multiple Choice Questions 105

(A) 1 (B) 1000 (C) Zero (D) Syntax error


13. What is the output of following statement?

for(i=1; i<4; i++)


printf(%d,(i%2) ? i : 2*i);

(A) 1 4 3 (B) 1 2 3 (C) 2 4 6 (D) 2 2 6


14. In a for loop, if the condition is missing, then, [ B ]
(A) It is assumed to be present and taken to be false.

(B) It is assumed to be present and taken to be true.

(C) It results in a syntax error.

(D) Execution will be terminated abruptly.


15. A possible output of the following program fragment is [ D ]

for (i=getchar();; i=get.char())


if (i==`x') break;
else putchar(i);

(A) mi (B) mix (C) mixx (D) none of the above


16. What is the output of the following C program? [ A ]

# include <stdio.h>
main ( )
{
int a, b=0;
static int c [10]={1,2,3,4,5,6,7,8,9,0};
for (a=0; a<10;+ + a)
if ((c[a]%2)= = 0) b+ = c [a];
printf (%d, b);
}

(A) 20 (B) 25 (C) 45 (D) 90


17. In the for statement: for (exp1; exp2; exp3) { . . . }
where exp1, exp2 and exp3 are expressions. What is optional? [ D ]
(A) None of the expressions is optional.

(B) Only exp1 is optional.

(C) Only exp1 and exp3 are optional.

(D) All the expressions are optional.


18. What is the following program doing? [ C ]

main ()
{ int d = 1;
do
printf(%d\n, d++);
while (d < = 9);}
106 Chapter 7. Looping Statements

(A) Adding 9 integers


(B) Adding integers from 1 to 9
(C) Displaying integers from 1 to 9
(D) None of these
19. Describe the output that will be generated by the code given

#include<stdio.h>
main( )
{
int i=0, x=0;
while(i<20)
{ if(i%5 = = 0)
{x + = i;
printf("%d", x);
}
++i;
}
printf(\nx = %d, x);
}
The output generated by given C program is: 051530 x=30
20. The output generated by given C program is:

main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love SWEETS");
else
printf("I hate MEDICINES");
}
Answer: I hate MEDICINES
21. The output generated by given C program is:

main()
{ int i=0;
for(;i++;printf("%d",i)) ;
printf("%d",i);
}
Answer: 1
22. main()
{
int i = 3;
for (;i++=0;) printf(%d,i);
}
Answer: Compiler Error: Lvalue required.
23. What is the output of th egiven code?
7.5 Multiple Choice Questions 107

main()
{
int i = 3;
for (;i++=0;) printf(%d,i);
}
Answer: Compiler Error: Lvalue required.
Explanation: As we know that increment operators return rvalues and hence it cannot appear
on the left hand side of an assignment operation.
24. Find the output for the following C program [ A ]
main()
{
i=20,k=0;
for(j=1;j<i;j=1+4*(i/j))
{
k+=j<10?4:3;
}
printf("%d", k);
}
(A) 4 (B) 9 (C) 1 (D) None of these
25. Find the output for the following C program [ C ]
int i =10
main()
{
int i =20,n;
for(n=0;n<=i; )
{
int i=10;
i++;
}
printf("%d", i);
}
(A) 24 (B) 29 (C) 20 (D) None of these
26. Find the output: [ A ]
main()
{
char ch;
int count=0;
while((ch = getch() != '\n')
{
while (ch == ' ')
ch = getch();
while((ch!=' ') && (ch!='.'))
{
count++;
ch=getch();
}
}
108 Chapter 7. Looping Statements

(A) 11 (B) 12 (C) 10 (D) None of these


27. how many times the printf statement is executed?
main()
{ int count =
11;
while (--count+1)
printf("count down is %d \n",count);
}
Answer: 11.
28. What is the output of the given Program?
int i =10
main()
{ int i=20,n;
for(n=0;n<=i;)
{ int i=10
i++;
}
printf("%d", i);
}
Answer is 1
29. Consider the following C program
main () {
int x, y, m, n ;
scanf ("%d %d", &x, &y); / * Assume x > 0 and y > 0 */
m = x; n = y ;
while ( m ! = n) {
if (m > n) m = m - n;
else n = n - m ;
}
printf("%d",n);
}
The program computes [ C ]
(A) x + y, using repeated subtraction
(B) x mod y using repeated subtraction
(C) the greatest common divisor of x and y
(D) the least common multiple of x and y
30. What does the following algorithm approximate? (Assume m > 1, i > 0).
x = m; y-i; while (x - y > i) { x = (x + y) / 2 ; y = m/x ; } print (x) ;
(A) log m
(B) m2
1
(C) m 2
1
(D) m 3
7.5 Multiple Choice Questions 109

31. When does the code block following while(x<100) execute? [ A ]


(A) When x is less than one hundred
(B) When x is greater than one hundred
(C) When x is equal to one hundred
(D) While it wishes
32. What is the output of the following problem ? [ A ]

main()
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
(A) 1 (B) 65000 (C) 0 (D) Compiler Error
33. What is the output of the following problem ?

main()
{
unsigned int i=10;
while(i-->=0)
printf("%u ",i);
}
Answer: 10 9 8 7 6 5 4 3 2 1 0 65535 65534. . . ..
34. What is the output of the following problem ?

main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
Answer: Compiler Error
35. What is the output of the following problem ? [ B ]

main()
{
signed char i=0;
110 Chapter 7. Looping Statements

for(;i>=0;i++) ;
printf("%d\n",i);
}
(A) 127 (B) -128 (C) -127 (D) Compiler Error
36. What is the output of the following problem ? [ C ]

main()
{
unsigned char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
(A) 127 (B) -128 (C) Infinite loop (D) Compiler Error
37. What is the output of the following problem ? [ A ]

void main()
{
static int i;
while(i<=10)
(i>2)?i++:i--;
printf(%d, i);
}
(A) 32767 (B) -32767 (C) Infinite loop (D) Compiler Error
8. Functions

8.1 Introduction
Functions act as the fundamental building blocks of large program. Each function normally
performs a specific task. Every C program must contain at least one function named as main where
the program always begins execution. The main function may call other functions with in it.

8.1.1 Importance of functions


If a programmer can identify whatever actrions are performed repeatedly in various part of the
program, write them as a function and call the function from the various parts of the program.
This approach avoids code duplication. Instead of duplicating the same code in different parts
of the program, you just write the function once and call it from different parts of the program,
thus reducing the executable code size. Breaking down your program into subroutines lends your
program a structure. You can divide your task into multiple sub-tasks, develop a function for
each sub-task, and integrate them into a single program. Once a function is written and tested, a
programmer can expect it to fit with the rest of the program modules. This approach encourages
code re-usability.

8.2 User-Define function


C functions can be classified into two categories namely library functions and user defined functions.
Main is an example of user defined functions, printf, scanf, sqrt, etc,. are examples of library
functions. The main difference between these two categories is that library functions are not written
by the user, where as a user defined functions has to be developed by the user, at the time of writing
a program. How ever, a user defined function can later become a part of the "C" program library.
The C function have three parts, they are function declaration, function call and function body.

Function declaration
A function can have a type. C allows bi-directional transmission of information between the caller
of a function and the called function. The caller can communicate with the function by passing
112 Chapter 8. Functions

parameters, whereas the called function can communicate with the caller by returning a value. The
caller will receive several parameters as many as you please. But the called function can return at
the most only one value of only one type. So the type of a function specifies the type of the value
that the function will return.
The general form :
type function_name(parameter list);
The function_name is must for every function. It may be combination of alphabets, digits and
underscore, first character must be an alphabet, no special symbols other than underscore.
Function call
Calling a function is straight forward, call it by name and by supplying a parenthesized set of
parameters as in.
value = function_name(par1, par2, . . .);
Function Body
The general form of any C function body is :
type function_name(parameter list)
parameters declaration
{
local variable declarations;
---------------;
---------------;
return(expression);
}
Parameter passing
Parameters are nothing but input given to a function. By passing parameters the caller can ask the
function to process a set of values. Parameter passing allows you to write generalized and re-usable
functions. Whatever parameters the caller passes are called the actual parameters and whatever
parameters the function has received are called the formal parameters. The actual parameter values
are copied to the formal parameters.
Return value and their types
A function may or may not send back a value to the calling function. If it does, it is done through
the return statement. The return statement can be any one of the following forms.
return;
(or)
return(expression);
The first return statement does not return any value, it acts much as the closing brace of the function,
when return is encountered the control is immediately passed back to the calling function. The
second return statement return the value of the expression.
8.3 Type of Functions 113

Calling a function
A function can be called by specifying the function name in a statement. When compiler encounters
a function call, the control is transferred to that function. Once the function execution completes
the control back to the calling function.

Local variables
A variable declared inside a function is called local variable. The scope of local variables is limited
to the functions in which they are declared, or in other words these variables are inaccessible outside
of this function. Like wise the scope of block variables is limited to that block in which they are
declared.

Global variables
The variables you declare in the global variable section are called Global variables or External
variables. While a local variable can be used only inside the function in which it is declared, a
global variable can be used anywhere in the program. Global variables have a scope that spans the
entire source program, because they can be used in any function.

Global vs Local variables


• Local variables can be used only inside the function or the block in which they are declared.
On the other hand global variables can be used throughout the program.
• All global variables, in the absence of explicit initialization, are automatically initialized to
zero, i.e. int initialized with the value 0, float gets initialized with 0.0, char holds the ASCII
null byte and pointer initialized with NULL. Local variables do not get initialized to any
specific value. Thus a local variable starts up with an unknown value (garbage value), which
may be different each time.
• Global variables get initialized only once, typically just before the program starts executing.
But, local variables get initialized each time the function or block gets called.
• The initial value that you supplied for a global variable must be a constant, where as a local
variable can contain variables in its initializer.
• A local variable loses its value the movement the function/block containing it is exited. So
you cannot expect a local variable to retain. Global variables retain there values through out
the program’s execution.

Scope of variables
The scope of local variables is limited to the functions in which they are declared, or in other words
these variables are inaccessible outside of this function. Like wise the scope of block variables is
limited to the block in which they are declared. Global variables have a scope that spans the entire
source program, because they can be used in any function.

8.3 Type of Functions


Function are categorized by depending on whether arguments are present or not or whether a value
is returned or not.
1. Function with no argument and no return values
2. Function with arguments and no return values
3. Function with arguments and return values

Function with no arguments and no return value


In this case, the functions do not contain any arguments and do not receive any data from the calling
function. The following example program demonstrates this feature.
Example :
114 Chapter 8. Functions

/* FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUES */


#include<stdio.h>
main()
{
lineprint();
power();
lineprint();
}
lineprint()
{
int i;
for(i=0;i<=50;i++)
printf("-");
printf("\n");
}
power()
{
int x,y,i,r;
printf(" Enter the base value : ");
scanf("%d",&x);
printf(" Enter the power value : ");
scanf("%d",&y);
r=1;
for(i=0;i<y;i++)
r=r*x;
printf(" %d power %d is : %d \n",x,y,r);
}
OUTPUT :
--------------------------------------------------
Enter the base value : 2
Enter the power value : 3
2 power 3 is : 8
--------------------------------------------------
Explanation : In the above program there are two functions names printline and power. The
printline function will print a line by using ’-’ character. The power function will accepts base and
power values from user as x and y will calculate xy value. Both functions are not returning any
value to main.
Function with Arguments and no return value
In this case, the function will accept the argument values from the user and send to and does not
contain any return values. The following example program demonstrates this feature
Example:
/* FUNCTION WITH ARGUMENTS AND NO RETURN VALUES */
#include<stdio.h>
main()
{
char c;
int x,y;
printf("Enter a character : ");
8.3 Type of Functions 115

c=getchar();
lineprint(c);
printf(" Enter the base value : ");
scanf("%d",&x);
printf(" Enter the power value : ");
scanf("%d",&y);
power(x,y);
lineprint(c);
}
lineprint(ch)
char ch;
{
int i;
for(i=0;i<=50;i++)
printf("%c",ch);
printf("\n");
}
power(a,b)
int a,b;
{
int i,r;
r=1;
for(i=0;i<b;i++)
r=r*a;
printf(" %d power %d is : %d \n",a,b,r);
}
OUTPUT :
Enter a character : *
**************************************************
Enter the base value : 2
Enter the power value : 3
2 power 3 is : 8
**************************************************
Explanation : In the above program there are two functions names printline and power. The
printline method will accept a character as parameter and print a line by using that character. The
power function will accepts base and power values as parameters and will calculate xy value. Both
functions are not returning any value to main.
Function with Arguments and return values
In this case, the functions will accept argument values from the user and contains the return values.
The following example program demonstrates this feature
Example:
/* FUNCTION WITH ARGUMENTS AND RETURN VALUES */
#include<stdio.h>
main()
{
char c;
int x,y;
printf(" Enter a character : ");
116 Chapter 8. Functions

c=getchar();
printline(c);
printf(" Enter the base value : ");
scanf("%d",&x);
printf(" Enter the power value : ");
scanf("%d",&y);
printf(" %d power %d is : %d \n",x,y,power(x,y));
printline(c);
}
printline(ch)
char ch;
{
int i;
for(i=0;i<=50;i++)
printf("%c",ch);
printf("\n");
}
power(a,b)
int a,b;
{
int i,r;
r=1;
for(i=0;i<b;i++)
r=r*a;
return(r);
}
OUTPUT :
Enter a character : *
**************************************************
Enter the base value : 2
Enter the power value : 3
2 power 3 is : 8
**************************************************

Explanation : In the above program there are two functions names printline and power. The
printline function will accept a character as parameter and print a line by using that character. This
function does not return any value to main function. The power function will accepts base and
power values as parameters and will calculate xy value and return to the main function for print it.

8.4 Storage Classes


All the variables should have a data type and a storage class. To define a variable in C, we need
to mention its data type and its storage class. If we do not specify the storage class of a variable
in its declaration, the compiler will assume a storage class dependent on the context in which the
variable is used. Thus C has got certain default storage classes.
The variables may also be categorized, depending on the place of their declaration, as INTER-
NAL (local) or EXTERNAL (global). Internal variables are within a particular function, while
external variables are declared outside of all functions.
From C compiler point of view, a variable name identifies some physical location within the
computer where the string of bits representing the variable’s value is stored. There are basically
8.4 Storage Classes 117

two kinds of locations in a computer where such a value may be kept: memory and CPU register.
The variable’s storage class determines which of these two locations the value is stored. Moreover,
a variable’s storage class tells us:
• Where the variable would be stored.
• What will be the initial value of the variable, if the initial value is not specifically assigned.
(i.e. the default initial value)
• What is the scope of the variable; i.e. in which function the value of the variable would be
available.
• What is the life of the variable; i.e. how long would the variable exist.

8.4.1 Types of Storage Classes


Automatic Variables
Automatic variables are declared inside a function. These are created when the function is called
and destroyed automatically when the function is exited. Automatic variables are private (or local)
to the function in which they are declared. Because of this property, automatic variables are also
referred to as local or internal variables. We may also use the keyword auto to declare automatic
variables explicitly. One of the important feature of automatic variables is that their value cannot be
changed accidentally by what happens in some other functions in the program. This assures that we
may declare and use the same name variable in different functions in the same program without
causing any confusion to the compiler. The automatic variable declaration may be :
main(){
int n;
---------
---------
}
(or)

main(){
auto int n;
---------
---------
}
Example:
/* PROGRAM TO ILLUSTRATION OF WORKING OF AUTO VARIABLES */
main()
{
int a=10000;
fun2();
printf("%d\n",a);
}
fun1()
{
int a=100;
printf("%d\n",a);
}
fun2()
{ int a=1000;
fun1();
118 Chapter 8. Functions

printf("%d\n",a);
}
OUTPUT:
10
100
1000
Explanation : In the main function the variable a is declared as local and holding the value 10000
this is the last line output. The main function is calling fun2, in this fun2 the variable a is declared
as local and holding the value of 1000, this is the second line output. This fun2 is calling fun1, in
the fun 1 the variable a is declared as local and holding the value 100, this is the first line output.
External Variables
Some variables are alive and active throughout the entire program are known as external variables
or global variables. External variables are declared outside of all function in the program. The
global variables can be accessed by any function in the program. Once a variable has been declared
as global, any function can use it. and change its value. Then subsequent function can refer only
that new values.
Example :
/* PROGRAM TO ILLUSTRATE PROPERTIES OF GLOBAL VARIABLES */
int a;
main()
{
a=25;
printf("a = %d\n",a);
printf("a = %d\n",function1());
printf("a = %d\n",function2());
printf("a = %d\n",function3());
}
function1()
{
a=a+10;
return(a);
}
function2()
{
int a;
a=10;
return(a);
}
function3()
{
a=a+10;
return(a);
}
OUTPUT:
a = 25
a = 35
a = 10
a = 45
8.4 Storage Classes 119

Explanation : In the above program the variable a is declared as global. In the main function 25 is
assigned to this variable a. The first line of output prints this value i.e. 25. In the function1 10 is
added to the variable a now its value is 35. This is the second line output. In the function3 10 is
added to the variable a now its value becomes 45, this is the last line output. In the function2 the
variable a declared as local is holdin value 10, this is the third line output.

Static Variables
A variable can be declared as static by using static keyword. The value of static variables persists
until the end of the program. A static variables may be either an internal type or an external
type, depending on the place of the declaration. Internal static variables are those which are
declared inside a function. The scope of internal static variable extend up to the end of the function.
Therefore internal static variables are similar to auto variables, except that they remain in existence
(alive) throughout the program. A static variable is initialized only once, when the program is
compiled; it is never initialized again.
Example:

/* PROGRAM TO ILLUSTRATE PROPERTIES OF STATIC VARIABLES */


main()
{
int c;
for(c=1;c<=3;c++)
fun();
}
fun()
{
static int a=5;
a=a+3;
printf("a = %d\n",a);
}
OUTPUT:
a = 8
a = 11
a = 14

Explanation : In the above program the first call of fun, a is initialized with 5 and add 3 to it, now
the new value is 8. Because a is static, this value persists and therefore, the next call adds another 3
to a now the new value is 11. The value of a becomes 14 during te third call of fun.

Register Variables
Some of the variables can store their values in one of the machine’s registers, instead of keeping
in the memory (where normal variables are stored). Since a register access is much faster than
a memory access. Keeping the frequently accessed variables (like loop control variables) in the
register will lead to faster execution. It can be done :

register int i;

Most compilers allow only int or char variables to be placed in the register, since only a few
variables can be placed in the register. However C will automatically convert register variables into
non-register variables once the limit is reached.
120 Chapter 8. Functions

8.4.2 Scope of Variables


The scope of a variable is the portion of a program in which the variable may be visible or available.
A variable is said to have Block scope if it is recognized only within the block. A variable with
block scope is known as a Local Variable or Private variable or Internal Variable.
If the declaration of a variable appears outside of all the blocks in a program, the variable is
said to have File Scope. Such a variable can be recognized in the entire program. A variable with
the file scope is known as a global variable or public variable or external variable. The same
variable name may appear in different scopes. It is the function of the compiler to decide whether
the different occurrences of the variable refer to the same variable or not. Based on the scope of the
variable, the compiler decides the linkage of the different occurrences of the same variable.

8.5 Standard Library Functions


The C language supports a number of library functions that carry out various commonly used
operations or calculations. A library function is access by writing the function name followed by a
list of arguments.

8.5.1 Commonly used Library Functions

Function Return Type Purpose


abs(x) int Returns the absolute value of x
cos(d) double Return the cosine of d
exp(d) double Raise e to the power d (e=2.71828)
log(d) double Return the natural logarithm of d
log10(d) double Return the logarithm (base 10) of d
pow(d1, d2) double Return d1 raised to the d2 power
sin(d) double Return the sine of d
sqrt(d) double Return the square root of d
tan(d) double Return the tangent of d
toascii(c) int Convert value of argument to ASCII
tolower(c) int Convert letter to lowercase
toupper(c) int Convert letter to uppercase
isalpha(c) int Determine if argument is alphabetic, Returns nonzero value if true,
0 otherwise
isdigit(c) int Determine if argument is a decimal digit, Returns nonzero value if
true, 0 otherwise
islower(c) int Determine if argument is lowercase, Returns nonzero value if true,
0 otherwise
isupper(c) int Determine if argument is uppercase, Returns nonzero value if true,
0 otherwise
isascii(c) int Determine if argument is an ASCII character, Returns nonzero
value if true, 0 otherwise

8.6 Recursion
The function called by itself is called recursive function and this process is often referred to as
recursion.
Example:

main()
8.6 Recursion 121

{
printf("Welcome to SHREETECH \n");
main();
}
Important Conditions
There are two important conditions that must be satisfied by any recursive procedure.
• Each time a procedure calls itself, it must be nearer to a solution.
• There must be a decision criterion for stopping the computation.
Types of recursion
There are two types of recursions.
1. The first type concerns recursively defined functions (or primitive recursive functions).
Factorial function is an example of this kind.
2. The second type of recursion is the recursive use of a procedure (nonprimitive recursive).
Ackermann’s function is an example of this kind.
Factorial of a Given Number
Here fact(n) is defined in terms of fact(n-1), which in turn is defined in terms of fact(n-2), etc., until
fact(0) is reached, whose value is given as "one".
Example :
/* FACTORIAL OF A GIVEN NUMBER BY USING RECURSION */
#include<stdio.h>
void main()
{
int n, rst;
int fact(int);
printf(" Enter any number : ");
scanf("%d",&n);
rst=fact(n);
printf(" Factorial of %d is : %d\n",n,rst);
}
int fact(int x)
{
if(x==0)
return 1;
else
return(x*fact(x-1));
}
OUTPUT:
Enter any number : 5
Factorial of 5 is : 120
Explanation : In the above program accepted value n will be passed to the fact function. The fact
function will call itself till the argument becomes 0. The final value will be saved in rst variable.
Fibonacci Number
Here fib(0) is 1 and fib(1) is also 1and fib(n) is defined in terms of fib(n-1)+fib(n-2), like :
fib(0) = 1
fib(1) = 1
fib(2) = fib(1)+fib(0)
122 Chapter 8. Functions

fib(3) = fib(2)+fib(1)
fib(4) = fib(3)+fib(2)

Example :
/* CALCULATED THE SPECIFIED NUMBER FIBONACCI NUMBER BY USING RECURSION */
#include<stdio.h>
void main()
{
int n, rst;
int fibo(int);
printf(" Enter any number : ");
scanf("%d",&n);
rst=fibo(n);
printf(" the %dth Fibonacci number is : %d\n",n,rst);
getch();
}
int fibo(int x)
{
if(x==0||x==1)
return 1;
else
return(fibo(x-1)+fibo(x-2));
}
OUTPUT:
Enter any number : 8
The 5th Fibonacci number is : 13
Explanation : In the above program accepted value n will be passed to the fibo function. The fibo
function will call itself till the argument becomes 0 or 1. The final value will be specified Fibonacci
number.
GCD of two number
/* Calculating the GCD of given two numbers by using recursion */
#include<stdio.h>
void main()
{
int a, b, rst;
int gcd(int,int);
clrscr();
printf(" Enter first number : ");
scanf("%d",&a);
printf(" Enter second number : ");
scanf("%d",&b);
rst=gcd(a,b);
printf(" GCD of %d and %d is : %d \n",a,b,rst);
getch();
}
int gcd(int x, int y)
{
if(y==0)
8.7 Header file 123

return x;
else
return(gcd(y,x%y));
}
OUTPUT:
Enter first number : 18
Enter second number : 45
GCD of 18 and 45 is : 9

Explanation : In the above program accepted two integer values a and b will be passed to the gcd
function. The gcd function will call itself till the second argument becomes 0. The final value will
be saved in rst variable.

8.7 Header file


C compiler provides a number of built-in or library functions. Certain definitions and declarations
are required when these library functions are to be used. They are available in a file called Header
File. Each header file contains the library functions along with the necessary definitions and
declarations. Standard I/O library functions are available in a file named stdio.h (standard input
output header file). The following line is included in a C program whenever standard I/O functions
are used.

#include<stdio.h>
It causes the contents of the header file to be included within the program. If it is not included in a
program, the user must define and declare the necessary I/O functions.

8.8 C Preprocessor
The C Preprocessor is a program that process is our program before it is passed to the compiler.
Here if the source code is stored in a file temp.c then the expanded source code gets stored in a file
temp.i. When this expanded source code is compiled the object code gets stored in temp.obj. When
this object code is linked with the object code of the library function the resultant executable code
gets stored in temp.exe.

A preprocessor carries out the following actions like (i) Simple string replacement, (ii) Macro
expansion, (iii) File inclusion and (iv) Conditional inclusion, on the source file before it is passed to
the compiler.

8.8.1 Simple string replacement


It is replacement of a string which is accomplished through #define statement. The general form of
directive is :
124 Chapter 8. Functions

#define macro_name sequence_of_characters

Ex : #define EX "This is my example program \n" When the identifier EX is encountered the
compiler will replace it by the string "This is y example program \n ".

8.8.2 Macro expansion


A macro is pseudo function i.e. it appears like a function in its form and usage. Macro can be
classified into two groups they are (i) Simple macro definition and (ii) Macro definition with
arguments.
Simple Macro Definition
A macro is simply substitution string that is placed in the program.
Ex :

#define PRINT printf("Welcome to Macros");

When we want to display this message, we just use the instruction PRINT. Once a macro name has
been defined, it may be used as part of the definition of other macro names. Ex :

#define TEN 10
#define HUNDRED (TEN * TEN)
#define THOUSAND (HUNDRED * TEN)

Macro definition with arguments


We can define macros with parameters. General form :

#define macro_name(n1, n2, . . .nn)


Ex :
#define SQUARE(x) ((x) * (x))
#define MAX(a,b) a>=b?a:b

8.8.3 File Inclusion


Some function from another file is required in the current program, then that file can be included in
the current program by include statement. Then all function written in the included file can be used
in the current file. This saves time and re-usability to avoid rewriting of readely available function.
Ex :

#include <stdio.h>
#include "stdio.h"

8.8.4 Conditional Inclusion


Conditional inclusion is used for conditional selection of parts of the source file. Conditional
selection is rarely performed using #defined values.
#if and #endif
#if evaluates a constant integer expression. #endif is a delimiter of end of statement. General form
of #if is :

#if constant_expression
Statements
#endif
8.9 Example Programs 125

#else
It works much similar to the else part in the C language.
Ex :

#define RUNS 60
.................
.................
#if RUNS>=100
printf("Century\n");
#else
printf("Not a Century\n");
#endif

#elif
It works much similar to the else-if in the C language.

8.9 Example Programs


1. Write a function rightrot(x, n) that returns the value of the integer x rotated to the
right by n positions.

#include<conio.h>
rightrot(x,n)
{
int x,n,k=0,num,rem,i,j,dig;
int arr1[10],arr2[10];
clrscr();
printf("\n Enter the integer to be rotated : ");
scanf("%d",&x);
printf("\n Enter the positions by which %d is to be rotated
: ",x);
scanf("%d",&n);
for(num=x;num!=0;num/=10)
{
rem=num%10;
arr1[k++]=rem;
}
i=k-1;
k=0;
for(;i>=0;i--)
arr2[k++]=arr1[i];
k-=1;
for(i=1;i<=n;i++)
{
dig=arr2[k];
for(j=k;j>0;j--)
arr2[j]=arr2[j-1];
arr2[0]=dig;
}
printf("\n\n The original number is : );
126 Chapter 8. Functions

return x;
printf("\n The rotated number is : ");
for(i=0;i<=k;i++)
printf("%d",arr2[i]);
getch();
}
2. Write a C function strend(s, t), which returns 1 if the string t occurs at the end of the
string s, and zero otherwise
#include<conio.h>
#include<string.h>
strend ()
{
char s[100],t[20],c[20];
int i,j,k=0,len1,len2;
clrscr();
printf("\n Enter the string : ");
gets(s);
printf("\n Enter the string to be searched for : ");
gets(t);
len1=strlen(s);
len2=strlen(t);
for(i=len1-(len2);i<=len1;i++)
{
c[k++]=s[i];
}
c[k]='\0';
if(strcmp(t,c)==0)
return 1;
else
return 0;
getch();
}

8.10 Multiple Choice Questions


1. Storage class controls [ D ]
(A) life time of a variable (B) scope of a variable
(C) linkage of a variable (D) all the above
2. Which is not a storage class [ B ]
(A) auto (B) struct (C) typedef (D) static
3. Automatic storage class has [ D ]
(A) temporary storage (B) block scope
(C) persistent storage (D) options c&b
4. The register storage class has [ D ]
(A) block scope (B) persistent storage
(C) temporary storage (D) options a&b
8.10 Multiple Choice Questions 127

5. The storage class type of external static has [ D ]


(A) persistent storage (B) block scope
(C) file scope (D) options a and c
6. The typedef statement is used to [ A ]
(A) create a new data type (B) rename the existing data type
(C) to define a storage class (D) create a structure
7. Which storage class may help in faster execution [ C ]
(A) static (B) extern (C) register (D) auto
8. Which storage class specifies local variables: [ D ]
(A) auto (B) register
(C) internal static (D) all the above
9. External variable declaration uses: [ B ]
(A) the keyword external (B) the keyword extern
(C) no keyword (D) the keyword auto
10. What would be the error in the following function at the time of compilation? [ C ]

f( int x, int y)
{
int x;
x=20;
return x;
}
(A) missing parentheses in return statement
(B) the function should be defined as intf(int x, int y)
(C) redeclaration of x
(D) None oth the above
11. The following code prints ’Computer’ ______ number of times.[ B ]

main() {
printf("\nComputer");
main( );
}
(A) infinite number of times (B) 32767 times
(C) 65536 times (D) Till the stack doesn’t overflow
12. What is the output of the following program? [ B ]

main( )
{
int i=0;
while(i<5)
{
sum(i);
128 Chapter 8. Functions

i++;
}
}
void sum(i)
int i;
{
static int k;
printf("%d",k++);
k++;
}
(A) 0 1 2 3 4 (B) 1 2 3 4 5 (C) 1 3 5 7 9 (D) 0 2 4 6 8
13. The variable that are declared outside all the functions are called ______. [ B ]
(A) Local variable (B) Global variable
(C) Auto variable (D) None of the above
14. For implementing recursive function the data structure used is: [ B ]
(A) Queue (B) Stack (C) Linked List (D) Tree
15. Which of the following statement is true about a function?[ A ]
(A) An invoking function must pass arguments to the invoked function.
(B) Every function returns a value to the invoker.
(C) A function may contain more than one return statement.
(D) Every function must be defined in its own separate file.
16. What is the name of built-in function for finding square roots? [ C ]
(A) square(x) (B) sqr(x)
(C) sqrt(x) (D) No built-in function
17. Choose the function that returns remainder of x/y - [ C ]
(A) remainder( ) (B) mod( )
(C) modulus( ) (D) rem( )
18. Choose the directive that is used to remove previously defined definition of the macro name
that follows it - [ C ]
(A) # remdef (B) # pragma
(C) # undef (D) # define
19. If storage class is missing in the array definition, by default it will be taken to be [ A ]
(A) automatic
(B) external
(C) static
(D) either automatic or external depending on the place of occurrence.
20. main ( ) is an example of [ A ]
(A) library function (B) user defined function
(C) header (D) statement
8.10 Multiple Choice Questions 129

21. A global variable is a variable [ C ]


(A) declared in the main ( ) function.
(B) declared in any function other than the main ( ) function.
(C) declared outside the body of every function.
(D) declared any where in the C program.
22. What is the following function computing? Assume a and b are positive integers. [ A ]

int fn( int a, int b) {


if (b == 0)
return b;
else
return (a * fn(a, b - 1));
}
(A) Output will be 0 always (B) Output will always be b
(C) Computing ab (D) Computing a + b
23. If a function is declared as void fn(int *p), then which of the following statements is valid to
call function fn? [ B ]
(A) fn(x) where x is defined as int x;
(B) fn(x) where x is defined as int *x;
(C) fn(&x) where x is defined as int *x;
(D) fn(*x) where x is defined as int *x;
24. What is the output of the following program? [ C ]

main ( )
{ extern int x;
x = 20;
printf(\n%d, x);
}
(A) 0 (B) 20 (C) error (D) garbage value
25. Choose the correct one [ D ]
(A) Address operator can not be applied to register variables
(B) Address operator can be applied to register variables
(C) Use of register declaration will increase the execution time
(D) None of the above
26. What is the output of the following program? [ D ]

main ( )
{ int x = 2, y = 5;
if (x < y) return (x = x+y); else printf (z1);
printf(z2);
}
(A) z2 (B) z1z2 (C) Compilation error (D) None of these
130 Chapter 8. Functions

27. What is the output of the following program? [ D ]

main()
{
int x=20;
int y=10;
swap(x,y);
printf("%d %d",y,x+2);
}
swap(int x,int y)
{
int temp;
temp =x;
x=y;
y=temp;
}

(A) 10,20 (B) 20,12 (C) 22,10 (D) 10,22


28. What is printed when this program is executed [ A ]

main()
{
printf ("%d\n",f(7));
}
f(X)
{
if ( x<= 4)
return x;
return f(--x);
}

(A) 4 (B) 5 (C) 3 (D) 7


29. what is printed when the following program is compiled and executed? [ C ]

int func (int x)


{
if (x<=0)
return(1);
return func(x -1) +x;
}
main()
{
printf("%d\n",func(5));
}

(A) 14 (B) 15 (C) 16 (D) 17


30. Find the output: [ B ]

main()
{
int a==4
8.10 Multiple Choice Questions 131

sqrt(a);
printf("%d",a);
}
(A) 2.0 (B) 2 (C) 4.0 (D) 4
31. Find the output
#include <stdio.h>
main()
{
int j,ans;
j = 4;
ans = count(4);
printf("%d\n",ans);
}
int count(int i)
{
if ( i < 0) return(i);
else
return( count(i-2) + count(i-1));
}
(A) 18 (B) -18 (C) Linking Error (D) Syntax Error
32. What is the output generated for the following code [ B ]
#define square (a) (a*a)
printf("%d",square(4+5));
(A) 81 (B) 4 (C) 29 (D) None of the above
33. output of the program?[ A ]
#define prn(a) printf("%d",a)
#define print(a,b,c) prn(a), prn(b), prn(c)
#define max(a,b) (a<b)? b:a
main()
{ int x=1, y=2;
print(max(x++,y),x,y);
print(max(x++,y),x,y);
}
(A) 3 4 2 (B) 3 4 1 (C) 3 3 2 (D) 4 4 2
34. output of the program?[ D ]
i=foo(2)
foo(int s){
if(!s)
return s;
else
{ int i=5; return i}
}
(A) 4 (B) 2 (C) 3 (D) 5
132 Chapter 8. Functions

35. output of the program?[ D ]


#define max(a,b) (a>b?b:a)
#define squre(x) x*x
int i = 2, j = 3, k = 1;
printf ("%d %d", max(i,j), squre(k));
(A) 32 (B) 21 (C) 24 (D) 31
36. What is the output generated for the following code [ B ]
main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}
(A) 132 (B) 321 (C) 123 (D) 312
37. Consider the following C function:
int f (int n) {
static int i = 1;
if (n >= 5) return n;
n = n + i;
i ++;
return f (n);
}
The value returned by f(1) is [ B ]
(A) 5 (B) 7 (C) 6 (D) 8
38. What is the correct value to return to the operating system upon the successful completion of
a program? [ C ]
(A) 1 (B) -1 (C) 0 (D) NULL
39. What is the output of the below code?
main()
{
printf("Hello\n");
fork();
printf("Hi\n");
}
40. Find the output : [ A ]
#define int char
main()
{
int i=65;
printf("sizeof(i)=%d",sizeof(i));
}
(A) 1 (B) 2 (C) 65 (D) Compiler Error
8.10 Multiple Choice Questions 133

41. Find the output [ A ]

#define val 1+2


printf("%d%d",val/val,val^3)

(A) 3 9 (B) 5 9 (C) 1 9 (D) Compiler Error


42. Find the output [ B ]

#define a 10
main()
{
#define a 50
printf("%d",a);
}

(A) 10 (B) 50 (C) Compiler Error (D) None


43. Find the output [ A ]

#define clrscr() 100


main()
{
clrscr();
printf("%d\n",clrscr());
}

(A) 100 (B) NULL (C) Compiler Error (D) None


44. Find the output [ A ]

#define f(g,g2) g##g2


main()
{ int var12=100;
printf("%d",f(var,12));
}

(A) 100 (B) NULL (C) Compiler Error (D) None


45. Find the output [ A ]

#define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}

(A) TRUE (B) NULL (C) Compiler Error (D) FALSE


46. Find the output [ A ]
134 Chapter 8. Functions

#define prod(a,b) a*b


main()
{
int x=3,y=4;
printf("%d",prod(x+2,y-1));
}

(A) 10 (B) 20 (C) Compiler Error (D) 11


47. What are the values printed by the following program? [ C ]

#define dprint(expr) printf(#expr "=%d\n",expr)


main()
{
int x=7;
int y=3;
dprintf(x/y);
}

(A) #2 = 2 (B) expr=2 (C) x/y=2 (D) Compiler Error


48. What is the output of the following problem ? [ D ]

#define INC(X) X++


main()
{
int X=4;
printf("%d",INC(X++));
}

(A) 4 (B) 5 (C) 6 (D) Compiler Error


49. What is the output of the following problem? [ D ]

void main()
{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
} int ret(int ret)
{
ret += 2.5;
return(ret);
}

(A) 4 (B) 5 (C) 6 (D) 7


50. What is the output of the following problem?

void pascal f(int i,int j,int k)


{
printf(%d %d %d,i, j, k);
}
void cdecl f(int i,int j,int k)
{
printf(%d %d %d,i, j, k);
8.10 Multiple Choice Questions 135

}
main()
{
int i=10;
f(i++,i++,i++);
printf(" %d\n",i);
i=10;
f(i++,i++,i++);
printf(" %d",i);
}
Answer:
10 11 12 13
12 11 10 13
Explanation: Pascal argument passing mechanism forces the arguments to be called from
left to right. cdecl is the normal C argument passing mechanism where the arguments are
passed from right to left.
51. What is the output of the below code? [ A ]

int i=10;
main()
{
extern int i;
{
int i=20;
{
const volatile unsigned i=30;
printf("%d",i);
}
printf("%d",i);
}
printf("%d",i);
}
(A) 30 20 10 (B) 10 20 30 (C) 30 10 20 (D) Error
52. What is the output of the below code? [ A ]

void main()
{
static int i=i++, j=j++, k=k++;
printf(i = %d j = %d k = %d, i, j, k);
}
(A) i = 1 j = 1 k = 1 (B) i = 0 j = 0 k = 0 (C) i = 2 j = 2 k = 2 (D) Error
9. Arrays & Strings

9.1 Introduction
Array is a homogeneous compound data type, or an array is a group of homogeneous data items
sharing a common name. The ability to use a single name to represent a collection of items is
achieved through arrays. The individual values are called ELEMENTS and the complete set of
values are referred as an array. A particular element can be referred by writing a number called
INDEX number or SUBSCRIPT in brackets after the array name.
Array properties
• The type of an array is the data type of its elements.
• The location of an array is the location of its first element.
• The length of an array is the number of data elements in the array.
• The size of an array is the length of the array times the size of an element.
Arrays whose elements are specified by one subscript are called single subscripted or single
dimensional array. Analogous array whose elements are specified by two and three subscripts are
called two-dimensional or double subscripted and three-dimensional or triple-sub-scripted arrays
respectively.

9.2 One-Dimensional Arrays


A list of items can be given one variable name and elements are specified by one subscript are
called a single-subscripted variable or a one-dimensional array.
int marks[5];
The computer will reserve five storage locations to store five integer values, as shown below.
The values to the array elements is assigned and stored as follows
marks[0] = 45
marks[1] = 65
marks[2] = 10
marks[3] = 93
138 Chapter 9. Arrays & Strings

marks[4] = 40

9.2.1 Array declaration


In C arrays must be declared before they are using. The type of the array is of that elements that
will hold in the array. Array of character elements are is called a string. When we declare an array
you must specify (either directly or indirecty) how many elements the array will have i.e. the size
of the array. This size of the array should be specified between in a pair square brackets ([]). This
size of the array cannot be a variable and has to be an integer constant. The general form of array
declaration is
type array_name[size];
Ex: int marks[10]
With the above declaration the computer will reserve 100 storage locations to store 100 integer
values, as shown below.

9.2.2 Array Initialization


Elements of an array can be assigned initial values by the following array definition with a list of
initializes enclosed in braces and separated by comma.
Ex:-
int marks[5] = {65, 98, 62, 48, 57};
Here it defines the array marks to contain five integer elements and initializes marks[0] to 65,
marks[1] to 98, marks[2] to 62, marks[3] to 48 and marks[4] to 57. The array initialization can be
done in the following ways :
1. If the number of initializers is less than the number of elements in the array, the remaining
elements are set to zero.
Ex:-
int m[5]={3,4,8}; is equivalent to
int m[5]={3,4,8,0,0};
2. If initializers have been provided for an array, it is not necessary to explicitly specify the
array length, in which case the length is derived from the initializers.
Ex:-
int m[]={3,7,3,9,10}; is equivalent to
int m[5]={3,7,3,9,10};
3. A character array may be initialized by a string constant, resulting in the first element of the
array being set to the first character in the string, the second element to the second character,
and so on. The array also receives the terminating ’\0’ in the string constant.
Ex:-
char name[10]="COMPUTERS"; is equivalent to
char name[10]={'C','O','M','P','U','T','E','R','S','\0'};

9.2.3 Storage and Accessing Elements


The array elements can be accessed by simply specifying the name of the array followed by an
index within the square braces. In the same way we can store the value in the specified indexes.
You can enter the element values of the array by using scanf() statement in the ’for’ loop.
Example:
9.3 Two-Dimensional Arrays 139

// PROGRAM TO READ AND PRINT AN ARRAY


#include<stdio.h>
main()
{
int m[100], i, n;
printf("Enter how many elements do you want? : ");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("Enter the value of m[%d] ; ",i+1);
scanf("%d",&m[i]);
}
printf("The values of the array a is : \n");
for(i=0; i<n; i++)
printf("m[%d] = %d\n",i+1,m[i]);
}
OUTPUT :
Enter how many elements do you want? : 5
Enter the value of m[1] ; 10
Enter the value of m[2] ; 20
Enter the value of m[3] ; 30
Enter the value of m[4] ; 40
Enter the value of m[5] ; 50
The values of the array a is :
m[1] = 10
m[2] = 20
m[3] = 30
m[4] = 40
m[5] = 50

Explanation : In the above program will accept the number of elements are present in the array
from the user as n. Accepts array element from the user and print it by using for loops.

9.2.4 Size of an array


By using the sizeof() operator, we can identify the total number of memory used by the array.

int marks[10];

with the above example the memory occupied by the array marks is

sizeof(marks);

will returns 20 since 10 ints will occupy 10 * 2 = 20 bytes. If the entered index of an array exceeds
the size leads unpredictable results.

9.3 Two-Dimensional Arrays


To store a table of values we will go for two-dimensional arrays. Array whose elements are
specified by two subscripts are called two-dimensional or double subscripted arrays. It is nothing
but collection of one-dimensional arrays, which are placed one after another.
140 Chapter 9. Arrays & Strings

9.3.1 Array declaration


The two-dimensional array can be declared by specifying the type of the array, then the name of the
array variable, and then the number of rows and column elements should be specified between a
pair square brackets ([][]).
Note that rows and column values cannot be a variable and has to be an integer constant.
General format :

type array_name[rwo_size][column_size];
Ex:- int marks[100][5];
float salary[1000][4];

9.3.2 Array Initialization


Elements of an array can be assigned initial values by following the array definition with a list of
initializers enclosed in braces and separated by comma.
Ex:-
int marks[2][3] = {65, 98, 62, 48, 57, 40};
Here it defines the marks array contain 2 rows and 3 columns totally six integer elements and
initializes marks[0][0] to 65, marks[0][1] to 98, marks[0][2] to 62, marks[1][0] to 48, marks[1][1]
to 57 and marks[1][2] to 40.

9.4 Multi-Dimensional Arrays


C program allows array of multi dimensions also. The syntax of multi-dimensional array is :
type array_name[size1][size2]. . . .[sizen]

9.5 Strings
A string is nothing but single dimensional char array. So whatever rules are applicable to single
dimensional arrays are applicable to strings also. Any string constant defined between double
quotation marks is a string.
Ex:- "Welcome to C"

9.5.1 Declaration and Initialization


A string declaration is as follows :
char string_name[size]
The size determines the number of characters in the string. If size is ’n’ then actual characters are
stored from 0 to (n-2), and (n-1)th character is stored as NULL (’\0’) character.
Ex:- char city[25]
The character array may be initialized when they are declared, like :
char city[25] = "Hyderabad"
or
char city[25] = {'H','y','d','e','r','a','b','a','d','\0'}
When a compiler assigns a character string to a character array, it automatically supplies a NULL
character ’\0’ at the end of the string. Therefore the size should be equal to the maximum number
of characters in the string plus one.
9.5 Strings 141

9.5.2 Reading a string


The input function scanf() can be used with %s format descriptor to read a string. The symbol & is
not required for strings in scanf statement. This scans only upto white space.
Ex:- char city[20];
scanf("%s",city);
The function gets accepts a character array as parameter. It reads string (until new line) from the
standard input. If no input is available (end of file is encountered) it returns a special value called
NULL.
Ex:- char city[20];
gets(city);

9.5.3 Writing a string


The print function printf() can be used with %s format descriptor to print a string.
Ex:- char city[20];
scanf("%s",city);
printf("%s\n",city);
The function puts accepts a string as parameter, to print the string on the standard output and further
automatically issues a new line.
Ex:- char city[20];
gets(city);
puts(city);
Reading String character by character
1. This code is work similar to gets() function
char city[50];
char ch;
do{
ch=getchar();
city[i]=ch;
i++;
}while(ch!='\n');
i=i-1;
city[i]='\0';
2. This code is simulation of scanf() function
char city[50];
char ch;
do{
ch=getchar();
city[i]=ch;
i++;
}while(ch!='\n');
i=i-1;
city[i]=' ';
To perform the above two codes it is necessary to include the header file stdio.h
142 Chapter 9. Arrays & Strings

Printing a string character by character


char ch, city[50]="Hyderabad";
int i=0;
while((ch=city[i])!='\0'){
putchar(ch);
i--;
}

9.6 String Operations


The following are the operations that can be performed on strings.
1. Reading and Writing of Strings
2. Concatenating of strings
3. Copying one string into another
4. Comparing Strings
5. Extracting a portion of a string
6. Converting the string from lower case to uppercase
’C’ provides string handling functions to perform the above specified operations.

9.7 String Handling Functions


strcpy()
It is used to copy one string into another string.
Syntax :

strcpy(str1, str2)

Here str1 is the source string and str2 is the target string.

strcmp()
It is used to compare two strings character by character and returns –1 (or) 0 (or) 1.
Syntax :

strcmp(str1, str2)

if the ASCII value of the character of the first string is less than the second string it returns –ve. If
both strings are equal it returns zero. If the ASCII value of the character of the first string is greater
than the second string it returns +ve.

strcat()
It is used to concatenate two strings i.e. it appends one string into another string.
Syntax :

strcat(str1, str2)

Here string str2 is appended to the end of the string str1.

strlen()
It is used to count the number of characters in the string.
Syntax :

strlen(str1)
9.8 Example Programs 143

strlwr()
It is used to convert any upper case letters into its equivalent lower case letters.
Syntax :

strlwr(str1)

strupr()
It is used to convert any lower case letters into its equivalent upper case letter.
Syntax :

strupr(str1)

9.8 Example Programs


1. FINDOUT THE MAXIMUM ELEMENT FROM THE GIVEN ARRAY

#include<stdio.h>
main()
{
int a[50],i,n,j,max;
clrscr();
printf("Enter the size of the array : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d] = ",i+1);
scanf("%d",&a[i]);
}
max=0;
for(j=0;j<n;j++)
if(a[j]>=max)
max=a[j];
printf("Maximum value from the given array : %d\n",max);
}
OUTPUT:
Enter the size of the array : 6
Enter a[1] = 8
Enter a[2] = 2
Enter a[3] = 6
Enter a[4] = 5
Enter a[5] = 1
Enter a[6] = 3
Maximum value from the given array : 8

Explanation : In the above program will accept the number of elements are present in the
array from the user as n. Accepts array element from the user and print it by using for loops.
The max variable is initialized with zero and compare all the array elements, if array element
is larger than the max value the max variable holds the array element value. Finally it will
print the max value from the array.
2. FINDOUT THE NUMBER OF PASS AND FAIL FROM THE GIVEN MARKS AR-
RAY
144 Chapter 9. Arrays & Strings

#include<stdio.h>
main()
{
int m[50],i,n,pass=0;
clrscr();
printf("Enter the number of students : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d student marks = ",i+1);
scanf("%d",&m[i]);
}
for(i=0;i<n;i++)
if(m[i]>=35)
pass++;
printf("Number of passed students are : %d\n",pass);
printf("Number of failed students are : %d\n",n-pass);
}
OUTPUT:
Enter the number of students : 8
Enter 1 student marks = 57
Enter 2 student marks = 23
Enter 3 student marks = 79
Enter 4 student marks = 82
Enter 5 student marks = 34
Enter 6 student marks = 51
Enter 7 student marks = 06
Enter 8 student marks = 65
Number of passed students are : 5
Number of failed students are : 3
Explanation : The above program will accept the number of students are present in the
array from the user as n. Accepts individual student marks from the user by using for loop.
The pass variable is initialized with zero. All the array elements will check that is it gereater
than or equal to 35, if so pass will be incremented by 1. It will be the no. of students pass
and no. students fail is n-pass.
3. ADD 5 GRACE MARKS FOR FAILED CANDIDATES FROM THE GIVEN ARRAY
#include<stdio.h>
main()
{
int m[50],i,n;
clrscr();
printf("Enter the number of students : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d student marks = ",i+1);
scanf("%d",&m[i]);
}
for(i=0;i<n;i++)
9.8 Example Programs 145

if(m[i]<35)
if(m[i]+5>35)
m[i]=35;
else
m[i]=m[i]+5;
printf("The modified marks are : \n");
for(i=0;i<n;i++)
printf("\t m[%d] = %d\n",i+1,m[i]);
}
OUTPUT:
Enter the number of students : 8
Enter 1 student marks = 57
Enter 2 student marks = 23
Enter 3 student marks = 79
Enter 4 student marks = 82
Enter 5 student marks = 34
Enter 6 student marks = 51
Enter 7 student marks = 32
Enter 8 student marks = 29
The modified marks are :
m[1] = 57
m[2] = 28
m[3] = 79
m[4] = 82
m[5] = 35
m[6] = 51
m[7] = 35
m[8] = 34
Explanation : The above program will accept the number of students are present in the
array from the user as n. Accepts individual student marks from the user by using for loop.
The pass variable is initialized with zero. All the array elements will check that is it less than
35 add five grace marks, after adding grace marks if it is greater than 35 it is rounded to 35,
the modified value will be stored into same location.
4. TRANSPOSE OF THE GIVEN MATRIX
#include<stdio.h>
main()
{
int a[5][5];
int i,j,row,col;
clrscr();
/* Collecting the number of rows and number of columns */
printf("Enter how many rows are there : ");
scanf("%d",&row);
printf("Enter how many columns are there : ");
scanf("%d",&col);
/* Matrix Reading */
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
146 Chapter 9. Arrays & Strings

{
printf("Enter a[%d][%d] = ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf(" The transposed matrix is : \n");
/* Printing the transpose matrix */
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("\t%d",a[j][i]);
printf("\n");
}
}
OUTPUT:
Enter how many rows are there : 3
Enter how many columns are there : 3
Enter a[1][1] = 2
Enter a[1][2] = 4
Enter a[1][3] = 6
Enter a[2][1] = 3
Enter a[2][2] = 5
Enter a[2][3] = 7
Enter a[3][1] = 9
Enter a[3][2] = 0
Enter a[3][3] = 8
The transposed matrix is :
2 3 9
4 5 0
6 7 8
Explanation : Number of Rows and Columns will be accepted by user and get the matrix
elements from the user. By using nester for loop the transposed matrix can be printed.
5. ADDITION OF TWO MATRICES
#include<stdio.h>
main()
{
int a[5][5], b[5][5], c[5][5];
int i,j,row,col;
clrscr();
/* Collecting the number of rows and number of columns */
printf("Enter how many rows are there : ");
scanf("%d",&row);
printf("Enter how many columns are there : ");
scanf("%d",&col);
/* First Matrix Reading */
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
9.8 Example Programs 147

printf("Enter a[%d][%d] = ",i+1,j+1);


scanf("%d",&a[i][j]);
}
}
/* Second Matrix Reading */
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Enter b[%d][%d] = ",i+1,j+1);
scanf("%d",&b[i][j]);
}
}
/* Addition of First and Second Matrices */
for(i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j]=a[i][j]+b[i][j];
/* Printing the resultant matrix */
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf(" %2d",a[i][j]);
printf("\t\t");
for(j=0;j<col;j++)
printf(" %2d",b[i][j]);
printf("\t\t");
for(j=0;j<col;j++)
printf(" %2d",c[i][j]);
printf("\n");
}
}
Explanation : Number of Rows and Columns of two matrices will be accepted by user and
get the two matrices elements from the user. By using nested for loop the addition of two
matrices can be performed and stored into other matrix. Finally three matrices can be printed.
6. FIND OUT THE LENGTH OF THE GIVEN STRINGS
#include<stdio.h>
main()
{
char str[80];
int i=0,len;
clrscr();
printf("Enter a string : ");
gets(str);
while(str[i]!=NULL)
i++;
printf(" Length of the given string is : %d\n",i);
}
OUTPUT:
Enter a string : Computer
148 Chapter 9. Arrays & Strings

Length of the given string is : 8

Explanation : The above program accepts a string from user. The variable i is initialized
with zero. If ith character of the string is not NULL i wil be incremented by 1. This process
will repeat till reacing the NULL haracter. Finally i is holding the length of the given string.
7. CONVERT THE GIVEN STRING INTO LOWER CASE LETTERS

#include<stdio.h>
main()
{
char str[80], lwr[80];
int i=0;
clrscr();
printf("Enter a string : ");
gets(str);
while(str[i]!=NULL)
{
if(str[i]>='A'&&str[i]<='Z')
lwr[i]=str[i]+32;
else
lwr[i]=str[i];
i++;
}
lwr[i]='\0';
printf(" The original string is : ");
puts(str);
printf(" Lowercase equivalent of the given string is : ");
puts(lwr);
}
OUTPUT:
Enter a string : CompuTER
Lowercase equivalent of the given string is : computer

Explanation : The above program accepts a string from user. The variable i is initialized
with zero. If ith character of the string is inbetween A to Z, 32 will be added to it and will be
stored into lwr string otherwise it will be stored same. Finally the lwr string will be printed.
8. FIND OUT THE NUMBER OF LETTERS, WORDS IN A GIVEN STRING

#include<stdio.h>
main()
{
char str[80];
int i=0, wc=1;
clrscr();
printf("Enter a string : ");
gets(str);
while(str[i]!=NULL)
{
if(str[i]==' '&&str[i+1]!=' ')
wc++;
i++;
9.8 Example Programs 149

}
printf(" The Character count is : %d\n",i);
printf(" The word count is : %d\n",wc);
}
OUTPUT:
Enter a string : Computer Science and Engineering
The Character count is : 32
The word count is : 4
Explanation : The above program accepts a string from user. The variables i and wc are
initialized with zero. Till getting the NULL character in the string the variable i will be
incremented by 1. If ith character is blank space and i+1th character is not blank space wc
will be incremented by 1. Now i value will be the character count and wc will be the word
count.
9. TO CONCATNATE THE GIVEN TWO STRINGS INTO THIRD STRING
#include<stdio.h>
main()
{
char s1[80], s2[80], s3[160];
int i=0,j=0;
clrscr();
printf("Enter the first string : ");
gets(s1);
printf("Enter the second string : ");
gets(s2);
while(s1[i]!=NULL)
{
s3[i]=s1[i];
i++;
}
while(s2[j]!=NULL)
{
s3[i]=s2[j];
i++;
j++;
}
s3[i]='\0';
printf(" The first string is : ");
puts(s1);
printf(" The second string is : ");
puts(s2);
printf(" The concatenated string is : ");
puts(s3);
}
OUTPUT:
Enter the first string : Software
Enter the second string : Engineer
The first string is : Software
The second string is : Engineer
The concatenated string is SoftwareEngineer
150 Chapter 9. Arrays & Strings

Explanation : The above program accepts two strings as s1 and s2 from user. Till getting the
NULL character of the first string all the characters will be copied into s3 string. Immediately
second string characters also will copied. Now s3 will be concatenated of first and second
strings.
10. FIND OUT THE NUMBER OF VOWELS ARE IN A GIVEN STRING
#include<stdio.h>
main()
{
char str[80];
int i=0,vc=0;
clrscr();
printf("Enter a string : ");
gets(str);
while(str[i]!=NULL)
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'||
str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
vc++;
i++;
}
printf(" The number of vowels are in the given string is : %d\n",vc);
}
OUTPUT:
Enter a string : Computers
The number of vowels are in the given string is : 3
Explanation : The above program accepts a string from user. The variables i and vc are
initialized with zero. Till getting the NULL character in the string the variable i will be
incremented by 1. Each ith character can be checked whether is it vowel or not, if so vc will
be incremented by 1.
11. CONVERT THE GIVEN STRING INTO UPPER CASE LETTERS
#include<stdio.h>
main()
{
char str[80], upr[80];
int i=0;
clrscr();
printf("Enter a string : ");
gets(str);
while(str[i]!=NULL)
{
if(str[i]>='a'&&str[i]<='z')
upr[i]=str[i]-32;
else
upr[i]=str[i];
i++;
}
upr[i]='\0';
printf(" The original string is : ");
9.8 Example Programs 151

puts(str);
printf(" Upper case equivalent of the given string is : ");
puts(upr);
}
OUTPUT :
Enter a string : VighNEsh
The original string is : VighNEsh
Upper case equivalent of the given string is : VIGHNESH
12. A Maruthi Car dealer maintains a record of sales of various vehicles in the following
form :

Vehicle type Month of sales Price (Rs)


Maruthi-800 02/87 75,000
Maruthi-DX 07/87 95,000
Gypsy 04/87 1,10,000
Mruthi Van 08/88 85,000

Write a C program to read this data into a table of strings and output the details of a
particular vehicle sold during a specified period. The program should request the user
to input the vehicle type and the period (starting month & ending month).
#include<stdio.h>
#include<conio.h>
#include<math.h>
/* Main program begins */
main()
{
int vt[100], date[100], price[100], num=0;
int cho, x, ivt, ismon, isyear, iemon, ieyear, flag;
char ovt[4][20]={"Maruthi-800","Maruthi-DX","Maruthi-
Gypsy","Maruthi Van"}
do
{
clrscr();
/* User Menu Code */
printf("\n 1 - Create Records ");
printf("\n 2 - Read Records for a particular vehicle ");
printf("\n 3 - Exit ");
printf("\n Enter your choice : ");
scanf("%d",&cho);
/* Evaluation of user choice */
if(cho==2&&num==0)
{
printf("\n\n Records not created yet, Press
any key to create records");
cho=1;
}
if(cho>=3&&cho<1)
{
printf(" Terminate the program, Press any key ");
152 Chapter 9. Arrays & Strings

getch();
exit();
}
printf("\n 1 - Maruthi-800");
printf("\n 2 - Maruthi-Dx");
printf("\n 3 - Maruthi-Gypsy");
printf("\n 4 - Maruthi-van");
printf("\n Enter your choice : ");
scanf("%d",&cho);
swich(cho)
{
case 1: /* Addition of records */
printf(" Enter no of vehicles : ");
scanf("%d",&num);
for(x=0;x<num;x++)
{
printf("\n Enter vehicle type ");
scanf("%d",&vt[x]);
if(vt[x]>4||vt[x]<1)
{
printf(" Invalid vehicle type");
x--;
continue;
}
printf(" Enter month of sale : ");
scanf("%d",&date[x][1]);
printf (" \n\t Enter year of Sale : " );
scanf("%d",&date[x][2]);
printf("\n\t Enter Price of Vehicle ");
scanf("%d",&price[x]);
}
printf("\n Records created successfully, Press any key to continue");
getch();
break;
case 2: /* Display of information */
printf("\n\t Enter vehicle type : ");
scanf("%d",&ivt);
printf("\n\t Enter Period of Sales : ");
printf("\n\t Enter Starting Month : ");
scanf("%d",&ismon);
printf ("\n\t Enter Starting Year : ");
scanf("%d',&isyear);
printf ("\n\t Enter Ending Month : ");
scanf("%d",&iemon);
printf ("\n\t Enter Ending Year : ");
scanf("%d",&ieyear);
if(ivt>4||ivt<l)
{
printf("\n\t Invalid Vehicle Type ");
9.8 Example Programs 153

getch();
break;
}
if(isyear==ieyear)
{
if(ismon>iemon)
prihtf("\n\t Invalid period Format");
getch();
break;
}
}
if(isyear>ieyear)
{
printf("\n\t Invalid Period Format");
getch();
break;
}
flag=0;
printf("\n\t Record for Sales of %s for the period
%d / %d to %d / %d \nl\n", ovt[ivt-1], ismon,
isyear, iemon, ieyear); for(x=0;x<num;x++)
{
if(ivt==vt[x])
{
if(date[x][2]>=isyear&&date[x][2]<=ieyear)
{
if(date[x][l]>=ismon&&date[x][1]<=ismon)
{
flag=1;
printf("\n\t\t Date of sale %d/%d,
price%d",date[x][1],
date[x][2],price[x]);
}
}
}
}
if(flag==0)
{
printf("\n\t No Data available, Vehicle
during the specified Period") ;
}
getch();
break;
}
}while(cho!=3);
}
OUTPUT:
enter 1 to create records
enter 2 to read recordsfor a particular vehicle
154 Chapter 9. Arrays & Strings

enter 3 to exit
enter choice 1
Enter 1 for Maruthi-800
Enter 1 for Maruthi-Dx
Enter 1 for Maruthi-Gypsy
Enter 1 for Maruthi-van
Enter total no of vehicles 1
Enter vehicle type 1
Enter month of sale 2
Enter year of sale 87
Enter price of vehicle 75,000
Records successfully created,
press any key to continue

13. TO EXTRACT A PORTION OF THE STRING FROM THE GIVEN STRING

#include<stdio.h>
main()
{
char str[80], ext[80];
int i=0,j,pos,n;
clrscr();
printf("Enter main string : ");
gets(str);
printf(" Enter the starting position the string to be extracted: ");
scanf("%d",&pos);
printf(" Enter number of character to be extracted : ");
scanf("%d",&n);
/* Extracting */
for(j=pos-1,i=0;i<n;j++,i++)
ext[i]=str[j];
ext[i]='\0';
/* Print the extracted string */
printf(" The extracted string is : ");
puts(ext);
getch();
}
OUTPUT:
Enter the main string : Skillsubsist
Enter the starting position the string to be extracted : 6
Enter number of character to be extracted : 4
The extracted String is : subs

14. Write a C program to rearrange the elements of an array so that those originally stored
at odd suffixes are placed before those at even suffixes.

main()
{
char a[25],ch,temp;
int i;
9.8 Example Programs 155

clrscr();
printf ("\nEnter the string:-> ");
gets(a);
for (i=0;a[i]!='\0';i++)
{
if (a[i+1]=='\0')break;
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
i++;
}
puts(a);
getch();
}
15. Write a C program that reads a string from keyboard and determines whether the
string is palindrome or not. (A string is palindrome if it is read from left or right gives
you the same string)
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,flag=1;
char a[20];
clrscr();
printf("enter any word:\n");
scanf("%s",a);
i=0;
while(a[i]!='\0')
i++;
k=i;
for(j=0;j<k/2;)
{
if(a[j]!=a[i-1])
{
flag=0;
break;
}
if(a[j]==a[i-1])
{
j++;
i--;
}
}
if(flag==0)
printf("it is a not palindrome");
else
printf("it is a palindrome");
getch();
}
156 Chapter 9. Arrays & Strings

16. Write a function to remove duplicates from an ordered array. For example, if input is:
a,a,c,d,q,q,r,s,u,w,w,w,w; then the output should be a,c,d,q,r,s,u,w.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,j,k,l,flag=0;
char a[50];
clrscr();
printf("enter the characters in the array");
gets(a);
l=strlen(a);
for(i=0;i<l-1;i++)
for(j=i+1;j<l;j++)
{
if(a[i]==a[j])
{ l=l-1;
for(k=j;k<l;k++)
a[k]=a[k+1];
flag=1;
j=j-1;
}
}
if(flag==0)
printf("No duplicates found");
else
for(i=0;i<l;i++)
printf("%c",a[i]);
getch();
}
17. Write a function to sort the characters of the string passed to it as argument.
main()
{
char a[100],ch;
int i,j;
printf ("\nEnter the string:-> ");
gets(a);
for (i=0;a[i]!='\0';i++)
{
for (j=i+1;a[j]!='\0';j++)
{
if (a[i]>a[j])
{
ch=a[i];
a[i]=a[j];
a[j]=ch;
}
9.9 Multiple Choice Questions 157

}
}
printf ("\nString after sorting\n");
puts(a);
getch();
}
18. Write a C program to concatenate two strings.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[100],b[100];
int i=0,j=0;
clrscr();
printf("enter the set of lines");
gets(a);
while(a[i]!='\0')
{
while(a[i]!=' '&&a[i]!='\t'&&a[i]!='\0')
{
b[j]=a[i];
j++;
i++;
}
while(a[i]==' '||a[i]=='\t')
i++;
}
b[j]='\0';
printf("%s",b);
getch();
}

9.9 Multiple Choice Questions


1. Array is used to represent: [ D ]
(A) a list of data items of integer data type
(B) a list of data items of real data type
(C) a list of data items of different data type
(D) a list of data items of same data type
2. One-dimensional array is known as [ A ]
(A) a vector (B) a table
(C) a matrix (D) an array of arrays
3. The array elements are represented by [ B ]
(A) index values (B) subscripted variables
(C) array name (D) size of array
158 Chapter 9. Arrays & Strings

4. Array elements occupy [ A ]


(A) subsequent memory locations
(B) random location for each element
(C) varying length of memory locations for each elements
(D) no space in memory
5. Array subscripts in C always start at [ B ]
(A) -1 (B) 0
(C) 1 (D) any value
6. Identify the correct declaration: [ A ]
(A) int a[10][10] (B) int a(10)(10)
(C) int a [10,10] (D) int a(10,10)
7. Maximum number of elements in the array declaration int x[5][8]: [ D ]
(A) 28 (B) 34 (C) 45 (D) 40
8. The value within the [] in an array declaration specifies [ B ]
(A) subscript value (B) size of the array
(C) value of the array element (D) array bound
9. When should an array be used? [ B ]
(A) When we need to hold variable constants
(B) When we need to hold data of the same type
(C) When we need to obtain automatic memory cleanup functionality
(D) when we need to hold data of different types
10. Which is string related function: [ D ]
(A) strcmp() (B) strcpy() (C) strcat() (D) all above
11. The function to compare two strings is: [ B ]
(A) strcat() (B) strcmp() (C) strcpy() (D) strlen()
12. The function to copy a string into another [ C ]
(A) strcat() (B) strcmp() (C) strcpy() (D) all above
13. When two strings are equal then strcmp() return: [ D ]
(A) 1 (B) 2 (C) -1 (D) 0
14. To find length of a string function is [ A ]
(A) strlen() (B) strcat() (C) strlength() (D) lengthstr()
15. Program execution starts with [ B ]
(A) the function which is first defined
(B) main() function
(C) the function which is last defined
(D) the function other than main()
9.9 Multiple Choice Questions 159

16. How many main() functions can be defined in a C program? [ A ]


(A) 1 (B) 2 (C) 3 (D) any number of times
17. A function is identified by an open parenthesis following [ B ]
(A) a keyword (B) an identifier other than keywords
(C) an identifier including keywords (D) an operator
18. Parameters are used [ C ]
(A) to return values from the called function
(B) to send values from the calling function
(C) options a and b
(D) to specify the data type of the return value
19. The default return data type in function definition is [ B ]
(A) void (B) int (C) float (D) char
20. To declare an array S that holds a 5-character string, you would write [ A ]
(A) char S[5] (B) String S[5] (C) char S[6] (D) String S[6]
21. The output of the following statements is [ C ]

char ch[6]={'e', 'n', 'd', '\0', 'p'};


printf("%s", ch);
(A) endp (B) end0p (C) end (D) error
22. The size of array int a[5]=1,2 is [ C ]
(A) 4 (B) 12 (C) 10 (D) 6
23. puts(argv[0]); [ D ]
(A) prints the name of the source code file.
(B) prints argv.
(C) prints the number of command line arguments.
(D) prints the name of the executable code file.
24. The maximum number of dimensions an array can have in C is [ D ]
(A) 3 (B) 4 (C) 5 (D) compiler dependent
25. What will be the output of the following code segment? [ A ]

main( ) {
char s[10];
strcpy(s, "abc");
printf("%d %d", strlen(s), sizeof(s));
}
(A) 3 10 (B) 3 3 (C) 10 3 (D) 10 10
26. what is the value of ’i’? [ D ]

i=strlen("Blue")+strlen("People")/strlen("Red")-strlen("green")
(A) 2 (B) 3 (C) 0 (D) 1
160 Chapter 9. Arrays & Strings

27. Which of the following correctly accesses the seventh element stored in a, an array with 100
elements? [ D ]
(A) a[7] (B) a[i-1] (C) Not possible (D) a[6]
28. Which of the following is a two-dimensional array? [ B ]
(A) array anarray[20][20]; (B) int anarray[20][20];

(C) int array[20, 20]; (D) char array[20];


29. What is the index number of the last element of an array with 29 elements?[ B ]
(A) 29 (B) 28 (C) 0 (D) Not possible to access
30. Which of the following correctly declares an array?[ A ]
(A) int anarray[10]; (B) int anarray;

(C) anarray10; (D) array anarray[10];


31. When an array is passed as parameter to a function, which of the following statement is
correct choice: [ A ]
(A) The function can change values in the (B) In C parameters are passed by value.
original array The function cannot change the original
value in the array

(C) It results in compilation error when the (D) Results in a run time error when the
function tries to access the elements in function tries to access the elements in
the array the array
32. The output of the following statements is [ C ]

main()
{
int a[] ={ 1,2,3,4,5,6,7};
char c[] = {' a','x','h','o','k'};
printf("%d\t %d ", (&a[3]-&a[0]),(&c[3]-&c[0]));
}

(A) 3 4 (B) 4 4 (C) 3 3 (D) 4 3


33. The output of the following statements is [ C ]

main()
{ int mat[3][3] =
{
1,2,3,4,5,6,7,8,9 };
int i, j;
for ( i = 2; i >= 0 ; i-- )
for ( j = 2; j >= 0 ; j-- )
printf("%d", *(*mat+j)+i);
}

(A) 9 8 7 6 5 4 3 2 1 (B) 1 2 3 4 5 6 7 8 9

(C) 9 6 3 8 5 2 7 4 1 (D) None


34. The output of the following statements is
9.9 Multiple Choice Questions 161

void main()
{
char a[]="12345\0";
int i=strlen(a);
printf("here in 3 %d\n",++i);
}
Answer: here in 3 6
35. The output of the following statements is [ C ]

main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
(A) H (B) Hello World (C) Hello (D) Compiler Error
36. The output of the following statements is

main( )
{
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
printf(%u %u %u %d \n,a,*a,**a,***a);
printf(%u %u %u %d \n,a+1,*a+1,**a+1,***a+1);
}
Answer:
100, 100, 100, 2
114, 104, 102, 3
37. What is the output for the following program [ B ]

main()
{
int arr2D[3][3];
printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) );
}
(A) 0 (B) 1 (C) Error (D) None of the above
38. What is the output for the following program [ A ]

main()
{
while (strcmp(some,some\0))
printf(Strings are not equal\n);
}
(A) No Output (B) Strings are not equal
(C) Error (D) None of the above
162 Chapter 9. Arrays & Strings

39. What is the output for the following program [ B ]

main()
{
char str1[] = {`s','o','m','e'};
char str2[] = {`s','o','m','e','\0'};
while (strcmp(str1,str2))
printf(Strings are not equal\n);
}
(A) No Output (B) Strings are not equal
(C) Error (D) None of the above
40. What is the output for the following program [ B ]

int DIM(int array[])


{
return sizeof(array)/sizeof(int );
}
main()
{
int arr[10];
printf(The dimension of the array is %d, DIM(arr));
}
(A) 0 (B) 1 (C) Error (D) None of the above
41. What is the output for the following program [ C ]

void main()
{
int i=10, j=2;
int *ip= &i, *jp = &j;
int k = *ip/*jp;
printf(%d,k);
}
(A) 0 (B) 1 (C) Error (D) None of the above
10. Pointers

10.1 Introduction
A Pointer is a derived data type in C. It is built from one of the fundamental data types available in
C. Pointers contain memory addresses as their values. Pointers are one of the most distinct and
exciting features of C language. It has added power and flexibility to the language. Pointers are
used frequently in C.

Advantages of pointers
• Pointers are more efficient in handling arrays and data tables.
• Pointers can be used to return multiple values from a function via function arguments
• Pointers permit references to functions and there by facilitating passing of functions as
arguments to other functions.
• The use of pointer arrays to character string results in saving of data storage space in memory.
• Pointers allow C to support dynamic memory management.
• Pointers provide an efficient tool for manipulating dynamic data structures such as structures,
linked lists, queues, stacks and trees.
• Pointers reduce length and complexity of programs.
• Pointers increase the execution speed and thus reduce the program execution time.

10.1.1 Pointer Declaration


The general syntax of the pointer declaration is :

data_type *pointer_name;

Here the * tells that variable pointer_name is pointer type variable. i.e. it holds the address of a
variable of type data_type. For example the statement int n=20 tells the C compiler to: (i) Reserve
space in memory to hold an integer value, (ii) Associate the name n with this memory location and
(iii) Store the value 20 at this location. The memory map for the above statement is :
164 Chapter 10. Pointers

10.1.2 Pointer Operators


A pointer operator are an asterisk (*) value at address operator, and an ampersand (&) address
operator. Address of operator : The address of operator (&) returns the address of a variable. The
operand may be a variable or a constant.

Ex : m = &n;
Here m is not an ordinary variable like any other integer variable. It is a variable which contains the
address of another variable n. The following memory map would illustrate the content of n and m.

As you can see n’s value is 20 and m’s value is n’s address. Here we can’t use m in a program
without declaring it. And since m is a variable which contains the address of n, it is declared as

int *m;
This declaration tells the compiler that m will be used to store the address of an integer value. In
other words m points to an integer.
Value at address operator
The value at address operator (*) returns the value stored at a particular address. The ’value at
address’ operator is also called ’indirection’ operator or ’deference’ operator.

Ex : x = *m;
Here m is holding the address of n, and x is holding the value at address of m i.e. n.
Example:

/* PROGRAM TO DEMONSTRATE & AND * OPERATORS */


#include<stdio.h>
main()
{
int n=20;
printf(" Address of n is : %u\n",&n);
printf(" Value of n is : %d\n",n);
printf(" Value of n is : %d",*(&n));
}
OUTPUT :
Address of n is : 65500
Value of n is : 20
Value of n is : 20
Explanation : The first printf statement print the address of a variable n, which in this it is 65500.
The second printf statement prints the n value. The third printf statement also prints the n value i.e.
value at address of 65500. Address of n ( &n) is 65500 in this case. The final output of the program
10.2 Types Of Pointers 165

says the value of *(&n) is same as n.

Example :

/* PROGRAM TO PRINT ADDRESS AND THE VALUE OF A VARIABLE BY USING & AND * OPERATORS */
#include<stdio.h>
main()
{
int n=20;
int *m;
m=&n;
clrscr();
printf(" Address of n is : %u\n",&n);
printf(" Address of n is : %u\n",m);
printf(" Address of m is : %u\n",&m);
printf(" Value of m is : %u\n",m);
printf(" Value of n is : %d\n",n);
printf(" Value of n is : %d\n",*(&n));
printf(" Value of n is : %d",*m);
}
OUTPUT:
Address of n is : 65498
Address of n is : 65498
Address of m is : 65500
Value of m is : 65498
Value of n is : 20
Value of n is : 20
Value of n is : 20

Explanation : Here n is declared as ordinary integer variable and m is declared as an integer


pointer variable, holding the address of a variable n. The first three printf statements will print the
addresses of n and m variables. The next three printf statements will print the value of n by using *,
& and combination of these two operators.

10.2 Types Of Pointers


10.2.1 Null Pointer
• NULL Pointer is a pointer which is pointing to nothing.
• NULL pointer points the base address of segment.
• In case, if you don’t have address to be assigned to pointer then you can simply use NULL
• Pointer which is initialized with NULL value is considered as NULL pointer.
• NULL is macro constant defined in following header files - stdio.h, alloc.h, mem.h, stddef.h
and stdlib.h

Defining NULL Value


#define NULL 0

Visual Representation
Below are some of the variable representations of NULL pointer.

float *ptr = (float *)0;


166 Chapter 10. Pointers

char *ptr = (char *)0;


double *ptr = (double *)0;
char *ptr = '\0';
int *ptr = NULL;
Example of NULL Pointer
#include <stdio.h>
int main()
{
int *ptr = NULL;
printf("The value of ptr is %u",ptr);
return 0;
}
Output :
The value of ptr is 0

10.2.2 Dangling Pointer


Dangling pointers arise when an object is deleted or de-allocated, without modifying the value of
the pointer, so that the pointer still points to the memory location of the de-allocated memory. In
short pointer pointing to non-existing memory location is called dangling pointer.
Examples of Dangling Pointer
There are different ways where Pointer acts as dangling pointer.
Way 1 : Using free or de-allocating memory
#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
.......
free (ptr); /* ptr now becomes a dangling pointer */
}

We have declared the character pointer in the first step. After execution of some statements we have
de-allocated memory which is allocated previously for the pointer.
As soon as memory is de-allocated for pointer, pointer becomes dangling pointer
Way 2 : Out of Scope
#include<stdlib.h>
void main()
10.2 Types Of Pointers 167

{
char *ptr = NULL;
.....
.....
{
char ch;
ptr = &ch;
}
..... /* dp is now a dangling pointer */
}

• Character Pointer is Declared in the first Step.


• Pointer Variable ’ptr’ is pointing to Character Variable ’ch’ declared in the inner block .
• As character variable is non-visible in Outer Block , then Pointer is Still Pointing to Same
Invalid memory location in Outer block , then Pointer becomes "Dangling"

10.2.3 Generic Pointers


When a variable is declared as being a pointer to type void it is known as a generic pointer. Since
you cannot have a variable of type void, the pointer will not point to any data and therefore cannot
be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of
pointer first. Hence the term Generic pointer.
This is very useful when you want a pointer to point to data of different types at different times.
Example of Generic Pointer Here is some code using a void pointer:

int main()
{
int i;
char c;
void *the_data;
i = 6;
c = 'a';
the_data = &i;
printf("the_data points to the integer value %d\n", *(int*) the_data);
the_data = &c;
printf("the_data now points to the character %c\n", *(char*) the_data);
return 0;
}

10.2.4 Wild Pointer


A Pointer in C that has not been initialized till its first use is known as Wild pointer. A wild pointer
points to some random memory location.
Example of Wild Pointer

int main()
{
int *ptr;
/* Ptr is a wild pointer, as it is not initialized Yet */
printf("%d", *ptr);
}
168 Chapter 10. Pointers

How can we avoid Wild Pointers ?


We can initialize a pointer at the point of declaration wither by the address of some object/variable
or by NULL;
int main()
{
int val = 5;
int *ptr = &val; /* Initializing pointer */
/* Ptr is not a wild pointer, it is pointing to the address of variable val */
printf("%d", *ptr);
}

10.2.5 Complex Pointers


Precedence : Operator precedence describes the order in which C reads expressions
Associativity : Order operators of equal precedence in an expression are applied
We need to assign the priority to the pointer declaration considering precedence and associative
according to following table. Where

(): This operator behaves as bracket operator or function operator.


[]: This operator behaves as array subscription operator.
*: This operator behaves as pointer operator not as multiplication operator.
Identifier: It is not an operator but it is name of pointer variable. You will always find the first
priority will be assigned to the name of pointer.
Data type: It is also not an operator. Data types also includes modifier (like signed int, long double
etc.)

10.2.6 Near Pointer


The pointer which can points only 64KB data segment or segment number 8 is known as near
pointer. That is near pointer cannot access beyond the data segment like graphics video memory,
text video memory etc. Size of near pointer is two byte. With the help of keyword near, we can
make any pointer as near pointer.
Example of Wild Pointer
#include<stdio.h>

int main()
{
int x=25;
int near* ptr;
ptr=&x;
printf("%d",sizeof ptr);
10.3 Pointer Arithmetic 169

return 0;
}
Output: 2

10.2.7 Far Pointer


The pointer which can point or access whole the residence memory of RAM i.e. which can access
all 16 segments is known as far pointer. Size of far pointer is 4 byte or 32 bit.
Example of Far Pointer

#include<stdio.h>
int main()
{
int x=10;
int far *ptr;
ptr=&x;
printf("%d",sizeof ptr);
return 0;
}

Output : 4

10.2.8 Huge Pointer


The pointer which can point or access whole the residence memory of RAM i.e. which can access
all 16 segments is known as huge pointer. Size of far pointer is 4 byte or 32 bit.
Example of Huge Pointer

#include<stdio.h>
int main()
{
char huge * far *p;
printf("%d %d %d",sizeof(p),sizeof(*p),sizeof(**p));
return 0;
}
Output : 4 4 1

Explanation: p is huge pointer, *p is far pointer and **p is char type data variable.

10.3 Pointer Arithmetic


We can perform arithmetic operations on pointer variable just as you can a numeric value. As we
know that, a pointer in C is a variable which is used to store the memory address which is a numeric
value. The arithmetic operations on pointer variable effects the memory address pointed by pointer.

Valid Pointer Arithmetic Operations


1. Adding a number to pointer.
2. Subtracting a number form a pointer.
3. Incrementing a pointer.
4. Decrementing a pointer.
5. Subtracting two pointers.
6. Comparison on two pointers.
170 Chapter 10. Pointers

Invalid Pointer Arithmetic Operations


• Addition of two pointers.
• Division of two pointers.
• Multiplication of two pointers.

10.3.1 Adding integer value with Pointer


In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable. In order to compute the final value we need to use
following formulae :

final value = (address) + (number * size of data type)


Consider the following example -

int *ptr , n;
ptr = &n ;
ptr = ptr + 3;
Example : Increment Integer Pointer

#include<stdio.h>
int main(){
int *ptr=(int *)1000;
ptr=ptr+3;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
New Value of ptr : 1006
Explanation of Program :
In the above program -

int *ptr=(int *)1000;


this line will store 1000 in the pointer variable considering 1000 is memory location for any of the
integer variable.
Formula :

ptr = ptr + 3 * (sizeof(integer))


= 1000 + 3 * (2)
= 1000 + 6
= 1006
Similarly if we have written above statement like this –

float *ptr=(float *)1000;


then result may be

ptr = ptr + 3 * (sizeof(float))


= 1000 + 3 * (4)
= 1000 + 12
= 1012
10.3 Pointer Arithmetic 171

10.3.2 Incrementing Pointer


Incrementing Pointer is generally used in array because we have contiguous memory in array and
we know the contents of next memory location. Incrementing Pointer Variable Depends Upon data
type of the Pointer variable
Formula : ( After incrementing )

new value = current address + i * size_of(data type)


Three Rules should be used to increment pointer - Address + 1 = Address
Address++ = Address
++Address = Address
Explanation : Incremeting Pointer

Data Type Older Address stored in pointer Next Address stored in pointer after incre-
menting (ptr++)
int 1000 1002
float 1000 1004
char 1000 1001

Incrementing a pointer to an integer data will cause its value to be incremented by 2 . This
differs from compiler to compiler as memory required to store integer vary compiler to compiler
Note : Increment and Decrement Operations on pointer should be used when we have Continues
memory (in Array).

Example : Increment Integer Pointer

#include<stdio.h>
int main(){
int *ptr=(int *)1000;
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
New Value of ptr : 1002

Example 2 : Increment Double Pointer

#include<stdio.h>
int main(){
double *ptr=(double *)1000;
172 Chapter 10. Pointers

ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
New Value of ptr : 1004

Example 3 : Array of Pointer

#include<stdio.h>
int main(){
float var[5]={1.1f,2.2f,3.3f};
float(*ptr)[5];
ptr=&var;
printf("Value inside ptr : %u",ptr);
ptr=ptr+1;
printf("Value inside ptr : %u",ptr);
return 0;
}
Output :
Value inside ptr : 1000
Value inside ptr : 1020

Explanation :

Address of ptr[0] = 1000

We are storing Address of float array to ptr[0].

Address of ptr[1]
= Address of ptr[0] + (Size of Data Type)*(Size of Array)
= 1000 + (4 bytes) * (5)
= 1020

Address of Var[0]. . . Var[4] :

Address of var[0] = 1000


Address of var[1] = 1004
Address of var[2] = 1008
Address of var[3] = 1012
Address of var[4] = 1016
10.3 Pointer Arithmetic 173

10.3.3 subtracting integer value from pointer


Suppose we have subtracted "n" from pointer of any data type having initial addess as "init_address"
then after subtraction we can write

ptr = initial_address - n * (sizeof(data_type))

Subtracting integer value with Pointer

int *ptr , n;
ptr = &n ;
ptr = ptr - 3;

Example 1 : Decrement Integer Pointer

#include<stdio.h>
int main(){
int *ptr=(int *)1000;
ptr=ptr-3;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :

New Value of ptr : 994

Formula :

ptr = ptr - 3 * (sizeof(integer))


= 1000 - 3 * (2)
= 1000 - 6
= 994

Summary : Pointer - Pointer = Integer


Pointer - Integer = Pointer

10.3.4 Decrementing pointer


Formula : ( After decrementing )

new_address = (current address) - i * size_of(data type)


Decrementation of Pointer Variable Depends Upon
data type of the Pointer variable Explanation :

Data Type Older Address stored in pointer Next Address stored in pointer after
decrementing
int 1000 998
float 1000 996
char 1000 999

• Decrementing a pointer to an integer data will cause its value to be decremented by 2


174 Chapter 10. Pointers

• This differs from compiler to compiler as memory required to store integer vary compiler to
compiler
Difference between two integer Pointers

#include<stdio.h>
int main(){
float *ptr1=(float *)1000;
float *ptr2=(float *)2000;
printf("\nDifference : %d",ptr2-ptr1);
return 0;
}
Output :
Difference : 250

Explanation :
Ptr1 and Ptr2 are two pointers which holds memory address of Float Variable.
Ptr2-Ptr1 will gives us number of floating point numbers that can be stored.

ptr2 - ptr1 = (2000 - 1000) / sizeof(float)


= 1000 / 4
= 250

Example:

#include<stdio.h>
struct var{
char cvar;
int ivar;
float fvar;
};
int main(){
struct var *ptr1,*ptr2;
ptr1 = (struct var *)1000;
ptr2 = (struct var *)2000;
printf("Difference= %d",ptr2-ptr1);
return 0;
}
Output :
Difference = 142

Explanation :
10.3 Pointer Arithmetic 175

ptr2-ptr1 = (2000 - 1000)/Sizeof(struct var)


= 1000 / (1+2+4)
= 1000 / 7
= 142

10.3.5 Subtracting pointers


Differencing Pointer in C Programming Language :
• Differencing Means Subtracting two Pointers.
• Subtraction gives the Total number of objects between them .
• Subtraction indicates "How apart the two Pointers are ?"
C Program to Compute Difference Between Pointers :

#include<stdio.h>
int main()
{
int num , *ptr1 ,*ptr2 ;
ptr1 = &num ;
ptr2 = ptr1 + 2 ;
printf("%d",ptr2 - ptr1);
return(0);
}
Output :
2

ptr1 stores the address of Variable num


Value of ptr2 is incremented by 4 bytes
Differencing two Pointers

Important Observations :
Suppose the Address of Variable num = 1000.

Statement Value of Ptr1 Value of Ptr2


int num , *ptr1 ,*ptr2 ; Garbage Garbage
ptr1 = &num ; 1000 Garbage
ptr2 = ptr1 + 2 ; 1000 1004
ptr2 - ptr1 1000 1004

Computation of Ptr2 – Ptr1 :


Remember the following formula while computing the difference between two pointers –

Final Result = (ptr2 - ptr1) / Size of Data Type

Step 1 : Compute Mathematical Difference (Numerical Difference)

ptr2 - ptr1 = Value of Ptr2 - Value of Ptr1


= 1004 - 1000
= 4

Step 2 : Finding Actual Difference (Technical Difference)


176 Chapter 10. Pointers

Final Result = 4 / Size of Integer


= 4 / 2
= 2
• Numerically Subtraction ( ptr2-ptr1 ) differs by 4
• As both are Integers they are numerically Differed by 4 and Technically by 2 objects
• Suppose Both pointers of float the they will be differed numerically by 8 and Technically by
2 objects
Consider the below statement and refer the following table -
int num = ptr2 - ptr1;

If Two Pointers are of Following Numerical Difference Technical Difference


Data Type
int 2 1
float 4 1
char 1 1

10.3.6 Comparing two pointer variables


Comparison between two Pointers :
1. Pointer comparison is Valid only if the two pointers are Pointing to same array
2. All Relational Operators can be used for comparing pointers of same type
3. All Equality and Inequality Operators can be used with all Pointer types
4. Pointers cannot be Divided or Multiplied
Example: Pointer Comparison
#include<stdio.h>
int main()
{
int *ptr1,*ptr2;
ptr1 = (int *)1000;
ptr2 = (int *)2000;
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
return(0);
}
Example: Pointer Comparison of Different Data Types
#include<stdio.h>
int main()
{
int *ptr1;
float *ptr2;

ptr1 = (int *)1000;


ptr2 = (float *)2000;
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
return(0);
}
10.3 Pointer Arithmetic 177

Explanation
• Two Pointers of different data types can be compared .
• In the above program we have compared two pointers of different data types.
• It is perfectly legal in C Programming.
As we know Pointers can store Address of any data type, address of the data type is “Integer" so we
can compare address of any two pointers although they are of different data types

Example: PROGRAM TO PERFORM POINTER ARITHEMATIC

#include<stdio.h>
main()
{
int i=5,*i1;
float j=5.8,*j1;
char k='z',*k1;
printf(" Value of i = %d\n",i);
printf(" Value of j = %f\n",j);
printf(" Value of k = %c\n",k);
i1=&i;
j1=&j;
k1=&k;
printf(" The Original value of i1 = %u\n",i1);
printf(" The Original value of j1 = %u\n",j1);
printf(" The Original value of k1 = %u\n",k1);
i1++;
j1++;
k1++;
printf(" New value in i1 = %u\n",i1);
printf(" New value in j1 = %u\n",j1);
printf(" New value in k1 = %u\n",k1);
}
OUTPUT:
Value of i = 5
Value of j = 5.800000
Value of k = z
The Original value of i1 = 65490
The Original value of j1 = 65492
The Original value of k1 = 65497
New Value in i1 = 65492
New Value in j1 = 65496
New Value in k1 = 65498

Explanation : The first three printf statements will print the values of i, j and k variables. Second
three printf statements will print the values of i1, j1 and k1 variables, i.e. addresses of i, j and
k variables. The last three printf statements will print the incremented values of i1, j1 and k1.
Here i1 is integer pointer variable because it will incremented by two bytes, j1 is float pointer
variable beause it will incremented by four bytes and k1 is character pointer variable because it will
incremented by one byte.
178 Chapter 10. Pointers

10.4 Pointers & Functions


Arguments can be passed to functions in two ways:
1. Sending the values of the arguments
2. Sending the address of the arguments

Sending the values of the arguments (Call by Value)


In this method the value of each actual argument in the calling function is copied into corresponding
formal arguments of the called function. With this method changes made in the formal arguments
in the called function have no effect on the values of the actual arguments in the calling function.
Example: PROGRAM TO ILLUSTRATE THE "CALL BY VALUE"

#include<stdio.h>
main()
{
int x,y;
printf("Enter first value i.e x : ");
scanf("%d",&x);
printf("Enter second value i.e y : ");
scanf("%d",&y);
swap(x,y);
printf(" In the main program : \n");
printf(" x = %d\n",x);
printf(" y = %d\n",y);
}
swap(int a, int b)
{
int t;
printf(" In the swap function : \n");
printf(" x = a = %d\n",a);
printf(" y = b = %d\n",b);
t=a;
a=b;
b=t;
printf(" After interchanging : \n");
printf(" x = a = %d\n",a);
printf(" y = b = %d\n",b);
}
OUTPUT :
Enter first value i.e. x : 43
Enter second value i.e. y : 94
In the swap function :
x = a = 43
y = b = 94
After interchanging :
x = a = 94
y = b = 43
In the main program :
x = 43
y = 94
10.4 Pointers & Functions 179

Explanation : Here actual argument in the calling function is copied into corresponding
formal arguments i.e. x value will be copied into a variable, y value will be copied into b variable.
The swap function will print these a, b values before swapping and after swapping. Within the swap
function a and b values are swapped but it will not affect the x and y which are in the main function.
Hence x and y values remains same.

Sending the address of the arguments (Call by reference)


In this method the address of actual arguments in the calling function are copied into formal
arguments of the called function. This means that using the formal arguments in the called function
we can make changes in the actual arguments of the calling function.
Example: PROGRAM ILLUSTRATE THE "CALL BY REFERENCE"

#include<stdio.h>
main()
{
int x,y;
printf("Enter first value i.e x : ");
scanf("%d",&x);
printf("Enter second value i.e y : ");
scanf("%d",&y);
swap(&x,&y);
printf(" In the main program : \n");
printf(" x = %d\n",x);
printf(" y = %d\n",y);
}
swap(int *a, int *b)
{
int t;
printf(" In the swap function : \n");
printf(" x = a = %d\n",*a);
printf(" y = b = %d\n",*b);
t=*a;
*a=*b;
*b=t;
printf(" After swapping : \n");
printf(" x = a = %d\n",*a);
printf(" y = b = %d\n",*b);
}
OUTPUT :
Enter first value i.e. x : 33
Enter second value i.e. y : 64
In the swap function :
x = a = 33
y = b = 64
After interchanging :
x = a = 64
y = b = 33
In the main program :
x = 64
y = 33
180 Chapter 10. Pointers

Explanation : Here actual argument addresses in the calling function is copied into corre-
sponding formal arguments i.e. address of x will be copied into a variable, address of y will be
copied into b variable. The swap function will prints these a, b values before swapping and after
swapping. Within the swap function a and b values are swapped and it will not affect the x and y
also which are in the main function. Hence x and y values are also swapped.

10.5 Pointers and Arrays


Array elements are always stored in contiguous memory locations. A pointer incremented always
points to an immediately next location of its type.
Example: PROGRAM TO PRINT ARRAY ELEMENTS
#include<stdio.h>
main()
{
int a[]={32,43,54,65,78},i,*j;
j=&a[0];
clrscr();
for(i=0;i<5;i++)
{
printf(a[%d] = Value of address at %u = %d\n",i,j,*j);
j++;
}
}
OUTPUT :
a[0] = Value of address at 65516 = 32
a[1] = Value of address at 65518 = 43
a[2] = Value of address at 65520 = 54
a[3] = Value of address at 65522 = 65
a[4] = Value of address at 65524 = 78
Explanation : Here the values j is holding starting location address of array a i.e. address of array
a. Whenever j is incremented by 1 it will holds the next location address of the array.

10.5.1 Passing an entire array to a function


We can pass the entire array to a function rather than individual elements.
Example: PROGRAM TO PASS THE ENTIRE ARRAY TO FUNCTION
#include<stdio.h>
main()
{
int a[]={32,43,54,65,78};
display(&a[0],5);
}
display(int *i, int x)
{
int j;
for(j=0;j<x;j++)
{
printf(a[%d] = Value of address at %u = %d\n",j,i,*i);
i++;
10.5 Pointers and Arrays 181

}
}
OUTPUT :
a[0] = Value of address at 65516 = 32
a[1] = Value of address at 65518 = 43
a[2] = Value of address at 65520 = 54
a[3] = Value of address at 65522 = 65
a[4] = Value of address at 65524 = 78
Explanation : Here the display function is accepting the starting address of the array instead of
accepting individual element addresses.

10.5.2 Passing array elements to functions


Array elements can be passed to a function by calling the function:
1. by value i.e. by passing values of array elements to the function.
2. by reference i.e. by passing addresses of array elements to the function.
Example: PROGRAM TO ACCEPT A STATIC ARRAY AND PRINT IT BY CALL BY VALUE

#include<stdio.h>
main()
{
int i;
int a[5]={33,44,55,66,77};
for(i=0;i<5;i++)
write(i,a[i]);
}
write(int c, int n)
{
printf("\ta[%d] = %d \n",c+1,n);
}
OUTPUT :
a[1] = 33
a[2] = 44
a[3] = 55
a[4] = 66
a[5] = 77
Explanation : Here the values of i and arrary elements will be send to write function.
Example: PROGRAM TO ACCEPT A STATIC ARRAY AND PRINT IT BY CALL BY
REFERENCE

#include<stdio.h>
main()
{
int i;
int a[5]={33,44,55,66,77};
for(i=0;i<5;i++)
write(i,&a[i]);
}
write(int c,int *n)
{
182 Chapter 10. Pointers

printf("\ta[%d] = %d \n",c+1,*n);
}
OUTPUT :
a[1] = 33
a[2] = 44
a[3] = 55
a[4] = 66
a[5] = 77

Explanation : Here the values of i and address of arrary elements will be send to write function.

10.5.3 Accessing array element in different ways


We can access the array elements in different ways. Assume that the ith element of the array can be
accessed :

num[i], *(num+i), *(i+num), i[num]

Ex: Example: ACCESSING ARRAY ELEMENT IN DIFFERENT WAYS

#include<stdio.h>
main()
{
int num[]={12,23,34,45,56};
int i;
for(i=0;i<5;i++)
{
printf("a[%d] = Value of address at %u = ",i,&num[i]);
printf("%d %d %d %d\n",num[i], *(num+i),*(i+num), i[num]);
}
}
OUTPUT :
Address = 65490 Element = 12 12 12 12
Address = 65492 Element = 23 23 23 23
Address = 65494 Element = 34 34 34 34
Address = 65496 Element = 45 45 45 45
Address = 65498 Element = 56 56 56 56

Explanation : The expression num[i], i[num], *(num+i) and *(i+num) are same.

10.6 Character pointers and Functions


If we wish to store "Computer". we can store it either in a string or some location in memory and
assign the address of the string in a char pointer. This is as shown below:

char str[] = "Computer";


char *p = "Computer";

The difference between these two forms is : we can’t assign a string to another, whereas, we can
assign a char pointer to another char pointer. This is shown in the following program.
Example: PROGRAM TO ASSIGN ONE STRING TO ANOTHER AND ASSIGN A CHAR-
ACTER POINTER TO ANOTHER
10.6 Character pointers and Functions 183

main()
{
char str1[]="Computer" ;
char str2[10];
char *s = "Good Morning";
char *q;
str2 = str1; /* It is error */
q=s; /* it will works */
}
Explanation : During the compilation will show error i.e. one string can not assign to another.
Once a string has been defined it can’t be initialized to another set of characters. Unlike strings,
such operation is perfectly valid in char pointers
Example: PROGRAM TO DEFINE A STRING AND TRYING TO INITIALIZE THAT STRING
main()
{
char str1[] = " hai! ";
char *p = " hai! ";
str1 = " Bye "; /* It is an error */
p = " Bye "; /* It will works */
}
Explanation : During the compilation will show error i.e. once string has been defined it
cannot initialize.
Example: PROGRAM TO PRINT THE GIVEN STRING
#include<stdio.h>
main()
{
char city[100];
int i,l;
printf(" Enter any city name : ");
scanf("%s",city);
printf(" The given string is : ");
prn(city);
}
prn(char *city)
{
while(*city!='\0')
{
printf("%c",*city);
city++;
}
}
OUTPUT :
Enter any city name : Hyderabad
The given string is : Hyderabad
Explanation : The city name will be passed to prn function by pointer i.e. city in prn function is a
char pointer to hold the starting address of the string.
184 Chapter 10. Pointers

Example: PROGRAM TO CALCULATE THE LENGTH OF THE GIVEN STRING


#include<stdio.h>
main()
{
char city[100];
int i,l;
printf(" Enter any city name : ");
scanf("%s",city);
l=len(city);
printf(" The length of the given string is : %d\n",l);
}
len(char *city)
{
int l1=0;
while(*city!='\0')
{
l1++;
city++;
}
return(l1);
}
OUTPUT :
Enter any city name : Bangalore
The length of the given string is : 9
Explanation : The city name wil be passed to len function by pointer i.e. city in len function is a
char pointer to hold the starting address of the string.

10.7 Array of Pointers


Homogeneous collection of pointers is referred to array of pointers, i.e. coection of pointers of the
same data type. The pointers are declared in array form like other data type. An integer pointer
array marks of size can be declared as :
int *marks[20]
A pointer may also be used for more than one array declaration of same data type.
Ex :
int s1[20], s2[20], s3[20];
int *marks[10];
Now we can assign the addresses of first element to each array as :
marks[0] = &s1[0];
marks[1] = &s2[0];
marks[2] = &s3[0];

10.8 Pointer to Functions


The function name itself represents the address of that function. Hence, it is possible to define a
pointer to a function. Functions are stored in memory similar to data. A function can be assigned,
10.9 Pointer to Pointers 185

placed in the arrays passed as an argument to other functions and returned by a function by means
of a pointer to a function. The declaration of a pointer to a function is :
data_type(*function_name)(type1,type2, . . ., typen)
The function call has the format :
(*function_name)(arg1, arg2,...,argn)
The parentheses in (*function_name) are necessary, since in *function_name() the parentheses have
higher precedence than * and they evaluated from left to right. If the parentheses are omitted, then
it becomes a function returning a pointer. The general format for a function returning a pointer is :
*function_name(arg1, arg2, ..., argn)
Thus, the pointer to a function must be declared carefully to avoid the confusion between a function
returning pointer and a pointer to a function. For example
double(*pf)(); /* pf is a pointer to a function */
double *fun(); /* fun is function returning a pointer */
Example: PROGRAM THAT ILLUSTRATES POINTER TO A FUNCTION
main()
{
int square(int),cubic(int);
int(*arr[2])(); /* pointer to function declaration */
arr[0]=square;
arr[1]=cubic;
printf(Square of %d is %d\n,5,(*ap[0](5));
printf(Cubic value of %d is %d\n,5,(*ap[1])(5));
}
square(int x)
{
return x*x;
}
cubic(int x)
{
return x*x*x;
}
OUTPUT :
Sqaure fo 5 is 25
Cubic value of 5 is 125

10.9 Pointer to Pointers


Pointers to pointers is logically same as the array of pointers. Consider the following declaration :
int n=20, *m;
m=&n;
Here m is not an ordinary variable like any other integer variable. It is a variable which contains
the address of another variable n. The following memory map would illustrate the content of n
and m. Generally a pointer is a variable which contains address of another variable, this variable
itself could be another pointer. Thus we have a pointer which contains another pointer’s address.
Consider the following declaration statements :
186 Chapter 10. Pointers

int n=20, *m, **p;


m=&n;
p=&m;
The above situation is called as pointer to pointer. First the address of n is assigned to m and
the address of m is assigned to p. The expression *m gives the value of n and *p gives the value
of m, which is the address of the variable n. Hence, the value of n can also be obtained by the
expression **p. Example: PROGRAM TO DEMONSTRATE THE CONCEPT OF POINTERS

TO POINTERS
#include<stdio.h>
main()
{
int n=20;
int *m;
int **p;
m=&n;
p=&m;
clrscr();
printf(" Address of n is : %u\n",&n);
printf(" Address of n is : %u\n",m);
printf(" Address of n is : %u\n",*p);
printf(" Address of m is : %u\n",&m);
printf(" Address of m is : %u\n",p);
printf(" Address of p is : %u\n",&p);
printf(" Value of m is : %u\n",m);
printf(" Value of p is : %u\n",p);
printf(" Value of n is : %d\n",n);
printf(" Value of n is : %d\n",*(&n));
printf(" Value of n is : %d\n",*m);
printf(" Value of n is : %d\n",**p);
}
OUTPUT :
Address of n is : 65496
Address of n is : 65496
Address of n is : 65496
Address of m is : 65498
Address of m is : 65498
Address of p is : 65500
Value of m is : 65496
Value of p is : 65498
10.10 Pointers and Multi dimentional Arrays 187

Value of n is : 20
Value of n is : 20
Value of n is : 20
Value of n is : 20

Explanation : Here the last printf statement prints the value of n by using **p. Here p value is
65498 value_at_address(65498) is 65496, now value_at_address(65496) is n.

10.10 Pointers and Multi dimentional Arrays


A multidimensional array can be accessed in different ways. as in a one dimensional array. The
array name of a multidimensional array also denotes the address of the 0th element in that array.
For example if the declaration int a[10][15], x[5][10][8]; the array names are a and x denote the
addresses of the array variable a[0][0] and x[0][0][0] respectively. The following table illustrate the
various expressions employed to refer to the elements in these arrays.

10.11 Dynamic Memory Allocation


During the compilation time the memory allocation performed is called static memory allocation.
This static allocation has a disadvantage that, there is no way the size of data structure can be
increased or decreased. If we declared the integer array m with the size of 100, the moment of
declaration 200 bytes are reserved for storing 100 integers in it. If we are using 25 locations
remaining memory will be wasted. If we want to store 101 elements there is no way.
The solution is to avoid static memory allocation is allocation of memory should be done at the
time of running, it is called the dynamic memory allocation. The functions malloc and calloc is
used for dynamic memory allocation.

C language offers 4 dynamic memory allocation functions. They are,


1. malloc()
2. calloc()
3. realloc()
4. free()

Function Syntax
malloc () malloc (number *sizeof(int));
calloc () calloc (number, sizeof(int));
realloc () realloc (pointer_name, number * sizeof(int));
free () free (pointer_name);

10.11.1 malloc()
• malloc () function is used to allocate space in memory during the execution of the program.
• malloc () does not initialize the memory allocated during execution. It carries garbage value.
188 Chapter 10. Pointers

• malloc () function returns null pointer if it couldn’t able to allocate requested amount of
memory.
Example:

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

int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"welcome to C");
}
printf("Dynamically allocated memory content : %s\n", mem_allocation );
free(mem_allocation);
}
OUTPUT:
Dynamically allocated memory content : welcome to C

10.11.2 calloc()
calloc () function is also like malloc () function. But calloc () initializes the allocated memory to
zero. But, malloc() doesn’t.

Example:

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

int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = calloc( 20, sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation," welcome to C");
}
10.11 Dynamic Memory Allocation 189

printf("Dynamically allocated memory content : " \


"%s\n", mem_allocation );
free(mem_allocation);
}
OUTPUT:
Dynamically allocated memory content : welcome to C

10.11.3 realloc()
realloc () function modifies the allocated memory size by malloc () and calloc () functions to new
size.
If enough space doesn’t exist in memory of current block to extend, new block is allocated for the
full size of reallocation, then copies the existing data to new block and then frees the old block.

10.11.4 free()
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns
the memory to the system.
Example: PROGRAM FOR REALLOC() AND FREE() FUNCTIONS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"welcome to C");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"space is extended upto " \
"100 characters");
}
printf("Resized memory : %s\n", mem_allocation );
free(mem_allocation);
}
190 Chapter 10. Pointers

OUTPUT:

Dynamically allocated memory content : welcome to C


Resized memory : space is extended upto 100 characters
DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC MEMORY ALLOCATION
IN C

Static memory allocation Dynamic memory allocation


In static memory allocation, memory is allo- In dynamic memory allocation, memory is al-
cated while writing the C program. Actually, located while executing the program. That
user requested memory will be allocated at means at run time.
compile time.
Memory size can’t be modified while execu- Memory size can be modified while execution.
tion. Example: array Example: Linked list

DIFFERENCE BETWEEN MALLOC() AND CALLOC() FUNCTIONS

malloc() calloc()
It allocates only single block of requested It allocates multiple blocks of requested mem-
memory ory
int *ptr;ptr = malloc( 20 * sizeof(int) );For theint *ptr;Ptr = calloc( 20, 20 * sizeof(int) );For
above, 20*4 bytes of memory only allocated the above, 20 blocks of memory will be cre-
in one block. Total = 80 bytes ated and each contains 20*4 bytes of memory.
Total = 1600 bytes
malloc () doesn’t initializes the allocated mem- calloc () initializes the allocated memory to
ory. It contains garbage values zero
type cast must be done since this func- Same as malloc () function int *ptr;ptr =
tion returns void pointer int *ptr;ptr = (int*)calloc( 20, 20 * sizeof(int) );
(int*)malloc(sizeof(int)*20 );

10.12 Example Programs


1. Write a program to find the highest of three numbers using pointer to function.

#include<conio.h>
void main()
{
int x,y,z;
clrscr();
printf("\n Enter three numbers : ");
scanf("%d %d %d",&x,&y,&z);
printf("\n\n The highest of the three numbers is : ");
highest(&x,&y,&z);
getch();
}
highest(a,b,c)
int *a,*b,*c;
{
10.13 Multiple Choice Questions 191

if(*a > *b && *a > *c)


printf("%d",*a);
else if(*b > *a && *b > *c)
printf("%d",*b);
else
printf("%d",*c);
}

10.13 Multiple Choice Questions


1. Pointers are supported in [ D ]
(A) FORTRAN (B) PASCAL
(C) C (D) both B and C
2. Pointer variable may be assigned [ C ]
(A) an address value (B) an address value (C) the address of an- (D) none
represented in hexadecimal
represented in octal other variable
3. A pointer value refers to [ C ]
(A) an integer constant (B) a float value
(C) any valid address in memory (D) any ordinary variable
4. Identify the correct declaration of variables p1,p2 [ D ]
(A) int p1,p2 (B) int *p1,p2
(C) int p1,*p2 (D) int *p1, *p2
5. The operators exclusively used in connection with pointers are [ B ]
(A) and /
(B) & and * (C) & and |
(D) - and >
6. Identify the invalid expression for given resiter int r=10; [ B ]
(A) r=20 (B) &r (C) r+15 (D) r/10
7. Identify the invalid expression [ D ]
(A) &275 (B) &a+b (C) &(a*b) (D) All the above
8. The operand of the address of pointer is [ C ]
(A) a constant (B) an expression
(C) a named region of storage (D) a register variable
9. The address of operator returns [ A ]
(A) The address of its operand (B) Lvalue
(C) Both a&b (D) R value
10. After the execution of the statement in x; the value of x is [ B ]
(A) 0 (B) undefined (C) 1 (D) -1
11. Identify the invalid pointer operator [ C ]
192 Chapter 10. Pointers

(A) & (B)


(C) >> (D) none of the above
12. The number if arguments used in malloc() is [ B ]
(A) 0 (B) 1 (C) 2 (D) 3
13. The number if arguments used in calloc() is [ C ]
(A) 0 (B) 1 (C) 2 (D) 3
14. The number if arguments used in realloc() is [ C ]
(A) 0 (B) 1 (C) 2 (D) 3
15. The function used for dynamic deallocation of memory is [ C ]
(A) destroy() (B) delete() (C) free() (D) remove()
16. The pointers can be used to achieve [ B ]
(A) call by function (B) call by reference
(C) call by name (D) call by procedure
17. The function that allocates requested size of bytes and returns a pointer to the first byte of the
allocated space is [ B ]
(A) realloc (B) malloc
(C) calloc (D) none of the above
18. The void type is used for [ B ]
(A) Returning the value (B) creating generic pointers
(C) Creating functions (D) Avoid error
19. What is the output of following program:- [ B ]
int q, *p, n;
q = 176;
p = &q;
n = *p;
printf(%d, n);
(If the address of q is 2801 and p is 2600)
(A) 2801 (B) 176
(C) 2600 (D) None of the above
20. Which is not dynamic memory allocation function? [ C ]
(A) malloc (B) free (C) alloc (D) calloc
21. While incrementing a pointer, its value gets increased by the length of the data type to which
it points. This length is called [ D ]
(A) scale factor (B) length factor
(C) pointer factor (D) increment factor
22. Consider the following code segment:
int a[10], *p1, *p2;
p1 = &a[4];
p2 = &a[6];
10.13 Multiple Choice Questions 193

Which of the following statements is incorrect w.r.t. pointers? [ C ]


(A) p1 + 2 (B) p2 – 2
(C) p2 + p1 (D) p2 – p1
23. Consider the following declaration [ D ]
int a, *b = &a, **c = &b;
The following program fragment
a = 4;
**c = 5;
(A) does not change the value of a (B) assigns address of c to a
(C) assigns the value of b to a (D) assigns 5 to a
24. If x is one dimensional array, then pick up the correct answer [ A ]
(A) (x + i) is same as &x[i]
(B) &x[i] is same as x + i
(C) (x + i) is same as x[i] +1
(D) (x + i) is same as *x[i]
25. Which of the following about the following two declaration is true [ C ]
i ) int *F()
ii) int (*F)()

(A) Both are identical


(B) The first is a correct declaration and the second is wrong
(C) The first declaration is a function returning a pointer to an integer and the second is a
pointer to function returning int
(D) Both are different ways of declaration pointer to a function
26. Consider the following program [ C ]
main()
{
int i=20,*j=&i;
f1(j);
*j+=10;
f2(j);
printf("%d and %d",i,*j);
}
f1(k)
int *k;
{
*k +=15;
}
f2(x)
int *x;
{
int m=*x,*n=&m;
*n += 10;
}
194 Chapter 10. Pointers

The values printed by the program will be


(A) 20 and 55

(B) 20 and 45

(C) 45 and 45

(D) 45 and 55
27. What is the output of following code:

void main()
{ int count=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=&sum;
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}

Answer: 20 20 20
28. what will be the value of *i? [ A ]

main()
{
char *p='a';
int *i=100/*p;
}

(A) 1 (B) 1.03 (C) Compiler Error (D) Can’t be determined


29. what will be the Output of below code? [ D ]

char *p="abc";
char *q="abc123";
while(*p=*q)
{
print("%c %c",*p,*q);
}

(A) aabbcc (B) aabbcc123 (C) abcabc123 (D) infinite loop


30. what will be the Output of below code? [ D ]

void main()
{
float j;
j=1000*1000;
printf("%f",j);
}

(A) 1000000 (B) Overflow (C) Error (D) None


31. What is the output of the given code:
10.13 Multiple Choice Questions 195

char *foo()
{c
har result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{c
har *j;
j=foo()
printf("%s",j);
}

Answer: anything is good.


32. Which of the choices is true for the mentioned declaration ? [ B ]

const char *p;


and
char * const p;

(A) You can’t change the character in both


(B) First : You can’t change the characterr & Second : You can;t change the pointer
(C) You can’t change the pointer in both
(D) First : You can’t change the pointer & Second : You can’t chanage the character
33. #define NULL 0
char *index(sp,c)
register char *sp,c;
{
do {
if(*sp == c)
return (sp);
} while (*sp++);
return NULL;
}
The first argument sp, is a pointer to a C string. The second argument, c, is a character. This
function scarches for the character c, in the string. If it is found a pointer to that location is
returned else NULL is returned. This function works
(A) Always
(B) Always, but fails when the first byte contains the character c
(C) works when c is a non NULL character only
(D) Works only when the character c is found in the string
34. What is the output of the below code? [ A ]

main()
{
int *j;
{
196 Chapter 10. Pointers

int i=10;
j=&i;
}
printf("%d",*j);
}
(A) 10 (B) 11 (C) Error (D) None
35. What is the output of the below code? [ A ]
main()
{
int i;
char *p;
i=0X89;
p=(char *)i;
p++;
printf("%x\n",p);
}
(A) 0X8A (B) 0X8B (C) 0X9A (D) None of the above
36. What is the output of the below code? [ D ]
main()
{
char *src = "Hello World";
char dst[100];
strcpy(src,dst);
printf("%s",dst);
}strcpy(char *dst,char *src)
{while(*src) *dst++ = *src++;
}
(A) "Hello World" (B) "Hello" (C) "World" (D) NULL
37. What is the output of the below code? [ D ]
main()
{
int var=25,varp;
varp=&var;
varp p = 10;
fnc(varp)
printf("%d%d,var,varp);
}
(A) 20, 55 (B) 20, 20 (C) 55, 20 (D) 55, 55
38. Which of the following is the proper declaration of a pointer? [ D ]
(A) int x; (B) int &x; (C) ptr x; (D) int *x;
39. Which of the following gives the memory address of integer variable a? [ C ]
(A) a;
(B) a; (C) &a; (D) address(a);
10.13 Multiple Choice Questions 197

40. Which of the following gives the memory address of a pointer a? [ B ]


(A) a;
(B) a; (C) &a; (D) address(a);
41. Which of the following gives the value stored in pointer a? [ A ]
(A) a;
(B) a; (C) &a; (D) address(a);
42. What is the output of the below code?

main()
{c
har* p="hello";
printf("%d %d",strlen(p),sizeof(p));
getch();
}
43. What is the output of the below code?

#include<stdio.h>
main(){
char a[]="hellow";
char *b="hellow";
char c[5]="hellow";
printf("%s %s %s ",a,b,c);
printf(" ",sizeof(a),sizeof(b),sizeof(c));
}
44. What is the output of the below code? [ C ]

main()
{
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}
(A) 300 (B) 302 (C) 556 (D) Error
Explanation: The integer value 300 in binary notation is: 00000001 00101100. It is stored
in memory (little endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes
the memory representation as: 00101100 00000010. So the integer corresponding to it is
00000010 00101100 ⇒ 556.
45. What is the output of the below code? [ C ]

#include <stdio.h>
main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
198 Chapter 10. Pointers

least = (*ptr<least ) ?*ptr :least;


printf("%d",least);
}
(A) 127 (B) 128 (C) 0 (D) Error
After ’ptr’ reaches the end of the string the value pointed by ’str’ is ’\0’. So the value of ’str’
is less than that of ’least’. So the value of ’least’ finally is 0.
46. What is the output of the below code?
void main()
{
printf(sizeof (void *) = %d \n, sizeof( void *));
printf(sizeof (int *) = %d \n, sizeof(int *));
printf(sizeof (double *) = %d \n, sizeof(double *));
printf(sizeof(struct unknown *) = %d \n, sizeof(struct unknown *));
}
Answer :
sizeof (void *) = 2
sizeof (int *) = 2
sizeof (double *) = 2
sizeof(struct unknown *) = 2
47. Is this code legal?
int *ptr;
ptr = (int *) 0x400;
Answer: Yes
48. What is the output of the below code? [ A ]
main()
{
int a=10,*j;
void *k;
j=k=&a;
j++;
k++;
printf("\n %u %u ",j,k);
}
(A) Compiler error (B) 11 (C) 0 (D) Compiler dependent
Explanation: Void pointers are generic pointers and they can be used only when the type is
not known and as an intermediate address storage type. No pointer arithmetic can be done on
it and you cannot apply indirection operator (*) on void pointers.
49. Find the output
char *someFun()
{char *temp = string constant";
return temp;
} int main()
{
puts(someFun());
}
10.13 Multiple Choice Questions 199

Answer: string constant


Explanation: The program suffers no problem and gives the output correctly because the
character constants are stored in code/data area and not allocated in stack, so this doesn’t
lead to dangling pointers.
50. Find the output?

char *someFun1()
{char temp[ ] = string";
return temp;
}char *someFun2()
{char temp[ ] = {`s', `t','r','i','n','g'};
return temp;
} int main()
{
puts(someFun1());
puts(someFun2());
}

Answer: Garbage values.


Explanation: Both the functions suffer from the problem of dangling pointers. In some-
Fun1() temp is a character array and so the space for it is allocated in heap and is initialized
with character string "string". This is created dynamically as the function is called, so is also
deleted dynamically on exiting the function so the string data is not available in the calling
function main() leading to print some garbage values. The function someFun2() also suffers
from the same problem but the problem can be easily identified in this case.
51. Find the output?

main()
{ int i, *p=&i;
p=malloc(10);
free(p);
printf("%d",p);
}

Answer : Garbage
52. Which of the following is the correct code for strcpy, that is used to copy the contents from
src to dest? [ B ]
(a) strcpy (char *dst,char *src)
{
while (*src)
*dst++ = *src++;
}
(b) strcpy (char *dst,char *src)
{
while(*dst++ = *src++ )
}
(c) strcpy (char *dst,char *src)
{
while(*src)
{
*dst = *src;
200 Chapter 10. Pointers

dst++; src++;
}
}
(d) strcpy(char *dst, char *src)
{
while(*++dst = *++src);
}
53. What will the following program do? [ B ]

void main()
{
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//
(A) Swap contents of p & a and print:(New string, string)
(B) Generate compilation error in line number 8
(C) Generate compilation error in line number 5
(D) Generate compilation error in line number 7
(E) Generate compilation error in line number 1
54. What is the output of the following problem ? [ B ]

main()
{
void swap();
int x=10,y=8;
swap(&x,&y);
printf("x=%d y=%d",x,y);
}
void swap(int *a, int *b)
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
(A) x=8, y=10 (B) x=10, y=8 (C) Error (D) None
55. What is the output of the following problem ? [ C ]

main()
{
10.13 Multiple Choice Questions 201

register int a=2;


printf("Address of a = %d",&a);
printf("Value of a = %d",a);
}
(A) 2 2 (B) garbage 2 (C) Error (D) None
56. What is the output of the following problem ? [ B ]
void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(%d,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(%d,*cptr);
}
(A) 1 1 (B) garbage 0 (C) Error (D) None
57. What is the output of the following problem ? [ B ]
main()
{c
har *p = ayqm;
printf(%c,++*(p++));
}
(A) a (B) b (C) y (D) q
58. What is the output of the following problem ? [ A ]
int swap(int *a,int *b)
{
*a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main()
{
int x=10,y=20;
swap(&x,&y);
printf("x= %d y = %d\n",x,y);
}
(A) x = 20 y = 10 (B) x=10 y=20 (C) Error (D) None
59. What is the output of the following problem ? [ A ]
main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
(A) H (B) He (C) Error (D) None
60. What is the output of the following problem ? [ A ]
202 Chapter 10. Pointers

#include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
(A) 77 (B) 32 (C) Error (D) None
61. What is the output of the following problem ?
main( )
{
void *vp;
char ch = `g', *cp = goofy;
int j = 20;
vp = &ch;
printf(%c, *(char *)vp);
vp = &j;
printf(%d,*(int *)vp);
vp = cp;
printf(%s,(char *)vp + 3);
}
Answer: g20fy
62. What is the output of the following problem?
main ( )
{
static char *s[ ] = {black, white, yellow, violet};
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
**++p;
printf(%s,*--*++p + 3);
}
Answer: ck
Explanation: In this problem we have an array of char pointers pointing to start of 4 strings.
Then we have ptr which is a pointer to a pointer of type char and a variable p which is a
pointer to a pointer to a pointer of type char. p hold the initial value of ptr, i.e. p = s+3. The
next statement increment value in p by 1 , thus now value of p = s+2. In the printf statement
the expression is evaluated *++p causes gets value s+1 then the pre decrement is executed
and we get s+1 - 1 = s . the indirection operator now gets the value from the array of s and
adds 3 to the starting address. The string is printed starting from this position. Thus, the
output is ’ck’.
63. What is the output of the following problem?
main()
{c
10.13 Multiple Choice Questions 203

har *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c%v",c,v);
}
Answer: Compiler error (at line number 4): size of v is Unknown.
Explanation: You can create a variable of type void * but not of type void, since void is an
empty type. In the second line you are creating variable vptr of type void * and v of type
void hence an error.
64. What is the output of the following problem? [ A ]

main()
{
int i = 258;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}
(A) 2 1 (B) 1 2 (C) 1 1 (D) Compiler Error
65. What is the output of the following problem? [ A ]

void main()
{ int count=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=&sum;
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}
(A) 20 20 20 (B) 20 20 21 (C) 21 21 10 (D) Compiler Error
11. Structures & Unions

A structure in C is a hetereogeneous data type, similar to the records of dBASE and Pascal. A struc-
ture can have its member of different types. A structure is a collection of variables referenced under
one name. The arrays and structures are different from each other as (i) arrays are homogeneous
in nature i.e., same type of elements, where as structures are heterogeneous i.e., different type of
elements. (ii) array element is referred by its position, where as structure elements has a unique
name.

11.1 Declaration of Structure


Structures help to organize complex data in a more meaningful way. Like other variables, a structure
variable also have to be declared. The structre declaration starts with the keyword struct followed
by a tag. The general format of a simple structure declaration is :

struct structure_name
{
type var1;
type var2;
.
.
type varn;
};

11.2 Definition of Structure


It is collection of logically related data items grouped together under a single name called structure
tag. The data items that make up a structure are called its members, components, or fields and can
be of different type.
Ex : Declaring a structure of name books with members of title, author, number of pages and
price.
206 Chapter 11. Structures & Unions

struct books
{
char title[25];
char author[20];
int pages;
float price;
};
struct books book1, book2, book3;
The above declaration may be written as :
struct books
{
char title[25];
char author[20];
int pages;
float price;
} book1,book2,book3;

11.3 Structure Initialization


Like other data types a structure variable can be initialized. A structure to be initialized must be
either static or external.
main()
{
static struct
{
char name[30];
int age;
float height;
}
student={"Srinivas",20,180.75};
. . . .
. . . .
}
This assigns the string "Srinivas" to student.name, value 20 to student.age and 180.75 to stu-
dent.height. Suppose you want to initialize more than one structure variable:
main()
{
struct sturec
{
char name[30];
int age;
float height;
};
static struct sturec student1={"Srinivas",20,180.75};
static struct sturec student2={"`Ramesh",22,177.25};
. . . .
. . . .
}
11.4 Accessing Elements in Structure 207

Another method is to initialize a structure variable outside the function

struct sturec
{
char name[30];
int age;
float height;
} student1={"Srinivas",20,189.76}
main()
{
static sturec student2={"Ramesh",22,177.25};
. . . .
. . . .
}

11.4 Accessing Elements in Structure


C provides the .(dot)/period operator using which structure members can be accessed independently.
The dot operator connects a structure variable with its member. The dot operator must have a
structure variable on its left and a legal member name on its right.
Ex :

student1.age=20;
Note that the structure tag is not a variable name. It is rather a name given to a templet of a structure.
Consider the following statement is a not valid one.

sturec.age=20;
Example: DEFINE A STRUCTURE TYPE, STUREC, THAT CONTAIN NAME, AGE,
HEIGHT. USING THIS STRUCTURE, WRITE A PROGRAM TO READ FOR ONE STUDENT
DETAILS FROM THE KEYBOARD AND PRINT THE SAME ON THE SCREEN

#include<stdio.h>
struct sturec
{
char name[30];
int age;
float height;
};
main()
{
struct sturec student
clrscr();
printf(" Enter a student details : \n");
printf(" Enter a student name : ");
scanf("%s",student.name);
printf(" Enter a student age : ");
scanf("%d",&student.age);
printf(" Enter a student height : ");
scanf("%f",student.height);
printf("\n\n Student's name is : %s\n",student.name);
208 Chapter 11. Structures & Unions

printf(" Student's age is : %d\n",student.age);


printf(" Student's height is : %f\n",student.salary);
}
OUTPUT:
Enter a student details :
Enter a student name : Rajesh
Enter a student age : 21
Enter a student height : 180.30
Student's name is : Rajesh
Student's age is : 21
Student's height is : 180.302314

11.4.1 Comparision of Structure Variables


Like ordinary ariables two variables of the same structure type can be compared. Example:
PROGRAM TO ILLUSTRATE THE COMPARISION OF STRUCTURE VARIABLES

#include<stdio.h>
struct sturec
{
char name[30];
int number;
int marks;
};
main()
{
int x;
static struct sturec stu1={"Nikhila",111,83};
static struct sturec stu2={"Vignesh",222,85};
struct sturec stu3;
stu3=stu2;
if(stu2.name==stu3.name && stu2.number==stu3.number &&
stu2.marks==stu3.marks)
printf("\n Student2 and Student3 are same\n");
else
printf("\n student2 and student3 are different\n");
}
OUTPUT:
Student2 and Student3 are same

11.5 Array of Structures


You can declare array of structures, each element of the array represents a structure variable.
Ex. :

struct stumarks student[100];


defines an array called ’student’ that consists of 100 elements, Each element is defined to be of the
type struct stumarks. Consider the following declaration.

struct emprec
{
11.5 Array of Structures 209

char name[25];
float basic;
float da;
float hra;
float pf;
float total;
};
main()
{
static struct emprec emp[3]=
{"Nagesh",8000.00,4000.00,1600.00,600.00,0.0},
{"Ramaiah",6000.00,3000.00,1250.00,600.00,0.0},
{"Kiran",10000.00,5400.00,2200.00,700.00,0.0};
. . . .
. . . .
}

Example: WRITE A PROGRAM TO CALCULATE THE TOTAL SALARY OF EACH EM-


PLOYEE AND INDIVIDUAL TOTALS

# include<stdio.h>
struct emprec
{
char name[25];
float basic;
float da;
float hra;
float pf;
float total;
};
main()
{
int i;
float tbasic=0.0, thra=0.0, tda=0.0, tpf=0.0,gtotal=0.0;
static struct emprec emp[3]=
{"Nagesh",8000.00,4000.00,1600.00,600.00,0.0},
{"Ramaiah",6000.00,3000.00,1250.00,600.00,0.0},
{"Kiran",10000.00,5400.00,2200.00,700.00,0.0};
for(i=0;i<3;i++)
{
emp[i].total= emp[i].basic+emp[i].da+ emp[i].hra-emp[i].pf;
tbasic=tbasic+emp[i].basic;
tda=tda+emp[i].da;
thra=thra+emp[i].hra;
tpf=tpf+emp[i].pf;
gtotal=gtotal+emp[i].total;
}
for(i=0;i<3;i++)
printf(" stu[%d] : %f\n",i+1,emp[i].total);
printf("Total Basic : %f\n,tbasic);
210 Chapter 11. Structures & Unions

printf("Total DA : %f\n,tda);
printf("Total HRA : %f\n,thra);
printf("Total PF : %f\n,tpf);
printf("\n Grand Total : %d\n", gtotal);
}

11.6 Array With in Structure


It is possible to have an array inside a function, i.e., an array as structure member. We can use
single or multi dimensional array of type int or float also.

struct marks
{
int no;
int sub[5];
int total;
} stu[10];

11.7 Nested Structures


The concept of nested structures refers to use of structures within a structure. The definition of C
says that any legal data type can be a member of a structure, any legal data type includes a structure
too.

struct emprec
{
char name[30];
int age;
struct
{
int day;
char month[20];
int year;
}j_date;
float sal;
}

11.8 Structures and Functions


A structure can also be used in functions, while using the same structure in different functions. It is
essential to pass the structure as an argument, the structure variable or a pointer to the structure
may be passed. When the structure variable is passed the changes made in the members of the
structure available only in the called function(Call by Value). But, if a pointer to a structure is used,
the changes are available in the calling function also (effect of Call by Reference). Based on the
requirement the structure may be passed simply as structure variable or pointer to a structure. It is
important to declare the parameters appropriately in the function definition.
A function definition shown below that contains the declaration of the structure in the left side
and the declaration of a pointer to structure on the right side. The actual and formal parameters can
have the same names or different names.
11.8 Structures and Functions 211

C consists of functions. The function main() subdivided into a number of modules. Hence, it is
a good programming style if a program is written using many functions. Observe the declaration of
the parameter in the function definition.
ONE:
main()
{
typedef struct
{
......
.......
}NODE;
NODE s,*p = &s;
............
create(s);
...........
}
create (NODE start)
{
.. .......
}
Two:
main()
{
typedef struct
{
......
......
}NODE;
NODE s,*p=&s;
............
create(p);
...........
}
create (NODE *start)
{
.. .......
}
Three
main()
{
typedef struct
{
int id;
char name[30];
}EMPLOYEE;
EMPLOYEE emp;
....................
212 Chapter 11. Structures & Unions

organize(emp.id); /* member passed */


........................
}
organize(int x)
{
....................
}

11.9 Structure and pointers


We specified that pointer is a variable that holds the memory address of other variables of basic
datatypes such as int, float, char, etc., A pointer can also be used to hold the address of structure
variables. Pointers along with structures are used to make linked list, trees, graphs, etc.,
Ex. :
struct emprec
{
char name[25];
float basic;
float da;
float hra;
float pf;
};
struct emprec *emp;
In the above declaration, *emp is a pointer variable which holds the address of the structure emprec.
Like other structure variables we can access the structure variables.
Ex. :
(*emp).basic
(or)
emp->basic
In the second declaration, pointer to structure is expressed using a – (iphen) sign followed by greater
than (>) sign.

11.10 Self-Referential Structures


It is possible to have a member of a structure as a pointer to itself (structure itself as a member is
not possible). In a structure, if one or more members are pointers pointing to the same structure,
then this structure is known as a self-referential structure.
Ex :
typedef struct vertex
{
int data;
struct vertex *np;
}NODE;
Recursive declaration of a structure as shown above is allowed in C. Here, np is a member, which
is a pointer to struct vertex. But it is illegal to use the structure itself as its member. One can
appreciate the use of a pointer yielding a self-referential structure. There is also an indirect way of
creating a self-referential structure as given below.
11.11 Union 213

struct first
{
....
struct second *s; /* s points to second */
};
struct second
{
:
struct first *f; /* f points to first */
};
The structure first has a member s pointing to the structure second, which has a member f pointing
to the structure first .
An indirect recursive declaration of a pointer to a structure also results in a self-referential structure.

11.11 Union
Unions are similar to structure data types. This union data type allows you to overlay more than
one variable in the same memory area. Normally, every variable is stored in separate locations, thus
each one has its own address. The major difference between the structure and union is in terms
of storage. In structures each member has its own storage location, whereas all the members of a
union use the same location. The general form of union declaration is :
union name
{
type var1;
type var2;
.
.
};
Example:
union item
{
int m;
float x;
char c;
}code;
In the above example a variable code declares the type union item. The union contains three
members each with a different data type. However we can use only one of them at a time. This is
due to the fact that only one location is allocated for a union variable, irrespective of its size.
The compiler allocates a piece of storage that is large enough to hold the largest variable type
in the union. In the above declaration the member x requires 4 bytes which is the largest among the
members. The above figure shows how all the three variables share the same address.

11.11.1 Accessing Union elements


To access a union member we can use the same syntax that we used in the structure members.
Example:
code.m
code.x
214 Chapter 11. Structures & Unions

11.12 Multiple Choice Questions


1. Structure is a [ B ]
(A) scalar data type (B) derived data type
(C) both a&b (D) primitive data type
2. Structure is a data type in which [ C ]
(A) each element must have the same element
(B) each element must have pointer type only
(C) each element must have different data type
(D) no element is defined
3. C provide a facility for user defined data type using [ C ]
(A) pointer (B) function (C) structure (D) array
4. The keyword used to represent a structure data type is [ B ]
(A) strictire (B) struct (C) struc (D) structr
5. Structure declaration [ A ]
(A) describes the prototype (B) creates structure variable
(C) define the structure function (D) is not necessary
6. Structure definition [ B ]
(A) describes the prototype
(B) creates structure (C) define the struc- (D) is not necessary
variable ture function
7. The operator used to access the structure member is [ B ]
(A)
(B) . (C) &
8. The operator exclusively used with pointer to structure is [ B ]
(A) . (B) − > (C)
9. If one or more members of a structure are other structure is known as [ A ]
(A) nested structure (B) invalid structure
(C) self-referential structure (D) unstructured
11.12 Multiple Choice Questions 215

10. Union is [ A ]
(A) a special type of strcture (B) a pointer data type

(C) a function data type (D) not a data type


11. What is not possible with union [ D ]
(A) Array of union (B) Pointer of union

(C) Self-referential union (D) None of the above


12. Structure is used to implement the data structure [ D ]
(A) Stack (B) Queue (C) Tree (D) All the above
13. The node in a linked list are implemented using [ A ]
(A) Self-referential structure (B) Nested structure

(C) Array of structure (D) Ordinary structure


14. A bit field is [ A ]
(A) int (B) float (C) double (D) all the above
15. The constructed datatype of C is known as [ C ]
(A) Pointers (B) String (C) Structure (D) Array
16. What will be the output of the following code segment, if any? [ D ]

myfunc ( struct test t) {


strcpy(t.s, world);
}
main( ) {
struct test { char s[10]; } t;
strcpy(t.s, Hello);
printf(%s, t.s);
myfunc(t);
printf(%s, t.s);
}

(A) Hello Hello (B) world world

(C) Hello world (D) the program will not compile


17. Which of the following is true for the statement: [ C ]
NurseryLand.Nursery.Students = 10;
(A) The structure Students is nested within the structure Nursery.

(B) The structure NurseryLand is nested within the structure Nursery.

(C) The structure Nursery is nested within the structure NurseryLand.

(D) The structure Nursery is nested within the structure Students.


18. What is the size of the following union. Assume that the size of int =2, size of float =4 and
size of
216 Chapter 11. Structures & Unions

char =1.
Union Tag
{
int a;
float b;
char c;
};
(A) 2 (B) 4 (C) 1 (D) 7
19. What is the output of the following code

void main()
{c
har *s[]={ "dharma","hewlett-packard","siemens","ibm"};
char **p;
p=s;
printf("%s",++*p);
printf("%s",*p++);
printf("%s",++*p);
}
Answer:
"harma" (p->add(dharma) && (*p)->harma)
"harma" (after printing, p->add(hewlett-packard) &&(*p)->harma)
"ewlett-packard"
20. What is the output of the below code?

#include<stdio.h>
#include<conio.h>
struct bit
{ int a:5;
int b:12;
};
main()
{clrscr();
printf("%d",sizeof(struct bit));
getch();
}
21. What is the size of the following union. Assume that the size of int=2, size of float=4 and
size of char=1. [ A ]

Union Tag{
int a;
float b;
char c;
};
(A) 2 (B) 4 (C) 7 (D) None
22. what can be said of the following [ C ]

struct Node {
11.12 Multiple Choice Questions 217

char *word;
int count;
struct Node left;
struct Node right;
}

(A) Incorrect definition


(B) structures cannot refer to other structure
(C) Structures can refer to themselves. Hence the statement is OK
(D) Structures can refer to maximum of one other structure
23. Is the following code legal?

struct a
{
int x;
struct a *b;
}

Answer: Yes.
Explanation: *b is a pointer to type struct a and so is legal. The compiler knows, the size of
the pointer to a structure even before the size of the structure is determined(as you know the
pointer to any type is of same size). This type of structures is known as ’self-referencing’
structure.
24. Is the following code legal?

struct a
{
int x;
struct a b;
}

Answer: No
Explanation: Is it not legal for a structure to contain a member that is of the same type as in
this case. Because this will cause the structure declaration to be recursive without end.
25. What is the output of the below code?

main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}

Answer: Compiler Error


Explanation: You should not initialize variables in declaration
218 Chapter 11. Structures & Unions

26. Is the following code legal?

typedef struct a
{
int x;
aType *b;
}aType
Answer: No
27. Is the following code legal?

typedef struct a aType;


struct a
{
int x;
aType *b;
};
Answer: Yes
Explanation: The typename aType is known at the point of declaring the structure, because
it is already typedefined.
28. What is the output of the following problem ? [ B ]

typedef struct error{int warning, error, exception;}error;


main()
{
error g1;
g1.error =1;
printf("%d",g1.error);
}
(A) 0 (B) 1 (C) Error (D) None of the above
12. Files

Files are used to store large amount of data. Computer stores files on secondary storage devices
such as harddisk, tapes, etc., A file is a group of related records. A employee file normally contains
the records of each employee. A record is a group of related fields. Each field belongs to the same
employee. These fields are composed of characters(or bytes). A field is a group of characters that
conveys meaning. A character may be a digit, letter and special symbols. Computers manipulate
and process these character as pattern of bits. Since computer can process only 0s and 1s. Byes are
most commonly composed of eight bits. A bit (either 0 or 1) is the smallest data item in a computer.

12.1 Types of Files


There are two types of files text and Binary. Binary files are collection of 1s and 0s, where as ASCII
or plain text files allocates a number to each letter, digit and symbol. A plain text files doesnot
contains formatting codes, i.e. no fonts, bold, italic, headers and etc., ASCII is being replaced in
many applications by Unicode, which uses 16 bits per character.

12.2 Streams
A stream is an abstraction that either produces or consumes information. A stream is linked to a
physical device by the I/O system. All streams behave in the same manner i.e. input stream can
abstract many different kinds of input : from a disk file, a keyboard, or a network socket. Likewise
an output stream may refer to the console, a disk file or a network connection.

Byte stream and character stream


Some programming languages like Java supports defines two types of streams : byte and character.
Byte streams provides a convenient means for handling input and output of bytes. Byte streams are
used when reading or writing binary data. Character streams provides a convenient for handling
input and output of characters. In some cases character streams are more efficient than byte streams.
220 Chapter 12. Files

12.3 Standard IO
Standard I/O library functions are available in a file named stdio.h (standard input output header
file). The following line is included in a C program whenever standard I/O functions are used.

#include <stdio.h>

It causes the contents of the header file to be included within the program. If it is not included in a
program, the user must define and declare the necessary I/O functions.

12.3.1 I/O Functions :


C supports many I/O functions. Some of the built-in functions are used to read the input from
keyboard and display the output on the screen. Here we are specifying two important I/O functions,
they are character oriented I/O functions and Formatted I/O functions.

12.3.2 Character oriented I/O functions:


Character oriented I/O functions are used to read or write one character at a time. The standard C
library provides several functions for this purpose. The simplest functions getchar( ) and putchar( ).

getchar( )
The functions getchar( ) is used to read a single character from the keyboard. This function returns
an integer value of the character in the machine’s character code. If the system uses the ASCII
character code, then the ASCII value of the character is returned. The general format for using this
function is

variable = getchar( );

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

putchar( )
The function putchar( ) writes its character argument on the screen. The general format for using
this function is:

putchar(ASCII_value);

Here the ASCII value may be represented by an integer constant or a variable or a character
constant.

12.3.3 Formatted I/O Functions


Character oriented I/O functions use the values of the machine’s character code for any character.
This low level (e.g. ASCII code of a character ) means of data transmission leads to other conversion
functions whenever a numeric data is to be read or written. In such situations, the formatted I/O
functions are very simple to use. The users may be interested in giving the inputs and getting the
outputs in a particular format. For this purpose the formatted I/O functions are used.

scanf( )
This functions is used to read input values from the keyboard. The general format is

scanf("format_string",address_list);
12.4 File Operations 221

Here the format_string contains the required formatting specifications enclosed within double
quotes. address_list contains the addresses of the memory locations where the input data is stored.
The addresses are separated by commas.
The format_string includes conversion specifications directing the conversion of the next input
data. The converted input is placed in the addresses of the variables given in the address_list.
Conversion specification is written as % followed by a conversion character. The conversion
character specifies the interpretation of the input data.

scanf("%d%d",&a,&b);
printf( )
This function is used to write the output values on the screen. It will be used in two different ways
1. printf("Any string") : It is used to display the string enclosed within double quotes.
2. printf("format_string",list_variables) : Here format_string is the same as defined in the
function scanf( ) or a combination of string and conversion sections. list_variables contains
constants or variables or expressions or functions separated by commas.

12.4 File Operations


The major basic operations on files that supports C is : naming a file, opening a file, reading data
from a file, writing data to a file and closing a file. There are two distinct ways to perform a file
operations in C. The first method is known as the low level I/O and uses UNIX system calls. The
second method is referred to as the high level I/O operation and uses functions in C’s standard I/O
library.
The FILE pointer
A FILE is a data type (defined in stdio.h), which is used to operate on files. A FILE pointer is a
pointer to a FILE. You may open several files simultaneously, when you want to perform I/O on
a file you need to identify and specify which file you want to operate on. This is the purpose the
FILE pointer variable serves.
Opening a File
To open a file, the stdio library provides a function fopen. The prototype of the function fopen is :

FILE* fopen(char* filename, char* mode)


This function expects two parameters. The first one is a character pointer to be pointing to a string
contains the name of the file to be opened. The second parameter is a character pointer to be
pointing to a string contains the mode of operation. Mode an be one of the following :

Mode Access
"r" Read only; File must be present and readable; Soon after opening current position is
set to top of file.
"w" Overwrite. If file present contents are discarded, If file is absent it is created.
"a" Append. If file present any output done gets appended. If file is absent it gets created.
As soon as file is opened current position is set to the end of file.
"r+" Update. File must present. Read as well as write access available. As soon as file is
opened current position is set to top of file.
"w+" Overwrite. It is same as "w" mode except both for reading and writing
"a+" Append. It is same as "a" mode except both for reading and writing

This fopen function tries to open the said file in the said mode. If successful, returns a FILE
222 Chapter 12. Files

pointer. If not successful, returns a NULL pointer.


The general format for declaring and opening a file
FILE *fp;
fp=fopen("filename","mode");

The first statement declares the variable fp as a pointer to the data type FILE. The second statement
opens the file, named filename and assigns an identifier to the FILE type pointer fp. This pointer
which contains all the information about the file is subsequently used as a communication link
between the system and the program.

12.4.1 Closing a file


A file must be closed as soon as all operations on it have been completed. We have to close a file is
when we want to reopen the same file in a different mode. fclose function is used to close a file.

fclose(file_pointer);
Ex:- FILE *x1,*x2;
x1=fopen("salary",r);
x2=fopen("employee",w);
. . . .
. . . .
. . . .
fclose(x1);
fclose(x2);

All files are closed automatically whenever a program terminates. However closing a file as soon as
you are done with it is a good programming habit.

12.4.2 Character I/O on files


C provides a number of functions to perform character input/output operations one files.
getc functions
The getc() function reads characters from a file opened in read mode by fopen(). Function getc
is functionally similar to getchar. It reads a character from the specified file and return an int
containing the value read. On end of file getc returns EOF. Prototype of getc function is :
int getc(File *fp);
Ex :
ch=getc(fptr);
putc functions
The putc() function writes characters to a file opened in write mode by fopen(). Function putc
is functionally similar to putchar. It has two parameters, a character expression and file pointer.
Prototype of putc function is :
putc(int, File *fp);
Ex :
putc(ch,fptr);
Example: WRITE A PROGRAM TO READ DATA FROM THE KEYBOARD, WRITE IT TO A
FILE CALLED IN, AGAIN READ THE SAME DATA FROM THE IN FILE AND DISPLAY IT
ON THE SCREEN
12.4 File Operations 223

#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf(" Enter data into a file : \n");
f1=fopen("IN","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
printf("\nData from the file : \n");
f1=fopen("IN","r");
while((c=getc(f1))!=EOF)
printf(" %c ",c);
fclose(f1);
}
OUTPUT :
Enter data into a file :
I am a Software Engineer
Data from the file :
I am a Software Engineer

12.4.3 getw AND putw FUNCTIONS


The getw and putw are integer oriented functions. They are similar to the getc and putc functions,
and are used to read and write integer values. These functions would be useful when we deal with
only integer data. The general form of
putw(integer, fp);
getw(fp);
Example: A file name DATA contains a series of integer numbers. Code a program to read
these numbers and then write all odd numbers to a file to be called ODD and all even numbers to a
file to be called EVEN.
#include<stdio.h>
main()
{
FILE *f1,*f2,*f3;
int num, i;
clrscr();
printf(" Contents of DATA file :\n");
f1=fopen("DATA","w");
for(i=1;i<=30;i++)
{
printf("Enter an integer number : ");
scanf("%d",&num);
if(num==-1)
break;
putw(num,f1);
}
224 Chapter 12. Files

fclose(f1);
f1=fopen("DATA","r");
f2=fopen("ODD","w");
f3=fopen("EVEN","w");
while((num=getw(f1))!=EOF)
{
if(num%2==0)
putw(num,f3);
else
putw(num,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("ODD","r");
f3=fopen("EVEN","r");
printf("\n\nContents of ODD file :\n\n");
while((num=getw(f2))!=EOF)
printf(" %4d",num);
printf("\n\nContents of EVEN file :\n\n");
while((num=getw(f3))!=EOF)
printf(" %4d",num);
fclose(f2);
fclose(f3);
}
OUTPUT :
Enter an integer number :
Enter an integer number : 5
Enter an integer number : 10
Enter an integer number : 15
Enter an integer number : 20
Enter an integer number : 25
Enter an integer number : 30
Enter an integer number : 35
Enter an integer number : 40
Enter an integer number : 45
Enter an integer number : 50
Enter an integer number : 55
Enter an integer number : 60
Contents of ODD file :
5 15 25 35 45 55
Contents of EVEN file :
10 20 30 40 50 60

12.4.4 THE fprintf AND fscanf FUNCTIONS


fscanf fuction
This function can be used to different data types from the specified file. It works in the similar way
of scanf function. The general form is :
fscanf(fp,"control string",list);
12.5 Error Handling 225

Here the statement reads the variable list from the file referred by the file pointer by using the
formats given in control string.
Ex:-
fscanf(fp,"%d%f",&age,&sal);
fprintf function
This function can be used to print different types of data. It works in the similar way of printf
function. The general form is :
fprintf(fp,"control string",list)
Example: Write a program to open a file named INVENTORY and store it the following data
Item name number price quantity
TV 111 25000.75 15
VCP 113 42000.00 3
VCR 123 50000.35 10
Extend the program to read this data from the file INVENTORY and display the inventory table
with the value of each item.
#include<stdio.h>
main()
{
FILE *fp;
int num,qty,i;
float price, value;
char item[10],filename[20];
printf(" Enter the name : ");
scanf("%s",filename);
fp=fopen(filename,"w");
printf(" Input inventory data : ");
printf(" Item name number price quantity ");
for(i=1;i<=3;i++)
fscanf(stdin,"%s%d%f%d",item,&num,&price,&qty);
fclose(fp);
fprintf(stdout,"\n");
fp=fopen(filename,"r");
printf(" Item name number price quantity value");
for(i=1;i<=3;i++)
{
fscanf(fp,"%s%d%f%d",item,&num,&price,&qty);
value=price*qty;
fprintf(stdout,"%s %d %f %d %f\n",item,num,price,qty,value);
}
fclose(fp);
}

12.5 Error Handling


When the program encounter an error, the C library functions set a variable called errno (error
number). The variable errno is an integer declared in the file errno.h. The C library functions deposit
226 Chapter 12. Files

different values in the variable errno for different kinds of errors. When a program encounters an
error it can inspect the value available in the variable errno and based on this decide on a suitable
course of action. The program will have to inclue the file errno.h to use these symbolic constants.
Some values deposited in errno for various error conditions are shown below :

errno value Meaning


EACCES Access denied
ENOENT No such file or directory
ENOMEM No room in RAM
ENOSPC Disk full
EMFILE Too many open files

When an error occurs, the program try to transmit error essages to the standard error device
rather than to the standard output. This is to ensure that te output message, which is meant for the
user’s inspection, does not get redirected to a file or drain down a pipeline. The stdio.h header
file, introduces three FILE pointer constants namely, stdin, stdout and stderr. These FILE pointer
constants point to the standard input, standard output and standard error devices, respectively.

getc(stdin) /* equivalent to getchar() */


fputs("Computer\n",stdout) /* same as puts("Computer")

The stderr FILE pointer is particularly useful with respect to error handling.

12.6 Example Programs


1. Write a C program that reads the text and counts all occurrences of a particular word.

#include <string.h>
void main()
{
char a[100],b[20],c[20];
int i,count=0,k=0,len;
clrscr();
printf ("\nEnter a string:-> ");
gets(a);
printf("\nEnter the word to be searched:-> ");
gets(b);
len=strlen(a);
for(i=0;i<=len;i++)
{
//Assuming Space , Tab and NULL as word separator
if(a[i]==32 || a[i]=='\t' || a[i]=='\0')
{
c[k]='\0';
if(strcmp(b,c)==0)count++;
k=0;
}
else
{
c[k]=a[i];
k++;
12.6 Example Programs 227

}
}
printf("Occurance of %s is = %d",b,count);
getch();
}
2. Write a function to compute the frequency of ’the’ in a file.
void main()
{
int i=0,j=0,k,n=0,m=0,l;
char a[100],b[10],c[10]="the";
clrscr();
printf("enter the sentence");
gets(a);
while(a[i]!='\0'){
if(a[i]==' '|| a[i]=='.')
m++;
i++;
}
i=0;
l=0;
while(l!=m+1){
while(a[i]!=' ' && a[i]!='.' && a[i]!='\0'){
b[j]=a[i];
j++;
i++;
}
b[j]='\0';
k=strcmp(b,c);
if(k==0)
{
n++;
j=0;
if(a[i]!='\0')
i++;
}else{
j=0;
i++;
}
l++;
}
if(n!=0)
printf("it is present %d times",n);
else
printf("it is not present");
getch();
}
3. Write a program which accepts two file names from the command line and prints
whether the contents of the two files are same or not. If not, then print the first line
228 Chapter 12. Files

number and then the contents of the lines from which they differ. Assume that the lines
in both the files have at most 80 characters.

#include<stdio.h>
main(int argc, char *argv[])
{
FILE *fp1, *fp2;
char ch1[80],ch2[80];
int i=1,j=1,l1=0,l2=0;
if (argc!=3)
{
printf ("\nWrong number of arguments.");
getch();
exit();
}
fp1=fopen(argv[1],"r");
if (fp1==NULL)
{
printf ("\nunable to open the file %s",argv[1]);
getch();
exit();
}
fp2=fopen(argv[2],"r");
if (fp2==NULL)
{
printf ("\nunable to open the file %s",argv[2]);
getch();
exit();
}
l1=0;
l2=0;
while (i!=0 && j!=0)
{
i=fgets(ch1,80,fp1);l1++;
j=fgets(ch2,80,fp2);l2++;
if (strcmp(ch1,ch2)!=0)
{
printf ("\nContents of both Files are not
Equal");
printf ("\nLine Number\tContents\tFile
name\n");
printf ("%d\t\t%s\t\tFrom %s",l1,ch1,argv[1]);
printf ("%d\t\t%s\t\tFrom %s",l2,ch2,argv[2]);
exit();
}
}
if (i==0 && j==0)
printf ("\nBoth Files are equal");
else
printf("\nBoth files are not equal");
12.7 Multiple Choice Questions 229

getch();
}

4. Write a C program to create a file contains a series of integer numbers and then reads
all numbers of this file and write all odd numbers to other file called odd and write all
even numbers to a file called even.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1,*f2,*f3;
int i,j;
printf("Enter the data\n");
f1=fopen("file1","w");
for(i=0;i<=10;i++)
{ scanf("%d",&j);
if(j== -1) break;
putw(j,f1);
}
fclose(f1);
f1=fopen("file1","r");
f2=fopen("od","w");
f3=fopen("ev","w");
while((j=getw(f1))!=EOF)
{ if(j%2==0)
putw(j,f3);
else
putw(j,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("od","r");
f3=fopen("ev","r");
printf("\nContents of odd file\n");
while((j=getw(f2))!=EOF)
printf("%4d",j);
printf("\nContents of even file\n");
while((j=getw(f3))!=EOF)
printf("%4d",j);
fclose(f2);
fclose(f3);
getch();
}

12.7 Multiple Choice Questions


1. A Stream is [ C ]
(A) a library function (B) a system call
230 Chapter 12. Files

(C) a source or destination of data that may (D) a file


be associated with a disk or other I/O
devices
2. I/O Stream can be [ C ]
(A) a text stream (B) a binary steam
(C) both a & b (D) an I/O operation
3. FILE defined in stdio.h is [ B ]
(A) a region of storage (B) a data type
(C) not a data type (D) a variable
4. A file pointer is [ D ]
(A) a stream pointer (B) a buffer pointer
(C) a pointer to FILE data type (D) all the above
5. The function used to read a character from a file that has been opened in read mode is [ B
]
(A) putc (B) getc (C) getchar (D) putchar
6. The function ftell ( ) [ C ]
(A) reads a character from a file
(B) reads an integer from a file
(C) gives the current position in the file
(D) sets the position to the beginning of the file.
7. The content of file will be lost if it is opened in [ A ]
(A) w mode (B) w+ mode
(C) a mode (D) a+ mode
A. Interview Questions

1. What values are automatically assigned to those array elements which are not explicitly
initialized?
Garbage values are automatically assigned to those array elements that are not explicitly
initialized. If garbage class is auto then array is assumed to contain garbage values. If storage
class were declared static or external then all the array elements would have a default initial
value as zero.
2.
3. what is alloca()
Answer : It allocates and frees memory after use/after getting out of scope
4. What is an unsigned integer constant? What is the significance of declaring a constant
as unsigned?
An integer constant is any number in the range -32768 to +32767, because an integer constant
always occupies two bytes in memory and in two bytes we cannot store a number bigger than
+32767 or smaller than -32768. Out of the two bytes to store an integer, the highest bit is
used to store the sign of the integer. This bit is 1 if the number is negative and 0 if number is
positive. Unsigned integer constant is an integer constant which has the permissible range
from 0 to 65536. Thus significance of declaring a constant as unsigned almost doubles the
size of the largest possible value. This happens because on declaring a constant as unsigned,
the sixteenth bit is free and is not used to store the sign of the constant.
5. Why ’&’ operator is not used with array names in a scanf statement?
In scanf() statement, the “address of” operator (&) either on the element of the array (e.g
marks[i]) or on the variables (e.g &rate) are used. In doing so, the address of this particular
array element is passed to the scanf() function, rather then its value; which is what scanf()
requires. BUT many times the address of zeroth element (also called as base address) can be
passed by just passing the name of the array.
6. How does an enum statement differ from a typedef statement?
Typedef statement allows user to define an identifier that would represent an exiting data
type. The user-defined data type identifier can be used further to declare variables. It has the
232 Chapter A. Interview Questions

following syntax

typedef datatype identifier;

where datatype refers to exiting data type and identifier is the new name given to this datatype.
For example

typedef int nos;

nos here symbolizes int type and now it can be used later to declare variables like

nos num1,num2,num3;

enum statement is used to declare variables that can have one of the values enclosed within
braces known as enumeration constant. After declaring this, we can declare variables to be
of this ‘new’ type. It has the following syntax

enum identifier {value1, value2, value3......,valuen);

where value1, value2 etc are values of the identifier. For example

enum day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}

We can define later

enum day working_day;


working_day=Monday;

The compiler automatically assigns integer digits beginning with 0 to all enumeration con-
stants.
7. Define macros. (or) What is a pre-processor? Which pre-processor is used to define a
macro?
A macro is a pre-processor directive which is a program that processes the source code before
it passes through the compiler. These are placed in the source program before the main. To
define a macro, # define statement is used. This statement, also known as macro definition
takes the following general form:

#define identifier string

The pre-processor replaces every occurrence of the identifier in the source code by the string.
The preprocessor directive definition is not terminated by a semicolon. For example

#define COUNT 100

will replace all occurrences of COUNT with 100 in the whole program before compilation.
8. Distinguish between malloc( ) and calloc( ).
While malloc allocates a single block of storage space, calloc allocates multiple block of
storage, each of the same size, and then sets all bytes to zero.
9. Differentiate between pointer (*) and address (&) operator using examples.
The indirection operator (*) gets the value stored in the memory location whose address is
stored in a pointer variable. The address of (&) operator returns the address of the memory
location in which the variable is stored. The output of the following example shows the
difference between * and &.
233

//difference between * and &.


#include<conio.h>
void main()
{
int k;
int *ptr;
clrscr();
k=10;
ptr=&k;
printf("\n Value of k is %d\n\n",k);
printf("%d is stored at addr %u\n",k,&k);
printf("%d is stored at addr %u\n",*ptr,ptr);
*ptr=25;
printf("\n Now k = %d\n",k);
getch();
}
Output: Value of k is 10
10 is stored at addr 65524
10 is stored at addr 65524
Now k=25
10. Write a program to find the highest of three numbers using pointer to function

#include<conio.h>
void main()
{
int x,y,z;
clrscr();
printf("\n Enter three numbers : ");
scanf("%d %d %d",&x,&y,&z);
printf("\n\n The highest of the three numbers is : ");
highest(&x,&y,&z);
getch();
}
highest(a,b,c)
int *a,*b,*c;
{
if(*a > *b && *a > *c)
printf("%d",*a);
else if(*b > *a && *b > *c)
printf("%d",*b);
else
printf("%d",*c);
}
11. Can a structure be used within a structure? Give appropriate examples to support
your answer
Yes, a structure can be used within a structure called nesting of structures. For example,
inside a structure rectangle, a point (x,y) needs to be represented. So we can first declare a
structure point as:
234 Chapter A. Interview Questions

struct point
{ int x;
int y;
};

We can now use this definition in defining points in any of geometrical figure. For example

struct rectangle
{ struct point pt;
int diagonal;
}

12. Distinguish between the functions islower() and tolower().


islower(c) is a character testing function defined in ctype.h header file. This function
determines if the passed argument, in this case c, is lowercase. It returns a nonzero value
if true otherwise 0. tolower (c) is a conversion function defined in ctype.h header file that
convert argument c to lowercase.
13. Are the following statements valid? Justify your answer
(i) k = (char*)& m
(ii) m= (float*)& p
Type of m is not known. If it is of type other than char and k is a pointer to char type then
statement is valid otherwise it is invalid. Similarly, second statement is valid if m is a pointer
to float and p is of type other than float and pointing to more thant four consecutive bytes.
14. Why is C standard library needed?
C would have been a tough programming language in absence of the standard library. The
standard library in C includes header files and standard functions in these files. Header
files are collection of macros, types, functions and constants. Any program that needs those
functions has to include these header files. For example, the standard library functions,
included in “stdlib.h” header file, are used for number conversions, storage allocation and
other functions on the same line. These functions are called utility functions. C does not
have any built-in input/output statements as part of its syntax. All I/O operations are carried
out through function calls such as printf and scanf. There are many functions that have
become standard for I/O operations in C, collectively known as standard I/O library “stdio.h”.
Because of this standard inputoutput header file, standard I/O functions can be used on many
machines without any change.
15. Compare the use of switch statement with the use of nested if-else statement.
If-else statement: When there are multiple conditional statements that may all evaluate to
true, but we want only one if statement’s body to execute. We can use an "else if" statement
following an if statement and its body; that way, if the first statement is true, the "else if"
will be ignored, but if the if statement is false, it will then check the condition for the else if
statement. If the if statement was true the else statement will not be checked. It is possible to
use numerous else if statements to ensure that only one block is executed.

#include <stdio.h>
void main()
{
int age;
printf( "Please enter your age" );
scanf( "%d", &age );
if ( age < 100 ) {
printf ("You are pretty young!\n" ); }
235

else if ( age == 100 ) {


printf( "You are old\n" );
}
else {
printf( "You are really old\n" );
}
}

Switch case statements are a substitute for long if statements that compare a variable to
several "integral" values ("integral" values are simply values that can be expressed as an
integer, such as the value of a char).The value of the variable given into switch is compared to
the value following each of the cases, and when one value matches the value of the variable,
the computer continues executing the program from that point. The condition of a switch
statement is a value. The case says that if it has the value of whatever is after that case then
do whatever follows the colon. The break is used to break out of the case statements. Break
is a keyword that breaks out of the code block, usually surrounded by braces, which it is in.
In this case, break prevents the program from falling through and executing the code in all
the other case statements.

#include<stdio.h>
#include<conio.h>
void main()
{
int flag;
printf( "Enter any value\n" );
scanf( "%d", &flag );
switch ( flag ) {
case 1:
printf( "It is hot weather!\n" );
break;
case 2:
printf( "It is a stormy weather!\n" );
break;
case 3:
printf( "It is a sticky weather!\n" );
break;
default:
printf( "It is a pleasant weather!\n" );
break;
}
getch();
}

16. Explain the need for user-defined functions.

(a) A programmer may have a block of code that he has repeated forty times throughout
the program. A function to execute that code would save a great deal of space, and it
would also make the program more readable.
(b) It is easy to locate and isolate a faulty function. Having only one copy of the code
makes it easier to make changes.
236 Chapter A. Interview Questions

(c) Another reason for functions is to break down a complex program into logical parts.
For example, take a menu program that runs complex code when a menu choice is
selected. The program would probably best be served by making functions for each of
the actual menu choices, and then breaking down the complex tasks into smaller, more
manageable tasks, which could be in their own functions. In this way, a program can be
designed that makes sense when read. And has a structure that is easier to understand
quickly. The worst programs usually only have the required function, main, and fill it
with pages of jumbled code.
(d) A function may be used by many other programs. A programmer can use already
compiled function instead of starting over from scratch.
17. Using recursion, write a C program to reverse a given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r;
clrscr();
printf("enter an integer");
scanf("%d",&n);
rev(n);
getch();
}
rev (int n)
{
if (n>0)
{
printf ("%d",n%10);
rev(n/10);
}
}
18. Write a C program using pointers to determine the length of a character string.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[10];
int marks;
};
void main()
{
int i,j;
static struct student stu1={"Simmi",78};
static struct student stu2={"Ruci",90};
static struct student stu3={"Seema",95};
clrscr();
stu1=stu3;
if((stu1.marks==stu3.marks))
{
237

printf(" Student 1 is same as student 3\n");


printf("%s",stu1.name);
printf("\t");
printf("%d",stu3.marks);
printf("\n");
}
else
printf("\nStudents are different\n");
getch();
}

19. How is multidimensional arrays defined in terms of an array of pointer? What does
each pointer represent?
An element in a multidimensional array like two-dimensional array can be represented by
pointer expression as follows:

*(*(a+i)+j)

It represent the element a[i][j]. The base address of the array a is &a[0][0] and starting at
this address, the compiler allocates contiguous space for all the element row-wise. The first
element of second row is immediately after last element of first row and so on.
20. Write a C program to calculate the standard deviation of an array of values. The array
elements are read from the terminal. Use functions to calculate standard deviations
and mean Standard Deviation

#include<math.h>
#include<conio.h>
#define MAXSIZE 100
void main()
{
int i,n;
float
value[MAXSIZE],deviation,sum,sumsqr,mean,variance,stddeviation
;
sum=sumsqr=n=0;
clrscr();
printf("\n Input values : input -1 to end \n");
for(i=1;i<MAXSIZE;i++)
{
scanf("%f",&value[i]);
if(value[i]==-1)
break;
sum+=value[i];
n+=1;
}
mean=sum/(float)n;
for(i=1;i<=n;i++)
{
deviation=value[i]-mean;
sumsqr+=deviation*deviation;
}
238 Chapter A. Interview Questions

variance=sumsqr/(float)n;
stddeviation=sqrt(variance);
printf("\n Number of items : %d\n",n);
printf(" Mean : %f\n",mean);
printf("Standard Deviation : %f\n",stddeviation);
getch();
}
21. Write a nested macro that gives the minimum of three values.

#include<stdio.h>
#include<conio.h>
#define min(a,b) ((a>b)?b:a)
#define minthree(a,b,c) (min(min(a,b),c))
void main()
{
int x,y,z,w;
clrscr();
printf("enter three numbers :\n");
scanf("%d%d%d",&x,&y,&w);
z=minthree(x,y,w);
printf("Minimum of three value is %d",z);
getch();
}
22. Write a function to display the binary number corresponding to the integer passed to
it as an argument.

#include<stdio.h>
#include<conio.h>
void dis_bin(int n)
{
num=n;
for(i=0;num!=0;i++)
{
q=num/2;
r[i]=num%2;
num=q;
}
clrscr();
printf("\n\n The integer the number is : %d\n",n);
printf("\n The binary conversion is : ");
for(i-=1;i>=0;i--)
printf("%d",r[i]);
getch();
}
23. Write a function, my_atoi, similar to the library function atoi that returns the numeric
value corresponding to the string passed to it as an argument.

#include <stdio.h>
main()
239

{
long int n=0;
char str[25];
clrscr();
printf ("\nEnter the string:-> ");
gets(str);
my_atoi(str,&n);
printf ("\nInteger Equvalent of string %s=%ld",str,n);
getch();
}
my_atoi(char str[25],long int *num)
{
int i=1;
long int s=1,l=0,j;
float po10=1;
//Trimming the string for integers
for (i=0;str[i]!='\0';i++)
{
if (str[i]==' ')
{
for (j=i;str[j]!='\0';j++)
str[j]=str[j+1];
i--;
}
else if (str[i]>=48 && str[j]<=57)
continue;
else
{
str[i]='\0';
break;
}
}
l=strlen(str);
for (i=l-1;i>=0;i--)
{
switch (str[i])
{
case 48: s*=0;break;
case 49: s*=1;break;
case 50: s*=2;break;
case 51: s*=3;break;
case 52: s*=4;break;
case 53: s*=5;break;
case 54: s*=6;break;
case 55: s*=7;break;
case 56: s*=8;break;
case 57: s*=9;break;
}
*num+=s;
240 Chapter A. Interview Questions

po10*=10;
s=po10;
}
}

24. Write a recursive function to print the reverse of a string passed to it as an argument.

void main()
{
char str[100];
clrscr();
printf("enter a string\n");
gets(str);
printf("reverse of the entered string is\n");
rev(str);
getch();
}
rev (char *string)
{
if (*string)
{
rev(string+1);
putchar(*string);
}
}

25. Differentiate between call by value and call by reference


Call by value means sending the values of the arguments- The value of each of the actual
arguments in the calling function is copied into corresponding formal arguments of the called
function. The changes made to the formal arguments have no effect on the values of actual
arguments in the calling function. This technique of passing arguments is called call by value
illustrated by swapv(int x, int y) function in the following example.
Call by reference means sending the addresses of the arguments- the addresses of actual
arguments in the calling function are copied into formal arguments of the called function.
Using these addresses we are actually working on actual argument so changes will be
reflected in the calling function. This technique of passing arguments is called call by
reference, illustrated by swapr(int *x,int *y) in following example.

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
int i=10,j=20;
clrscr();
printf("The values before swap is i: %d, j:%d\n",i,j);
swapv(i,j);
printf("The values after swap is i: %d, j:%d\n",i,j);
printf("\n");
swapr(&i,&j);
printf("The values after swap is i: %d, j:%d\n",i,j);
printf("\n");
241

getch();
}
swapv(int x,int y)
{ int temp;
temp=x;
x=y;
y=temp;
}
swapr(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
The value of i and j is 10 and 20 only after calling function swapv, that is call by value.
However the result of calling swapr(), call by reference is i=20 and j=10
26. Write a function that accepts two strings str1 and str2 as arguments and finds which
of the two is alphabetically greater (without using the library functions). The function
should return 1 if str1 is greater than str2, 0 if str1 is equal to str2, and -1 is str1 is
smaller than str2.
void main()
{
char a[10],b[10];
int k;
clrscr();
printf("enter 1st string");
gets(a);
printf("enter 2nd string");
gets(b);
k=comp(a,b);
if(k==1)
printf("%s is greater than %s",a,b);
if(k==-1)printf("%s is less than %s",a,b);
if(k==0)
printf("%s is equal to %s",a,b);
getch();
}
int comp(char *a,char *b)
{
int i=0,j=0,k;
while(a[i]!='\0'&& b[j]!='\0){
if (a[i]<b[j])
return (-1);
else if(a[i]>b[j])
return (1);
else
i++;
j++;
242 Chapter A. Interview Questions

}
if(i==j)
return (0);
if (i<j)
return (-1);
if(i>j)
return (1);
}
27. What is looping?
Loop is a control structure used to perform repetitive operation. Some programs involve
repeating a set of instruction either a specified number of times or until a particular condition
is met. This is done using a loop control structure. A program loop consists of two parts:
Body of the loop and control statement. The control statement tests certain conditions and
then decides repeated execution or termination of statements. Most real programs contain
some construct that loops within the program, performing repetitive actions on a stream of
data or a region of memory.
28. What do you understand by scope, lifetime and visibility of the variables?
Scope, Visibility and Lifetime of variables: The scope of a variable determines the region
of the program in which it is known. An identifier’s "visibility" determines the portions of the
program in which it can be referenced—its "scope." An identifier is visible only in portions
of a program encompassed by its "scope," which may be limited to the file, function or block
in which it appears.
File scope: The variables and functions with file scope appear outside any block or list
of parameters and is accessible from any place in the translation unit after its declaration.
Identifier names with file scope are often called "global" or "external." The scope of a global
identifier begins at the point of its definition or declaration and terminates at the end of the
translation unit. A function has file scope.
Function scope: A label is the only kind of identifier that has function scope. A label is
declared implicitly by its use in a statement. Label names must be unique within a function
however a label having the same name in two different functions is allowed.
Block scope: The variables with block scope appear inside a block or within the list of
formal parameter declarations in a function definition. It is visible only from the point of its
declaration or definition to the end of the block containing its declaration or definition.
29. Write a recursive code to compute the sum of squares as shown in the series
m2 + (m+1)2 +. . . . + n2 for m, n integers 1 ≤ m ≤ n
A recursive code to compute sum of squares from m to n. Make int n a global variable so
that it is not passed in every recursive cell.

int n;
void main()
{
int m,sum;
clrscr();
printf (" Value of m : ");
scanf ("%d",&m);
printf (" Value of n : ");
scanf ("%d",&n);
sum=sum_recursive(m);
printf ("\n\n\n\n%d",sum);
243

}
int sum_recursive(int m)
{
int sum;
if (m == n)
return (n*n);
else
sum = (m*m) + sum_recursive(m+1);
printf ("\t%d",sum);
return sum;
}
30. What is the output of the following source code?
main()
{
float i=1.5;
switch(i)
{
case 1: printf("1");
case 2: printf("2");
default : printf("0");
}
}
Answer: Compiler Error: switch expression not integral
Explanation: Switch statements can be applied only to integral types.
31. main()
{
printf("%p",main);
}
Answer: Some address will be printed.
Explanation: Function names are just addresses (just like array names are addresses). main()
is also a function. So the address of function main will be printed. %p in printf specifies that
the argument is an address. They are printed as hexadecimal numbers.
32. Output of the below source code
main()
{
show();
}
void show()
{
printf("I'm the greatest");
}
Answer: Compier error: Type mismatch in redeclaration of show.
Explanation: When the compiler sees the function show it doesn’t know anything about it.
So the default return type (ie, int) is assumed. But when compiler sees the actual definition
of show mismatch occurs since it is declared as void. Hence the error.
The solutions are as follows:
i. declare void show() in main() .
244 Chapter A. Interview Questions

ii. define show() before main().


iii. declare extern void show() before the use of show().
33. Output of the below source code

main()
{
main();
}
Answer: Runtime error : Stack overflow.
Explanation: main function calls itself again and again. Each time the function is called its
return address is stored in the call stack. Since there is no condition to terminate the function
call, the call stack overflows at runtime. So it terminates the program and results in an error.
34. What is the Output of following source code:

#include<studio.h>
main()
{
func(1);
}
func(int i){
static char *str[] ={ "One","Two","Three","Four"};
printf("%s\n",str[i++]);
return;
}
Answer:- it will give warning because str is pointer to the char but it is initialized with more
values if it is not considered then the answer is Two
35. what does exit() do?
Answer : come out of executing programme.
36. In ’C’ how are the arguments passed?
Answer : by value.
37. What is the prototype of sine function.
Answer : extern double sin(double)
38. Scope of a global variable which is declared as static?
Answer : File
39. Output of the following code is:

n=7623
while(n>0)
{
temp=n/10;
result=temp*10+ result;
n=n/10
}
Answer : 3267
40. which of the following is the correct declaration for the function main() ?
Answer : main( int , char *[])
41. What is int *p(char (*s)[])
Answer: p is a function which is returning a pointer to integer which takes arguments as
pointer to array of characters.
245

42. What is the output?


For the following C program
#define AREA(x)(3.14*x*x)
main()
{
float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}
Answer:
Area of the circle is 122.656250
Area of the circle is 19.625000
43. #define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
Answer: "one is defined"
44. #define MAX(x,y) (x)>(y)?(x):(y)
{
int i=10;
j=5;
k=0;
k=MAX(i++,++j);
printf(%d %d %d %d,i,j,k);
}
Answer: 10 5 0
45. What is the output of given program?
void main()
{
while(1){
if(printf("%d",printf("%d")))
break;
else
continue;
}
}
Answer: Garbage values
46. What is the output of given program?
#include<conio.h>
main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
246 Chapter A. Interview Questions

printf("%d %d ",z,x);
}

Answer: Garbage-value 0
47. What is the final value of i and how many times loop is Executed ? (the input is given
as 1234 567)

#include<stdio.h>
main()
{
int i,j,k,l,lc=0;
printf("Enter the number string:<1234 567 >\n");
scanf("%2d%d%1d",&i,&j,&k);
for(;k;k--,i++)
for(l=0;l> printf("%d %d\n",i,l);)
printf("LOOPS= %d\n", lc-1);
}

Answer : ( i = 17, and loop is executed for 169 times)


48. What is the output of the below code:

void main()
{ int d=5;
printf("%f",d);
}

Answer: Undefined
49. What is the output of the following code:

main()
{
float value=10.00;
printf("%g %0.2g %0.4g %f",value,value,value,value)
}

Answer: 10,10,10,10.000000
50. Find the output

main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}

Answer: hai
51. Find the output

main()
{
int i=400,j=300;
printf("%d..%d");
}
247

Answer: 400..300
52. Find the output:
main()
{char not;
not=!2;
printf("%d",not);
}
Answer: 0
Explanation: is a logical operator. In C the value 0 is considered to be the boolean value
FALSE, and any non-zero value is considered to be the boolean value TRUE. Here 2 is a
nonzero value so TRUE. TRUE is FALSE (0) so it prints 0.
53. Find the output
main()
{
char p[ ]="%d\n";
p[1] = 'c';
printf(p,65);
}
Answer: A
Explanation: Due to the assignment p[1] = ’c’ the string becomes, "%c\n". Since this string
becomes the format string for printf and ASCII value of 65 is ’A’, the same gets printed.
54. Find the value :
main()
{
int i=5,j=10;
i=i&=j&&10;
printf("%d %d",i,j);
}
Answer: 1 10
Explanation: The expression can be written as i=(i&=(j&&10)); The inner expression
(j&&10) evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result.
55. What is the output of the given program
main()
{
int i=4,j=7;
j = j || i++ && printf("YOU CAN");
printf("%d %d", i, j);
}
Answer: 4 1
Explanation: The boolean expression needs to be evaluated only till the truth value of the
expression is not known. j is not equal to zero itself means that the expression’s truth value
is 1. Because it is followed by || and true || (anything) => true where (anything) will not
be evaluated. So the remaining expression is not evaluated and so the value of i remains the
same.
Similarly when && operator is involved in an expression, when any of the operands become
248 Chapter A. Interview Questions

false, the whole expression’s truth value becomes false and hence the remaining expression
will not be evaluated.

false && (anything) => false


where (anything) will not be evaluated.
56. What is the output of the following code snippet

main()
{
printf(5+"Fascimile");
}
Answer : mile
57. Find the output

#define square(x) x*x


main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer: 64
Explanation: the macro call square(4) will substituted by 4*4 so the expression becomes i
= 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e.
16*4 = 64
58. Printf can be implemented by using ...... list.
Answer: Variable length argument
59. In C parameters are passed by
Answer : value only.
60. What is the output of the below code?

void main()
{c
har *s[]={ "dharma","hewlett-packard","siemens","ibm"};
char **p;
p=s;
printf("%s",++*p);
printf("%s",*p++);
printf("%s",++*p);
}
Answer:
"harma" (p->add(dharma) && (*p)->harma)
"harma" (after printing, p->add(hewlett-packard) &&(*p)->harma)
"ewlett-packard"
61. What is int *p(char (*s)[])
Answer: p is a function which is returning a pointer to integer which takes arguments as
pointer to array of characters.
B. Coding Interview

B.1 Coding Interview Questions


All the below questions are asked by various companies in coding test or face to face technical
interview. Here we given only logic not the complete source codes.
1. Write code to reverse a C-Style String. (C-String means that “abcd” is represented as
five characters, including the null character.)
void reverse(char *str) {
char * end = str;
char tmp;
if (str) {
while (*end) {
++end;
}
--end;
while (str < end) {
tmp = *str;
*str++ = *end;
*end-- = tmp;
}
}
}
2. W.A.P. to determine how much money is in a piggy bank that contains several 50 paise
coins, 25 paise coins, 20 paise coins, 10 paise coins and 5 paise coins. Use the following
values to test your program : Five 50 paise coins, Three 25 paise coins, Two 20 paise
coins, One 10 paise coin and Fifteen 5 paise coins.
int main(void)
{
float coin1=0.5,coin2=0.25,coin3=0.2,coin4=0.1,coin5=0.05,total=0.0;
250 Chapter B. Coding Interview

int ncoins;
clrscr();
printf("How many 50 paise coins : ");
scanf("%d",&ncoins);
total += (ncoins * coin1);
printf("** %.2f **",total);
printf("\nHow many 25 paise coins : ");
scanf("%d",&ncoins);
total += (ncoins * coin2);
printf("** %.2f **",total);
printf("\nHow many 20 paise coins : ");
scanf("%d",&ncoins);
total += (ncoins * coin3);
printf("** %.2f **",total);
printf("\nHow many 10 paise coins : ");
scanf("%d",&ncoins);
total += (ncoins * coin4);
printf("** %.2f **",total);
printf("\nHow many 5 paise coins : ");
scanf("%d",&ncoins);
total += (ncoins * coin5);
printf("\n\nThe total amount is Rs.%.2f",total);
getch();
return(0);
}

3. Write the code to display the series 1 ,2,6,15,31,56....N (PRATIAN-2015)

#include<stdio.h>
#include<math.h>
int main()
{
int n;
int i=1,j=1;
printf("enter no of terms in series");
scanf("%d",&n);
printf("%d\t",i);
while(j<=n)
{
i+=(pow(j,2));
j++;
printf("%d\t",i);
}
return 0;
}

4. Write a Program to Counting the numbers of Words, Lines and Characters in an


array.

#include<stdio.h>
main()
B.1 Coding Interview Questions 251

{
char a[100];
int i,w=1,l=1,c=0;
clrscr();
printf("Enter the text:");
for(i=0;(a[i]=getchar())!='$';i++);
a[i]='\0';
for(i=0;a[i];i++)
{
if((a[i]==' '&&a[i+1]!=' ')||(a[i]=='\n'&&a[i+1]!='\n')||
(a[i]=='\t'&&a[i+1]!='\t'))
w++;
if(a[i]=='\n'&&a[i+1]!='\n')
l++;
if(a[i]!=' '&&a[i]!='\n'&&a[i]!='\t')
c++;
}
printf("The number of words in the text is %d\n",w);
printf("The number of lines in the text is %d\n",l);
printf("The number of characters in the text is %d",c);
getch();
}

5. Write a Program to print pascal triangle using binomial formula

#include<stdio.h>
double fact(int n)
{
if(n<=1)
return 1;
return n*fact(n-1);
}
int main()
{
int i=0, num =0, n=0,k=0;
printf("enter the no of rows\n");
scanf("%d",&num);
n = num-1;
for(i=0;i<num;i++)
{
for(k=n;k>i;k--)
printf(" ");
for(k=0;k<=i;k++)
{
printf(" %.0f", fact(i)/(fact(i-k)*fact(k)));
}
printf("\n");
}
return 0;
}
252 Chapter B. Coding Interview

6. Write a Program to find the number of ways can one climb a staircase with ’n’ steps,
taking one or two steps at a time
Hi this is one of this problems that looks extremaly intimidating but somehow ends up being
easy. If you check the number of ways for first few stairs length you can see that ways
one can climb a staircase in respect to staircase length grows exacly like fibonacci number
sequence. Lets say one step move = 1, and two steps move = 2. Possible ways for:
1 step staircase => 1 = {1} -> 1 way
2 step => 2 = {1+1}, {2} -> 2 ways
3 step => 3 = {1+1+1}, {1+2}, {2+1} -> 3 ways
4 step => 4 = {1+1+1+1}, {1+1+2}, {2+1+1}, {1+2+1}, {2+2} -> 5 ways
5 step => 5 = {1+1+1+1+1}, {2+1+1+1}, {1+2+1+1}, {1+1+2+1}, {1+1+1+2}, {2+2+1},
{1+2+2}, {2+1+2} = 8 ways.
ways(5) = ways(4) + ways(3) = 5 + 3 = 8.
I use sequential code for optimal space complexity and additional array to store partial results
to reduce time complexity to linear.
int countWays(int n)
{
if(n < 1)return -1;
if(n == 1)return 1;
int res[] = new int[n+1];
res[1] = 1;
res[2] = 2;
for(int i = 3; i < n+1; i++)
{
res[i] = res[i-1] + res[i-2];
}
return res[n];
}
void main()
{int i
for(i = 1; i < 10; i++)
printf("%d\n"countWays(i));
}
7. 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.
int heaviest(int a, int b, int c, int d){
if(a + b > c + d){
// heavier is either a or b
if (a - c > 0){
return a;
}
return b;
}
else {
// heavier is either c or d
if (c - a > 0){
return c;
B.1 Coding Interview Questions 253

}
return d;
}
}
8. Write a C program to check biggest among two numbers without using any relational
operators
int a,b;
//read a,b
if(a/b)
printf("a is big");
else
printf("b is big");
9. Write a program to get a string and replace with the mentioned string Example given
string "dinesh" replace with "rame" and display it as "ramesh"
void main()
{
char *str1,*str2;
gets(str1);
gets(str2);
l1 = strlen(str1);
l2=strlen(str2);
strcat(str2,str1);
printf("%s",str2);
}
10. write a function called reverse to print the reverse of the digit entered by the user.
int reverse(int n)
{
int res = 0;
while(n > 0)
{
int digit = n % 10;
res = res * 10 + digit;
n /= 10;
}
return res;
}

void main(){
printf("%d"reverse(78421));//12487
}
11. Counting the number of digits before and after the decimal point without using string
( using double data type).
int temp1 = f;
int count1 = 0;
int count2 = 0;
254 Chapter B. Coding Interview

while (temp1 > 0)


{
temp1 = temp1 / 10;
count1++;

}
int temp2 = f;
while ((double)temp2 != f) {
f = f * 10;
temp2 = f;
count2++;
}
printf("Integer Count = %d, Decimal count = %d", count1, count2);
return 0;
}

12. write a program to convert char *mac_address to int array.


eg mac_address ="ab:cd:ef:12:34:56" to
result= [ab, cd, ef, 12,34,56] (samsung)

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

int main ()
{
int a[6]; int ab,i=0;
char mac[]="aa:bb:cc:12:23:34";
char *aa=NULL;
char delims[] = ":";
getch();
ab= (int)strtok(mac,delims);
while (ab!=NULL)
{
printf(" %d %s ",ab,(char *)ab);
a[i]=ab;
i++;
ab= (int) strtok(NULL,delims);
}
getch();
}

13. Push all the zero’s of a given array to the end of the array. In place only. Ex 1,2,0,4,0,0,8
becomes 1,2,4,8,0,0,0(Facebook)

#define size 10

int arr[size] = {0, 0, 1, 2, 0, 4, 0, 0, 8, 9};


int pos = 0, i;
for(i = 0; i < size; i++) {
if(arr[i] != 0) {
arr[pos] = arr[i];
B.1 Coding Interview Questions 255

pos++;
}
}
for(i = size-1; i >= pos; i--) {
arr[i] = 0;
}

14. Predict the out put of the following code(Microsoft)

#include<stdio.h>
int g = 0;
int Add(int i)
{
static int s=0;
s =s+i;
g=g+i;
return s;
}
int main()
{
int s=0;int g=0,j;
for(int i=1;i<=11;i++)
{ g=0;s=0;
j = add(i);
}
printf("%d,%d",j,g);

return 0;
}

15. Write Program to find longest common contiguous intersection from 2 lists provided
to the function.
Example: list1: abcrfghwetf
list2: abrfghwwetxyab
Longest common intersection here is: fghw
Need Effecient Algorithm to implement this in Java or C, not using arrays.(amazon)

char str1[] = "abcrfghwetf";


char str2[] = "abrfghwwetxyab";
int max, i, j, l1, l2, cnt, sovi, sovj;
max=0;
l1=strlen(str1);
l2=strlen(str2);
for(i=0; i<l1 ; i++)
{
cnt=0;
for(j=i; j<l2 ; j++)
{
if((str1[i]==str2[j]))
{
cnt++;
256 Chapter B. Coding Interview

i++;
j++
}
else
break;
}
if(cnt>max)
{
max=cnt;
sovi=i;
sovj=j;
}
}
printf("\n str: %s", str1+i-cnt);
16. Given a number in the form of string. Output the binary equivalent of that number.
Sample Input: "8.5"
Sample Output: 1000.1
Sample Input: "12.34.23"
Sample Output: "ERROR"(amazon)
int binaryD(char *bin,int n,int depth)
{
static int count;

if(n)
{
count++;
binaryD(bin,n/2,depth+1);
bin[depth]=(n&;1)?'1':'0';
}
return count;
}

int binaryF(char* bin,float f,int *depth)


{
int count=0,i;

if(f<=0.0f)
return 1;
if(f==1.0f)
{
bin[*depth]='1';
return 1;
}
while(f)
{
f*=2;
if(f==1.0f)
{
bin[++*depth]='1';
B.1 Coding Interview Questions 257

return 1;
}
i=f;
if(f>;1.0f)
{
bin[++*depth]='1';
f=f-i;
}
else
bin[++*depth]='0';
if(++count>;32)
return 0;
}
}

void toBinary(char *s)


{
int num=0,i,depth=0,po=10,count;
char bin[50];
float f=0.0f;

for(i=0;s[i] && s[i]!='.';i++)


{
if(s[i]>='0' && s[i]<='9')
num=num*10 + s[i]-'0';
else
return;
}

if(s[i]=='.')
{
for(++i,po=10;s[i];i++,po*=10)
if(s[i]>='0' && s[i]<='9')
f=f+ (s[i]-'0')/(float)po;
else
return;
}

i=binaryD(bin,num,depth);

for(count=i-1;count>=0;count--)
printf("%c",bin[count]);

count=i;
if(f!=0.0f)
{
bin[i]='.';
binaryF(bin,f,&i);
258 Chapter B. Coding Interview

for(;count<=i;count++)
printf("%c",bin[count]);
}
}
17. write atoi() function(bloomberg-lp)

int atoi(char *s)


{
int number = 0,i;
int len = strlen(s);
for(i=0;i<len;i++)
number = (number*10) + (int) (s[i] - '0');
return number;
}
18. reverse the words in a sentence: "hello world" -> "world hello"

while (*str != '\0') {


start = str;

while (*str != ' ' && *str != '\0')


{
str++;
}
end = str-1;

while (start < end)


{
char c; // to swap characters
c = *start;
*start = *end;
*end = c;
start++;
end--;
}
if (*str != '\0')
str++;
}
19. Write a C program which counts 1, 2, 3... and so on, every second. On pressing Ctrl+C,
the timer should pause and then pressing Ctrl+Z should resume the timer

#include<stdio.h>
#include<time.h>//for another implementation..!
#include<signal.h>

#define wait_sec 1

void run_loop();
void myHandler_1(int );
void myHandler_1(int );
B.1 Coding Interview Questions 259

int main()
{
run_loop();
}
void run_loop()
{
static int print_cal = 1; //initialized to 1; as question is prompting..
while(1)
{
signal(SIGINT, myHandler_1);
sleep(wait_sec);
printf("%d", print_val);
++print_val;
}
}
void myHandler_1(int sig)
{
signal(sig, SIG_IGN);
pause();
signal(SIGTSTP, myHandler_2);
}
void myHandler_2(int sig)
{
signal(sig, SIG_IGN);
run_loop();
}
20. Starting point is m[0][0], need to find a path go to m[9][9]. 0 means OK, 1 means
cannot go there, boundary is 0 and 9, cannot go beyond boundary. Each step can be
made horizontally or vertically for one more grid (diagonal jump is not allowed).
Your program should print a series of grid coordinates that start from m[0][0] and go
to m[9][9]
Hint: No need to find the shortest path, only need to find one path that gets you to
desitination
int isSafe(int (*maze)[N],int x,int y)
{
if(x>=0 && x<N && y>=0 && y<N && !maze[x][y])
return 1;
return 0;
}

void Maze(int (*maze)[N],int x,int y,int (*sol)[N])


{
static int i,j;
if(x==N-1 && y==N-1)
{
printf("\n\nSolution\n\n");
sol[x][y]=1;
for(i=0;i<N;i++)
{
260 Chapter B. Coding Interview

for(j=0;j<N;j++)
printf("%d ",sol[i][j]);
printf("\n");
}
}
else
{
if(isSafe(maze,x,y))
{
sol[x][y]=1;

Maze(maze,x+1,y,sol);
Maze(maze,x,y+1,sol);

sol[x][y]=0;
}
}
}

21. How will you find out size of a variable without using sizeof ();

int a;
int *pa = &a;
int *ps = pa+1;
int sz = (int)ps - (int)pa; // the size of the variable @a

22. Implement user defined malloc().(microsoft)

typedef
struct
{
int is_available;
int size;
} MCB, *MCB_P;

char *mem_start_p;
int max_mem;
int allocated_mem; /* this is the memory in use. */
int mcb_count;
char *heap_end;
enum {NEW_MCB=0,NO_MCB,REUSE_MCB};
enum {FREE,IN_USE};
void InitMem(char *ptr, int size_in_bytes)
{
/* store the ptr and size_in_bytes in global variable */
max_mem = size_in_bytes;
mem_start_p = ptr;
mcb_count = 0;
allocated_mem = 0;
heap_end = mem_start_p + size_in_bytes;
memset(mem_start_p,0x00,max_mem);
B.1 Coding Interview Questions 261

/* This function is complete :-) */


}

void * myalloc(int elem_size)


{
/* check whether any chunk (allocated before) is free first */
MCB_P p_mcb;
int flag = NO_MCB;
int sz;

p_mcb = (MCB_P)mem_start_p;
sz = sizeof(MCB);
if( (elem_size + sz) > (max_mem - (allocated_mem + mcb_count * sz ) ) )
{
return NULL;
}
while( heap_end > ( (char *)p_mcb + elem_size + sz) )
{
if ( p_mcb->is_available == 0)
{
if( p_mcb->size == 0)
{
flag = NEW_MCB;
break;
}
if( p_mcb->size >= (elem_size + sz) )
{
flag = REUSE_MCB;
break;
}
}
p_mcb = (MCB_P) ( (char *)p_mcb + p_mcb->size);
}
if( flag != NO_MCB)
{
p_mcb->is_available = 1;
if( flag == NEW_MCB)
{
p_mcb->size = elem_size + sizeof(MCB);
}
else if( flag == REUSE_MCB)
{
elem_size = p_mcb->size - sizeof(MCB);
}
mcb_count++;
allocated_mem += elem_size;
return ( (char *) p_mcb + sz);
}
return NULL;
262 Chapter B. Coding Interview

/* if size of the available chunk is equal to greater than required size, use that chu
}
void myfree(void *p)
{
/* Mark in MCB that this chunk is free */
MCB_P ptr = (MCB_P)p;
ptr--;
if(ptr->is_available != FREE)
{
mcb_count--;
ptr->is_available = FREE;
allocated_mem -= (ptr->size - sizeof(MCB));
}
}
23. suppose a matrix A. find a element x in this matrix,x is the smallest in his line but the
biggest in his column. Give codes in C
#include <stdio.h>
const int rowN = 3;
const int colN = 3;
int findElement(int matrix[rowN][colN]){

/* if matrix is null, return null*/


if(matrix == NULL)
return NULL;

int result = NULL;

/* matrix size */
int numOfRows = rowN;
int numOfCols = colN;

/* create an auxiliary list boolean array */


int smallestColPerRow[numOfRows];

/*find the smallest element in each row*/


int rowIter, colIter;
for(rowIter=0; rowIter < numOfRows; rowIter++){

int smallestCol = 0;
for(colIter=0; colIter < numOfCols; colIter++){
if(matrix[rowIter][colIter] < matrix[rowIter][smallestCol])
smallestCol = colIter;
}
smallestColPerRow[rowIter]= smallestCol;
}
/* search for largetst element in each col, check if it is the smallest element in tha

for(colIter=0; colIter< numOfCols; colIter++){


int largestRow = -100000;
B.1 Coding Interview Questions 263

for(rowIter=0; rowIter< numOfRows; rowIter++){


if(matrix[rowIter][colIter] > matrix[largestRow][colIter])
largestRow = rowIter;
}
if(smallestColPerRow[largestRow]== colIter){
result =matrix[largestRow][colIter];
break;
}
}
return result;
}

int main(){
int matrix [rowN][colN] = {
{1,1,3},
{0,1,-1},
{1,-1,2}};
int result = findElement(matrix);
if(result == NULL)
printf("\nnot found");
else
printf("\nresult is:%d\n", result);
return 0;
}

24. WAP which print its source code as its output!!!:)

int main()
{
char d;
int ret=0;
FILE *fp;
fp = fopen(__FILE__,"r");
ret = fscanf(fp,"%c",&d);
while(ret != EOF)
{
printf("%c",d);
ret = fscanf(fp,"%c",&d);
}
return 0;
}

25. Write a code in C for the following:


Starting from 1, assign an alphabet to each integer, for e.g. if input is 1 then A should
be the output, 2 = B ....... 26 = Z. Similarly, 27 = AA, 28 = AB..........52 = AZ. 702
= ZZ, 703 = AAA and so on. The function takes only one integer argument . for
e.g ConvertToAphabet(int x). One additional consideration here is, the user is free to
provide any length of integer (bigint long int etc), no restriction there.

#include<stdio.h>
#include<math.h>
264 Chapter B. Coding Interview

int main()
{
long long int x = 704;
char *ptr = (char *)malloc(sizeof(char));
int i=0;
while(x > 0)
{
int r = x%26;
x = x/26;

if(r==0)
{
*(ptr+i)='Z';
i++;
x = x-1;
}
else
{
*(ptr+i)=(char)r+'A'-1;
i++;
}

}
*(ptr+i)='\0';
for(i=i-1;i>=0;i--)
printf("%c",*(ptr+i));
return 0;
}
26. white your own printf() function in c? (Abs india pvt. ltd.)
#include<stdio.h>
#include<stdarg.h>

void myprintf(char *,...);


char* convert(unsigned int, int);

int main()
{
int i=65;
char str[]="This is my string";
myprintf("\nMessage = %s%d%x",str,i,i);
}

void myprintf(char* fmt,...)


{
char *p;
int i;
unsigned u;
char *s;
va_list argp;
B.1 Coding Interview Questions 265

va_start(argp, fmt);
p=fmt;

for(p=fmt; *p!='\0';p++)
{
while(*p!='%')
{
putchar(*p);p++;
}
p++;
switch(*p)
{
case 'c' : i=va_arg(argp,int);putchar(i);break;
case 'd' : i=va_arg(argp,int);
if(i<0)
{
i=-i;putchar('-');
}
puts(convert(i,10));break;
case 'o': i=va_arg(argp,unsigned int); puts(convert(i,8));break;
case 's': s=va_arg(argp,char *); puts(s); break;
case 'u': u=va_arg(argp,unsigned int); puts(convert(u,10));break;
case 'x': u=va_arg(argp,unsigned int); puts(convert(u,16));break;
case '%': putchar('%');break;
}
}
va_end(argp);
}
char *convert(unsigned int num, int base)
{
static char buf[33];
char *ptr;
ptr=&buf[sizeof(buf)-1];
*ptr='\0';
do
{
*--ptr="0123456789abcdef"[num%base];
num/=base;
}while(num!=0);
return(ptr);
}
27. First find out the number 1’s in the binary digit of a given integer. Then find out an
integer which is greater than the given integer and contains same number of binary 1’s
#include <conio.h>
#include<stdio.h>
int findone(int temp);
int main( )
{
int n,l,lnext;
266 Chapter B. Coding Interview

printf("enter the number");


scanf("%d",&n);
l=findone(n);
printf("No of 1's in given number are %d",l);
lnext=findone(++n);
while(l!=lnext)
{
lnext=findone(++n);
}
printf("\nthe next number is %d",n);
getch();
return 0;
}

int findone(int temp)


{
int len=0,bin;
while(temp!=0)
{
bin=temp%2;
temp=temp/2;
if(bin==1)
{
len++;
}
}
return len;
}
28. Given two parameters (a target string and a source string), write code that returns the
number of times characters found in the source string occur in the target string.
For example, if target="Hello world" and source="llld" then return 4(citrix-system-
inc)
int Count(char *t, char *s)
{
int a [26]={};
int b=0;
for(int i=0;i<strlen(s);i++)
{
if(a[*(s+i)-'a']==0)
{
a[*(s+i)-'a']=1;
b++;
}
}
for(int i=0;i<strlen(t);i++)
{
if(a[*(t+i)-'a']>=1)
{
a[*(t+i)-'a']++;
B.1 Coding Interview Questions 267

}
}
int count=0;
for(int i=0;i<;26;i++)
{
count=count+a[i];
}
return count-b;
}

29. Reverse a string without using any temporary variable. Suppose {{char str[] = "Hello";
then str[] = "olleH";}}. I told him we can "shift H to o then o to H", similarly so on.
But could able to write the code.

void reverse(char *str)


{
if(*str)
{
reverse(str+1);
printf("%c", *str);
}
}int main()
{
char a[] = "hello";
reverse(a);
getchar();
return 0;
}

30. Write a program to check whether a substring is present in a main string.

int main()
{
char string[] = "my name is megharaj I an from india";
char *stringp = string;
char sub[] = "an";
int length = strlen(sub) -1;
char *temp;
while(*stringp != '\0') {
temp = sub;
length = 2;
while((stringp != '\0') && (*stringp == *temp) && length > 0) {
stringp++;
temp++;
length--;
if(length == 0) {
printf("substring found\n");
return 0;
}
}
stringp++;
268 Chapter B. Coding Interview

}
printf("substring not found\n");
return 0;
}
31. Write a c program to print Floyd’s triangle

#include<stdio.h>
int main(){
int i,j,r,k=1;
printf("Enter the range: ");
scanf("%d",&r);
printf("FLOYD'S TRIANGLE\n\n");
for(i=1;i<=r;i++){
for(j=1;j<=i;j++,k++)
printf(" %d",k);
printf("\n");
}
return 0;
}
32. Write a c program to check whether a number is strong or not

#include<stdio.h>
int main(){
int num,i,f,r,sum=0,temp;

printf("Enter a number: ");


scanf("%d",&num);

temp=num;
while(num){
i=1,f=1;
r=num%10;
while(i<=r){
f=f*i;
i++;
}
sum=sum+f;
num=num/10;
}
if(sum==temp)
printf("%d is a strong number",temp);
else
printf("%d is not a strong number",temp);

return 0;
}
33. HCF program with multiple numbers in c

#include<stdio.h>
B.1 Coding Interview Questions 269

int main(){
int x,y=-1;
printf("Insert numbers. To exit insert zero: ");

while(1){
scanf("%d",&x);
if(x<1)
break;
else if(y==-1)
y=x;
else if (x<y)
y=gcd(x,y);
else
y=gcd(y,x);
}

printf("GCD is %d",y);

return 0;
}

int gcd(int x,int y){


int i;
for(i=x;i>=1;i--){
if(x%i==0&&y%i==0){
break;
}
}
return i;
}
34. Design an algorithm and write code to remove the duplicate characters in a string
without using any additional buffer. NOTE: One or two additional variables are fine.
An extra copy of the array is not.
if (str == null) return;
int len = str.length;
if (len < 2) return;

int tail = 1;

for (int i = 1; i < len; ++i) {


int j;
for (j = 0; j < tail; ++j) {
if (str[i] == str[j]) break;
}
if (j == tail) {
str[tail] = str[i];
++tail;
}
}
270 Chapter B. Coding Interview

str[tail] = 0;

B.2 List of Basic Programs


At least we learn the following programs before attending any interview.
1. Write a c program to find the area of circle.
2. Write a c program to find the area of any triangle.
3. Write a c program to find the area of equilateral triangle.
4. Write a c program to find the area of right angled triangle.
5. Write a c program to find the area of rectangle.
6. Write a c program to find the area of trapezium.
7. Write a c program to find the area of rhombus.
8. Write a c program to find the area of parallelogram.
9. Write a c program to find the volume and surface area of cube.
10. Write a c program to find the volume and surface area of cuboids.
11. Write a c program to find the volume and surface area of cylinder.
12. Write a c program to find the surface area and volume of a cone.
13. Write a c program to find the volume and surface area of sphere.
14. Write a c program to find the perimeter of a circle, rectangle and triangle.
15. Write a c program to check given number is perfect number or not.
16. Write a c program to check given number is Armstrong number or not.
17. Write a c program to check given number is prime number or not.
18. Write a c program to check given number is strong number or not.
19. C program to check a number is odd or even.
20. Write a c program to check given number is palindrome number or not.
21. Write a c program to check given string is palindrome number or not.
22. Write a c program to solve quadratic equation.
23. Write a c program to print Fibonacci series of given range.
24. Write a c program to get factorial of given number.
25. Write a c program for Floyd’s triangle.
26. Write a c program to print Pascal triangle.
27. Write a c program to generate multiplication table.
28. Write a c program to print ASCII value of all characters.
29. C program to print hello world without using semicolon
30. Write a c program which produces its own source code as its output
31. Write a c program to reverse any number.
32. Write a c program to find out sum of digit of given number.
33. Write a c program to find out power of number.
34. Write a c program to add two numbers without using addition operator.
35. Write a c program to subtract two numbers without using subtraction operator.
36. Write a c program to find largest among three numbers using binary minus operator.
37. Write a c program to find largest among three numbers using conditional operator
38. Write a c program to find out generic root of any number.
39. Write a c program to find out prime factor of given number.
40. Write a c program to find out NCR factor of given number.
41. How to convert string to int without using library functions in c
42. Program in c to print 1 to 100 without using loop
43. C program for swapping of two numbers
44. Program to find largest of n numbers in c
45. Split number into digits in c programming
B.2 List of Basic Programs 271

46. C program to count number of digits in a number


47. Write a c program to find out L.C.M. of two numbers.
48. Write a c program to find out H.C.F. of two numbers.
49. Write a c program to find out G.C.D. of two numbers.
50. Write a c program to swap two numbers.
51. Write a c program to swap two numbers without using third variable.
52. Write a c program for swapping of two arrays.
53. Write a c program for swapping of two string.
54. Write a c program to convert decimal number to binary number.
55. Write a c program to convert decimal number to octal number.
56. Write a c program to convert decimal number to hexadecimal number.
57. Write a c program to convert octal number to binary number.
58. Write a c program to convert octal number to decimal number.
59. Write a c program to convert octal number to hexadecimal number.
60. Write a c program to convert hexadecimal number to binary number.
61. Write a c program to convert hexadecimal number to octal number.
62. Write a c program to convert hexadecimal number to decimal number.
63. Write a c program to convert binary number to octal number.
64. Write a c program to convert binary number to decimal number.
65. Write a c program to convert binary number to hexadecimal number.
66. C program for addition of binary numbers .
67. C program for multiplication of two binary numbers.
68. C program fractional binary conversion from decimal.
69. C program for fractional decimal to binary fraction conversion.
70. C program to convert decimal number to roman.
71. C program to convert roman number to decimal number.
72. C program to convert each digits of a number in words
73. C program to convert currency or number in word.
74. Write a c program to convert the string from upper case to lower case.
75. Write a c program to convert the string from lower case to upper case.
76. Write a c program to delete the all consonants from given string.
77. Write a c program to count the different types of characters in given string.
78. Write a c program to sort the characters of a string.
79. Write a c program for concatenation two strings without using string.h header file.
80. Write a c program to find the length of a string using pointer.
81. Write a c program which prints initial of any name.
82. Write a c program to print the string from given character.
83. Write a c program to reverse a string
84. Reverse a string using recursion in c
85. String concatenation in c without using strcat
86. How to compare two strings in c without using strcmp
87. String copy without using strcpy in c
88. Convert a string to ASCII in c
89. Write a c program for addition of two matrices.
90. Write a c program for subtraction of two matrices
91. Write a c program for multiplication of two matrices.
92. Write a c program to find out sum of diagonal element of a matrix.
93. Write a c program to find out transport of a matrix.
94. Write a c program for scalar multiplication of matrix.
272 Chapter B. Coding Interview

95. C program to find inverse of a matrix


96. Lower triangular matrix in c
97. Upper triangular matrix in c
98. C program to find determinant of a matrix
99. Write a c program to find out the sum of series 1 + 2 + . . . . + n.
100. Write a c program to find out the sum of series 12 + 22 + . . . . + n2 .
101. Write a c program to find out the sum of series 13 + 23 + . . . . + n3 .
102. Write a c program to find out the sum of given A.P.
103. Write a c program to find out the sum of given G.P.
104. Write a c program to find out the sum of given H.P.
105. Write a c program to find out the sum of series 1 + 2 + 4 + 8 . . . to infinity.
106. Write a c program to find out largest element of an array.
107. Write a c program to find out second largest element of an unsorted array.
108. Write a c program to find out second smallest element of an unsorted array.
109. Write a c program which deletes the duplicate element of an array.
110. Write a c program for delete an element at desired position in an array.
111. Write a c program for insert an element at desired position in an array.
112. C program to find largest and smallest number in an array
113. Write a c program to find factorial of a number using recursion.
114. Write a c program to find GCD of a two numbers using recursion.
115. Write a c program to find out sum digits of a number using recursion.
116. Write a c program to find power of a number using function recursion.
117. Write a c program to reverse any number using recursion.
C. GATE

1. Consider a two-dimensional array A[0..9] [0..19]. Each element occupies one byte and A is
stored in row major order starting from location 100. The address of element A[7][15] is :
Answer: 255
Explanation: A[7][15] = 100 + [7*20+15]*1 = 255
2. Consider the following code snippet:

#include<studio.h>
#define a 10
int main()
{
printf(%d,%d,%d,a++,++a,a++);
return 0;
}

What will be the output?


(A) 12, 12, 10 (B) 52, 52, 50 (C) 52, 51, 50 (D) Compiler Error
- Answer
3. What will be the output of the following program?

int main()
{
int x=10, y=20, z=5, p=1,i;
i=x<y<z<p;
printf (%d;i);
return 0;
}

(A) 0 - Answer (B) 1 (C) 5 (D) 10


4. Consider the following code segment.
274 Chapter C. GATE

void foo(int x, int y)


{
X+=y;
Y+=x;
}
main()
{
int x=4.5;
foo(x,x);
}
What is the final value of x in both call by value and call by reference respectively?
(A) 4 and 12 (B) 5 and 12 (C) 12 and 16 (D) 4 and 16
5. What will be the output of following c-code?

int main ()
{
int a[3] = {67, 43, 23};
int *p =a;
printf("%d",++*p);
printf("%d",*++p);
printf("%d",*p++);
return 0;
}
(A) 68 43 43 (B) 37 43 43 (C) 67 43 23 (D) 68 43 23
6. Consider following c-code.

int fun (int n) {


Static int i=10;
if (n>=200) return (n+i);
else{
n=n+i;
i=n+i
return fun(n);
}
}
The value returned by fun (10) is: _____
Answer: 890
7. What will be the output of the following piece of code?

void foo() {
int i=1; fork(); i++;
printf(%d,i); fork(); i++;
printf(%d,i); fork(); i++;
printf(%d,i);
}
(A) 2 2 3 3 3 3 4 4 4 4 4 4 4 4
(B) 2 3 3 2 3 4 4 4 3 4 4 4 4 4
275

(C) 2 3 4 2 3 4 4 3 4 4 4 3 4 4
(D) All of these
8. What will be the output of following C-code?
void fun( void * p);
static int i;
int main() {
void * ptr;
ptr &i;
fun (ptr );
return 0;
}
void fun( void * p)
{
int **q;
q int** &p;
printf( "%d", **q );
}
(A) Garbage value (B) 0 (C) 1- Answer (D) Error
9. What will be the output of the following program using dynamic scope and call by reference
respectively?
int n;
void a(int *x){
x++; printf(%d,x);
}
void b(int *n){
n=10; a(n);
}
main(){
int n=2;
a(n);
b(n);
}
(A) 3 4 (B) 2 3
(C) 3 11 - Answer (D) 2 11
10. Consider the following code segment
main
{
int a=5;
f (a,a) ;
print a;
}
f (int x, int y)
{
x --;
y= y+ 15;
}
276 Chapter C. GATE

What will be printed if „call by copy restore" mechanism is used for passing parameters?
(A) 4 (B) 20
(C) Both (A) and (B) (D) either (A) or (B) - Answer
11. What will be the output of the following program?

main(){
static int i=0;
i++;
if(i<=5){
int i=3;
printf("\n%d",i);
main();
}
else
exit(1);
}
(A) 1 2 3 4 5
(B) 3 3 3 3 3 - Answer
(C) Compiler error
(D) Infinite loop until stack overflows
Explanation:In C, we can declare variables at the start of new block which is considered to
be block scope. Also when inner and outer blocks have same variable name declared, the
variable referred within in the block will be the one that is declared locally. The variable
i used in comparison is the value of i declared in main. The value of i printed within the
if block is the value if i (3) declared in if block. The i declared in if block is destroyed an
created in every recursive call. Since the recursion is called 5 times, and the value printed is
3, it prints 3 3 3 3 3.
12. What will be the output of the following program?

void main( )
{
enum months {jan, feb, march=300,april,may=500,june=600};
printf(%d %d %d %d %d , jan, feb, march, april, may, june);
}
(A) 100 200 300 400 500 600
(B) 0 1 300 3 500
(C) 0 1 300 301 500 - Answer
(D) Compilation error
13. Consider the following C program: int b = 10;

int a = 4;
void foo( int *, int );
main(){
int a = 5;
int b = 6;
277

foo( &a, b);


printf(%d,a);
}
void foo(int *a, int c){
a = a+10;
b = b+6;
printf(%d,b);
}
What will be the output produced by the program?
(A) 12, 15 (B) 15, 16
(C) 16, 15 - Answer (D) 15, 6
14. What is the cyclomatic complexity of the following program?_____________
void foo() {
int i=20;
while (i<10) {
printf("%d", i);
if (i%2 == 0) {
printf("even");
} else {
printf("odd");
}
}
}
Answer: 3
15. Consider the following code fragment:
int func(int a, int b)
{
if(a < b)
return 0;
else if(a==b)
return a + func(a-1,b);
else
return b + func(a-2,b-1);
}
int main()
{
printf(%d , func(7,5));
return 0;
}
The output of the above code fragment is"’
Answer: 12
Explanation: func (7,5) ; a > b
5+ func (5,4); a > b
5+ 4+ func (3,3) ; a==b
5+ 4+3+ func (2,3); a<b return 0
5+ 4+3+0
=12
278 Chapter C. GATE

16. The following C function takes a simply-linked list as input argument.

typedef struct node {


int value;
struct node *next;
}
int func(node *head){
node *p;
int a;
if(head == NULL)
return 0;
if(head->next == NULL)
return(head->value)
p =head;
a = head->value;
while(p->next!= NULL){
p=p->next; if(p->value < a)
a = p->value;
}
return a;
}

Which of the following is true for the above function?


(A) The function returns maximum value from the list
(B) The function returns minimum value from the list - Answer
(C) The function returns length of the list
(D) The function returns addition of numbers in the list
17. What will be the output of the following program for call by name and copy restore parameter
passing mechanism respectively?

int i;
void func(int a, int b){
a=a+b; b=a+b; a=b-a; b=a-b;
}
main(){
int j; i=4;
int arr [10]={1,2,3,4,5,6,7,8,9,0};
func(i,arr[i]);
for(j=0;j<10;j++)
printf(%d,arr[j]);
}

(A) Call by name: -1 2 3 4 5 6 7 8 9 9 Copy restore: 1 2 3 4 -9 6 7 8 9 0


(B) Call by name: 0 2 3 4 5 6 7 8 9 0 Copy restore: 1 2 3 4 -9 6 7 8 9 0
(C) Call by name: -1 2 3 4 5 6 7 8 9 9 Copy restore: 1 2 3 4 5 6 7 8 9 0
(D) Call by name: 1 2 3 4 5 6 7 8 9 9 Copy restore: 1 2 3 4 -8 6 7 8 9 0
18. Consider the following program
279

int R(int n)
{
static int i=1;
if (n<=1)
return i;
else
{
i= i * R(n-1);
return i;
}
}
What is the value of R(5)=
Answer: 1
19. What will be the output of the following program?
#define val 100
void main()
{
printf("%d',val);
#define val 1000
printf("%d",val*10);
}
(A) Compile – Time error
(B) 100 1000
(C) 100 10000 - Answers
(D) None of these
20. Consider the following program:
void main()
{
static int a[]={510,20,30,40,50};
int *pt;
pt funct(a);
printf("M=%d",*pt);
}
int *funct(int *p)
{
int i,m2,m10;
for(i=0;i<5;++i)
if(*(p+i)>m1)
{
m1=*(p+i);
m2=i;
}
return (p+m2);
}
From the above program find the value assigned to pt when function is accessed and value of
m1.
280 Chapter C. GATE

(A) Element of a, 20
(B) Address of a, 30
(C) Address of element of a, 40
(D) Address of element of a, 50 - Answer
21. Find the output of the following program: int a=100,b=200; int funct1(int count); int
funct2(int c); void main() int count; for(count=1;count<5;++count) printf(" int funct1(int x)
int c,d; c = funct2(x); d = c<100?a+c:b; return d; int funct2(int x) static int prod=1; prod *x;
return prod;
(A) 101 102 104 106 124
(B) 101 102 103 104 105
(C) 101 102 106 108 110
(D) 101 102 106 124 200 - Answer
22. What does the following C program do?
# include<stdio.h>
static unsigned int a[32],b[32];
int i=0;
void main()
{
Unsigned int n; // assume that size of unsigned int is 32 bits
printf(Enter a positive decimal number);
scanf(%u, &n);
while(n!=0) { a[i++]=n % 2;
n/=2;
}
b[31] = a[31];
for(i=30;i>=0;i--)
b[i] = a[i+1] ^ a[i]; // ^ is Ex-or operator
for(i=31;i>=0;i--)
printf("%d ",b[i]);
}
(A) Converts 32 bit gray code of a decimal number to binary code
(B) Converts 32 bit binary code of a decimal number to gray code
(C) Gives 2’s complement of a decimal number
(D) Gives excess 3 code representation of a decimal number
23. The following program is to be tested for branch coverage
int fun(int a,int b,int c)
{
if(a>=0)
print a;
if(b>=0)
print b;
if(c>=0)
print c;
return a+b+c;
}
281

Minimum number of test cases needed to ensure 100% branch coverage of above program is:
Answer: 2
24. Consider the following program:

int x=5,y=10;
void main ( ) {
int i=2,j=3;
A(i,j);
}
void A( int i, int j) {
int x=10,y=5;
i=i+x; j=i+y;
printf(%d %d,i,j); B(i,j);
}
void B( int i, int j) {
i=j+y; j=i+x;
printf(%d,i+j);
}
The parameter passing method is call by reference. What is the output printed using static
scope?
(A) 10, 20, 31 (B) 10, 20, 49
(C) 12, 17, 54 (D) 12, 17, 59 - Answer
25. What is the output of the following program?

void main()
{
int A[10][10] ;
int *p=&A[0][0] ,i,j,count=0 ;
for(i=0;i<10;i++)
for(j=0;j<10;j++)
*(p+j*10+i)=count++;
printf("%d",A[5][5]- A[5][4]);
}
Answer: 10
26. What is the output of the following program?

void main()
{
int const *p=5;
printf("%d",++(*p));
}
(A) 5 (B) 6 (C) 7 (D) Compiler Error
- Answer
27. What will be the output of the following program?

int main(){
int i = 1234;
foo(i);
282 Chapter C. GATE

return 0;
}
int foo (int i){
if (i > 0){
printf(-%d||,i);
i = i%10 + foo(i/10);
printf(" %d ", i);
}
return i;
}

(A) 1234 1 123 2 12 3 1 4

(B) 1234 1 123 3 12 6 1 10

(C) 1234 1 123 12 12 123 1 1234

(D) 1234 123 12 1 1 3 6 10 - Answer


28. What will be the output of the program?

int main()
{
int a[5] = {0,1,2,3,4};
int i, j, k, l;
i = ++a[1];
j = a[i]++;
k = a[j++];
l = a[++k];
printf("%d %d %d%d", i, j, k, l);
return 0;
}

(A) 2 3 3 3 (B) 2 2 3 3

(C) 2 3 4 4 - Answer (D) 2 3 3 4


29. Output of the following program is?

int main() {
void test();
void (*f)();
f = test; (*f)();
f(); return 0;
}
void test()
{
printf(2015);
}

(A) 2015 (B) 20152015 - Answer

(C) Compiler error (D) None of these


30. If x is an array of integer, then the value of &x[i] is same as
283

(A) &x[i-1] + sizeof(int) (B) x + sizeof(int)*i


(C) x+i - Answer (D) Both (A) & (C)
31. In C, if y is integer type, then the expressions 3*(y-8)/9 and (y-8)/9*3 yield the same value if
(A) y is an even number
(B) y is an odd number
(C) (y-8) is an integral multiple of 9 - Answer
(D) (y-8) is an integral multiple of 3
32. Consider the C-function:

int f(int a,int b)


{
if (b= =0)
return a;
else
return ( f (b, a mod b) );
}
The value returned by the function call f(1071,462) is _________
Answer: 21
33. What is the output of the following C-code program?

int* fun();
void main()
{
int a=10,*p=&a;
p=fun();
*p=20;
printf(%d %d,a,*p);
}
int* fun()
{
int *x = (int*) malloc(sizeof(int));
*x = 30;
return x;
}
(A) 10 20 - Answer
(B) 10 30
(C) 10 10
(D) Error as memory pointed by x is destroyed once function execution is completed.
34. Consider the following recursive method (Ackermann’s function):

int acker(int m, int n){


int result;
if (m == 0)
result = n+1;
else if (n == 0)
284 Chapter C. GATE

result = acker(m-1, 1);


else
result = acker(m-1, acker(m, n-1));
return result;
}

What is the value of acker(1,2)? ______ Anser: 4


Explanation:
acker(1,2) = acker(0, acker(1,1))
= acker(0, acker(0, acker(1,0)))
= acker(0, acker(0, acker(0,1)))
= acker(0, acker(0, 2))
= acker(0, 3)
=4
35. Consider the following C code:

int Fun(int n)
{
int i = 0;
while( (i*i) <n)
i++;
return i;
}

Assuming that n takes on positive integer values, what is the value returned by Fun(n)?

(A) d ne - Answer

(B) b nc

(C) d ne + 1

(D) b nc+ 1
36. Consider the following program:

int i=0;
main()
{
int i=9,j=8;
swap(i,j);
print(i,j);
}
swap(int c,int d)
{
int t;
t = c;
c = d;
d = t;
}

What is the parameter passing mechanism to be used by the program such that the program
prints (8,9) ?
285

(A) Only call by value


(B) Only call by reference - Answer
(C) Both (A) & (B)
(D) neither (A) nor (B)
D. Mock Tests

D.1 Mock Test 1


1. What is the output of the C program?
f()
{ int a=2;
f1(a++);
}
f1(int c)
{
printf("%d", c);
2. What is the value of c after execution of the below code?
f1()
{
f(3);
}
f(int t)
{
switch(t);
{
case 2: c=3;
case 3: c=4;
case 4: c=5;
case 5: c=6;
default: c=0;
}
3. which of the functions is int a available for?
{
288 Chapter D. Mock Tests

}
int a;
f1(){}
f2(){}

(A) all of them (B) only f2 (C) only f1 (D) f1 and f2 only
4. What is the output of the below code?

#include<stdio.h>
main()
{
1+2;
}

(A) 3 (B) 1 (C) Error (D) None


5. What is the output of the below code?

what is an error in the following sequence of a program.


int i1;
switch(i1)
{
case 1: goto lure;
break;
case 2: printf("This is second choice");
break;
default: printf("This is default choice");
}
void fun(void)
{ lure: printf("This is unconditional jump");
}

6. What is the output generated by the following program ?

#include<stdio.h>
main()
{
int a , count;
int func(int);
for (count = 1 ;count <=5;++count)
{a
= func(count);
printf("%d", a);
}
} int func(int x)
{ int y;
y=x*x;
return(y);
}

(A) 1234567 (B) 2516941 (C) 9162514 (D) 1491625


7. What is the output generated by the following program ?
D.1 Mock Test 1 289

#include<stdio.h>
void main(void)
{
int oldvar=25,newvar=-25;
int swap(int,int);
swap(oldvar,newvar);
printf("Numbers are %d\t%d",newvar,oldvar);
} int swap(int oldval,int newval)
{
int tempval=oldval;
oldval=newval;
newval=tempval;
}
8. What is the output generated by the following program ?

#include<stdio.h>
void main(void);
double dbl=20.4530,d=4.5710,dblvar3;
void main(void)
{
double dbln(void);
dblvar3=dbln();
printf("%.2f\t%.2f\t%.2f\n",dbl,d,dblvar3);
}
double dbln(void)
{
double dblvar3;
dbl=dblvar3=4.5;
return(dbl+d+dblvar3);
}
9. What is the output generated by the following program ?

main()
{
int n=10;
int func(int);
printf("%d",func(n));
}
int func(int n)
{
if(n>0)
return(n+func(n-2));
}
10. What is the output generated by the following program ?

#include<stdio.h>
void function;
int ivalue=100;
main()
290 Chapter D. Mock Tests

{
ivalue=50;
function1;
printf("ivalue in the function=",ivalue);
printf("ivalue after the function=",ivalue);
}
printf("ivalue at the end of main=",ivalue);
function()
i-value=25;
11. What is the output generated by the following program ?

main(){
char s[] = "T.C.S", *A;
print(s);
}
print (char *p)
{
while (*p != '\0')
{
if (*p != ".")
printf ("%s", *p);
p++;
}
}
12. What is the output generated by the following program ?

main()
{
char *x="new";
char *y="dictonary";
char *t;
void swap (char * , char *);
swap (x,y);
printf("(%s, %s)",x,y);
char *t;
t=x;x=y;y=t;
printf("-(%s, %s)",x,y);
}
void swap (char *x,char *y)
{
char *t;
y=x;x=y;y=t;
}
13. What is the output generated by the following program ?

main()
{
funct(int n);
{
D.1 Mock Test 1 291

switch(n)
case1:m=2; break;
case2:m=5; break;
case3: m=7; break;
default: m=0;
}
14. What is the output generated by the following program ?
Switch (i)
i=1;
case 1: i++;
case 2: ++i; break;
case 3: --i;
15. What is the output generated by the following program ?
#include<stdio.h>
int SumElement(int *,int);
void main(void)
{
int x[10];
int i=10;
for(;i;)
{
i--;
*(x+i)=i;
}
printf("%d",SumElement(x,10));
} int SumElement(int array[],int size)
{ int i=0;
float sum=0;
for(;i<size;i++)
sum+=array[i];
return sum;
}
16. What is the output generated by the following program ?
void main(void);
int printf(const char*,...);
void main(void)
{
int i=100,j=10,k=20;
int sum;
float ave;
char myformat[]="ave=%.2f";
sum=i+j+k;
ave=sum/3.0;
printf(myformat,ave);
}
17. What is the output generated by the following program ?
292 Chapter D. Mock Tests

#include<stdio.h>
void main(void);
void main(void)
{
int a[10];
printf("%d",((a+9) + (a+1)));
}
18. What is the output generated by the following program ?

#include<stdio.h>
int fn(void);
void print(int,int(*)());
int i=10;
void main(void)
{
int i=20;
print(i,fn);
}
void print(int i,int (*fn1)())
{
printf("%d\n",(*fn1)());
} int fn(void)
{
return(i-=5);
}
19. What is the output generated by the following program ?

int bags[5]={20,5,20,3,20};
void main(void)
{
int pos=5,*next();
*next()=pos;
printf("%d %d %d",pos,*next(),bags[0]);
} int *
next()
{ int i;
for(i=0;i<5;i++)
if (bags[i]==20)
return(bags+i);
printf("Error!");
exit(0);
}
20. What is the output generated by the following program ?

void main(void);
int newval(int);
void main(void)
{
int ia[]={12,24,45,0},i,sum=0;
D.1 Mock Test 1 293

for(i=0;ia[i];i++)
{
sum+=newval(ia[i]);
}
printf("Sum= %d",sum);
}
int newval(int x)
{
static int div=1;
return(x/div++);
}
21. What is the output generated by the following program ?

#include<stdio.h>
void main(void);
void main(void)
{
void pa(int *a,int n);
int arr[5]={5,4,3,2,1};
pa(arr,5);
}
void pa(int *a,int n)
{ int i;
for(i=0;i<n;i++)
printf("%d\n",*(a++)+i);
}
22. What is the output generated by the following program ?

#include<stdio.h>
void main(void);
void print(void);
void main(void)
{
print();
}
void f1(void)
{
printf("\nf1():");
}
23. What is the output generated by the following program ?

main()
{
void f(int,int);
int i=10;
f(i,i++);
}
void f(int i,int j)
{
294 Chapter D. Mock Tests

if(i>50) return;
i+=j;
f(i,j);
printf("%d,",i);
}
24. What is the output generated by the following program ?

#include<stdio.h>
void main(void);
static int i=50;
int print(int i);
void main(void)
{
static int i=100;
while(print(i))
{
printf("%d\n",i);
i--;
}} int print(int x)
{
static int i=2;
return(i--);
}
25. What is the output generated by the following program ?

#include<stdio.h>
void main(void);
const int k=100;
void main(void)
{
int a[100],sum=0;
for(k=0;k<100;k++)
*(a+k)=k;
sum+=a[--k];
printf("%d",sum);
}
26. What is the output generated by the following program ?

main ()
{
char *name = "name";
change (name);
printf ("%s", name);
}
change (char *name)
{
char *nm = "newname";
name = nm;
}
D.2 Mock Test 2 295

27. What is the output generated by the following program ?

main()
{
int n = 3;
f(n);
printf("MAIN");
}
void f(int n)
{
printf("F");
if ( n != 0 ) f(n-1);
}
28. What is the output generated by the following program ?

void main()
{ int i=7;
printf("%d",i++*i++);
}
29. What is the output generated by the following program ?

main()
{
int i;
i=1;
i=i+2*i++;
printf(%d,i);
30. What is the output generated by the following program ?

main(){ int i=3;


while(i--)
{
int i=100
i--;
printf("%d..",i);
}
}

D.2 Mock Test 2


1. Find the output:

void main()
{
int a=3,c=4,c=5;
a=b+c;
c=a+b;
b=a+c;
printf("%d %d %d",a+b,b+c,c+d);
a=b*c;
296 Chapter D. Mock Tests

c=a*b;
printf(%d %d",a.c);
}

2. main()
{ int x=14,y=10,z=3;
x*=y+1+z;
printf(%d,x);
}
what is the value of x?
3. Find the output:

main()
{
char a,b;
printf("%d%d%d%d",sizeof('a'),sizeof(NULL),sizeof(b),sizeof(main));
}

4. Find the output:

#define hello(x,y)
printf(#expr"%d",expr);
main()
{
float x=1,y=2;
expr=x/y;
hello(expr);
}

5. Find the output:

#define prod((a>b)?a*a:b*b)
main()
{ int p==0,q==-1;
prod(p++,q++)
}

6. Find the output:

# define cube(x) x * x * x
main()
{
int a=3;
cube(a++);
}

7. Find the output:

# define mult(x) x*y


main()
{
mult(2+1);
}
D.2 Mock Test 2 297

8. Find the output:

main()
{ int x=5,y=10;
swap1(x,y);
printf("%d %d\n",x,y);
swap2(x,y);
printf("%d %d\n",x,y);
} int swap2(int a,int b)
{ int temp;
temp=a;
b=a;
a=temp;
return;
}
9. Find the output:

main()
{
char a[10];
char *p1=a;
char *p1=&a[a];
{
*p1++;
*p2--;
}
}
10. Find the output:

main()
{char *ptr = "Ramco Systems";
(*ptr)++;
printf("%s\n",ptr);
ptr++;
printf("%s\n",ptr);
}
11. Find the output:

main()
{
int x=5,y;
y= x&y;
}
12. Find the output:

main()
{
int *p, i==4;
p==&i ;
298 Chapter D. Mock Tests

(*p)++ ;
printf("%d",p);
}

13. Find the value of y after execution of the below code:

main()
{
int x=5,y;
y= x&y;
www.csetf.blogspot.com
return y;
}

14. Find the output:

main()
{c
har *ptr = "Ramco Systems";
(*ptr)++;
printf("%s\n",ptr);
ptr++;
printf("%s\n",ptr);
}

15. Find the output:

main()
{
int *p, i==4;
p==&i ;
(*p)++ ;
printf("%d",p);
}

16. Find the output:

x=0;
switch(x)
{
case 1: printf( "One" );
case 0: printf( "Zero" );
case 2: printf( "Hello World" );
}

17. Find the output:

main()
{ int a=2, b=3;
printf(" %d ", a+++b);
}

18. For the following statement find the values generated for p and q?
D.2 Mock Test 2 299

int p = 0, q =1;
p = q++;
p = ++q;
p = q--;
p = --q;
19. Find the output:

main()
{ int a=2, b=3;
printf(" %d ", a+++b);
}
20. #include<stdio.h>
void main(void);
typedef struct NType
{ int i;
char c;
long x;
} NewType;
void main(void)
{
NewType *c;
c=(NewType *)malloc(sizeof(NewType));
c->i=100;
c->c='C';
(*c).x=100L;
printf("(%d,%c,%4Ld)",c->i,c->c,c->x);
}
21. Find the output:

main()
{
union u
{
struct s
{
char c1, c2;
};
long x;
float y;
};
u example ;
example.s.c1 = 'a' ;
example.s.c2 = 'b' ;
example.x = 5;
printf("%c %c %d", example.s.c1, example.s.c2, example.x);
}
22. Find the output:

signed int a=-1;


300 Chapter D. Mock Tests

int b;
a=~a;
b=~0;
a=~a;
printf("%d %d",a,b);
23. Find the output:

main()
{
int a=10,b=8,c=3;
printf("%d %d %d %d ",a,a=9,a<b);
}
24. Find the output:

main()
{
www.csetf.blogspot.com
int i=-3,j=2,k=0,m;
m=++j && ++i || ++k;
printf("%d %d %d %d ",i,j,k,m);
getch();
}
25. Find the output:

int x=2;
x=x<<2;
printf("%d ",x);
26. Find the output:

int a[]={0,0X4,4,9}; /*some values are given*/


int i=2;
printf("%d %d",a[i],i[a]);
27. Find the output:

void main(void)
{ int y,z;
int x=y=z=10;
int f=x;
float ans=0.0;
f *=x*y;
ans=x/3.0+y/3;
printf("%d %.2f",f,ans);
}
28. Find the output:

main()
{
int rows=3,colums=4;
D.3 Mock Test-3 301

int a[rows][colums]={1,2,3,4,5,6,7,8,9,10,11,12};
i=j=k=99;
for(i=0;i<rows;i++)
for(j=0;j<colums;j++)
if(a[k][j]<k) k=a[i][j];
printf("%d\n",k);
}
29. Find the output:
main()
{
int x[]={0,0,0,0,0}
for(i=1;i<=4;i++)
x[x[i]]++;
for(i=0;i<5;i++)
printf(" %d",a[i]);
}
30. Find the output:
main()
{
char p[]="string";
char t;
int i,j;
for(i=0,j=strlen(p);i<j;i++)
{
t=p[i];
p[i]=p[j-i];
p[j-i]=t;
}
printf("%s",p);
}

D.3 Mock Test-3


1. Find the output:
printf("%d%d",val/val,val^3)
2. Find the output:
main()
{c
har *src = "Hello World";
char dst[100];
strcpy(src,dst);
printf("%s",dst);
}
strcpy(char *dst,char *src)
{
while(*src) *dst++ = *src++;
}
302 Chapter D. Mock Tests

3. Find the output:

struct a
{ int age,
char *name;
}xx,*p=&x;
main()
{c
har c;
xx.name="mohan singhal"
c=*(((*p).name)+2);
printf("%c",c);
}

4. Find the output:

void myalloc(char *x, int n)


{
x= (char *)malloc(n*sizeof(char));
memset(x,\0,n*sizeof(char));
}
main()
{c
har *g="String";
myalloc(g,20);
strcpy(g,"Oldstring");
printf("The string is %s",g);
}

5. Find the output:

void myalloc(char *x, int n)


{
x= (char *)malloc(n*sizeof(char));
memset(x,\0,n*sizeof(char));
}main()
{c
har *g="String";
myalloc(g,20);
strcpy(g,"Oldstring");
printf("The string is %s",g);
}

6. Find the output:

char *gxxx()
{
static char xxx[1024];
return xxx;
}
main()
{c
D.3 Mock Test-3 303

har *g="string";
strcpy(gxxx(),g);
g = gxxx();
strcpy(g,"oldstring");
printf("The string is : %s",gxxx());
}
7. Find the output:
char *someFun1()
{c
har temp[ ] = string";
return temp;
}c
har *someFun2()
{c
har temp[ ] = {`s', `t','r','i','n','g'};
return temp;
} int main()
{
puts(someFun1());
puts(someFun2());}
8. Find the output:
char *someFun()
{char *temp = string constant";
return temp;
} int main()
{
puts(someFun());
}
9. Find the output:
main()
{
int a=10,*j;
void *k;
j=k=&a;
j++;
k++;
printf("\n %u %u ",j,k);
}
10. Find the output:
void main(){
printf(sizeof (void *) = %d \n, sizeof( void *));
printf(sizeof (int *) = %d \n, sizeof(int *));
printf(sizeof (double *) = %d \n, sizeof(double *));
printf(sizeof(struct unknown *) = %d \n, sizeof(struct unknown *));
}
304 Chapter D. Mock Tests

11. Find the output:

main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
least = (*ptr<least ) ?*ptr :least;
printf("%d",least);
}
12. Find the output:

main()
{
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}
13. Find the output:

main()
{
printf("Hello\n");
fork();
printf("Hi\n");
14. Find the output:

main(){
char a[]="hellow";
char *b="hellow";
char c[5]="hellow";
printf("%s %s %s ",a,b,c);
printf(" ",sizeof(a),sizeof(b),sizeof(c));
}
15. Find the output:

{char* p="hello";
printf("%d %d",strlen(p),sizeof(p));
getch();
}
16. Find the output:

struct bit
{ int a:5;
int b:12;
};main()
{c
D.3 Mock Test-3 305

lrscr();
printf("%d",sizeof(struct bit));
getch();
}

17. Find the output:

main()
{
char *p;
p=malloc(10);
free(p);
printf("%d",p);
}

18. Find the output:

main()
{c
har *p1="Name";
char *p2;
p2=(char *)malloc(20);
while(*p2++=*p1++);
printf("%s\n",p2);
}

19. Find the output:

{char *p1;
char *p2;
p1=(char *) malloc(25);
p2=(char *) malloc(25);
strcpy(p1,"subsist");
strcpy(p2,"skill");
strcat(p1,p2);
printf("%s",p1);
}

20. Find the output:

main()
{
char *c;
int *ip;
c =(char *)malloc(100);
ip=(int *)c;
free(ip);
}

21. Find the output:

main()
{
306 Chapter D. Mock Tests

static char names[5][20]={"pascal","ada","cobol","fortran","perl"};


int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}
22. Find the output:
main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++) {
printf(" %d ",*c);
++q; }
for(j=0;j<5;j++){
printf(" %d ",*p);
++p; }
}
23. Find the output:
main()
{
char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}
24. Find the output:
void main()
{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
25. Find the output:
main()
{
int i, n;
char *x = girl;
n = strlen(x);
*x = x[n];
for(i=0; i<n; ++i)
{
printf(%s\n,x);
x++;
}
}
D.3 Mock Test-3 307

26. Find the output:

main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
r++;
printf("%p...%p...%p",p,q,r);
}

27. Find the output:

# include <stdio.h>
int one_d[]={1,2,3};
main()
{
int *ptr;
ptr=one_d;
ptr+=3;
printf("%d",*ptr);
}

28. Find the output:

main()
{c
har *p;
p="%d\n";
p++;
p++;
printf(p-2,300);
}

(A) 300 (B) 301 (C) 600 (D) None


29. Find the output:

int aaa() {printf(Hi);}


int bbb(){printf(hello);}
iny ccc(){printf(bye);}
main()
{ int (*ptr[3]) ();
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();
}

(A) bye (B) aaa (C) hello (D) Hi


308 Chapter D. Mock Tests

30. Find the output:

main()
{
int a=2,*f1,*f2;
f1=f2=&a;
*f2+=*f2+=a+=2.5;
printf("\n%d %d %d",a,*f1,*f2);
}
(A) 16 16 16 (B) 16 16 15 (C) 16 15 16 (D) None

You might also like