Cracking The C Interview PDF
Cracking The C Interview PDF
Cracking The C Interview PDF
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.
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
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
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
C GATE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
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.
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!
#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
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.
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.
(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
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".
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.
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.
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.
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.
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.
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 :
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:
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 PI 3.142
#define MAX 100
(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
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 ]
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
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
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)
Example:
c = a + b;
c = 5;
c = a;
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:
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
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
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;
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.
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
Example:
y = (x > 5 ? 3 : 4) is equivalent to
if (x>5)
then
y = 3;
else
y = 4;
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.
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.10 Expressions
An expression is a combination of variables, constants and operators arranged as per the syntax of
the language.
(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
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
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
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
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).
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.
Explanation: In the above program character ch will be read through getchar() function and
character will print through putchar() function.
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.
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
Output :
5.2 Formatted IO 45
Explanation : In the above program integer i is initialized with 3214, it is printed with various
formats.
Output:
Explanation : In the above program float i is initialized with 2500.321, it is printed with
various formats.
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.
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.
float n;
scanf("%f",&n);
char n;
scanf("%c",&n);
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
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);
}
#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
#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
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);
}
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
#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
#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
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");
}
#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;
#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
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.
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.
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:
#include<stdio.h>
main()
{
int x,y,rst;
char opt;
printf(" Enter first number : ");
scanf("%d",&x);
6.4 goto 65
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.
#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();
}
#include<stdio.h>
main()
{
int n;
printf("Enter any number : ");
scanf("%d",&n);
if(n%2==0)
6.5 Example Programs 67
#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
#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.
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
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);
}
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")
}
int zap(int n)
{
if(n<=1)then zap=1;
else zap=zap(n-3)+zap(n-1);
}
6.6 Multiple Choice Questions 73
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
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.
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.
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.3 exit() :
It is a standard library function used to terminate the program execution.
The general format : exit(argument);
#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
#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
OUTPUT:
86 Chapter 7. Looping Statements
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
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
*/
#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
#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
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
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
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
#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
#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
(C) exit the outermost block even if it occurs inside the innermost
#include<stdio.h>
main()
{
int x=5,y=0;
while(y<10)
{
printf("%d%d",y++,x++);
}
}
#include<stdio.h>
main()
{
int i=1;
for( ; ; )
{
printf("%d",i++);
if (i>5)
break;
}
}
104 Chapter 7. Looping Statements
#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 ]
# 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);
}
main ()
{ int d = 1;
do
printf(%d\n, d++);
while (d < = 9);}
106 Chapter 7. Looping Statements
#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
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.
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.
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.
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.
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.
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:
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.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.
#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.
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 ".
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)
#include <stdio.h>
#include "stdio.h"
#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.
#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();
}
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
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
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;
}
main()
{
printf ("%d\n",f(7));
}
f(X)
{
if ( x<= 4)
return x;
return f(--x);
}
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
#define a 10
main()
{
#define a 50
printf("%d",a);
}
#define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}
void main()
{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
} int ret(int ret)
{
ret += 2.5;
return(ret);
}
}
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.
marks[4] = 40
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.
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.
type array_name[rwo_size][column_size];
Ex:- int marks[100][5];
float salary[1000][4];
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"
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)
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)
#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
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 :
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
#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();
}
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) 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]));
}
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
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
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 ]
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.
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
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:
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
Visual Representation
Below are some of the variable representations of NULL 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 */
}
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;
}
int main()
{
int *ptr;
/* Ptr is a wild pointer, as it is not initialized Yet */
printf("%d", *ptr);
}
168 Chapter 10. Pointers
int main()
{
int x=25;
int near* ptr;
ptr=&x;
printf("%d",sizeof ptr);
10.3 Pointer Arithmetic 169
return 0;
}
Output: 2
#include<stdio.h>
int main()
{
int x=10;
int far *ptr;
ptr=&x;
printf("%d",sizeof ptr);
return 0;
}
Output : 4
#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.
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 -
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).
#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
#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
#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[1]
= Address of ptr[0] + (Size of Data Type)*(Size of Array)
= 1000 + (4 bytes) * (5)
= 1020
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
#include<stdio.h>
int main(){
int *ptr=(int *)1000;
ptr=ptr-3;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
Formula :
Data Type Older Address stored in pointer Next Address stored in pointer after
decrementing
int 1000 998
float 1000 996
char 1000 999
• 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.
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
#include<stdio.h>
int main()
{
int num , *ptr1 ,*ptr2 ;
ptr1 = &num ;
ptr2 = ptr1 + 2 ;
printf("%d",ptr2 - ptr1);
return(0);
}
Output :
2
Important Observations :
Suppose the Address of Variable num = 1000.
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
#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
#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.
#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.
}
}
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.
#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.
#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.
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
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
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.
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
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:
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 );
#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
(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=∑
*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;
}
char *p="abc";
char *q="abc123";
while(*p=*q)
{
print("%c %c",*p,*q);
}
void main()
{
float j;
j=1000*1000;
printf("%f",j);
}
char *foo()
{c
har result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{c
har *j;
j=foo()
printf("%s",j);
}
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
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
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());
}
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
#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=∑
*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.
struct structure_name
{
type var1;
type var2;
.
.
type varn;
};
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;
struct sturec
{
char name[30];
int age;
float height;
} student1={"Srinivas",20,189.76}
main()
{
static sturec student2={"Ramesh",22,177.25};
. . . .
. . . .
}
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
#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
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};
. . . .
. . . .
}
# 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);
}
struct marks
{
int no;
int sub[5];
int total;
} stu[10];
struct emprec
{
char name[30];
int age;
struct
{
int day;
char month[20];
int year;
}j_date;
float sal;
}
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
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.
10. Union is [ A ]
(A) a special type of strcture (B) a pointer data type
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;
}
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);
}
typedef struct a
{
int x;
aType *b;
}aType
Answer: No
27. Is the following code legal?
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.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.
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.
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.
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.
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
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.
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.
#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
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
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);
}
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 :
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.
The stderr FILE pointer is particularly useful with respect to error handling.
#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();
}
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
where datatype refers to exiting data type and identifier is the new name given to this datatype.
For example
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
where value1, value2 etc are values of the identifier. For example
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:
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
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
#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;
}
#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
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();
}
(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
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);
}
}
#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
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
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);
}
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.
main()
{
printf(5+"Fascimile");
}
Answer : mile
57. Find the output
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
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);
}
#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;
}
#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();
}
#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
}
int temp2 = f;
while ((double)temp2 != f) {
f = f * 10;
temp2 = f;
count2++;
}
printf("Integer Count = %d, Decimal count = %d", count1, count2);
return 0;
}
#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
pos++;
}
}
for(i = size-1; i >= pos; i--) {
arr[i] = 0;
}
#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)
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;
}
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;
}
}
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)
#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;
}
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
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
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]){
/* matrix size */
int numOfRows = rowN;
int numOfCols = colN;
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
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;
}
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;
}
#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>
int main()
{
int i=65;
char str[]="This is my string";
myprintf("\nMessage = %s%d%x",str,i,i);
}
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
}
}
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.
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;
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 tail = 1;
str[tail] = 0;
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;
}
int main()
{
int x=10, y=20, z=5, p=1,i;
i=x<y<z<p;
printf (%d;i);
return 0;
}
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.
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
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]);
}
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;
}
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
int main() {
void test();
void (*f)();
f = test; (*f)();
f(); return 0;
}
void test()
{
printf(2015);
}
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 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
}
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;
}
#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);
}
#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
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 ?
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));
}
#define hello(x,y)
printf(#expr"%d",expr);
main()
{
float x=1,y=2;
expr=x/y;
hello(expr);
}
#define prod((a>b)?a*a:b*b)
main()
{ int p==0,q==-1;
prod(p++,q++)
}
# define cube(x) x * x * x
main()
{
int a=3;
cube(a++);
}
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);
}
main()
{
int x=5,y;
y= x&y;
www.csetf.blogspot.com
return y;
}
main()
{c
har *ptr = "Ramco Systems";
(*ptr)++;
printf("%s\n",ptr);
ptr++;
printf("%s\n",ptr);
}
main()
{
int *p, i==4;
p==&i ;
(*p)++ ;
printf("%d",p);
}
x=0;
switch(x)
{
case 1: printf( "One" );
case 0: printf( "Zero" );
case 2: printf( "Hello World" );
}
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:
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:
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);
}
struct a
{ int age,
char *name;
}xx,*p=&x;
main()
{c
har c;
xx.name="mohan singhal"
c=*(((*p).name)+2);
printf("%c",c);
}
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
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();
}
main()
{
char *p;
p=malloc(10);
free(p);
printf("%d",p);
}
main()
{c
har *p1="Name";
char *p2;
p2=(char *)malloc(20);
while(*p2++=*p1++);
printf("%s\n",p2);
}
{char *p1;
char *p2;
p1=(char *) malloc(25);
p2=(char *) malloc(25);
strcpy(p1,"subsist");
strcpy(p2,"skill");
strcat(p1,p2);
printf("%s",p1);
}
main()
{
char *c;
int *ip;
c =(char *)malloc(100);
ip=(int *)c;
free(ip);
}
main()
{
306 Chapter D. Mock Tests
main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
r++;
printf("%p...%p...%p",p,q,r);
}
# include <stdio.h>
int one_d[]={1,2,3};
main()
{
int *ptr;
ptr=one_d;
ptr+=3;
printf("%d",*ptr);
}
main()
{c
har *p;
p="%d\n";
p++;
p++;
printf(p-2,300);
}
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