c Programming
c Programming
C Programming
(Course Code : FEC205)
First Year Engineering (Common to All Branches)
(Semester II) (Mumbai University)
.
C Programming (Course Code : FEC205)
About Managing Director….
(MU - F.E. - Semester II / Common to All Branches
– For New Syll. 2019-20) - Mr. Sachin Shah
Author : Er. Manoj S. Kavedia, Pankaj B. Brahmankar Over 25 years of experience in Academic
Publishing…
First Edition for New Syllabus : May 2021
Tech-Neo ID : M2-05 With over two and a half decades of experience
in bringing out more than 1200 titles in
Copyright © by Authors. All rights reserved. Engineering, Polytechnic, Pharmacy, Computer
No part of this publication may be reproduced, Sciences and Information Technology,
copied, or stored in a retrieval system, distributed or Sachin Shah is a name synonymous with
transmitted in any form or by any means, including quality and innovative content.
photocopy, recording, or other electronic or A driven Educationalist…
mechanical methods, without the prior written
1. A B.E. in Industrial Electronics
permission of the Publisher. (1992 Batch) from Bharati Vidyapeeth’s
This book is sold subject to the condition that it shall College of Engineering, affiliated to
not, by the way of trade or otherwise, be lent, resold, University of Pune.
hired out, or otherwise circulated without the 2. An Alumnus of IIM Ahmedabad.
publisher’s prior written consent in any form of 3. A Co-Author of a bestselling book on
binding or cover other than which it is published and “Engineering Mathematics” for Polytechnic
without a similar condition including this condition Students of Maharashtra State.
being imposed on the subsequent purchaser and 4. Sachin has for over a decade, been working
without limiting the rights under copyright reserved as a Consultant for Higher Education in
above. USA and several other countries.
Published by With path-breaking career…
Mrs. Nayana Shah A publishing career that started with
Mr. Sachin S. Shah handwritten cyclostyled notes back in 1992,
Managing Director, B. E (Industrial Electronics) Sachin Shah has to his credit setting up and
An Alumunus of IIM Ahmedabad expansion of one of the leading companies in
Mr. Rahul S. Shah higher education publishing.
Permanent Address An experienced professional and an expert…
Tech-Neo Publications LLP An energetic, creative & resourceful
Dugane Ind. Area, Survey No. 28/25, Dhayari Near professional Sachin Shah's extensive
Pari Company, Pune - 411041. Maharashtra State, experience of closely working with the best &
India. the most eminent authors of Publishing
Email : info@techneobooks.com Industry, ensures high standards of quality in
Website : www.techneobooks.com contents. This ability has helped students to
attain better understanding and in-depth
Printed at : Image Offset (Mr. Rahul Shah) knowledge of the subject.
Dugane Ind. Area, Survey No. 28/25, Dhayari Near A visionary…
Pari Company, Pune - 411041. Maharashtra State, A gregarious person, SACHIN SHAH is a thought
India. leader who has been simplifying the methods of
learning and bridging the gap between the best
E-mail : rahulshahimage@gmail.com authors in the publishing industry and the student
community for decades.
Preface
We are divided the subject into small chapters so that the topics can be
arranged and understood properly. The topics within the chapters have been
support that they have extended to us. We are also thankful to the staff
members of Tech-Neo Publications and others for their efforts to make this
book as good as it is. We are jointly made every possible efforts to eliminate
all the errors in this book. However if you find any, please let us know,
We are also thankful to our family members and friends for their
- Authors
Syllabus…
Course Course Name Teaching Scheme Credits Assigned
Code (Contact Hours)
Theory Pract. Tut. Theory Tut. Pract. Total
FEC205 C Programming 02 - - 02 - - 2
Course Course Name Examination Scheme
Code Theory Term Work Pract. Total
Internal Assessment End Exam. Duration /Oral
Introduction to Arrays
Array of Structures
Pointers
Fundamentals of pointers
Operations on Pointers
Assessment consists of two class tests of 15 marks each. The first class test is to be conducted when approx. 40%
syllabus is completed and second class test when additional 35% syllabus is completed. Duration of each test shall
be one hour.
3. Question No: 01 will be compulsory and based on entire syllabus wherein sub-questions of 2 to 5 marks will be
asked.
4. Remaining questions will be mixed in nature.( e.g. Suppose Q.2 has part (a) from module3 then part (b) will be
from any module other than module 3)
5. In question paper weightage of each module will be proportional to number of respective lecture hrs as
mentioned in the syllabus.
Course Teaching Scheme Credits Assigned
Code Course Name (Contact Hours)
Theory Pract. Tut. Theory Tut. Pract. Total
FEL204 C programming -- 2 -- -- -- 1 1
Examination Scheme
Theory
Course Course Name Term Pract.
Internal Assessment End Exam.
Code Work
Sem. Duration /oral Total
Test1 Test 2
Exam. (in Hrs)
Avg
FEL204 C programming -- -- -- -- -- 25 25 50
Outcomes: Learner will be able to…
1. Translate given algorithms to a program.
2. Correct syntax and logical errors.
3. Write iterative as well as recursive programs.
4. Represent data in arrays, strings and structures and manipulate them through a program.
5. Declare pointers and demonstrate call by reference concept.
Lab Description
Weekly 2 hours of laboratory Programming Assignments on the following topics:
1. Basic data types and I/O operations
2. Branching Statements
3. Loop Statements
4. Arrays
5. Strings
6. Functions
7. Recursion
8. Structure and Union
9. Pointers
Term Work
Experiments (20 Programs) and Assignments (2 Assignments) should be completed by students on the given time
duration
Experiments: 15 Marks
Assignment: 05 Marks
Attendance: 05 Marks
Total: 25 Marks
The final certification and acceptance of TW ensures the satisfactory performance of laboratory work and
minimum passing in the TW.
Practical and Oral
Practical and oral Exam should be conducted for the Lab, on Computer Programming in C subject for
given list of experiments.
Implementation: 15 Marks
Oral: 10 Marks
Index
Module I
Module II
Chapter 3 : Control Structures ............................................................. 3-1 to 3-47
Module III
Chapter 4 : Functions ...........................................................................4-1 to 4-24
Module IV
Chapter 5 : Arrays and Strings ............................................................. 5-1 to 5-30
Module V
Chapter 6 : Structure and Union .......................................................... 6-1 to 6-17
Module VI
Chapter 7 : Pointers ............................................................................. 7-1 to 7-39
Module I
Chapter… 1
Introduction to Computer,
Algorithm and Flowchart
University Prescribed New Syllabus w.e.f Academic Year 2019-2020
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-3)
Nowadays computer is being used in all the fields. It is (A) Input Unit
a useful tool that will continue its development as time Computers need to receive data and instruction in order
passes to solve any problem. Therefore we need to input the
data and instructions into the computers.
The input unit consists of one or more input devices.
Keyboard is the one of the most commonly used input
device.
Other commonly used input devices are the mouse,
floppy disk drive, magnetic tape, etc. All the input
devices perform the following functions.
o Accept the data and instructions from the outside
world.
Fig. 1.1.3 : Third Generation of Computers o Convert it to a form that the computer can
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-4)
The programs that run on the computer are first (E) Control Unit
transferred to the primary memory before their
It controls all other units in the computer. The control
execution.
unit instructs the input unit, where to store the data
Whenever the results are generated, they are also after receiving it from the user.
stored in the secondary memory. The secondary
It controls the flow of data and instructions from the
memory is slower and cheaper than the primary
storage unit to ALU. It also controls the flow of results
memory. Some of the commonly used secondary from the ALU to the storage unit.
memory devices are Hard disk, CD, etc.,
The control unit is generally referred as the central
Memory Size nervous system of the computer that control and
All digital computers use the binary system, i.e. 0’s synchronizes its working.
and 1’s. Each character or a number is represented by (F) Central-Processing-Unit
an 8 bit code.
The control unit and ALU of the computer are together
The set of 8 bits is called a byte. A character occupies
known as the Central Processing Unit (CPU). The CPU
1 byte space. A number occupies 2 bytes space. Byte is
is like brain which performs the following functions :
the measurement unit of space occupied in the
o It performs all calculations.
memory.
o It takes all decisions.
The size of the primary storage is specified in KB
(Kilobytes) or MB (Megabyte). One KB is equal to o It controls all units of the computer.
1024 bytes and one MB is equal to 1000KB. The size
of the primary storage in a typical PC usually starts at
1.1.2 Input Devices
16MB. PCs having 32 MB, 48MB, 128 MB, 256MB GQ. Explain various input devices in detail. (5 Marks)
memory are quite common.
Ans. : Input Devices
(C) Output Unit
Input devices are used to provide input to computer.
The output unit of a computer provides the information
There are number of Input devices, out of which we
and results of a computation to outside world. Printers,
will see some frequently used devices such as
Visual Display Unit (VDU) are the commonly used
keyboard, mouse and scanner.
output devices. Other commonly used output devices
are floppy disk drive, hard disk drive, and magnetic 1. Keyboard
tape drive. As the name suggest, keyboard uses an arrangement of
(D) Arithmetic Logical Unit buttons or keys. Keyboard is main input device for
computer.
All calculations are performed in the Arithmetic Logic
Unit (ALU) of the computer. It also does comparison A keyboard has characters printed on the keys. Each
and takes decision. key corresponds to a specific symbol.
The ALU can perform basic operations such as
addition, subtraction, multiplication, division, etc. and
does logical operations viz, >, <, =, etc.
Whenever calculations are required, the control unit
transfers the data from storage unit to ALU once the
computations are done, the results are transferred to the Fig. 1.1.5 : Keyboard
storage unit by the control unit and then it is sent to the
Letters, numbers or signs are generated by keys on
output unit for displaying results.
keyboard. Keyboard is the device which is used for
direct input of alphanumeric data.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-5)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-6)
These pins produce patterns of dots on the paper to A nozzle for black ink may be all that’s needed to print
form the individual characters. text, but full-color printing is also possible with the
The 24 pin dot-matrix printer produces more dots than addition of three extra nozzles for the cyan, magenta,
a 9 pin dot-matrix printer, which results in much better and yellow primary colors.
quality and clearer characters. Several manufacturers produce color ink-jet printers.
The general rule is : the more pins, the clearer the Some of these printers come with all their color inks in
letters on the paper. The pins strike the ribbon a cartridge; if you want to replace color, you must
individually as the print mechanism moves across the replace all the colors.
entire print line in both directions, i.e, from left to Other color ink-jet printers allow you to replace ink
right, then right to left, and so on. individually. These printers are a better choice if user
The user can produce a coloured output with a dot- uses one color more than other colors.
matrix printer (the user will change the black ribbon These printers produce less noise and print in better
with a ribbon that has colour stripes). quality with greater speed.
Dot-matrix printers are inexpensive and typically print
at speeds of 100-600 characters per second.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-7)
When high speed laser printers were introduced they (i) Electrostatic Plotters
were expensive. Developments in the last few years Electrostatic plotters used a dry toner transfer process
have provided relatively low-cost laser printers for use similar to that in many photocopiers.
in small businesses.
They were faster than pen plotters and were available
3. Speaker in large formats, suitable for reproducing engineering
Speakers are one of the most common output devices drawings.
used with computer systems. The quality of image was often not as good as
Some speakers are designed to work specifically with contemporary pen plotters. Electrostatic plotters were
computers, while others can be hooked up to any type made in both flat-bed and drum types.
of sound system. (ii) Cutting plotters
Regardless of their design, the purpose of speakers is Cutting plotters use knives to cut into a piece of
to produce audio output that can be heard by the material (such as paper, vinyl etc.) that is lying on the
listener. flat surface area of the plotter.
Speakers are transducers that convert electromagnetic It is achieved because the cutting plotter is connected
waves into sound waves. to a computer, which is equipped with specialized
The speakers receive audio input from a device such as cutting design or drawing computer software
a computer or an audio receiver. programs.
This input may be either in analog or digital form. Those computer software programs are responsible for
Analog speakers simply amplify the analog sending the necessary cutting dimensions or designs in
electromagnetic waves into sound waves. Since sound order to command the cutting knife to produce the
waves are produced in analog form, digital speakers correct project cutting needs.
must first convert the digital input to an analog signal
and then generate the sound waves.
1.1.4 Hardware
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-8)
unit is not possible. GQ. Explain types of Software in detail with its types.
Hardware is limited to specifically designed tasks that (5 Marks)
are taken independently. Software implements
algorithms (problem solutions) that allow the computer
Ans. :
to complete much more complex tasks. Types of Software
Practical computer systems divide software systems
into two major classes : System and Application.
1. System software
System software is nothing but a type of computer
program. System software is designed to run
computer’s hardware and application programs.
System software is the interface between the hardware
and user applications.
Two main types of system software are the operating
system and the software installed with the operating
system. Software installed with operating system is
Fig. 1.1.12 : Basic internal hardware
also known as utility software.
GQ. Explain concept of Software. (2 Marks) An operating system is a set of programs that manage
Ans. : computer hardware resources and provide common
services for application software.
Software
The operating system is the most important type of
Software, commonly known as programs or apps, system software in a computer system. User cannot run
consists of all the instructions that tell the hardware an application program on their computer without
how to perform a task. operating system.
These instructions come from a software developer in Utility software is a type of system software. Utility
the form that will be accepted by the platform software performs specific task related to the working
(operating system + CPU) that they are based on. of the computer. The operating system and utility
For example, a program that is designed for the software typically depend on each other to function
Windows operating system will only work for that properly
specific operating system.
Operating System Examples
Compatibility of software will vary as the design of the
software and the operating system differ. Software that Windows x p/7/8/8.1/10 Ms-DOS
is designed for Windows XP may experience a Ubuntu UNIX
compatibility issue when running under Windows 2000
Android 4.xx(kitkat) Android 5.xx(lollipop)
or NT.
Android
Software is capable of performing many tasks, as 6.xx(marshmallow)
opposed to hardware which can only perform
mechanical tasks that they are designed for. 2. Application software
Software provides the means for accomplishing many Application software is nothing but program that can
different tasks with the same basic hardware. be designed to use by end users.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-9)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-10)
GQ. Write advantages of Machine Level Programming The programmers are freed from tedious repetitive
(2 Marks) calculations and assembler programs are much more
readable than machine code.
Ans. :
Many assemblers offer additional mechanisms to
Advantages of Machine Level Programming
facilitate program development, to control the
1. Machine language makes fast and efficient use of the
assembly process, and to support debugging.
computer.
An assembler program creates object code by
2. There is no need of any translator to translate the code.
translating combinations of mnemonics and syntax for
As it is directly understood by the computer.
operations and addressing modes into their numerical
GQ. Write disadvantages of Machine Level
equivalents.
Programming (2 Marks)
This representation typically includes an operation
Ans. : code ("opcode") as well as other control bits and data.
Disadvantages of Machine Level Programming The assembler also calculates constant expressions and
1. Need to remember all operation codes. resolves symbolic names for memory locations and
2. Need to remember all memory addresses. other entities.
3. It is very difficult to find errors in a program written in The use of symbolic references is a key feature of
the machine language. assemblers, saving tedious calculations and manual
address updates after program modifications.
1.1.7 Assembly Level Programming
GQ. Write advantages of Assembly Level
GQ. Write note on Assembly Level Programming Programming (2 Marks)
(5 Marks) Ans. :
Ans. : Advantages of Assembly Level Programming
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-11)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-12)
It is responsibility of compiler to check whether the Ans. : Difference between Compiler and Interpreter
program of user follow all the syntax rules of language Parameter Compiler Interpreter
or not. Input An entire program is A single line of
taken by compiler at code or
However, we have to keep it in mind that the compiler a time. instruction is
is only a program and cannot fix errors found in that taken by
program. Compiler will just show the errors. interpreter at a
Programmer has to solve those errors. time.
Output It outputs It does not
Examples of compiled programming languages are C intermediate object generate any
and C++. code. intermediate
object code.
Working The compilation is Compilation and
mechanism implemented prior to execution are
Fig. 1.1.15 : Working of Compiler execution. implemented
simultaneously.
Interpreter Speed Faster Comparatively
slower
1. An interpreter is also a computer program that
Memory Memory requirement Memory
transforms high-level program statements into the is more as object requirement is
machine code. This conversion includes source code, code is created. more as object
pre-compiled code, and scripts. code does not
created.
2. An Interpreter directly executes instructions written in Errors Shows all the errors Displays errors
a programming or scripting language without after compilation, at a line by line.
previously converting them to an object code or time.
machine code. Examples of interpreted languages are Error Comparatively Easier
Perl, Python and Matlab. detection difficult
Pertaining C, C++, C#, Scala, Java, PHP, Perl,
Programming typescript uses Python, Ruby
languages compiler. uses an
interpreter.
Fig. 1.1.15 : Working of Interpreter
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-13)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-14)
GQ. Explain problem solving techniques in detail. notion of algorithm is given below.
(5 Marks) Algorithm is set of ordered instructions which are
Ans. : Problem solving techniques
written in simple English Language. Algorithm is used
to solve certain problems.
Algorithm defines the step by step logic for a program
to solve specific problem.
Writing algorithm for a problem is the best way of
expressing the logic to solve that problem on paper
Fig. 1.1.18 before doing actual programming on computer to solve
it.
1. Algorithm
Algorithm helps the programmer to write actual logic
Algorithm is set of ordered instructions which are of a problem on paper and validate it with the help of
written in simple English Language. Algorithm defines paper and pencil, and correct it if any fault is noticed.
the step by step logic for a program to solve specific
UQ. An algorithm is a graphical representation of the
problem.
logic of a program. MU - May 18, 1 Mark.
In this type of problem solving the required inputs and
expected outputs are identified and according to that Ans. : False
the processing will be done.
1.2.1 Characteristics of Algorithm
More explanation about Algorithm will be given in
next sections. GQ. Explain characteristics of an algorithm. (4 Marks)
2. Flowchart Ans. : Characteristics of an algorithm
Flowchart is a good problem solving technique. Following are important characteristics of an
Flowchart is graphical representation of an algorithm. algorithm :
The sequence of steps in algorithm is maintained and
represented in the flowchart by using some standard
symbols such as rectangles and directed lines.
More explanation about flowchart will be given in next
sections.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-15)
3. Definiteness 2. Comments
The contents followed by \\ symbol are considered as
Each instruction should be clear and unambiguous.
Comments. Comments are necessary to provide extra
4. Effectiveness information about the statements.
Each instruction should have proper meaning and
3. Input and Output
effectiveness to produce the final result. Each
instruction in the algorithm should have meaning, and Inputs and expected outputs of an algorithm should be
importance in the process of generating output. provided.
5. Finiteness 4. Steps
The algorithm must terminate after fixed number of Provide number to all the steps in an algorithm.
steps. Numbering will help to refer specific statement again.
5. Variables
1.2.2 Basic Conventions of Algorithm
All the variable names should be written in uppercase.
GQ. What are the basic conventions used while 6. Assignment Statement
writing an Algorithm (5 Marks) For Assignment use symbol to assign the value of
Ans. : Basic conventions while writing an Algorithm
right hand side to left hand side. For example : A 20
A single value can be assigned to multiple variables
To write a paragraph in English language there are
like : A B C 5.
some standards to follow like every statement starts
with capital letter and ends with full stop. The right hand side of symbol may be a value
(for example 0…9), another variable (for example A,
Similarly while writing an algorithm some conventions
X, COUNT, MAX1 ,…) or an expression(for example
should be followed. These conventions are as follows.
A+B, B-10,…).
Whereas the left hand side of symbol should be an
individual variable (for example COUNT, MAX,
A1, B, ….)
7. If Statement
This statement will be written in following format :
if condition 1
statement 1
else
statement 2
More description about this statement is given in next
chapter.
8. Repeat Statement
This statement will be written in following format :
Repeat the steps until condition 1
Statement 1
Fig. 1.2.2 : Conventions while writing an algorithm More description about this statement is given in next
chapter.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-16)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-17)
It defines set of unambiguous, finite number of ordered Step 3 : Read value for NUM
steps which will process the input and generate Step 4 : Multiply NUM to itself and assign the result to
expected output. Each step in the algorithm should be SQUARE
carried out easily. SQUARE ← NUM * NUM
Step 5 : Display value of SQUARE
1.2.5 Examples of Algorithm
Step 6 : Stop
GQ. Write an algorithm for accepting two numbers
GQ. Write an algorithm to calculate cube of given
and performing addition, subtraction, division
number. (4 Marks)
and multiplication on them. (4 Marks)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-18)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-19)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-20)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-21)
Each upcoming flowline should be connected at the top GQ. Draw flowchart for calculating square of given
of the symbol, and each outgoing flowline should start number. (4 Marks)
with the bottom of the symbol as shown in Fig. 1.3.1.
Ans. :
Calculate square of Given Number
Ans. :
Calculate cube of Given Number
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-22)
GQ. Draw flowchart for calculating area of circle. GQ. Draw flowchart for calculating area of rectangle.
(4 Marks)
(4 Marks)
Ans. : Ans. :
Calculate area of rectangle
Calculate area of Circle
Ans. :
Calculate area of triangle
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-23)
GQ. Draw flowchart for finding largest number among three numbers. (4 Marks)
Ans. :
Find the Greatest of Three Numbers
Fig. 1.3.8 : Flowchart for finding largest number among three numbers
GQ. Draw flowchart for checking whether given number is even or odd. (2 Marks)
Ans. :
Determine Whether a Given Number is Even or Odd
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-24)
GQ. Draw flowchart for checking whether given GQ. Write an algorithm and draw a flowchart to print
number is prime or not. (4 Marks) first N Fibonacci numbers. (4 Marks)
GQ. Draw a flow chart to do the sum of 100 elements Fig. 1.3.12
read from the user. (5 Marks) GQ. Draw a flowchart to find out smallest number
from given three numbers. (5 Marks)
Ans. :
Sum of 100 elements
Ans. : Smallest number out of 3 numbers
Fig. 1.3.13
Fig. 1.3.11
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-25)
GQ. Draw a flow chart that shows how to find root of GQ. State any four disadvantages of using
2
quadratic equation ax + bx + c. (4 Marks)
flow-chart. (4 Marks)
Ans. : Root of quadratic equation ax 2
+ bx + c
Ans. :
Disadvantages of Flowchart
1. Flowcharts are not suitable for communication between
human and a computer.
2. If modifications has to be done then the flowchart must
be redrawn which is wastage of time.
3. Flowcharts are waste of time and slow down process of
software development.
4. Flowchart are quiet costly to produce and difficult to
use and manage.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
Module I
Chapter… 2
Fundamentals of
C Programming
University Prescribed New Syllabus w.e.f Academic Year 2019-2020
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-3)
2.1 INTRODUCTION TO
C PROGRAMMING
Ans. :
C Language
GQ. Write note on History of C. (5 Marks) This language was hard to learn and difficult to
implement. That’s why this language doesn’t become
Ans. : popular.
History of C
As time passes BCPL (Basic Combined Programming
Studying History of C is an interesting part, let’s start. Language) is developed by Martin Ritchie in 1967 at
Cambridge University.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-4)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-5)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-6)
Some applications of C Programming language are as While learning any language knowing the alphabets is
follows : the very first step.
o C programming language can be used to develop After that, words are created using those alphabets.
the system software like operating systems Collections of valid words make a sentence.
(For example, UNIX, LINUX) and their
And the collection of valid sentences makes a
operations.
paragraph.
o C can be used to develop the Language Compilers
Like this we are going to learn the C language. See
which takes input from one language and produce
Fig. 2.1.5.
output in another language (usually lower level
language).
o C is used to develop the Language Interpreters,
and Assemblers.
o C is used to develop the application software like
database (MySQL) and Spread sheets.
o C is used to develop the Network Devices.
o C is used to develop the Embedded Systems.
o C is used to develop the Firmware for several
electronics communications products which are
used in microcontroller.
(a) English language (b) C language
o C can be used to develop the Simulators, test code
Fig. 2.1.5 : Process of learning
and verification software for other applications
and hardware products. While learning any programming language knowing
o UNIX kernel is developed in C language. the character set is the very first step.
o C can be used to develop the Graphics related After familiar with the character set keywords,
application like computer and mobile games and identifiers, variables and constants are created using
also 3D Games. this character set.
o C can be used to develop the desktop applications An instruction is made up of valid set of keywords,
like text editors. identifiers, variable, constants, and valid symbols.
o Also C can be used to develop the print spoolers. A program is nothing but the set of instructions.
o C is also used to develop other programming In a paragraph every individual word and the
languages like PHP. punctuation marks are known as tokens, like that in C
every smallest individual unit of a program is known
o C can be used to develop virus as well as
as token.
antivirus.
Let’s see all the terms in detail.
2.1.4 Concept of Data in C
2.1.5 Concept of Character in C
GQ. Explain concept of Data in C. (2 Marks)
GQ. What is character in C ? (2 Marks)
Ans. :
Ans. : Character in C
Concept of Data in C
A character indicates any alphabet, digit or special
Learning C is as same as learning any natural language
symbol used to represent the data. The characters are used to
like English.
construct the keywords, variables, identifiers, constants, and
expressions.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-7)
GQ. Explain character set in C. (2 Marks) Special Symbols Name of Special Symbols
? Question mark
Ans. : Character set in C
, Comma
C language uses number of characters to develop a
program. C Character set is made-up of following elements : / Forward Slash
(i) Alphabets . Period
o Uppercase letters : A to Z
2.1.6 C Tokens
o Lowercase letters : a to z.
(ii) Digits : 0 to 9 GQ. Explain different C tokens with appropriate
(ii) Special Symbols : The C character set includes examples. (5 Marks)
following special symbols given in Table 2.1.1. Ans. :
Table 2.1.1 : Special symbols in C Character set
C tokens
Special Symbols Name of Special Symbols C tokens are defined as the smallest individual units in
~ Tilde a C program. Tokens in C program can be
! Exclamation mark o A keyword - For example : void, do, struct, etc.
@ At Sign o An identifier - For example : function_name,
# Number sign variable_name, etc.
$ Dollar sign o A constant - For example : 5, 0.25, etc.
% Percentage sign
o A string literal - For example : “Hello”,
^ Caret “Phoenix”, “A”, etc.
& Ampersand sign
o A symbol : ( , ) , # , ; , { , + etc.
* Asterisk
( Lest parenthesis Example
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-8)
Some examples for each type is given below : Data types Loop
1. Keywords : int, while, if etc. extern void
2. Identifiers : roll_number, book_1, count, etc. register return
static Others
3. Constants : 100,150, etc.
Derived Const
4. Strings : “Hello”, “Phoenix”, etc.
struct Volatile
5. Special Symbols : ;, (, ), :, etc. union Sizeof
6. Operators : +, - ,*, /, etc. UQ. Which of the following is not a keyword of ‘C’ ?
In next section we will discuss these tokens in detail. (A) auto (B) register
(C) int (D) function
2.1.7 C Keywords MU - May 18, 1 Mark.
GQ. List any four keywords used in C with their use.
Ans. : (D)
(2 Marks)
GQ. Write the rules that should be followed while
Ans. : Keywords used in C using keywords. (2 Marks)
Keywords are also known as the reserved words Ans. : Rules while using keywords
because the meanings of these words are predefined to
Keywords are the special words meaning of which is
the compiler.
pre-defined for the C compiler and it cannot be
There are only 32 keywords in C; 27 keywords are changed.
given by Ritchie and 5 keywords are added by ANSI. All keywords must be written in lowercase.
As the meaning of keywords is previously known by Keywords can be used only for their intended purpose.
compiler we cannot use these keywords as an
Keywords cannot be used as user-defined variables /
identifier. identifiers.
All the keywords are written in lowercase letters,
GQ. Enlist any four keywords used in C. (2 Marks)
C compiler only recognize these keywords if they are
written in lowercase because C is case sensitive Ans. : Keywords used in C
language.
The keywords are used for their specific purposes.
These are given in the Table 2.1.2.
Table 2.1.2 : Keywords in C
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-9)
(i) signed : the variable can hold a positive or negative 6. Storage Class Keywords
value.
(ii) unsigned : the variable can hold only a positive value.
(iii) short : the variable can hold a fairly small integer
value.
(iv) long : the variable can hold a fairly large integer value.
3. Loop Control Structure Keywords
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-10)
(ii) register : It indicates that the variable is stored in CPU 9. Derived Keyword
register and the scope of this variable is local to the
block where it is defined. The default value of this
variable is garbage. It is active till the control remains
in the block where it is defined.
(iii) static : It indicates that the variable is stored in
memory and the scope of this variable is local to the
Fig. 2.1.15 : Derived keywords
block where it is defined. The default value of this
variable is zero. The value of that variable persist (i) struct : This keyword is used to define the derived data
between different function calls. types.
(iv) extern : It indicates that the variable is stored in (ii) union : Just like struct, it is also used to define the
memory and the scope of this variable is global. The derived data types.
default value of this variable is zero. The value of that 10. Other Keywords
variable persists until the control comes to the end of
program.
7. Function Keywords
Fig. 2.1.13 : Function keywords (i) const : To declare an identifier as a constant this
keyword is used.
(i) void : It is one of the return type and used with the
For example : const int price =20; the value of this
functions.
variable cannot be changed during program.
(ii) return : This keyword is used with the function. The
(ii) volatile : It is used to create volatile variables means
last statement in the function is return. It is used to
that its value can be changed by some external sources
return a value to calling location.
outside the program.
8. Decision Keywords
(iii) sizeof : This keyword is used to know the size of an
variable in memory.
For Example : sizeof(a); if a is of integer type then it
will return 2 or 4 as the result according to the
compiler being used.
(i) if, else : These are used to check the condition and GQ. What is identifier? (2 Marks)
make decision depending upon the condition
satisfaction.
Ans. :
Identifier
(ii) switch, case, default : These keywords are used to
compare a variable with different values and make Identifier is a collection of alphanumeric characters.
decision according to the condition satisfaction. Identifiers are used to give names to the programming
elements like variables, arrays, functions, structures,
unions, and labels.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-11)
Identifier is formed by combination of uppercase case (because it is keyword and can’t be used as
letters, lowercase letters, digits, and the underscore identifier),
symbol. total_of_a&b (because & symbol is not allowed in
Basically, an identifier is user-defined word. identifiers).
It is valid to use any number and sequence of GQ. What is difference between keywords and
characters from 63 alphanumeric characters (among identifiers? (2 Marks)
those 52 characters are uppercase and lowercase
alphabets and 10 characters are 0 to 9 digits and Ans. :
1 character is the underscore symbol) from the Difference between keywords and identifiers
C character set to form an identifier.
Parameter Keywords Identifiers
Identifiers start with the alphabets or underscore
symbol. Usually the underscore is used to separate two Predefined or Keywords are the Identifiers are User-
words in the long identifiers. user-defined Pre-defined word defined means
means their meaning meaning is not
GQ. Explain rules for naming an identifier. (2 Marks)
is already explained explained to the
Ans. : to the compiler compiler
Identifier should not start with digit. Meaningful Each keyword has Each identifier should
Identifier must be a unique name given to the elements fixed meaning be meaningful
of a program. Lowercase Keywords are Identifiers can be
Identifiers are case sensitive so the max and MAX are and uppercase written in lowercase written in both
considered as two different identifiers. letters only lowercase and
An identifier should not contain special symbols, uppercase
comma or blank space. Use Keywords are used Identifiers are used
Identifiers are user-defined words so they should not for its intended for its required
be same as of the keywords otherwise compiler will purpose purpose
generate an error.
Underscore Underscore character Underscore character
There is no rule on the length of an identifier but first symbol is not used in is considered as a
31 characters are used by the compiler to recognize the keywords letter in identifier.
uniqueness of it.
Identifiers must be meaningful names given to the 2.1.9 Structure of C Program
elements; it should be short and specific so that it will
be easily understandable and remembered by the GQ. Explain the structure of C program. (5 Marks)
programmers.
Ans. :
Example Structure of C program
Correct identifiers : sum, _area_of_circle, After getting knowledge about the types of variables,
average_of_marks, x, number1, etc. constants and keywords the next step is to combine
Incorrect identifiers : 1number (because it begins with them to form instruction. Now let’s directly start to
number), write a program.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-12)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-13)
Ans. :
main() Function
Every C program must have main( ) function.
main() function is the entry point of the program
execution. It is not possible to run the program without
main() function.
Also the body of main() function is written within
{ and } braces. All the expressions and statements like
declaration statement, assignment statement, arithmetic Fig. 2.1.18
expression are usually written within the main()
function’s body.
Type the Program
# include<stdio.h>
The syntax of main ( ) function is :
int main()
return_type main()
{
{
printf(“My first C Program”);
//statements;
}
}
The main () function is important part of C program.
The return_type may be void or int.
Step 4 : The click file>new> source file or use shortcut Comments are used to give extra information about the
ctrl+N as shown in Fig. 2.1.18. program. Comments are ignored by C compiler.
Comments are helpful for the programmer or user
while developing an application.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-14)
Example of comments
/* Program name: Program1.c
Date modified: 15-8-2018 Multiline comment
Author: Phoenix InfoTech */
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-15)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-16)
The meaningful name given to the memory locations GQ. How to declare a variable? Explain with syntax
where the value is stored is known as the variable. The and example. (2 Marks)
name given to the variable is an identifier.
Ans. :
A variable is a program entity which is used to hold
the value. Declaring variables
One variable can store only one value at a time. The It is mandatory to declare a variable which is going to
value stored in variable can be changeable during be used in the program.
program execution. Variable is declared with its data type so that the
Specific type of variables store only those type of compiler will know how much memory it will require
values, for example : integer type of variables store and what type of data is going to be stored in it.
only natural numbers.
Syntax of declaring variable
Each variable has a particular type. The type
data_type variable_name;
determines :
o The size and storage layout of the variable in Example
memory int marks;
o The range of values that can be stored within that char ch;
memory float salary;
o The set of operations that can be applied on the UQ. Which of these is a valid variable declaration ?
variable. (A) in temp salary; (B) float marks_student;
To specify the variable type, data type is used. Variable (C) float roll-no; (D) int main;
may belong to any of the data type e.g. int, char, float, MU - May 18, 1 Mark.
etc. Ans. : (B)
GQ. State rules for assigning variable name. (3 Marks)
GQ. How to initialize a variable? Explain with syntax
Ans. : and example. (2 Marks)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-17)
Example of constant
2.2.2 Constants
Ans. :
Constants
Fig. 2.2.7 shows exact difference between a variable
and a constant. The box which is open to put anything
in it is called variable which means that the content of
this box varies.
Fig. 2.2.7 : Variable and constant Fig. 2.2.8 : Various Types of Constants
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-18)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-19)
Ans. :
Difference between variable and constant
Parameters Variable Constant
Stored Variables are memory Constantans are
Location locations where values used to stored
are stored. fixed values.
Definition Values in the variables Values in the
can be changed. constants cannot
be changed.
Initialization Values can be initialized At the time of
later after declaration declaration only,
also. the value is
assigned to
constant or it is Fig. 2.3.1 : Operators in C
predefined. 2.3.1 Arithmetic Operators
Store To store user inputs and Constants can’t be
outputs during programs used to store user GQ. State four arithmetic operators with their uses.
variables are used. That inputs and outputs. (2 Marks)
means we can assign That means we
values to variables cannot assign Ans. : Arithmetic operators
dynamically. values to constants Arithmetic operators are binary operators, means that
dynamically.
they take two operands to perform operation.
Syntax data_type const data_type
variable_name; variable_name; Addition, subtraction, division, multiplication are the
Name Variable name can be It is good practice basic operations performed by using arithmetic
combination of to write constants operators.
lowercase, uppercase, in uppercase
The Table 2.3.1 shows all the arithmetic operators
digit and underscore letters.
letter. supported by the C language.
Example int num; const float PI=3.14 Here we consider two variables M = 5 and N = 10 then
Table 2.3.1
2.3 OPERATORS IN C Operator Description Example
+ Performs addition of two M + N = 15
operands
GQ. Define operator. (2 Marks)
− Performs subtraction of two N–M=5
Ans. : Operator operands. Subtract second
operand from first.
An operator is a symbol which operates on one or more * Performs multiplication of M * N = 50
values or variables. For example : + is an operator which two operands
performs addition of more than one values or variables. / Performs division of two N/M=2
operands and produces
GQ. List different types of operators used in quotient as a result
c language. (2 Marks) % Performs division of two N%M =0
operands and produces
reminder as a result.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-20)
2.3.2 Increment and Decrement Operators GQ. State the difference between i++ and ++i.
(4 Marks)
GQ. Explain increment and decrement operators with
example. (4 Marks) Ans. :
Difference between i++ and ++i
Ans. :
Increment and decrement operators Parameter ++i i++
Increment and Decrement operators are unary Name Known as pre increment Known as
operators means that they take one operand to perform operator. post
increment
operation on it.
operator
Increment operator adds 1 to the variable.
Working After incrementing the value First the
Decrement operator subtracts 1 from the variable.
of i by one its updated value expression
Pre-increment and pre-decrement add and subtract one is used in expression. gets
to and from the variable first and then perform evaluated
assignment operation. and then the
Example 1 value of i
Pre-increment: int a=5; will be
incremented
int b=++a;
by one.
Here a and b both have 6.
Pre-decrement: int a=5; Effect to If we use this operator in an If we use
result expression then it will affect this
int b=--a;
the result of that expression. operator in
Here a and b both have 4.
an
Post-increment and Post-decrement do the assignment expression
operation first and then perform add and subtract one then it will
to and from the variable. not affect
Example 2
the result of
that
Post-increment: int a=5;
expression.
int b=a++;
Here value a will be 6 and b will be 5 Example For Example : For
Post-decrement: int a=5; Consider a=7, b=0 then, Example :
int b=a--; b= b + 2 + (++a); Consider
Here value a will be 4 and b will be 5 After execution of above a=7, b=0
statement the value of a and then,
Here we consider a variable M =5
b will be : b= b + 2 +
Operator Description Example (a++);
a = 8, b = 10.
++ Increment operator Pre-increment: After
increases the integer ++M = 6 execution
value by 1. Post-increment: of above
M++ = 6 statement
the value of
-- Decrement operator Pre-decrement:
decreases the integer --M = 4 a and b will
value by 1. be :
Post-decrement:
a = 8, b = 9.
M-- = 4
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-21)
GQ. Compare --i and i. (2 Marks) UQ. Predict output of following program segment.
main( )
Ans. : {
Compare --i and i-- int x=4, y=9, z;
Parameter --i i-- z = x+++ --y + y;
printf(“\n %d %d %d” , x, y, z) ;
Name Known as pre Known as post
decrement operator. decrement operator z= --x + x + y --;
printf(“\n %d %d %d”, x, y, z);
}
Working After decrementing First the expression
the value of i by gets evaluated and MU - May 18, 4 Marks.
one its updated then the value of i
value is used in will be
Ans. :
expression. decremented by Output
one.
Effect to If we use this If we use this
result operator in an operator in an
expression then it expression then it
will affect the result will not affect the
of that expression. result of that
expression.
Example Consider a=7, b=0 Consider a=7, b=0 2.3.3 Relational Operators
then, then,
b= b + 2 + (--a); b= b + 2 + (a--); GQ. List any four relational operators. (4 Marks)
After execution of After execution of
above statement the above statement the Ans. :
value of a and b value of a and b Relational operators
will be: will be:
Relational operators check the relation between two
a = 6, b = 8. a = 6, b = 9.
operands. Table 2.3.2 shows all the relational operators
UQ. Write a output for following program : supported by C.
int main ( ) Here we consider two variables M=10 and N=20
{ Table 2.3.2
int x=10,y,z;
z=y=x; Operator Description Example
y-=--x; == Determines whether the two (M == N) is
operands have same values or not. not true.
z-=x--;
If equal then condition is true.
x-=--x-x--;
!= Determines whether the two (M != N) is
printf("x = %d y = %d z = %d",x,y,z) ;
operands have same values or not. true.
If not equal then condition is true.
} MU - May 13, 6 Marks. > Determines whether the left side (M > N) is
Ans. : Output
operand has greater value than the not true.
right side operand. If it is, then the
condition is true.
< Determines whether the left side (M < N) is
operand has less value than the true.
right side operand. If it is, then the
condition is true.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-22)
Ans. : True
2.3.4 Logical Operators
(iii) 5.10 || 10 < 20 && 3 < 5
GQ. State four logical operators with examples. Ans. : True
(2 Marks)
Ans. :
2.3.5 Bitwise Operators
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-23)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-24)
Table 2.3.5 lists the assignment operators supported by 2.3.7 Conditional / Ternary Operator
the C language.
Here consider M=10, N=5 and A=0. UQ. Explain : ? operator in C. MU - May 16, 2 Marks.
Operator Description Example There are also some other operators which are
= Simple assignment operator. A = M + N will important and supported by C language. One of them is
Assigns values from right assign the value Ternary operator (? :) which is performed on three
side operands to left side of M + N i.e. operands.
operand (10+5=15) to A It is also known as conditional operator.
+= Add AND assignment M += N is Ternary operator perform on three operands like:
operator. It adds the right equivalent to M
operand to the left operand =M+N A?B:C
and assigns the result to the Now M will be Means that if A is true then perform B otherwise
left operand. 10+5 = 15 perform C. Here A is condition and B, C can be
–= Subtract AND assignment M – = N is expressions.
operator. It subtracts the right equivalent to M Example
operand from the left operand =M–N
and assigns the result to the Now M will be Here consider two variables X=10 and Y=20.
left operand. 10–5 = 5 MAX = (X>Y) ? X : Y
*= Multiply AND assignment M *= N is Here the value of variable having greater value will be
operator. It multiplies the equivalent to M assigned to the MAX. In this case the value of Y will
right operand with the left =M*N be assigned to the MAX.
operand and assigns the result Now M will be
to the left operand. 10 * 5 = 50 UQ. Write a program to find the biggest of given 3
no’s using conditional operator.
/= Divide AND assignment M /= N is
operator. It divides the left equivalent to M MU - Dec. 14, May 16, 5 Marks.
operand with the right =M/N
operand and assigns the result Now M will be Ans. :
to the left operand. 10/5 = 2 Program
%= Modulus AND assignment M %= N is int main ( )
operator. It takes modulus equivalent to M {
using two operands and =M%N int X,Y,Z,MAX;
assigns the result to the left Now M will be
operand. 10 % 5 = 0 X=10;
<<= Left shift AND assignment M <<= 2 is same Y=20;
operator. as M = M << 2 Z = 15;
>>= Right shift AND assignment M >>= 2 is same MAX=(X>Y)?((X>Z)?X:Z):((Y>Z)?Y:Z);
operator. as M = M >> 2 printf("Max is %d",MAX);
&= Bitwise AND assignment M &= 2 is same
operator. as M = M & 2 }
^= Bitwise exclusive OR and M ^= 2 is same Output
assignment operator. as M = M ^ 2
|= Bitwise inclusive OR and M |= 2 is same as
assignment operator. M=M|2
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-25)
GQ. Explain special operators in C with example. logical; in more elaborate settings, it can be an
arbitrary complex data type.
(4 Marks)
For example, 2 + 3 is an arithmetic and programming
Ans. : expression which evaluates to 5.
Special operators in C A variable is an expression because it denotes a value
Apart from this, some other special operators which are in memory, so y + 6 is an expression.
supported by C are listed in Table 2.3.6. An example of a relational expression is 4 ≠ 4, which
Table 2.3.6 evaluates to false.
In C every expression evaluates to a value i.e., every
Operator Description Example
expression results in some value of a certain type that
sizeof() The sizeof operator will If M is an integer can be assigned to a variable.
return the size of the variable then,
variable as result. sizeof(M); Some examples of expression are shown in the table
This statement will given below.
return the result as 4 o X+Y
or 2 according to the
o 3.14 * r * r
compiler.
o P*p+2*p*q+q*q
& The address operator will If M is an variable
return the address of the &M :
variable as result. This statement will
2.5 PRECEDENCE OF OPERATORS
return the actual
memory location of GQ. Explain Precedence and Associativity. (5 Marks)
the variable M.
Ans. :
* This operator is used as If M=5; and
the pointer to the variable. N = *&M; then Precedence and Associativity
The * will return 5. Precedence
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-26)
Here + and minus operators has same priority. As their Usually the inputs are accepted from user through
associativity is left to right, addition will be performed keyboard (which is an input device) and the output is
first and then subtraction. Hence the result will be 8. given to the user through monitor (which is an output
As shown in the Table 2.5.1 the operators with the device) or file.
highest precedence are listed at the top of the table, and To use Inputs coming from keyboard in the program
those with the lowest are listed at the bottom of the and transfer the outputs of program to monitor, some C
table. library functions are used as given in following
Table 2.5.1 sections.
UQ. Which operator has the lowest priority ?
Category Operator Associativity
(A) ++ (B) % (C) + (D) ||
Postfix () [] -> . ++ - - Left to right MU - May 18, 1 Mark.
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Ans. : (D)
Multiplicative * / % Left to right
Additive +- Left to right 2.7 INBUILT FUNCTIONS
Shift << >> Left to right
Relational < <= > >= Left to right GQ. Enlist different functions provided by C library
for formatting the input and output. (2 Marks)
Equality == != Left to right
Bitwise AND & Left to right Ans. :
Bitwise XOR ^ Left to right Functions for formatting the input and output
Bitwise OR | Left to right Input and output are the processes of accepting data
Logical AND && Left to right from user and displaying the data or result on the
screen.
Logical OR || Left to right
Conditional ?: Right to left C has collection of standard library functions to accept
and display the data.
Assignment = += –= *= /= %=>>= <<= Right to left
&= ^= |= These functions allow C to communicate with
Comma , Left to right hardware means transferring the information from and
to input (e.g. keyboard, mouse) and output (e.g.
Example monitor) devices and computer.
x = 7 + 3 * 2; The stdio.h (Standard input output) header file is used
After the execution of above statement x will hold to perform all these operations.
value 13 and not 20, because * has the highest As mentioned earlier using the pre-processor directive
precedence than +, so 3*2 = 6 and then the 7+6=13 this file can be included in our program.
will be evaluated.
Input Functions
2.6 BASIC INPUT AND OUTPUT Input functions are used to accept the input by user for
OPERATIONS a program. User enters the data through the keyboard;
then input function captures the entered data which can
GQ. What are input and output operations? (2 Marks) be processed in the program.
Ans. : Standard library has following input functions.
o scanf( )
Input and output operations
o getchar( )
In a program, the data given by user is called as input.
o getch( )
On this data some processing is performed and result is
generated which is referred as output of the program. o gets( )
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-27)
The most commonly used input function is the scanf( ) GQ. Explain different format specifiers (3 Marks)
function. The detailed explanation is in next section.
Ans. :
Output Functions
Format specifiers
Output functions are used to print the values of The format specifiers are listed in the Table 2.7.1.
variables on the monitor.
Table 2.7.1
Standard library has following input functions :
Format Use of Format Specifier
o printf( )
Specifier
o putchar( ) %c Reads a single character from user.
o putch( ) %d Reads a decimal integer from user.
o puts( ) %e Reads a floating point value from user.
The most commonly used output function is the %f Reads a floating point value from user.
printf( ) function. The detailed explanation will be in %g Reads a floating point value from user.
next section. %h Reads a short integer from user.
%i Reads a decimal, hexadecimal or octal
2.7.1 scanf() and printf() Functions integer from user.
%o Reads an octal integer from user.
GQ. Write the syntax of scanf() and printf() function. %s Reads a string from user.
(2 Marks) %u Reads an unsigned decimal integer from
user.
Ans. :
%x Reads a hexadecimal integer from user.
scanf() and printf() function
%[..] Reads a string of words from user.
scanf( ) function The data type of variable must be matched with
Use corresponding character group in the format specifier.
Each variable name must be preceded by an ampersand
This function is used to accept any type of data, for
(&).
example : int, float, double, char or set of characters
from user. For example: Consider rno is a variable of type integer
then,
The scanf () function reads input from the stdin
scanf("%d", &rno);
(standard input stream) and then scans that input
This statement accepts an integer value from user and
according to the provided format.
stores it in rno.
Syntax
We can accept more than one inputs using single
scanf("format specifier", &variable_name); scanf() statement as follows :
The format specifier tells the compiler which type of Consider a is a variable of integer type, b is variable of
data should be accepted from user. character type and c is variable of float type then
To accept number of inputs we can use number of scanf(“%d %c %f”, &a,&b,&c);
format specifiers separated by comma (,).
Another way is to use different scanf() functions for
UQ. scanf ( ) function is used to input string having each input as shown below :
multiple words. MU - May 18, 1 Mark. scanf("%d", &a);
scanf("%c", &b);
Ans. : False
scanf("%f", &c);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-28)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-29)
printf("\n Modulo : %d",r); printf("\n\nPress any key to exit.");
getch();
getch(); }
} Output
Output
GQ. Develop an application program to convert and 2.7.2 getchar() and putchar() Functions
print distance between two cities in meters, feet,
inches & centimeters. The distance between two GQ. Explain following functions : getchar() and
cities (In KM) is input through key board.
putchar() with suitable example (3 Marks)
Ans. :
Ans. :
Program to convert distance
getchar() and putchar()
#include <stdio.h>
getchar() function is used to read one character at a
void main() time from standard input. It waits till the key is pressed
{ and then echoes the value on the screen.
getchar() function can be used to read int or char type
float Distance_In_KiloMeters = 0; of data. While reading the input from file, it tries to
float Distance_In_Meters = 0; read beyond the last byte so it returns -1 as the value of
float Distance_In_Feet = 0; EOF (End of File).
float Distance_In_Inches = 0; The drawback with getchar()function is that it buffers
float Distance_In_Centimeters = 0; input until ENTER is pressed.
putchar() function is used for the output. It prints
printf("Enter the distance between write cities in kilometers
character argument on the screen at the current position
: ");
of cursor. It is used for int and char data types only.
scanf("%f", &Distance_In_KiloMeters);
Example
# include<stdio.h> //including header file
Distance_In_Meters = Distance_In_KiloMeters * 1000; int main()
Distance_In_Feet = Distance_In_KiloMeters * 3280.84; {
Distance_In_Inches = Distance_In_KiloMeters * 39370.1; int a= getchar();
Distance_In_Centimeters = Distance_In_KiloMeters * putchar(a);
100000.054; return 0;
}
Output
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-30)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-31)
the number should be integer value. To format the output while displaying single character
on the screen, we use following pattern of format
Formatting output
specifier %ws
We use printf( ) function to format the output. While where ‘w’ is the width of input to be displayed on the
printing the output, different field widths are used screen.
Example while printing the integer numbers Example of printing the strings
The statement For Example if a string “ C Programming ” is stored in
printf(“%2d”,2017); will print str then,
2 0 1 7 C P r o g r a m m i n g
printf(%-4d”, 09); will print
printf(“%s”, str); //will print
0 9 C P r
Suppose a float variable stores 25.331 Then The UQ. What is storage class? Explain extern storage
following statement class with example .
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-32)
{
2.8.1 Automatic Storage Class int x=100; //auto
Automatic variables are allocated memory char y = ‘a’;
automatically at runtime. float z = 123.45;
printf("%d %c %f",x,y,z);
The visibility of the automatic variables is limited to
//printing initialized value of automatic variables x, y, and z.
the block in which they are defined.
getch();
The scope of the automatic variables is limited to the }
block in which they are defined.
Output
The automatic variables are initialized to garbage by
default.
The memory assigned to automatic variables gets freed
upon exiting from the block. This time when the program is executed variables are
The keyword used for defining automatic variables is initialised and program prints the value of the variable
auto. initialised.
Every local variable is automatic in C by default.
2.8.2 Static Storage Class
Example 1
The variables defined as static specifier can hold their
Program to demonstrate auto storage class with value between the multiple function calls.
unitialised variable Static local variables are visible only to the function or
#include <stdio.h> the block in which they are defined.
#include<conio.h>
A same static variable can be declared many times but
void main()
can be assigned at only one time.
{
int x; //auto Default initial value of the static integral variable is 0
char y; otherwise null.
float z; The visibility of the static global variable is limited to
printf("%d %c %f",x,y,z); the file in which it has declared.
//printing initial default value of automatic variables x, y, and The keyword used to define static variable is static.
z.
getch(); Example 1
} Program to demonstrate static key word
Output #include<stdio.h>
#include<conio.h>
static char c;
static int i;
Since the variables are uninitialized program display static float f;
garbage value of the variable. static char s[100];
void main ()
Example 2 {
Program to demonstrate auto storage class with printf("%d %d %f %s",c,i,f);
initialised variable // the initial default value of c, i, and f will be printed.
getch();
#include <stdio.h>
}
#include <conio.h>
void main()
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-33)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-34)
register Inside a CPU Registers Garbage Within the Within the function/block
function/block function/block
extern Outside all Memory Zero Entire the file and program runtime
functions other files where
the variable is
declared as extern
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
Module II
Chapter… 3
Control Structures
University Prescribed New Syllabus w.e.f Academic Year 2019-2020
Control Structures
Introduction to Control Structures
Branching and looping structures
If statement, If-else statement, Nested if-else, else-if Ladder
Switch statement
For loop, While loop, Do while loop
break and continue
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-3)
(5 Marks)
Ans. :
if Statement
Use
“if” is a decision making statement. It is generally used
when we want to check a single condition. If it satisfied we
will execute some code.
if (Condition 1 )
3.2 BRANCHING STRUCTURES {
Statement 1;
}
GQ. Write use of decision making statements.
(1 Mark)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-4)
printf("\n Number is greater than 100");
Flowchart of if statement
}
return 0;
}
Output
Program 3.2.1 When the user enters value less than 100 then nothing
Write a program to accept a number from user and check is executed. This is happens because we have given
whether it is more than 100. statement to execute if the condition satisfies, but if the
condition does not satisfy then what to do? that we do
Soln. : not tell the compiler. This can be done using “else”
Flowchart statement.
Explanation
Here program accepts a number from user
If the number is greater than 100, it will print the
message – “Number is greater than 100”.
If number is less than 100, message will not be printed.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-5)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-6)
Program Soln. :
#include<stdio.h> Flowchart
#include<conio.h>
main()
{
int n;
printf("\n Enter a number : ");
scanf("%d",&n);
Checks whether number is
if(n%2==0) completely divisible by 2.
{
This statement is
printf("\n Number is even");
executed if number is
} exactly divisible by 2.
else Fig. P. 3.2.4 : Flowchart of Program 3.2.4
{
Program
This statement is executed #include<stdio.h>
printf("\n Number is odd"); if number is not exactly
#include<conio.h>
divisible by 2
main()
} {
} int hindi,marathi,english,total,average;
printf("\n Enter a marks of 3 subects : "); Accepts
Output
marks
scanf("%d %d %d",&hindi, from user
&marathi,&english);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-7)
Explanation
Here program marks of 3 subjects from user.
Calculates and prints the total and average of marks.
Program checks whether the average is >= 40 or not
If average is >= 40 it will print “Pass”
If average is not >= 40 it will print “Fail”
Fig. 3.2.4 : Flowchart of else if ladder
3.2.3 else if ladder
Program 3.2.5
UQ. Explain if-else ladder with example. Write a program to accept a number from user and check
MU - Dec. 17, 2 Marks. whether it is positive, negative or zero.
Ans. : else-if ladder OR
Use : The “else if” ladder is used to test set of With suitable example(program), explain how else ... if
conditions in a sequence. It is also considered as multi-way ladder can be used.
decision making statement. Number of conditions are given Soln. : Flowchart
in a sequence with subsequent statements. If any of the
given condition is satisfied then the related statements are
executed and the control exits from the else if ladder. That
means further conditions are not going to be checked. But if
the condition does not satisfy then the compiler goes to next
condition to check the condition.
Syntax of else if ladder
if(Condition 1)
{
Statement 1;
}
else if(Condition 2)
{
Statement 2;
}
---------------- Fig. P. 3.2.5 : Flowchart of Program 3.2.5
else if(Condition n)
{ Program
Statement n; #include<stdio.h>
}
#include<conio.h>
else
main()
{
{
Statement m;
} int n;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-8)
printf("\n Enter a number : "); printf("\n Enter marks marathi, hindi and english : ");
scanf("%d",&n); scanf("%d %d %d",&marathi,&hindi,&english);
if(n>0)
Checks whether n > 0 or not.
{ Accepts marks from user
printf("\n Number is positive"); If condition is true
} then display this total = marathi + hindi + english; Calculate total
message. and average
else if(n<0) average = total / 3;
of marks
{ if(average>=80)
printf("\n Number is negative"); If condition is false {
} then display this printf("\n Grade - A");
message.
else }
{ else if(average>=60)
printf("\n Number is zero"); { If above condition is not
} printf("\n Grade - B"); satisfied instead of that
} } average>= 60 condition is
else if(average>=40) then this message will be
Output displayed
{
printf("\n Grade - C");
If both the above conditions
} are not satisfied and
else average >=40 condition is
satisfied then this message
will be displayed
{
Explanation printf("\n Fail..."); If all of the above conditions are
unsatisfied then this message will
Here program accepts a number from user. } be displayed
}
If the number is greater than 0, it will print the message
Flowchart
– “Number is positive”.
If the number is less than 0, it will print the message –
“Number is negative”.
If both the conditions does not satisfy, it indicates that
the number is zero hence it will print the message –
“Number is zero”.
Program 3.2.6
Write a program to accept marks of 3 subjects from student.
Calculate the total and average of marks. If the average is
>= 80 then give the grade as “A” , if average>= 60 then give
the grade as “B”, if average>= 40 then give the grade as “C”
and below 40 “Fail”.
Soln. : Program
#include<stdio.h>
#include<conio.h>
main()
{
int hindi,marathi,english,total,average; Fig. P. 3.2.6 : Flowchart of Program 3.2.6
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-9)
Output }
else
{
Statement 2;
}
Explanation }
else
Here program accepts marks of 3 subjects from user.
{
If average>= 80 then this
Calculates and prints the total and average of marks. Statement 3; message will be displayed.
If the average is >=80, it will print “Grade – A” }
If the average is >=60, it will print “Grade – B” Program 3.2.7
If the average is >=40, it will print “Grade – C” Write a program to find largest of three numbers using
nested if-else.
If all the given conditions does not satisfy, it indicates
that average is below 40, hence it will print message as
Soln. :
“Fail…”. Flowchart
Use
Writing if statement inside another if is known as
nested if. While checking number of conditions, we may
need to nest if statement inside another if statement.
Flowchart of Nested if else Statement
Program
#include<stdio.h>
#include<conio.h>
main()
{
int n1,n2,n3;
Accepts 3
printf("\n Enter three numbers : ");
numbers
scanf("%d %d %d",&n1,&n2,&n3); from user
if(n1>n2)
{
Fig. 3.2.5
if(n1>n3)
Syntax of nested if else statement {
if(condition 1) printf("\n Max is n1 : %d",n1);
{ } Inner if else block
if(condition 2) else
{ {
Statement 1; printf("\n Max is n3 : %d",n3);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-10)
} Soln. Flowchart
}
else
{
if(n2>n3)
{
printf("\n Max is n2 : %d",n2);
}
else
If n1>n2 and n2>n3
{ both conditions are
printf("\n Max is n3 : %d",n3); unsatisfied then this
message will be
} displayed
}
}
Output
Explanation
Fig. P. 3.2.8 : Flowchart of Program 3.2.8
Here program accepts three numbers from user.
Program
The first number n1 is compared with both n2 and n3,
if it is greater then a message “Max is n1” will be #include<stdio.h>
Includes header files
printed with value of n1. #include<conio.h>
main()
The second number n2 is compared with both n1 and
{
n3, if it is greater, then a message “Max is n2” will be
int hindi,marathi,english,total,average;
printed with value of n2.
printf("\n Enter marks marathi,hindi and english :");
The third number n3 is compared with both n1 and n2, scanf("%d %d %d",&marathi,&hindi, &english);
if it is greater then a message “Max is n3” will be
printed with value of n3. Accepts marks from user
Program 3.2.8
Write a program to accept marks of 3 subjects from student. total = marathi + hindi + english; Calculates total
and average of
Calculate the total and average of marks. If the average average = total / 3; marks
is >= 80 then give the grade as “A”, if average>= 60 then
give the grade as “B”, if average>= 40 then give the grade as if(hindi>=40 && marathi>=40 && english>=40)
“C” and below 40 “Fail”.
Checks whether marks of all subjects are >=40 in all subjects.
Note : Student should get the grade only if the marks of
all the subjects are >=40. {
if(average>=80)
If the condition
{ average >= 80 is satisfied
printf("\n Grade - A"); then this message will be
displayed
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-11)
else if(average>=60) Ans. :
{ If the above condition is
unsatisfied and the condition Switch Statement
printf("\n Grade - B"); average >= 60 is satisfied then
} this message will be displayed In the situation where lots of comparisons are needed,
use of if else statement is bad idea as the number of
else if(average>=40) If both of the above conditions comparisons needs number of if else statements which
{ are unsatisfied and the increases the complexity. Hence C language provides a
condition average >= 40 is
printf("\n Grade - C"); satisfied then this message will
selection statement called as switch statement to deal with
} be displayed. the above situation.
} The switch case is multi way decision making
else statement which helps to select a single option from multiple
{ If all above conditions are given options.
printf("\n Fail..."); unsatisfied, this message will
} be displayed Syntax of switch statement
} switch(expression)
Output {
case constant_expression 1:
Statement 1;
break;
case constant_expression 2:
Explanation Statement 2;
Here program accepts marks of 3 subjects from user. break;
Calculates and prints the total and average of marks. --------------
case constant_expression n:
The program first checks whether marks of all the
Statement n;
subjects are >= 40 or not if not then control directly
break;
goes to the last else statement and print the message
default:
“Fail….”.
Statement m ;
If marks of all the subjects are >= 40 then it checks }
following conditions:
If the average is >=80, it will print “Grade – A”
Expression
It is usually name of a variable value of which we want
If the average is >=60, it will print “Grade – B”
to check.
If the average is >=40, it will print “Grade – C”
Constant_expression
3.2.5 Switch Statement
These are the constant values with the value of
UQ. Explain syntax of switch case? Discuss what is
need of break statement in switch case? expression is compared. The statements in the case are
MU - May 15, 5 Marks. executed, whose value matches with the expression. If none
OR Explain switch case with example. of the constant expression is matched with the expression,
MU - Dec. 17, 2 Marks. then the statement written in default are executed.
Note
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-12)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-13)
Program
#include<stdio.h>
#include<conio.h>
main()
{
int n;
printf("\n Enter a number between 1 to 5 : ");
scanf("%d",&n);
switch(n) Passes the number to switch block to match it with different cases.
{
case 1:
printf("\n One"); Prints if n matches with 1
Explanation
Here program accepts a number from user.
The number is compared with all the cases from 1 to 5.
The statement will be printed where the value match and control transfer outside the switch because of break statement.
If none of the case matches with the value entered by user then message of default case will be printed.
Program 3.2.10
Write a program to accepts a character from user from a/ A to e/E and print the suitable message.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-14)
Soln. : Flowchart
case 'b':
case 'B': Explanation
printf("\n Character is b or B"); Prints if ch matches
Here program accepts an alphabet from user.
with ‘b’ or ‘B’
break;
The alphabet is compared with all the cases from
case 'c':
a to e.
case 'C':
printf("\n Character is c or C"); Prints if ch matches The statement will be printed where the value match
with ‘c’ or ‘C’ and control transfer outside the switch because of
break;
case 'd': break statement.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-15)
Here we have mentioned multiple constant expressions Note : In division case if the second number entered by
for common output. user is zero then print an error message.
For example for ‘e’ or ‘E’ same message will be Program 3.2.11 MU - Dec. 14, 6 Marks.
printed. Write an program to implement calculator with following
operations.
If none of the case matches with the alphabet entered
(i) Add two numbers
by user then message of default case will be printed. (ii) Subtract two numbers.
Program 3.2.11 (iii) Division two numbers
Write a menu driven program which should accepts two (iv) Multiply two numbers.
numbers from user and print the result of addition,
subtraction, multiplication or division as per user’s choice.
Soln. : Flowchart
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-16)
Program Output
#include<stdio.h>
#include<conio.h>
main()
{
int n1,n2,result,choice;
printf("\n--------Menu---------");
printf("\n 1 : Addition"); Accepts user’s
printf("\n 2 : Subtraction"); choice from
printf("\n 3 : Multiplication"); given menu and
store it in
printf("\n 4 : Division"); choice variable. Explanation
printf("\n Select your choice : "); Here we consider that user has entered choice as 1
scanf("%d",&choice); As choice is in the range : 1 to 4
if(choice>= 1 && choice<=4) Two numbers are accepted from user n1 = 10, n2 = 5
{
As choice is 1. case 1 (i.e. addition of n1 and n2) will
printf("\n Enter two numbers :" ); Only if user
choice is in be performed
scanf("%d %d",&n1,&n2);
between 1 to 4 So result = 10 + 5 = 15
} then only two
The result will be displayed.
switch(choice) numbers will be
accepted.
{ 3.2.6 Difference between if else and switch
case 1: Statement
Addition if
result = n1 + n2; choice
printf("\n Addition is %d",result); matches with 1. UQ. Explain difference between switch statement,
break; ladder of if else and nested if else.
case 2: Subtraction if MU - May 13, 6 Marks.
choice
result = n1 - n2; matches Ans. : Differences between if else and switch
printf("\n Subtraction is %d",result); with 2 statement
break; Parameters if else switch case
case 3: Number of curly Multiple curly Single pair of curly
Multiplicatio brackets brackets are used bracket is used.
result = n1 * n2; n if choice Impact on code Code becomes Code does not become
printf("\n Multiplication is %d",result); matches
if no. of complicated when complicated when
with 3.
break; condition conditions conditions increase.
case 4: increases increase
if(n2!=0) Use of break Do not use break Use break statement
statement statement
{
Values used in Tentative values Exact values are
result = n1 / n2; condition can be given in expected in the
printf("\n Division is %d",result); condition condition.
Division if
} choice matches e.g. >=80
else with 4 Syntax if(condition) switch(expression)
{ { {
Statements case const_expr:
printf("\n Cannot divide by zero");
} statements;
} else break
break; { ---
default: If none of the above case is Statements default:
printf("\n Invalid choice"); satisfied then this } statements;
} message will be displayed. }
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-17)
GQ. Write use of looping statements with example. Ans. : Flowchart of while loop
(2 Marks)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-18)
Output {
printf("\n %d",i); Value of i will be printed repeatedly
until the condition satisfies.
i = i + 1;
}
}
Output
Explanation
Here the program will print the message 10 times.
The variable i is known as loop variable which decides
how many times the loop code should be repeated.
The initial value of i is 1. Explanation
After every iteration it is incremented by one. Here by using the same logic of previous program,
except the message we are printing the value of loop
When the value of i becomes 11, the condition
variable itself.
becomes false and compiler does not go inside the loop
The initial value of loop variable i is 1 which
again. Up till then the message is printed 10 times.
increments upto 10
Program 3.3.2
The compiler comes out of the loop when value
Write a program to print 1 to 10 numbers. becomes 11.
Soln. : Flowchart Program 3.3.3
Write a program to accept a number from user and print
factorial of it.
e.g. Factorial of 5 is calculated as : = 5*4*3*2*1 = 120
Soln. : Flowchart
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-19)
Explanation
Here we accept a number, for which factorial is to be
calculated from user and store it in the variable n.
The initial value of f is 1 (In f final result will be
stored).
The f is multiplied by n and result is stored in f itself.
This process is repeated until n becomes zero
Following code shows the updating values of f and n.
Iteration 1 : (5>0) is true so
f=1 & n=5
f = 1*5 = 5
n = 5-1 = 4
Iteration 2 : (4>0) is true so Fig. P. 3.3.4 : Flowchart of Program 3.3.4
f=5 & n=4 Program
f = 5*4 = 20 #include<stdio.h>
n = 4-1 = 3 #include<conio.h>
Iteration 3 : (3>0) is true so main()
{
f=20 & n=3
int n,i,flag; flag is a conventional variable which is
f = 20*3 = 60 i=2; used here to check whether number is prime
or not . Here initially it is set to 0.
n = 3-1 = 2 flag = 0;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-20)
printf("\n Enter a number : "); Iteration 2 : now flag=0, n= 11 and i=3
scanf("%d",&n);
(3<=5) is true so
while(i<=n/2)
{ (2==0) is false so it will skip statements
if(n%i==0) Until value of i becomes half of the in if block
{ number, the loop statements will be
i = 3+1 = 4
repeated. It checks whether given
flag = 1; number is divisible by any other Iteration 3 : now flag=0, n= 11 and i=4
break; number If yes the flag is set to 1.
} (4<=5) is true so
i = i + 1; (3==0) is false so it will skip statements
} in if block
if initial value
if(flag==0) of flag (i.e. 0) i=4+1=5
printf("\n Number is prime"); remains same
else then it will be a Iteration 4 : now flag=0, n= 11 and i=5
prime number
printf("\n Number is not prime"); otherwise the (5<=5) is true so
number will not (1==0) is false so it will skip statements
be prime.
in if block
}
i=5+1=6
Output
Iteration 5 : now flag=0, n= 11 and i=6
(6<=5) is false so it exits the while loop and goes to the
next statement after while block.
(flag == 0) is true so it will print Number is prime
Program 3.3.5
Explanation
Write a program to take input as a number and reverse it by
Here we accepts a number from user and store it in the using while loop.
variable n.
Soln. : Flowchart
Now starting from 2(variable i), the n is divided by all
the numbers through which it may be divisible
completely.
If by any of the number the n is divisible, the value of
flag is updated to 1 and control exits from the loop
because of break statement.
As flag becomes 1, message of non prime is printed.
If by any of the number the n is not divisible, the value
of flag remains 0.
As flag remains 0, message of prime is printed.
Here flag=0, n= 11 and i=2
Iteration 1 : now flag=0, n= 11 and i=2
(2<=5) is true so
(1==0) is false so it will skip statements
in if block
i = 2+1 = 3 Fig. P. 3.3.5 : Flowchart of Program 3.3.5
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-21)
Explanation
Here we accepts the number and store it in variable n.
We divide the number by 10, calculate the remainder
and print it.
Then the number is divided by 10 to get the division
result.
Every time we get the last digit as remainder which we
print.
Ultimately the number is printed in reverse order.
See the updated values of n and rem by considering the
initial value of n as 123
Iteration 1 : now n= 123
(123>0) is true so
rem = n%10 = 123%10 = 3
Prints value of rem Fig. P. 3.3.6 : Flowchart of Program 3.3.6
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-22)
Explanation
Here we accepts the number and store it in variable n,
and initialize sum = 0
We divide the number by 10, calculate the remainder.
Add the remainder to sum.
We calculate the quotient of the division and assign it
to n.
Every time we get the last digit as remainder which we
add to sum until the value of n becomes 0.
After calculating sum of digits we print the result.
See the updated values of n, sum and rem by
considering the initial value of n as 123
Fig. P. 3.3.7 : Flowchart of Program 3.3.7
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-23)
Explanation
The remainder logic is same as of previous programs.
The value of n becomes zero at the end of loop hence
we store it initially in the variable n1.
And n1 is compared with the sum.
See the updated values of n, sum and rem by
considering the initial value of n as 153
Iteration 1 : now n= 153 and n1 = 153
(153>0) is true so
rem = n%10 = 153%10 = 3
sum = sum + (rem*rem*rem) = 0+(3*3*3) = 0+27 = 27
n= n/10 = 153/10 = 15 Fig. P. 3.3.8 : Flowchart of Program 3.3.8
Iteration 2 : now n= 15 and sum= 27
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-24)
Explanation
Here the accepted number n is divided by all the
numbers from 1 by which it may be divisible.
All the numbers by which n is divisible are added in
sum.
After completion of loop, the value of sum is compared
with n.
If n and sum are equal, number is Perfect else not.
See the updated values of n, sum and i by considering
the initial value of n as 153
Iteration 1 : now n = 6, i = 1, sum = 0
(1<=3) is true so
(6%1 ==0) is true so
sum = sum +i = 0+1 = 1
Fig. P. 3.3.9 : Flowchart of Program 3.3.9
i= i+1 = 1+1 = 2
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-25)
Flowchart
Explanation
See the updated values of n, reverse_no, rem and
original_no by considering the initial value of n as 121
while( n!= 0) n reverse_no rem original_no
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-26)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-27)
Soln. :
Flowchart
Explanation
Here the default value of variable ch is kept as ‘y’.
At the end of iteration, program asks user for
continuity. The answer is stored in ch. If it is ‘y’ then
the process is repeated.
Program 3.3.13 MU - May 13, 6 Marks.
Write a program to display Armstrong numbers between 1
to 1000.
Soln. :
#include <stdio.h>
main()
{
int number, temp, digit1, digit2, digit3;
printf("Print all Armstrong numbers between 1 and
1000:\n");
number = 001;
Fig. P. 3.3.12 : Flowchart of Program 3.3.12 while (number <= 900)
{
Program digit1 = number - ((number / 10) * 10);
#include<stdio.h> digit2 = (number / 10) - ((number / 100) * 10);
#include<conio.h> digit3 = (number / 100) - ((number / 1000) * 10);
main() temp = (digit1 * digit1 * digit1) + (digit2 * digit2 *
{ digit2) + (digit3 * digit3 * digit3);
int n,cube; if (temp == number)
{
char ch = 'y';
printf("\n %d", temp);
while(ch=='y')
}
{ number++;
printf("\n Enter a number : "); }
scanf("%d",&n); }
cube = n * n * n; Output
printf(" Cube is %d",cube);
printf("\n\n Do u want to continue?(y/n) : ");
scanf("%s",&ch);
}
If user enter ‘y’ for continuity then loop will be repeated.
getch();
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-28)
UQ. Write a program to find GCD and LCM of 2 nos. int decimalnum, rem, temp = 1;
MU - Dec. 14, 6 Marks. long binarynum = 0;
printf("Enter a Decimal Number: ");
Ans. : scanf("%d", &decimalnum);
#include <stdio.h> while (decimalnum!=0)
main() {
{ rem = decimalnum%2;
int num1, num2, gcd, lcm, remainder, numerator, decimalnum = decimalnum / 2;
denominator;
binarynum = binarynum + rem*temp;
printf("Enter two numbers : ");
temp = temp * 10;
scanf("%d %d", &num1, &num2);
if (num1 > num2) }
{ printf("Equivalent Binary Number is: %ld", binarynum);
numerator = num1; }
denominator = num2; Output:
}
else
{
numerator = num2;
denominator = num1;
} 3.3.2 do while Loop
remainder = numerator % denominator;
while (remainder != 0) GQ. Explain do while loop with syntax and flowchart.
{ (5 Marks)
numerator = denominator;
denominator = remainder;
Ans. : do while loop
remainder = numerator % denominator; The do while loop is exit controlled loop. That is the
} condition is checked at the end of loop.
gcd = denominator; Hence even if the condition does not satisfy, the loop
lcm = num1 * num2 / gcd;
statements will be executed at least once.
printf("GCD of %d and %d = %d\n", num1, num2, gcd);
printf("LCM of %d and %d = %d\n", num1, num2, lcm); Syntax of do while loop
} do
Output {
Statement 1;
}while(condition 1);
Flowchart
Ans. :
#include<stdio.h>
int main()
{ Fig. 3.3.3 : Flowchart of do while loop
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-29)
Soln. :
Flowchart
Explanation
Here the default value of variable ch is not set as ‘y’.
Even then the first iteration is done without checking
any condition.
From second iteration ,condition will get checked, If
user enters y for continuity then only the loop will be
repeated.
Program 3.3.15
Write a program to print Fibonacci series.
Soln. :
Flowchart
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-30)
b = c;
i = i + 1;
}while(i<5);
Fig. P. 3.3.16 : Flowchart of Program 3.3.16
}
Program
Output
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
Explanation i = 1;
printf(“\n Enter value for n : “);
See the updated values of n, rem and count by
scanf(“%d”,&n);
considering the initial value of n as 135.
do
while( i < 5) i a b c O/P on screen {
if(i%2==0) Checks whether i is even?
Initially 112 - 12
printf(“ %d ”,i); If yes prints value of i
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-31)
Program
#include<stdio.h>
Flowchart
#include<conio.h>
main()
{
int i,n,sum,avg;
i = 1;
sum = 0;
do{
printf(“\n Enter number : “);
scanf(“%d”,&n); Accepts a number from user
sum = sum + n; and adds it to the sum.
i++;
}while(i<=10); 10 times loop will be executed.
avg = sum / 10;
printf(“\n Average is %d”,avg);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-32)
while( i <= 10) n sum i Use : In for loop the initialization, condition and
increment or decrement of loop variable is implemented in a
Initially - 0 1 single statement. This loop is basically used to minimize the
Iteration 1 while(1<= 10)is true 1 0+1=1 2 code.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-33)
Program 3.3.20
Write a program to accept a number from user and print
Fig. P. 3.3.19 : Flowchart of Program 3.3.19 factorial of it.
Program OR Write a program to find factorial of a number using for
#include<stdio.h> loop. (n = 10)
#include<conio.h> Soln. :
Flowchart
main()
{
int i;
Explanation
The updated values of i, sum and n are given in
following table :
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-34)
Explanation
Here at the initialization we have kept nothing. Such
code is allowed.
3.3.4 Nested Loops
The updated values of fact and n are given in following GQ. Give syntax and flowchart of nested loops.
table: (5 Marks)
( n > 0) Fact n
Ans. :
Initially 1 10
Nested Loops
Iteration 1 (10 > 0)is true 1 * 10 = 10 9
Iteration 2 (9 > 0)is true 10 * 9 = 90 8 Writing a loop inside another loop is known as nested
loop
Iteration 3 (8 > 0)is true 90 * 8 = 720 7
Iteration 4 (7 > 0)is true 720 * 7 = 5040 6 Syntax
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-35)
for(i=1;i<=5;i++)
Outer loop Initially, i = 1 so 1 <= 5 is true
{
And j = 1 so 1 <=1 is true so one * is printed as shown
for(j=1;j<=i;j++)
below:
{
Inner loop *
printf("* ");
}
printf("\n");
}
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-36)
Then j is incremented therefore 2 <= 1 is false and Then j is incremented therefore 5 <= 4 is false and
control goes out from inner loop and cursor goes to the next control goes out from inner loop and cursor goes to the next
line due to printf (“\n”) statement. line due to printf (“\n”) statement
The i is incremented therefore 2 <= 5 is true.
The i is incremented therefore 5 <= 5 is true
And j = 1 so 1 <=2 is true so one * is printed as shown
And again the inner loop will be executed 5 times as
below:
j = 1 to 5 and it will print 4 * as shown below:
*
*
*
* *
* * *
* * * *
* * * * *
Then j is incremented therefore 2 <= 2 is tru e so one *
Then j is incremented therefore 6 <= 5 is false and
is printed as shown below:
control goes out from inner loop and cursor goes to the next
*
line due to printf (“\n”) statement
* *
The i is incremented therefore 6 <= 5 is false and
control goes out from outer loop.
The pattern is printed.
Program 3.3.22
Then j is incremented therefore 3 <= 2 is false and
Write a program to print following pattern
control goes out from inner loop and cursor goes to the next 1
line due to printf (“\n”) statement 12
The i is incremented therefore 3 <= 5 is true 123
And again the inner loop will be executed 3 times as 1234
12345
j = 1 to 3 and it will print 3 * as shown below.
* Soln. : Program
* * #include<stdio.h>
#include<conio.h>
* * *
main()
{
int i,j;
Then j is incremented therefore 4 <= 3 is false and
5 times outer loop will
control goes out from inner loop and cursor goes to the next for(i=1;i<=5;i++) be executed
line due to printf (“\n”) statement {
The i is incremented therefore 4 <= 5 is true
Loop will executes until j
And again the inner loop will be executed 4 times as for(j=1;j<=i;j++) becomes equal to i
j = 1 to 4 and it will print 4 * as shown below: {
*
printf("%d ",j); Prints the value of j
* *
}
* * *
printf("\n"); Cursor goes to next line
* * * * }
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-37)
1 2
1 2
1 2 3
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-38)
1 2
1 2 3
1 2 3 4
1 2
1 2 3
1 2 3 4
4444
printf("%d ",i); Prints the value of i
55555
}
printf("\n"); Cursor goes to next line
}
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-39)
Here the outer loop is used for rows ( i ) and inner loop The i is incremented therefore 3 <= 5 is true.
is used for columns ( j ). And again the inner loop will be executed 3 times as
j = 1 to 3 and it will print value of i (i.e. 3) 3 times as
shown below.
1
2 2
3 3 3
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-40)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-41)
* * * * {
count = 0;
* * *
for (i = 2; i <= Number/2; i++)
{
if(Number%i == 0)
Then j is incremented therefore 4 <= 3 is false and {
control goes out from inner loop and cursor goes to the next count++;
line due to printf (“\n”) statement break;
The i is decremented therefore 2 >= 1 is true }
}
And again the inner loop will be executed 2 times as
if(count == 0 && Number != 1 )
j = 1 to 2 and it will print 2 * as shown below.
{
* * * * printf("\n %d ", Number);
* * * }
* * }
return 0;
}
Then j is incremented therefore 3 <= 2 is false and
Output
control goes out from inner loop and cursor goes to the next
line due to printf (“\n”) statement
The i is decremented therefore 1 >= 1 is true
And again the inner loop will be executed once as j = 1
and 1<= 1 it will print one * as shown below.
* * * *
* * *
* *
*
Then j is incremented therefore 2 <= 1 is false and
control goes out from inner loop and cursor goes to the next
line due to printf (“\n”) statement
The variable i is decremented therefore 0 >= 1 is false
and control goes out from outer loop.
The pattern is printed.
Soln.
#include <stdio.h>
int main()
{
int i, Number, count;
printf(" Prime Number from 1 to 100 are: \n");
for(Number = 1; Number <= 100; Number++)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-42)
A B C D E Output
Soln.
#include<stdio.h>
int main() {
int i, j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%c ",'A' + j-1); UQ. Write a program to generate following patterns.
} 1
printf("\n"); 23
} 456
} 7 8 9 10 MU - May 14, 5 Marks.
Output
Ans. :
#include<stdio.h>
int main() {
int i,j, k=1;
for(i=1;i<=5;i++)
{
for(j=1;j<i;j++)
{
printf("%d ",k);
GQ. Write a program to generate following patterns.
k++;
5
}
4 4
printf("\n");
3 3 3
}
2 2 2 2
return 0;
1 1 1 1 1
}
Ans. : UQ. Write a program to calculate summation of
#include<stdio.h> series. 1/2 – 3/4 + 5/6 – 7/8 + …….. upto n terms.
int main() {
MU - May 14, 10 Marks.
int a, i;
for(a = 5; a >= 1; a--)
{
for(i = a;i <= 5;i++)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-43)
#include<stdio.h> ABCD
int i,j,n; AB
}
for (i=1; i <=4; i++)
Output {
for (j=1; j <=i-1; j++)
{
printf (" ");
}
UQ. Write a program to print the following pattern. for (j=1; j <=5-i; j++)
Note : Not only 4 lines, it should print n lines taken {
from user printf ("%c",(char)(j+64));
}
A printf ("\n");
B B }
C C C
}
D D D D MU - Dec. 14, 8 Marks.
UQ. Write a Program to calculate summation of
Ans. : series. 1 – x2/2! + x4/4! – x6/6! + x8/8! upto n
#include<stdio.h> terms. MU - Dec. 15, May 16, 10 Marks.
int main() {
int i,j;
Soln.
#include<stdio.h>
for(i='A';i<'E';i++)
{
int main()
for(j='A';j<=i;j++)
{
{
printf("%c ",i);
int counter,f_coun;
}
float sum=0,x,power,fact;
printf("\n");
}
printf("\nEQUATION SERIES : 1- X^2/2! + X^4/4! -
}
X^6/6! + X^8/8! - X^10/10!");
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-44)
for(space=1; space <= rows-i; ++space)
for(counter=0, power=0; power<=10; {
counter++,power=power+2) printf(" ");
{ ++count; //increment count after each space
fact=1; }
//Factorial of POWER value.
for(f_coun=power; f_coun>=1; f_coun--) //after printing all spaces, let's start number printing loop
fact *= f_coun; // here while loop is used and it will print unless
//The main equation for sum of series is... //k is not euqal to 2*CurrentRow-1
sum=sum+(pow(-1,counter)*(pow(x,power)/fact)); while(k != 2*i-1)
} {
//Now, looking at pattern formula is to print
printf("\nSUM : %f",sum); I(CurrentRow)+ Current K
// if Count is less than TotalRow -1
} if (count <= rows-1)
Output: {
printf("%d ", i+k);
++count;
}
else
{
UQ. Generate the following pattern of digits using ++count1;
nested loops. printf("%d ", (i+k-2*count1));
1 }
++k;
232
}
34543 //reset all values to 0,except CurrentRow value and total
row value
4567654 MU - Dec. 15, Dec. 17, 5 Marks.
count1 = count = k = 0;
Soln. printf("\n");
#include<stdio.h> }
return 0;
int main()
{ }
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-45)
Soln.
int main()
#include<stdio.h>
{
int main()
int n,i,j,m=65,k=64;
{
n = 5;
int n,i;
for(i=1;i<=n;i++)
int sum=0;
{
printf("Enter the n i.e. max values of series: ");
k=k+i;
scanf("%d",&n);
m=k;
sum = (n * (n + 1)) / 2;
for(j=0;j<=n-i;j++)
printf("Sum of the series: ");
printf(" ");
for (i =1;i <= n;i++) {
for(j=1;j<=i;j++)
if (i!=n)
printf("%c", m--);
printf("%d + ",i); else
printf("\n");
printf("%d = %d ",i,sum);
}
}
}
return 0;
UQ. Write a program to generate following pattern. }
5 Output
54
543
5432
54321 MU - May 17, 5 Marks.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-46)
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
If i is equal to 5 then
break; Exit from loop
printf(" %d ",i);
}
}
Output
Program 3.3.25
come out of the loop because of break statement.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-47)
Explanation
Continue does not mean continue the next code.
The continue statement sets the control at the
beginning of loop and the statements below the
Fig. 3.3.6 : Flowchart of continue statement
continue statements does not execute for the particular
Program 3.3.26
Write a program to demonstrate use of continue statement. condition.
OR Give example use of continue statement. In this example the when the value of i becomes 5, the
Soln. : Flowchart printf statement which is below continue will not
execute.
Hence except 5 all the numbers from 1 to 10 will be
printed.
Fig. P. 3.3.26 : Flowchart of Program 3.3.26 working break statement terminates continue statement does not
the execution process for terminate the execution
Program given condition. process , rather it skips the
#include<stdio.h> statements which appears
#include<conio.h> after it for particular
condition.
main()
{ Program When break statement When continue statement
int i; Control appears, the control goes appears, the control goes at
out of the switch or loop the beginning of loop
for(i=1;i<=10;i++)
Chapter Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
Module III
Chapter… 4
Functions
Introduction to functions
Function prototype, Function definition, Accessing a function and parameter passing.
Recursion.
(i) Floor( ) (ii) ceil( ) (iii) sqrt( ) MU - May 13, 3 Marks. ............................................................................ 4-12
OR. State any 2 library functions in math.h along with its uses. MU - Dec. 13, 4 Marks. ................................... 4-12
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-2)
OR Explain pow(), abs() and ceil() function.MU - Dec. 15, 3 Marks. ................................................................... 4-12
Using formula A=P(1+R/100)^n, where P=Principal Amt., R is Rate of interest, n = number of years. Your
program should make use of user defined function to calculate power. Program should accept P, R and N,
Display interest earned for each year.MU - May 16, 10 Marks...................................................................... 4-17
UQ. Write a menu driven program to perform arithmetic operations on two integers. The menu should be repeated
until the user selects 'STOP' option. Program should have independent user defined function for each case.
MU - May 17, 10 Marks. ................................................................................................................................ 4-18
OR What do you mean by recursion ? MU - Dec. 13, May 14, Dec. 15, May 16, Dec. 18, 2 Marks. ................. 4-20
UQ. What are advantages of recursion? MU - May 17, 2 Marks. ......................................................................... 4-20
UQ. What are disadvantages of recursion? MU - May 17, 2 Marks ..................................................................... 4-20
UQ. Write a recursive program to calculate factorial of accepted number. MU - May 13, 6 Marks. ..................... 4-20
UQ. Write a program to display Fibonacci series using recursion. MU - May 13, 6 Marks. ................................ 4-21
OR Write a program using function to print first ‘n’ numbers in Fibonacci series.
UQ. Write a program which will add first n natural numbers using recursion MU - Dec. 15, 8 Marks. ................ 4-23
UQ. Write a program to reverse a number using recursion. MU - May 16, 8 Marks. ........................................... 4-23
y
UQ. Write a program to find x using recursion MU - Dec. 18, 4 Marks. ............................................................... 4-24
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-3)
1. Return_type
4.1 INTRODUCTION TO FUNCTIONS
A function may or may not return a value. The return
type is the data type of the value which the function
GQ. What is a function? (2 Marks)
returns. By default a function returns integer value so
Ans. : Function the return type is int by default. If a function doesn’t
Function is a block of code which is defined to return any value, then the return type will be void.
perform specific task repeatedly. Set of functions are 2. Function_name
combined to form a program. It is compulsory and it indicates the name of the
Function concept provides the feature of reusability, function. Function name is any valid C identifier.
means a function once defined can be called any Function name starts with a letter or underscore and
number of times repeatedly. then followed by any combination of letters, digits or
Function minimizes the code of a program. underscores. Function name doesn’t allow space
character.
4.1.1 Function Definition / Elements of
3. List of formal parameters
Function
The formal parameter list is optional, it may be present
GQ. How to define a function? Explain function or absent depending on the need of the function.
elements. (10 Marks) Formal parameter list declares the variables which hold
the values sent by calling function. The formal
Ans. : parameters in the list are separated by comma and are
Elements of function enclosed in parentheses. The list consists of type of the
In C programming a function definition will have parameters and name of the parameters.
following six elements. The function signature is formed by the function name
These elements are combined into two parts: and the list of formal parameters. Here order, type and
i. Function header: Function header is made-up of the number of the formal parameters matters.
return type, function name, and list of formal 4. Function Body
parameters enclosed in parentheses (element 1, 2 and The function body includes a set of statements that
3). define operation of the function. Function body is
ii. Function body : Function body consists of local enclosed in { and } braces. It consists of three parts:
variables declaration statements, function statements, o Declaration of local variables needed by function.
and a return statement (element 4, 5 and 6).
o Executable statements that performs task of
function.
o Returned value as the output of function.
Local variables are variables that are defined within
function and are accessible only in that function
and cannot be used outside the functions.
The return statement returns the expression or the
value needed. Absence of the return statement in
function body indicates that no value is being returned
to the calling function.
Fig. 4.1.1 : Elements of function
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-4)
Syntax of function These elements are same as of the function header in
The syntax of the function is as follows. function definition.
return_type Function_name(list of formal parameters) It is possible to have different parameter names in
{ function prototype from the names present in the
local variable declaration ; function definition.
statement 1; But it is mandatory to match return type in function
statement 2; prototype with return type in function definition.
……
Also type, order, and number of the formal parameters
……
of list in function prototype should match with type,
return statement;
order and number of formal parameters in function
}
definition.
Example of function
Function declaration is done in global section i.e. after
int div(int a, int b) including the header files and above all the functions
Function header
{ including main ().
int result;
Globally declared functions are available to all the
if (b == 0)
functions in the program. Also we can declare a
printf(“Error ! can’t divided by zero”); Function
body function inside a function this is called local
else
declaration so its life is limited to the function in which
result = a / b;
it is declared. It is better to place function prototype in
return result;
global section.
}
Example of function declaration
Here div is the function name. It performs division.
div returns an integer value. The result is local #include <stdio.h>
variable. The variables a and b are two parameters of #include<conio.h>
div. a and b are called as formal parameters. int div (int a, int b); Function prototype
int main()
C function can take any number of formal parameters
{
but it can return at most one value per call.
………
The function is called in two ways as Call by Value ………
and Call by Reference. }
4.1.2 Function Prototype If return type is absent then it is assumed that the
GQ. Explain with the proper syntax Function function returns int value. Parameter names are
prototype (5Marks) optional in function prototyping. We can declare
function div in following way:
Ans. : Function Prototype
int div (int a, int b);
Same as of variable, before using a function in
or
program it can be declared. The declaration of function
div (int a, int b);
is called as function prototyping.
or
The function declaration follows following format.
div (int, int);
return_type function_name(list of formal parameters);
These all declarations are valid.
Function declaration also referred as function
prototype. It has four parts as listed. The prototype of a function which doesn’t accept any
1. Return_type 2. Function_name parameters and doesn’t return any value is written as
follows:
3. List of formal parameters
void add(void);
4. Semicolon
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-5)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-6)
It doesn’t matter in which order the m, n, o and p are Four categories of function
passed after encountering this function call. but order
of passing parameters matters a lot for certain
examples like following:
Power(x,y);
Ans. :
Fig. 4.2.1 : Functions in C
Advantages of Function
Instead of writing all the code in main ( ) function itself 4.2.1 Function with no Return Type and no
Argument
it is easy to write code into small functions according
to their functionalities. GQ. Explain No-Argument-No-Return-Value function
As the huge code is divided into functions it is easy to type with example. (2 Marks)
read, debug, test, maintain, and modify the function
Ans. : No-Argument-No-Return-Value function
individually.
When a function does not have any argument, we use
Top down manner is followed while calling the
void in the parenthesis.
functions. First main ( ) function gets called and then
according to the order in which functions are called When the function doesn’t return any value void is
execution is done. written at the place of return type.
Code reusability is achieved by defining the function. So general form of declaring the function with no
Any number of times the block of code with different return type and no arguments is given below :
values can be called. Syntax
Also length of program gets reduced as function void function_name (void);
defined only once and later whenever required can be To call the function with no return type and no
called any number of times. arguments following format is used:
C allows us to use library functions and also allows function_name ( );
extending the standard library functions by adding user An empty parenthesis indicates that the function call
defined functions into C library. So that the functions doesn’t pass any parameter.
can be used by other programs.
GQ. Write a program to demonstrate the function
without return type and without arguments.
4.2 TYPES OF FUNCTION (4 Marks)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-7)
Example
1
message(); For example, if prototype of function is like:
void sum(int a, int b, int c);
printf("\nAfter function call\n");
Following all are the valid function calls
return 1;
1. sum(5,10,20);
}
void message (void) 2
2. int x=5, y=10, z=20;
{
sum(x,y,z);
printf("\nFunction with no return type
and no arguments\n");
} 3. sum(x,y,20);
Output
4. sum(x+5,y-5,z);
All are valid because the function sum( ) has three
arguments of type integer. We can pass the constants
(as shown in 1.), variables(as shown in 2.),
expressions(as shown in 4.), or any combination of
these(as shown in 3.) as function arguments.
Explanation When expressions are used as function arguments then,
Here function message doesn’t accept any argument first the expression is solved and corresponding result
from calling function. is passed and mapped with formal parameters. As
shown above first argument of sum will be
And also doesn’t return any value to calling function.
x+5=5+5=10, second argument of sum will be y-5=10-
The } brace of message() denotes the end of function
5=5, and third is z i.e. 20 is passed.
and returns the control back to main().
4.2.2 Function with Arguments and no GQ. Write a program to demonstrate the function
Return Type without return type but with argument. (4 Marks)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-8)
Explanation then, the following all are the valid function calls
1. int result= mul();
When the main( ) function calls cube( ) function the
2. printf(“%d”, mul());
value of num i.e. 5 is copied into formal parameter a and
z = 5 + mul();
the control goes to the cube( ) function. After executing the
printf( ) statement the control goes back to calling function. We can use a variable to store value returned by the
Note that cube( ) function’s return type is void because it function (as shown in 1.), or without creating new
doesn’t want to return any value. The closing brace of cube variable we can print the returned value (as shown in
( ) function indicates the end of the function so the control 2.) by taking the function call as argument of printf()
goes back to the calling function and continues execution of function. The function call can be used in an
main(). expression (as shown in 3.) The return value of the
function acts as the operand of expression.
4.2.3 Function with Return Type and no GQ. Write a program to demonstrate the function
Arguments with return type but no arguments. ( 5 Marks)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-9)
Output result= sub(x, y);
3. printf(“%d”, sub(x,y+1));
4. z = 5 + sub(2,y);
We can use a variable to store value returned by the
function (as shown in 1,2).
Explanation The arguments of function can be constants (as shown
The square() function returns an integer value so at in 1.), variables (as shown in 2.), of expressions (as
calling location, result variable is used to store the shown in 3.).
returned value. Another way is to call the function with return type and
When the main() function calls square() function the arguments is shown in 3 where the value is printed
control goes to the square() function, calculates the directly by passing the function call as argument to
square and return the result back to the calling printf() function.
function.
The function call can be used in an expression (as
4.2.4 Function with Return Type and with shown in 4.) The returned value of the function acts as
the operand of expression.
Arguments
GQ. Write a program to calculate result of the
GQ. Explain With-Argument-with-Return-Value 4 -3
expression z = x + y + 3 using function with
function type with example. (5 Marks) return type and with arguments. ( 5 Marks)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-10)
else Different Header Files and its Library Functions
{
Calculates the negative powers. Some of the frequently used header files are: conio.h,
while (p++) At second call to pow() p is 4 stdio.h, stdlib.h, math.h, string.h, time.h, etc.
{ so if block will be executed.
result/=n; GQ. Explain library functions under conio.h header
} file. (5 Marks)
Returns the control back to
} main() function with value of Ans. :
return result; result .
Functions under conio.h Header File
}
conio.h file includes the functions related to console.
Output
Some frequently used functions of them are explained
below.
clrscr()
clrscr() clears the old text of output window and places
the cursor in the upper left corner of the window (at
position 1,1).
Explanation Declaration
Ans. : Library functions Writes a string to the current text window on the screen
C has huge set of library functions which makes the C and puts the cursor after the string.
more powerful. These functions grouped under Declaration
different header files. int cputs(const char *str);
To use these library functions, header files should be
GQ. Differentiate between getch() and getche()
included in the program. As we know every c program
(2 Marks)
has a section called as header file section where the
required header files are included.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-11)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-12)
tolower()
printf("\nupper: %s",string);
It converts the character to lowercase.
return 0;
toupper() }
It converts the character to uppercase. Output
isalpha()
It checks whether the character is letter.
isdigit()
It checks whether the character is digit.
Explanation
islower()
tolower() function converts a character into lowercase,
It checks whether the character is in lowercase.
so to convert a string, for loop is used here, the loop
isupper() will execute until the value of i is less than the length
It checks whether the character is in uppercase. of string. If block is used to convert uppercase
characters into lowercase
GQ. Write a program to convert a string from lower
to upper and vice versa using library functions.
toupper() function accepts single character and
performs conversion.
Ans. : Program But here character is converted into uppercase and to
#include<string.h> convert all the characters in the string for loop is used.
#include<stdio.h> The loop will execute until value of i is less than length
#include<ctype.h> of string.
int main(void)
If block is used to convert only lowercase characters
{ into uppercase
int length, i;
char string[20] = "THIS IS A STRING."; GQ. List any five library functions under math.h
header file. (2 Marks)
length = strlen(string);
Ans. :
for (i = 0; i < length; i++) Functions under math.h header file
{
Mathematics related functions are contained by math.h
if ((string[i] >= 'A') && (string[i] <= 'Z'))
header file.
{
Some of the frequently used functions are: sqrt(),
string[i] = tolower(string[i]);
ceil(), floor(), log(), log10(), abs(), cos(), sin(), tan(),
}
pow(), sqrt(),etc.
}
Converts string to lowercase by using
UQ. Explain the purpose of following standard library
tolower() character by character
printf("lower: %s",string); functions :
for (i = 0; i < length; i++)
(i) Floor( ) (ii) ceil( ) (iii) sqrt( )
{
Converts string to MU - May 13, 3 Marks.
if ((string[i] >= 'a') uppercase by
&& (string[i] <= 'z')) using toupper() OR. State any 2 library functions in math.h along with
{ character by
its uses. MU - Dec. 13, 4 Marks.
character
string[i] = toupper(string[i]);
OR Explain pow(), abs() and ceil() function.
}
} MU - Dec. 15, 3 Marks.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-13)
Ans. : Program
result= labs(x); labs() returns absolute
value of a long number
#include <stdlib.h>
#include <stdio.h>
printf("%ld is the absolute value of long: %ld\n", result,x); #include <string.h> swab() swaps
double number = 625.54; char source[25] = "wSpat ehS rtni g"; the bytes here it
double down, up; char target[25]; swaps the
floor() will round down source string
the number i.e. 5.8
int main(void) and store it into
down = floor(number); becomes 5.03 { target
swab(source, target, strlen(source));
ceil() will round up the number
printf("This is target: %s\n", target);
up = ceil(number); i.e. 5.8 becomes 6.0. return 0;
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-14)
Output Explanation
For loop is used to call the rand() 5 times
rand() is a library function which is used to print the
random values
Explanation
GQ. Explain any two library functions under time.h
swab() function accepts three arguments as source header file. (5 Marks)
string, target string and length of source string.
Here strlen() is used to find the length of source which
Ans. : Functions under time.h Header File
is 16. Swaps the source string as follows and store it in time.h includes functions which manipulates the
target string : System time. It also contains functions which format the
time while printing on the screen. Some of them are as
follows :
ctime()
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-15)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-16)
int sub(int a,int b) GQ. Write a function to calculate area of a circle.
{
(4 Marks)
return a-b;
} Ans. :
Output Program
#include <string.h>
#include <stdio.h>
float area(float);
int main(void)
{
float r;
printf("\nEnter radious of circle:\n");
scanf("%f",&r);
Explanation
printf("Area of the circle is :\t%5.2f",area(r));
Accepts value of a and b from user i.e. a=10 and b=5
return 0;
main() }
a b result float area(float r)
10 5 add(10,5) {
---
result=add(10,5) a b return r*r*3.14;
}
10 5
So result =15 Returns 10+5 =15 Output
Prints result i.e. 15
sub(10,5)
result=sub(10,5) a b
10 5
Returns 10-5 =5
Explanation
So result =5
Here main() accepts radius from user i.e. 5
Prints result i.e. 5
mul(10,5) Pass it to area() as its argument.
result= mul (10,5) a b area(r) will suspend the execution of main() and
10 5 transfers the control to function definition and copies 5
Returns 10*5 =50 into formal parameter of area() : r
So result =50 It will calculate the area r*r*3.14 = 5*5*3.14 = 78.50
Prints result i.e. 50 and return the result back to main().
returned value is printed on screen i.e. 78.50
result= div (10,5) div(10,5)
GQ. Write program to reverse the number 1234
a b (i.e. 4321) using function.
10 5
So result =2 Returns 10/5 =2
Prints result i.e. 2
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-17)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-18)
if(n2!=0)
float comp_int_calc(float AMT,float RATE,int YEARS) {
{ result = n1 / n2;
float COMP_INT=0; printf("\n Division is %d",result);
COMP_INT=pow(1+RATE,YEARS); }
COMP_INT=AMT*COMP_INT; else
return COMP_INT; {
} printf("\n Cannot divide by zero");
Output }
}
main()
{
int n1,n2,choice;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-19)
case 5: Scope of the variable defines certain area in which the
break; variable is accessible.
Types of variables
default:
printf("\n Invalid choice"); Variables can be of two types.
}
}
}
Output
1. Global variables
Scope of the global variable is throughout the program
i.e. every function in the program can access that
variable. Global variables are declared outside all the
function (including main()).
2. Local variables
Scope of the local variable is limited to the function in
which it is declared. Other functions can’t have access
to that variable.
Local variables are declared within function.
To understand the scope of variables see Program 5.8.1
Example
#include <stdio.h>
void display(int a);
int a=50; Global variable
int main( )
{
int i = 20; Local variable of main()
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-20)
k and j are local variables of display function. Recursive solution is always more logical and it is very
difficult to trace (debug and understand).
4.5 RECURSIVE FUNCTIONS In recursive we must have an if statement somewhere
to force the function to return without the recursive call
UQ. Explain recursion concept. MU - May 13, 2 Marks. being executed, otherwise the function will never
OR What do you mean by recursion ? return.
Recursion takes a lot of stack space, usually not
MU - Dec. 13, May 14, Dec. 15, May 16, Dec. 18, 2
considerable when the program is small and running on
Marks.
a PC.
OR Explain recursive function MU - Dec.17, 2 Marks.
Recursion uses more processor time.
Ans. :
4.5.3 Programs on of Recursive Functions
Recursive function
The process of calling a function inside itself is called UQ. Write a recursive program to calculate factorial
as recursion. The function which calls itself is referred of accepted number. MU - May 13, 6 Marks.
as recursive function. Ans. : Program
Recursion is the process of defining something in #include <stdio.h>
terms of itself. It is little bit difficult to understand the int fact(int);
recursion but in some cases it provides better solution int main( )
than looping. {
int n, f ;
4.5.1 Advantages of Recursive Functions
UQ. What are advantages of recursion? printf ( "\nEnter any number " ) ;
scanf ( "%d", &n ) ;
MU - May 17, 2 Marks.
Ans. : f = fact ( n ) ;
printf ("Factorial value = %d", f ); Suspend execution of
Advantages of recursion main() and transfers
control to definition
Recursive function has following advantages. of fact() and passes
It helps to reduce the time complexity of program return 1; value of n to num.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-21)
{ int Fibbo(int);
int f ;
if (num == 1) int main()
{ {
return (1) ; int n, i = 0, c;
} printf("\n Enter value of n : ");
else scanf("%d",&n);
Loop will execute n
{ printf("\nFibonacci series\n"); times it will call
f = num * fact (num - 1) ; for (c = 1 ; c <= n ; c++) Fibbo() each times and
prints return value of
} { Fibbo()
return (f) ; Recursively calls itself printf(" %d ", Fibbo(i));
} i++;
Output
}
getch();
}
Explanation
int Fibbo(int n)
{
if (n == 0)
return 0;
else if (n == 1)
Recursively
return 1;
calls itself
else
return (Fibbo(n-1) + Fibbo(n-2) );
}
Output
Fig. 4.5.1
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-22)
i++ i++
Now Now
n i c n i c
10 1 2 10 5 6
c < = n is true. c < = n is true.
Fibbo(1)
Fibbo(5)
So prints 1. Fibbo(1)
So prints 5. Fibbo(5)
else if(1==1) true
(5==0) and (5==1)both are false so
Returns 1
Else
i++
Returns Fibbo(5-1) + Fibbo(5-2)
Now
= Fibbo(4) + Fibbo(3) i.e. 3 + 2 = 5
n i c
i++
10 2 3
Now
c < = n is true.
n i c
Fibbo(2)
10 6 7
So prints 1. Fibbo(2)
c < = n is true.
(2==0) and (2==1)both are false so
Else Fibbo(6)
Returns Fibbo(2-1) + Fibbo(2-2) So prints 8. Fibbo(6)
= Fibbo(1) + Fibbo(0) i.e. 1 + 0 = 1 (6==0) and (6==1)both are false so
i++ Else
Now Returns Fibbo(6-1) + Fibbo(6-2)
n i c = Fibbo(5) + Fibbo(4) i.e. 5 + 3 =8
10 3 4 i++
c < = n is true. Now
Fibbo(3) n i c
So prints 2. Fibbo(3) 10 7 8
(3==0) and (3==1)both are false so
c < = n is true.
Else
Fibbo(7)
Returns Fibbo(3-1) + Fibbo(3-2)
= Fibbo(2) + Fibbo(1) i.e. 1 + 1 = 2 So prints 13. Fibbo(7)
i++ (7==0) and (7==1)both are false so
Now Else
n i c Returns Fibbo(7-1) + Fibbo(7-2)
10 4 5 = Fibbo(6) + Fibbo(5) i.e. 8 + 5 = 13
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-23)
10 9 10 Ans. :
c < = n is true. Program
Fibbo(9)
#include <stdio.h>
So prints 9. Fibbo(9) long reverse(long);
(9==0) and (9==1)both are false so
Else int main()
Returns Fibbo(9-1) + Fibbo(9-2) {
= Fibbo(7) + Fibbo(8) i.e. 21 + 13 = 34 long n, r;
i++ printf("\n Enter a number : ");
Now scanf("%ld", &n);
n i c
10 10 11 r = reverse(n);
c < = n is false.
printf("Reverse number is : %ld\n", r);
Exit from loop i.e. end of program.
Ans. : Program
long reverse(long n) {
#include <stdio.h> static long r = 0;
int addNumbers(int n);
int main() { if (n == 0)
return 0;
int num;
printf("Enter a positive integer: ");
r = r * 10;
scanf("%d", &num); r = r + n % 10;
printf("Sum = %d", addNumbers(num)); reverse(n/10);
return 0; return r;
} }
int addNumbers(int n) { Output
if (n != 0)
return n + addNumbers(n - 1);
else
return n;
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (4-24)
y
UQ. Write a program to find x using recursion
Chapter Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
Module IV
Chapter… 5
Arrays and Strings
Introduction to Arrays
Declaration and initialization of one dimensional and two-dimensional arrays.
Definition and initialization of String
String functions
UQ. Write a program in C to find minimum number in an array. MU - Dec. 15, 10 Marks. .................................. 5-7
UQ. Write a program to search a number within the array. MU - Dec.15, 10 Marks. ............................................. 5-7
UQ. Write a program to sort given numbers in ascending order. MU - May 14, Dec. 17, 10 Marks. .................... 5-11
UQ. Write a program to sort list elements in descending order. MU - May 13,8 Marks. ...................................... 5-11
OR Write a program to sort given nos in descending order. MU - Dec. 13, 10 Marks. ..................................... 5-11
UQ. Write a program in C to accept an ARRAY A with n elements and Separate it into two different arrays B and C
in such a way that B contains Odd numbers and C contains Even numbers. i.e. if ARRAY A contains
A={3,2,4,2,5,7,8} then B={3,5,7} and C={2,4,2,8}.MU - May 16, 10 Marks.................................................... 5-12
UQ. Write a program which will accept 2 dimensional square matrix and find out transpose of it. Program should
not make use of another matrix.MU - Dec. 13, May 14, Dec. 15, 10 Marks. ................................................. 5-14
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-2)
iii. Write a function that will return true (1) if entered matrix is symmetric or false (0) is not symmetric
iv. Print whether entered matrix is symmetric or not [ in main function ] MU - May 18, 10 Marks. .............. 5-17
UQ. Write a program to calculate matrix multiplication and transpose for a matrix.
UQ. Write a program to calculate sum of list by passing array to a function.MU - May ,13, 5 Marks.................... 5-22
MU - May 13, 5 Marks, Dec. 13, May 14, Dec. 18, 10 Marks. ..................................................................... 5-23
UQ. Write a program to find reverse of given string without using string library function.
UQ. Implements string copy function STRCOPY (str1, str2) that copies a string str1 (source) to another string str2
(destination) without using library function. MU - May 18, 5 Marks. ............................................................. 5-24
UQ. Explain any three string standard library functions. MU - May 13, 3 Marks.................................................. 5-24
MU - Dec. 13, Dec. 15,May 17, Dec. 17, Dec. 18, 5 Marks. ........................................................................ 5-24
UQ. Write a user defined function to copy one string to another. MU - Dec. 14, 5 Marks................................... 5-27
(i) strcat (ii) strlen MU - May 16, Dec. 17, 10 Marks. .................................................................................... 5-29
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-3)
GQ. Explain need of array with suitable example. Array can handle lots of elements using single name.
Instead of declaring lots of variables, use a subscripted
(5 Marks)
variable called as array to store the weights of children.
Ans. : Using the subscript we can manage random elements
of the array.
Need of Array
Example
First scenario
Consider the following group
To store weight of 5 children we need 5 variables as
follows : Weight = { 25, 20, 30, 19, 22}
void main( ) It represents weights of five children. To refer the
{ element 20 of the group the notation weight 2 is used.
int rajesh, suvrna, surya, pritesh, chitra; Similarly, to refer the element 22 of the group the
rajesh = 25; notation weight 5 is used.
chitra = 20; But in the case of array, the element 25 is referred as
suvrna = 30; weight[0] ; because the array
surya = 19;
pritesh = 22;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-4)
needed.
6. The first element in the array is numbered 0, so the last
element is 1 less than the size of the array.
Fig. 5.1.1
7. Before using an array its type and dimension must be
Element’s index counting starts with 0 instead of 1. declared.
Similarly, the element 22 is referred as weight[4]. In
GQ. List types of arrays ? (2 Marks)
general to refer any element of an array this notation
should be used Ans. :
Here weight is the subscripted variable (array), Types of Arrays
whereas i is its subscript. Where i is in the range 0-4 in Arrays are categorized according to the dimensions
our example. used to define them. Here dimension indicates the
Need of array number of rows and columns used to set size of array.
Let’s consider the following scenario for proper Array is categorized into following types.
understanding the need of arrays.
Array variables are needed because of following
requirements of user :
o Store multiple values in the variable with same
name.
o Store multiple values (with same data type)
together i.e. store them one after another.
o For easy access or retrieval of stored data Fig. 5.1.2 : Types of array
elements.
Note that the elements should be of same data type 5.2 DECLARATION AND
means it can be group of integers (int s), group of real INITIALIZATION OF ONE
numbers (float s or double s), group of characters DIMENSIONAL ARRAYS
(char s), etc. Usually array of character is called as
string. GQ. How elements are allocated with space in
memory for one dimensional array? (5 Marks)
5.1.1 Characteristics of Array
Ans. :
GQ. What are the characteristics of array? (5 Marks)
One Dimensional Arrays
Ans. : An array with single subscript is called as one
Characteristics of an Array dimensional array.
Following are important characteristics of an array : Declaration of one dimensional array
1. An array can hold only similar type of data. Syntax
2. Array is a subscripted variable which holds several Syntax for declaring one dimensional array is given
elements at a time. below :
3. Using subscript random elements can be referred. data_type array_name [ size ];
4. Contiguous memory is allocated for elements of array. Example
5. Always the array_name is followed by [ ] which tells Declare an array to store percentage of 10 students
the compiler that we are dealing with an array. float percentage[10];
Between [ and ] bracket int type of value (size) is
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-5)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-6)
Ans. :
scanf("%d", &n);
Program
printf("Enter %d elements\n", n);
for ( i = 0 ; i < n ; i++ ) #include <conio.h>
{
Accepts elements for #include <stdio.h>
array from user
scanf("%d", &array[i]); int main()
} {
printf("Enter the position of element to be deleted\n"); float percentage[10]; Array declaration
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-7)
Ans. :
Program
int main()
{
int arr[5],num,i;
printf("\nEnter 5 array eles : ");
for(i=0;i<5;i++)
{
scanf("%d",&arr[i]);
UQ. Write a program in C to find minimum number in }
an array. MU - Dec. 15, 10 Marks. printf("\nEnter number to search : ");
scanf("%d",&num);
Ans. :
Program for(i=0;i<5;i++)
#include<stdio.h> {
#include<conio.h> if(num==arr[i])
int main() {
{ printf("\nNumber found");
int array[5]={33,30,34,31,32},j; break;
printf("\n array elements are:\t"); }
for(j=0;j<5;j++) }
{ if(i==5)
printf("%d\t",array[j]); printf("\nNumber not found");
} }
Sets the minimum number is
int min=array[0]; the first element of array. Output:
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-8)
return 1;
}
Output
(5 Marks)
Ans : Program
#include<stdio.h>
#include<conio.h> GQ. Write a program to find out number of positive,
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-9)
# include<stdio.h> arrays and add and multiply them and print the
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-10)
}
Output
Enter elements for first array
Enter number for array1[0]:10
Enter number for array1[1]:20
Enter number for array1[2]:30
GQ. Write a program to accept values for 2 integer
Enter number for array1[3]:40
arrays and subtract and divide them and print the
result of subtraction and division. (5 Marks) Enter number for array1[4]:50
Enter elements for second array
Ans : Program
Enter number for array1[0]:1
# include<stdio.h>
Enter number for array1[1]:2
main()
Enter number for array1[2]:3
{
Enter number for array1[3]:4
int array1[5], array2[5], array3[5];
Enter number for array1[4]:5
int i=0;
subtraction of array1 and array2
printf("\n Enter elements for first array");
array1[0]-array2[0]=array3[0]=9
for(i=0;i<5;i++)
Accepts array1[1]-array2[1]=array3[1]=18
{ elements
printf("\nEnter number for array1[%d]:",i); for 1st
array1[2]-array2[2]=array3[2]=27
scanf("%d",&array1[i]); array. array1[3]-array2[3]=array3[3]=36
} array1[4]-array2[4]=array3[4]=45
printf("\n Enter elements for second array"); division of array1 and array2
for(i=0;i<5;i++) array1[0] / array2[0] = array3[0]=10
Accepts
{ array1[1] / array2[1] = array3[1]=10
elements
printf("\nEnter number for array1[%d]:",i); for 2nd array1[2] / array2[2] = array3[2]=10
scanf("%d",&array2[i]); array.
array1[3] / array2[3] = array3[3]=10
} array1[4] / array2[4] = array3[4]=10
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-11)
{ #include<stdio.h>
int array[10],i, j,temp; #include<conio.h>
printf("enter 10 elements for array:"); int main()
for(i=0;i<10;i++) {
{ Accepts 10 elements from int array[10],i, j,temp;
scanf("%d",&array[i]); user and store it in array. printf("enter 10 elements for array:");
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-12)
for(i=0;i<10;i++)
{ Accepts 10 elements from printf("Enter the size of array : ");
user and store it in array.
scanf("%d",&array[i]); scanf("%d", &n);
}
th
for(i=0;i<9;i++) Used to compare i element printf("Enter the elements of the array : ");
with all the remaining elements
{ in the array. for (i = 0; i < n; i++)
for(j=i+1;j<10;j++) {
{ scanf("%d", &ARR[i]);
if(array[j]>array[i]) Compare array[i] with array[j]
}
{
temp=array[i]; If condition satisfies
array[i]=array[j]; Swap the array[i] and for (i = 0; i < n; i++)
array[j].
array[j]=temp; {
} if (ARR[i] % 2 == 0)
} {
} EAR[j] = ARR[i];
printf("\n ascending ordered array :\n"); j++;
for(i=0;i<10;i++) }
{ Prints the sorted array in else
printf("%d\t",array[i]); ascending order. {
} OAR[k] = ARR[i];
return 1; k++;
} }
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-13)
Example
5.3 DECLARATION AND
INITIALIZATION OF TWO Initialize an array to store values for 2 × 2 matrix
DIMENSIONAL ARRAYS matrix[1][1]= 9;
matrix[0][0]= 7;
GQ. What is two dimensional array? How it is matrix[0][1]= 6;
declared and initialized? Give example of it.
matrix[1][0]= 5;
(5 Marks)
Using the subscript we can assign value to specific
Ans. : array element. The order of assignment statement
An array with two subscripts is called as two doesn’t matter in above example. It will assign the
dimensional array. 2D arrays are mostly used to values given as in Fig. 5.3.3.
perform matrix operations.
Declaration of two dimensional array
Ans. :
Entering or Writing Data into Two Dimensional Arrays
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-14)
For 2D array, two for loops are used. One for loop (i.e. for ( i = 0 ; i <2 ; i++ )
outer for loop) for row and another for loop (i.e. inner {
for loop) is for column. for ( j = 0 ; j <2 ; j++ )
{
printf() function is used to request user to enter the
printf ( "\n matrix [%d] [%d] :\t ", i, j ) ;
data.
scanf ( "%d", &matrix[i][j] ) ;
scanf() function is used to take input from user.
}
&matrix[i][j] tells the compiler to store the entered
}
value at ith row and jth column in matrix. Here value of Accepts array elements from user for 2D array.
i and j varies from 0 to 1.
Ans. :
Program UQ. Write a program which will accept 2 dimensional
# include<stdio.h> square matrix and find out transpose of it.
#include<conio.h> Program should not make use of another matrix.
MU - Dec. 13, May 14, Dec. 15, 10 Marks.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-15)
for (i=0;i<2;i++) GQ. Write a program to read two matrices and print
{ their addition. (5 Marks)
for(j=0;j<2;j++)
{ Ans. :
printf("Enter matrix[%d][%d] element : ",i, j); Program
# include<stdio.h>
scanf("%d", &matrix[i][j]); int main()
} {
} int matrix1[2][2],matrix2[2][2], matrix3[2][2];
int i=0,j=0;
printf("\n Original matrix:\n\t"); printf("\n Enter array elements of first matrix:");
for (i=0;i<2;i++)
{ for (i=0;i<2;i++)
for (j=0;j<2;j++) {
{
printf("%d\t",matrix[i][j]); for(j=0;j<2;j++)
} {
printf("\n\t"); printf("\n Enter matrix1[%d][%d] element\t", i,j);
} scanf("%d", & matrix1[i][j]);
printf("\n Transposed matrix:\n\t");
for (i=0;i<2;i++) Accepts elements of 1st matrix from user and store it in
matrix1.
{
for (j=0;j<2;j++) }
{ }
printf("%d\t",matrix[j][i]);
} printf("\n Enter array elements of second matrix:");
printf("\n\t");
} for (i=0;i<2;i++)
} {
Output
for(j=0;j<2;j++)
{
printf("\n Enter matrix2[%d][%d] element\t", i,j);
}
}
printf("\n matrix1: \n\t\t");
for (i=0;i<2;i++)
{
for(j=0;j<2;j++)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-16)
{ GQ. Write a program to read two matrices and print
Prints elements of
printf("%d\t", matrix1[i][j]); 1st matrix. their subtraction and division. (5 Marks)
}
printf("\n\t\t"); Ans. :
} Program
printf("\n matrix2: \n\t\t"); # include<stdio.h>
for (i=0;i<2;i++) int main()
{ {
for(j=0;j<2;j++) int matrix1[2][2],matrix2[2][2], matrix3[2][2];
{ int i=0,j=0;
Prints elements of
printf("%d\t", matrix2[i][j]); 2nd matrix. printf("\n Enter array elements of first matrix:");
} for (i=0;i<2;i++)
printf("\n\t\t"); {
} for(j=0;j<2;j++)
printf("\n Addition of two 2 × 2 matrix is:\n\t\t"); {
for (i=0;i<2;i++) scanf("%d", &matrix1[i][j]);
Accepts elements of
first matrix from user.
{ }
for(j=0;j<2;j++) }
{ printf("\n Enter array elements of second matrix:");
matrix3[i][j]=matrix1[i][j] +matrix2[i][j]; for (i=0;i<2;i++)
printf("%d\t",matrix3[i][j]); {
} for(j=0;j<2;j++) Accepts elements of
printf("\n\t\t"); { second matrix from
} th th scanf("%d", &matrix2[i][j]); user.
Adds elements of i row and j column of first matrix with
th th
the element of i row and j column of second matrix and }
th th
store it in i row and j column of third matrix. }
printf("\n matrix1: \n\t\t");
} for (i=0;i<2;i++)
Output {
for(j=0;j<2;j++)
Prints elements of
{ first matrix.
printf("%d\t", matrix1[i][j]);
}
printf("\n\t\t");
}
printf("\n matrix2: \n\t\t");
for (i=0;i<2;i++)
{
for(j=0;j<2;j++)
Prints elements of
{ second matrix.
printf("%d\t",matrix2[i][j]);
}
printf("\n\t\t");
}
printf("\n subtraction of two 2 X 2 matrix is:\n\t\t");
for (i=0;i<2;i++)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-17)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-18)
if(r==1) But in memory it will form different structure.
printf("Symmetric Matrix");
Memory arrangement after declaring multidimensional
else
array shown in bellow Table 5.4.1.
printf("Not Symmetric Matrix");
Table 5.4.1
} Array[0][0][0] 1000
Fig. 5.4.2
Fig. 5.4.1
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-19)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-20)
trans_matrix[j][i] = orign_matrix[i][j]; GQ. How to add elements in 3D array? (5 Marks)
Accepts element of 3 × 3 matrix and store it in ith row and jth Ans. :
column of origin matrix. Entering or Writing Data into multidimensional Array
}
The following code is used to accept ten elements from
}
user and store into 3D array :
printf("\n Original matrix:\n\t");
printf ( "\nEnter data for 3D array\n” );
for (i=0;i<3;i++)
for ( i = 0 ; i <2 ; i++ )
{
Copies the entered element at jth row and ith column of
trans_matrix. for ( j = 0 ; j <2 ; j++ )
{
{
for ( k = 0 ; k <2 ; k++ )
for (j=0;j<3;j++)
{
{
Prints original printf ( "\n array[%d] [%d] [%d]:\t ", i, j, k ) ;
printf("%d\t",orign_matrix[i][j]); matrix.
}
scanf ( "%d", &array[i][j][k] ) ;
printf("\n\t");
}
}
}
printf("\n Transposed matrix:\n\t");
}
for (i=0;i<3;i++)
{ As we know for 2D array two for loops are used
for (j=0;j<3;j++) similarly for 3D array three for loops will be used.
Prints transpose of
{ original matrix. printf() function is used to request user to enter the
printf("%d\t",trans_matrix[i][j]); data.
} scanf() function is used to take input from user.
printf("\n\t"); &array[i][j][k] tells the compiler to store the entered
} value at jth row and kth column of ith row in matrix.
} Here value of i, j and k varies from 0 to 1.
Output
GQ. How elements of 3-D array can be accessed ?
(2 Marks)
Ans. :
Accessing or Reading Data from an Three Dimensional
Array
As we use three for loops for writing the data into 3D
array likewise we use three for loops to read the data
from 3D array.
printf(“\nThe array is:\n”);
for ( i = 0 ; i <2 ; i++ )
{
for ( j = 0 ; j <2 ; j++ )
{
for ( k = 0 ; k <2 ; k++ )
{
printf ( " %d ", array[i][j][k] ) ;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-21)
} Output
}
printf(“\n”);
}
Ans. :
Program
# include<stdio.h>
#include<conio.h>
int main() row
row
{
column
int array[2][2][2],i,j,k;
printf ( "\nEnter data for 3D array\n” );
for ( i = 0 ; i <2 ; i++ )
{ 5.5 Defining and Initializing String
Accepts value for jth row
for ( j = 0 ; j <2 ; j++ ) and kth column of ith row
{ of array. GQ. What is String? How to declare and initialize it?
for ( k = 0 ; k <2 ; k++ )
(5 Marks)
{
printf ( "\n array[%d] [%d] [%d]:\t ", i, j, k ) ; Ans. :
scanf ( "%d", &array[i][j][k] ) ; String
}
An array with character (char) data type is called as
}
character array.
}
printf(“\nThe array is:\n”); Character array forms a string. String is collection
for ( i = 0 ; i <2 ; i++ ) of characters, numbers and special symbols.
{ Numbers or special symbols can be stored in character
for ( j = 0 ; j <2 ; j++ ) array but not recommended.
{ At the end of character array or string, ‘\0’ (NULL
for ( k = 0 ; k <2 ; k++ ) value) will be stored.
{ Prints value of jth row
Declaring String
printf ( " %d ", array[i][j][k] ) ; and kth column of ith
row of array. Syntax
}
} Syntax for declaring string is given below :
printf(“\n”); char string_name [ size ];
}
Example
return 1;
} Declare a string of 6 characters
char str1[6];
Memory arrangement after declaring string shown in
Fig. 5.5.1.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-22)
Displaying String
For taking a character array as input %c access-
specifier is used with scanf() function.
The following code is used to accept characters from
user and store it in array.
for (i = 0; i < 10; i++) UQ. Write a program to calculate sum of list by
{ passing array to a function.
printf ("\nEnter a character :\t “) ;
MU - May ,13, 5 Marks.
scanf ("%c", &array[i]) ;
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-23)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-24)
end = count - 1;
for (begin = 0; begin < count; begin++) { second_str[i]=’\0’; Copies null character at the end.
r[begin] = s[end];
end--; printf("\nAfter copy:\t First String=%s and Second
} String=%s", first_str,second_str);
printf("\nNumber of characters copied are %d", i);
r[begin] = '\0'; return 1;
}
printf("%s\n", r); Output
return 0;
}
Output
Program Ans. :
# include<stdio.h> String Functions
int main() String.h header file includes the string manipulating
{ functions. Some of the frequently used functions are:
char first_str[20],second_str[20]; strcat(), strchr(), strcmp(), strcpy(), strlen(),
int count=0, i=0; strlwr(), strrev(), strstr(), strupr(), etc.
printf("\n Enter first string :\t"); GQ. Give the syntax and use of strcat ( ) string
scanf("%s", first_str); function? (2 Marks)
printf("\n Enter Second string:\t");
Ans. :
scanf("%s", second_str);
strcat() string function
printf("\n Before copy:\t First String=%s and Second
String=%s", first_str,second_str); Use
Until the end of string the strcat() string function is used to combine two strings.
while (first_str[i]!='\0') loop will continue.
Syntax of strcat() declaration
{
second_str[i]=first_str[i]; char *strcat(char *dest, const char *src);
Copies character at
i++; first_str[i] into Syntax of calling strcat() function
second_str[i].
} strcat(string1 , string2);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-25)
strcat(string1,string2) appends a copy of string2 at So now string1 will be” Dennis Ritchie”.
the end of string1. Length of string1 after
GQ. Give the syntax and use of strchr ( ) string
concatenating is equal to the sum of both the strings
function? (2 Marks)
before concatenation.
It returns a pointer to the concatenated string. Ans. :
strchr() string function
GQ. Write a program to concatenate two strings.
Use
(5 Marks)
strchr() is used to find the first occurrence of given
Ans. : character in string.
Program Syntax of declaring strchr()
#include <string.h> char *strchr(const char *s, int c);
#include <stdio.h>
Syntax of calling strchr() function
int main(void)
{ int pos = strchr(string1 ,ch)-string1;
strchr() returns the address where character is located
char string1[25] = "Dennis",string2[25]="Ritchie"; in the string.
char string3[]=" ";
GQ. Write a program to accept a string from user and
printf("\nFirst string:\t\t %s", string1);
check whether the string contains the character o
printf("\nSecond string:\t\t%s", string2);
or not. (5 Marks)
Ans. :
First call to strcat()
strcat(string1, string3); appends a space to Program
“Dennis” and stores
#include <string.h>
result back in string1
#include <stdio.h>
#include<conio.h>
strcat(string1,string2);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-26)
Output Output
Explanation
Explanation
Here user enters a string program. Suppose it is stored
at location 3000 means first character P is stored at The gets() function accepts a string from user and store
3000, r is stored at 3001, o is stored at 3002 and so on. it in string .
Strchr() will return 3002 (i.e. location of character to And the strlen() function returns the length of string.
be search o). so corresponding position of o in the
GQ. Explain with syntax and example strcpy ( )
string program is calculated as 3
function. (2 Marks)
GQ. Explain the use of the strlen function with syntax.
(2 Marks)
Ans. : strcpy() string function
Use
Ans. : strlen() string function
strcpy() string function is used to copy one string into
Use
another. While copying a string into destination the
strlen() is used to calculate length of given string initial value is cleared first and then the new string is
Syntax of declaring strlen() copied into destination string.
size_t strlen(const char *s); Syntax of strcpy() function declaration
Syntax of calling strlen() char *strcpy(char *dest, const char *src);
int len= strlen(string); Syntax of calling strcpy() function
strlen() calculates the length of string and returns an strcpy(dest_str, src_str);
integer. strlen() doesn’t count the null character. This statement copies string src_str to dest_str. The
GQ. Write a program to accept a string from user and process of copying the characters from src_str to
print its length. (2 Marks) dest_str stops after moving the terminating null
character. And then the function returns dest_str.
Ans. :
GQ. Write a program to copy one string into another.
Program
#include <stdio.h> Ans. :
#include <string.h> Program
int main(void) #include <stdio.h>
{ #include <string.h>
char string[25];
printf(“Enter a string: \t\t”); int main(void)
gets(string); gets() is used to accept a {
string from user.
char dest_string[]="Programming
language",src_string[]="C Programming";
printf("The length of entered string is:%d", strlen(string)); printf("\nBefore copy “);
printf(“\nDestination string:\t%s\nSource string :
strlen() returns length of string. \t\t%s\n",dest_string,src_string);
return 0; strcpy(dest_string, src_string); Copies src_string
} printf("\nAfter copy “); into dest_string
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-27)
printf(“\nDestination string:\t%s\nSource string :
\t\t%s\n",dest_string,src_string); { Checks whether
return 0; int i=0,j=0; memory is
} if(l1+l2<20) sufficient to copy a
string or not
Output {
for(i; i<l2;i++)
{
s1[i]=s2[i];
}
Specifies the end of
s1[i]='\0'; string after copy
}
else
{
printf("string is too large can't be copied.");
Explanation
}
In this program printf("\nAfter copy\nFirst string: \t%s”,s1);
dest_string is = Programming language printf(“\nSecond string:\t%s",s2);
src_string is = C Programming }
Ans. :
Program
#include <string.h> Explanation
Here org_string: mumbai, new_string: pune
#include <stdio.h>
So l1=strlen(mumbai) = 6 & l2 = strlen(“pune”) = 4
void copy(char s1[],char s2[],int l1,int l2);
int main(void) The function call copy(“mumbai”,”pune”,7,4) will
suspend execution of main() and transfers control to its
{
function definition and passes mumbai to s1, pune to
char org_string[20], new_string[20];
s2, 7 to l1 and 4 to l2.
printf("Enter first string: \t");
gets(org_string); If l1+l2<20 then only s2 will copy into s1 otherwise
printf("Enter second string:\t"); prints error message.
gets(new_string); Here 6+4=10 so 10<20 condition is true
Iteration1 : Now i=0,l2=4
int l1 = strlen(org_string); So i<l2 i.e. 0<4 is true so
int l2 = strlen(new_string);
S1[0]=s2[0]=”p”
i++
copy(org_string,new_string,l1,l2);
return 1; Iteration2 : Now i=1,l2=4
} So i<l2 i.e. 1<4 is true so
S1[1]=s2[1]=”u”
void copy(char s1[], char s2[], int l1, int l2) i++
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-28)
S1[3]=s2[3]=”e”
i++
printf("%s is less than %s",string2,string1);
Iteration5 : Now i=4,l2=4
Prints if string1 > string2
So i<l2 i.e. 4<4 is false }
S1[i]=’\0’ and exits the loop
else if (d == 0)
Now value of s1 and s2 are printed on the screen.
{
i.e. s1= pune, s2 = pune.
printf("%s and %s are equal\n",string1,string2);
GQ. Explain the use of the strcmp( ) function with
Prints if string1 == string2
syntax. (2 Marks) }
else
Ans. : {
strcmp() string function printf("%s is greater than %s",string2,string1);
Use
Prints if string1 < string2
}
strcmp() string function is used to compare two
return 0;
strings.
}
Syntax of declaring strcmp() function
Output
int strcmp(const char *s1, const char*s2);
Syntax of calling strcmp() function
int d= strcmp(string1, string2);
strcmp() performs an unsigned comparison of string1 Explanation
to string2. The string comparison starts with the first strcmp() compares two string character by character i.e
character in each string and continues with subsequent
string1 is = pen
characters until the corresponding characters differ or
until the end of the strings is reached. string2 is = pens
strcmp() returns an integer value. The value can be GQ. Write a program to convert all the characters of
either negative (if string1 < string2), or zero ( if string in lowercase. (2 Marks)
string1 == string2), or positive (if string1 > string2).
Ans. :
GQ. Write a program to compare two strings.
strlwr() string function
Ans. : Use
Program strlwr() is used to convert the characters of string to
#include <string.h> lowercase.
#include <stdio.h> Syntax of declaring strlwr()
char *strlwr(const char *s);
int main(void)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-29)
GQ. Write a program to convert all the characters of a GQ. Write a program to convert all the characters of
string in lowercase. (5 Marks) string in uppercase. (2 Marks)
Ans. : Ans. :
Program Program
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
#include<conio.h>
#include<conio.h> int main(void)
int main(void) {
char string[15];
{
Converts the string into
char string[15]; uppercase
printf("Enter a string: \t");
Converts the string into gets(string);
printf("Enter a string: \t"); lowercase printf("the string in uppercase: %s", strupr(string));
gets(string); return 0;
printf("the string in lowercase: %s", strlwr(string)); }
return 0; Output
}
Output
Explanation
Here user enters a string hello. strupr(string) will
Explanation converts all the characters in string to uppercase and
Here user enters a string HELLO. strlwr(string) will then returns the result back to the printf() function i.e.
converts all the characters in string to lowercase and HELLO.
then returns the result back to the printf() function. UQ. Write user defined functions to implement
GQ. Write a program to convert all the characters of following string operations
string in uppercase. (2 Marks) (i) strcat (ii) strlen
MU - May 16, Dec. 17, 10 Marks.
Ans. :
strupr() string function
Ans. :
Program
Use
#include <stdio.h>
strupr() is used to convert the characters in string to
int main()
uppercase.
{
Syntax of declaring strupr() getstrlen();
char *strupr(const char *s); strconcat();
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (5-30)
void strconcat()
{
int i,j;
char str1[20],str2[20];
printf("\n\nEnter first string : ");
gets(str1);
printf("\nEnter second string : ");
gets(str2);
for(i=0; str1[i]!='\0'; ++i);
Chapter Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
Module V
Chapter… 6
Structure and Union
UQ. What do you mean by struct ? MU - May 13, 2 Marks. ................................................................................... 6-4
UQ. What do mean by nested structure ? MU - May 13, 2 Marks. ......................................................................... 6-5
OR Explain nested structure with example.MU - May 15, Dec.17, 4 Marks. ......................................................... 6-5
OR What do you mean by nested structures ? MU - May 16, 2 Marks. ................................................................. 6-5
UQ. How to create array of structure variables and assign values to its members ? MU - May 18, 5 Marks.......... 6-7
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-2)
Input 20 player information of test playing county. Write a program which will display detail information of
player with given player name. MU - May 15, 6 Marks.................................................................................... 6-9
UQ. A company needs to maintain data about their employees. Details to be maintained are Employee name,
Department, Date of joining, Salary. Write a program which will store these details and list the employees
whose salary is greater than Rs. 50000.00. MU - May 16 6 Marks. ............................................................. 6-10
UQ. Write a program to read Title, Author and Price of 10 books using array of structures. Display the records in
ascending order of Price. MU - May 17, 6 Marks. ......................................................................................... 6-10
UQ. Write a program using structure to create an Array of structure to store the details of N students. The details
are,
Student name
Student Roll no
Write a program to read records of 5 students and display same. MU - Dec. 18, 10 Marks. ....................... 6-12
UQ. Differentiate between structure and union. MU - May 17, May 18, 4 Marks. ................................................ 6-16
UQ. When is union preferred over struct ? MU - May 18, 1 Mark. ........................................................................ 6-17
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-3)
{
6.1 CONCEPT OF STRUCTURE char name[3][10] ;
int price[3] ;
GQ. Explain concept of structure with suitable int pages[3], i ;
example. (10 Marks)
OR
for ( i = 0 ; i <= 2 ; i++ )
{
UQ. Explain structures in C ? MU - May 16, 2 Marks. printf ( "\nEnter details for book %d\n",i+1);
OR What are structures? MU - May 17, 2 Marks. printf("\tname:\t\t");
scanf ( "%s", name[i] );
Ans. : printf("\tno. of pages:\t");
Structure scanf ( "%d", &pages[i] );
We have learned that C provides various data types printf("\tprice:\t\t");
which make C more powerful language. scanf ( "%d", &price[i] );
}
Variables are used to store a single value at a time.
printf ( "\n\n\tBook detail:\n " ) ;
We can use primary data types to handle different
for ( i = 0 ; i <= 2 ; i++ )
kinds of data.
printf ( "\t%d.\n\tname: \t%s \n\tprice: \t%d \n\tno. of pages:
To store set of values of similar type at a time, array is \t%d\n", i+1,name[i], price[i], pages[i] );
used which is a derived data type. One of the return 1;
disadvantages of array is that it can’t store elements of }
different data types. Output
There are some situations where set of dissimilar types
of data is needed.
For example, consider a situation where we need to
keep record of 3 books. A book has name (string),
number of pages (int), and price (int). To store this data
we can follows two approaches :
1. Use individual arrays, one character array for storing
names, one integer array for storing number of pages
and one more integer array for storing price.
2. Use a structure.
First approach
As we discussed, keeping record of 3 books using first
approach needs to declare 3 individual arrays as
illustrates in following Program :
Example
Write a program to accept books details from user and
display it.
Solution
#include <stdio.h> This approach will work properly if number of items
#include <string.h> related to books are less. As the items related to the
int main( ) book increases number of arrays in the program also
increases.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-4)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-5)
{ GQ. Define a structure called cricket that will describe
struct book the following information :
{ (a) Player name (b) Team name
char name[3][10] ; Structure definition
(c) Batting average (2 Marks)
int price ;
int pages ; Ans. :
}; Struct Cricket
Declaration of structure
struct book b1, b2, b3 ; variables. {
Char pl_name[20],team_name[20];
Float avg;
printf ( "\nEnter name, price & no. of pages of book 1\n" ); }s;
scanf ( "%s%d%d", &b1.name[0], &b1.price, &b1.pages );
GQ. What are important advantages of Structure
printf ( "\nEnter name, price & no. of pages of book 2\n" );
scanf ( "%s %d %d", &b2.name[1],&b2.price,&b2.pages ); (3 Marks)
printf ( "\nEnter name, price & no. of pages of book 3\n" ); Ans. : Important advantages of Structure
scanf ( "%s %d %d", &b3.name[2],&b3.price, &b3.pages );
Structure gives flexibility to access data easily.
Accepts details of book from user and store it
in respective members. Avoid need of several variable declarations.
Used to combine related data.
printf ( "\n\n\tBook detail:\n " ); Improves code efficiency.
printf ( "\t1.\n\tname: \t%s \n\tprice: \t%d \n\tno. of pages:
Avoid repetition of code allowing loops.
\t%d\n", b1.name[0], b1.price, b1.pages );
printf ( "\t2.\n\tname: \t%s \n\tprice: \t%d \n\tno. of pages:
\t%d\n", b2.name[1], b2.price, b2.pages ); 6.3 NESTED STRUCTURES
printf ( "\t3.\n\tname: \t%s \n\tprice: \t%d \n\tno. of pages:
\t%d\n", b3.name[2], b3.price, b3.pages ); UQ. What do mean by nested structure ?
return 1; MU - May 13, 2 Marks.
} OR Explain nested structure with example.
Output MU - May 15, Dec.17, 4 Marks.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-6)
member_1; struct student
member_2; {
member_3;
struct person info;
...
int per_roll_no;
member_n;
}, var1 float per_marks;
} var2; };
Example
int main()
struct product {
{ struct student s1;
char p_name[40]; printf("Details of student: \n\n");
int p_id printf("Enter per_name: ");
float price; scanf("%s", s1.info.per_name);
int p_qty;
printf("Enter per_age: ");
struct m_date
scanf("%d", &s1.info.per_age);
{
int date; printf("Enter per_dob: ");
int month; scanf("%s", s1.info.per_dob);
int year; printf("Enter roll no: ");
}dom; scanf("%d", &s1.per_roll_no);
}p; printf("Enter per_marks: ");
This structure store details of product like name of the scanf("%f", &s1.per_marks);
product(p_name), product id(p_id), price of the printf("\n*******************************\n\n");
product(price), quantity of product(p_qty) and
printf("Per_name: %s\n", s1.info.per_name);
manufacturing date(m_date). The manufacturing date
printf("Per_age: %d\n", s1.info.per_age);
is a structure which holds date, month and year when
the product is manufactured. printf("PER_DOB: %s\n", s1.info.per_dob);
These variables accessed and initialize like : printf("Roll no: %d\n", s1.per_roll_no);
p.p_name = “Harddisk”; printf("Per_marks: %.2f\n", s1.per_marks);
p.p_id = 1001; getch();
p.price = 1000; }
p.p_qty = 2; Output
p.m_date.date = 12;
p.m_date.month = 4;
p.m_date.year = 2015;
Program
#include<stdio.h>
struct person
{
char per_name[20];
int per_age;
char per_dob[20];
};
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-7)
Example
6.4 ARRAY OF STRUCTURES / ARRAY
OF STRUCTURE VARIABLES Write a program to declare structure employee having
data member name, street, city. Accept data for three
UQ. How to create array of structure variables and
employees and display it.
assign values to its members ? Solution
return 1;
}
Fig. 6.4.1
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-8)
Ans. :
GQ. Write a program in c using structure to enter
Program
rollno, marks of the three subject for 3 students
#include <stdio.h> and find total obtained by each student.
#include<conio.h>
(5 Marks)
#include <string.h>
int main( ) Ans. : Program
{ #include<stdio.h>
int i; main()
{
struct stationary struct student
{ Structure definition {
char name[10] ; int rno,hindi,marathi,english,total;
int cost,qty; }s[3];
Declaration of array
}; of structure int i;
struct stationary s[5];
for(i=0;i<5;i++) for(i=0;i<3;i++)
{ {
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-9)
printf("\n Enter rollno and marks of hindi, marathi and {
english : ");
struct cricket c1[25];
scanf("%d %d %d %d",
&s[i].rno,&s[i].hindi,&s[i].marathi,&s[i].english); int i;
s[i].total = s[i].hindi + s[i].marathi + s[i].english; for(i=0;i<20;i++)
} {
printf("\n Rollno \t Total");
printf("Enter the player_name, country_name and
for(i=0;i<3;i++)
average runs scored : ");
{
printf("\n %d \t\t %d",s[i].rno,s[i].total); scanf("%s %s %f",c1[i].player_name,c1[i].country_name,
} &c1[i].batting_average);
}
getch(); printf("\nDetails : \n");
}
for(i=0;i<20;i++)
Output
{
printf("%s\t%s\t%f\n",c1[i].player_name,c1[i].country_na
me,c1[i].batting_average);
}
}
Output
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-10)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-11)
if(c1[j].price>c1[j+1].price) Ans. :
{
Program
temp=c1[j];
#include<stdio.h>
c1[j]=c1[j+1];
c1[j+1]=temp;
main()
}
} {
} struct student
printf("\nDetails of books in ascending order on price : \n"); {
for(i=0;i<10;i++) int rno,Physics,Chemestry,Maths,total;
{ char name[20];
printf("%s\t%s\t%.2f\n",c1[i].title,c1[i].author,c1[i].price); }s[3];
} int i;
}
Output for(i=0;i<3;i++)
{
printf("\n Enter name, rollno and marks of
Physics,Chemestry,Maths : ");
scanf("%s %d %d %d %d",&s[i].name,
&s[i].rno,&s[i].Physics,&s[i].Chemestry,&s[i].Maths);
s[i].total = s[i].Physics + s[i].Chemestry + s[i].Maths;
}
printf("\n Name \t Rno \t Total");
for(i=0;i<3;i++)
{
printf("\n %s \t %d \t %d",s[i].name,s[i].rno,s[i].total);
}
}
Output
UQ. Write a program using structure to create an
Array of structure to store the details of N
students. The details are,
Student name
Student Roll no.
Marks of Physics, Chemistry, Maths.
Calculate the total of P-C-M. Display the data in
the format
Name Roll no Total marks
MU - Dec. 17, 8 Marks.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-12)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-13)
printf("\n");
}
Output
6.6.1 Passing Structure by Value
Ans. :
Passing structure by value
If a structure contains few members then it is easy to 6.6.2 More Examples on Structure
pass them to function but if they are more, then it is
GQ. Write a program to read structure elements from
little bit difficult. It is a tiresome and error-prone
user. (5 Marks)
process. Hence in such cases instead of passing
members individually, we can pass structure variable Ans. :
itself. Program
The following program demonstrates how we can pass #include <stdio.h>
structure variable as an argument to the function. #include <string.h>
#include<stdio.h> int main( )
{
/*
struct book
structure is defined above all functions so it is global.
{
*/ Structure definition
char name[3][10] ;
struct student int price ;
{ int pages ;
char Stu_name[20]; }; Declaration of structure
int Stu_roll_no; struct book b1, b2, b3 ; variables.
int Stu_marks;
}; printf ( "\nEnter name, price & no. of pages of book 1\n" );
scanf ( "%s%d%d", &b1.name[0], &b1.price, &b1.pages );
void print_struct(struct student s); printf ( "\nEnter name, price & no. of pages of book 2\n" );
scanf ( "%s %d %d", &b2.name[1],&b2.price,&b2.pages );
int main() printf ( "\nEnter name, price & no. of pages of book 3\n" );
{
scanf ( "%s %d %d", &b3.name[2],&b3.price, &b3.pages );
struct student s = {"Kunal", 1, 98};
print_struct(s); Accepts details of book from user and store it in with
getch(); respective members.
}
void print_struct(struct student s) printf ( "\n\n\tBook detail:\n " );
{ printf ( "\t1.\n\tname: \t%s \n\tprice: \t%d \n\tno. of pages:
\t%d\n", b1.name[0], b1.price, b1.pages );
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-14)
getch();
}
Output
GQ. Define a structure type struct personal that GQ. Define structure data type called time_struct
containing three member’s integer hour, integer
would contain person name, date of joining and
minute and integer second. Develop a program
salary using this structure to read this
that would assign values to the individual
information of 5 people and print the same on number and display the time in the following
screen (5 Marks) format: 16: 40:51 (5 Marks)
Ans. : Ans. :
Program Program
#include<stdio.h> #include<stdio.h>
main()
{ main()
struct personal {
{ struct time_struct
char pname[20],dob[20]; {
int sal; int hour,minute,second;
}p[5]; }t;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-15)
scanf("%d",&t.minute); for(i=0;i<10;i++)
printf("\n Enter second : "); {
scanf("%d",&t.second); printf("\n %s \t %s \t
%d",p[i].name,p[i].branch,p[i].total);
printf("\n\n Timing : %d : %d : }
%d",t.hour,t.minute,t.second);
getch();
}
getch(); Output
}
Output
Ans. : Program
#include<stdio.h>
main()
{
struct student_record
{
char name[20],branch[20]; 6.7 CONCEPT OF UNION :
int total; DECLARATION AND
}p[10]; INITIALIZATION OF UNION
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-16)
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main() 6.7.1 Difference between Structure
{ and Union
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (6-17)
Chapter Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
Module VI
Chapter… 7
Pointers
Fundamentals of pointers
Declaration, initialization and dereferencing of pointers
Operations on Pointers
Concept of dynamic memory allocation
UQ. Define pointer and its use.MU - Dec. 17, 2 Marks. .......................................................................................... 7-3
UQ. Explain how the pointer variable declared and initialized. MU - Dec. 18, 2 Marks. ........................................ 7-4
UQ. Explain reference and de-reference operators with example. MU - May 13, 3 Marks. .................................. 7-5
UQ. Explain array of pointers with example. MU - Dec. 17, 4 Marks. ................................................................... 7-24
UQ. What are the different ways for parameter passing to a function. Explain along with example.
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-2)
UQ. What are the different ways for parameter passing to a function. Explain along with example.
OR Explain the difference in using call by reference and call by value methods for argument passing, for swapping
2 numbers. MU - Dec. 14, 8 Marks ............................................................................................................ 7-27
OR Explain call by value and call by reference with necessary example. MU - May 15, 8 Marks. ..................... 7-27
OR With reference to parameter passing to function explain call by value and call by reference with an example.
MU - Dec. 15, 10 Marks. ............................................................................................................................... 7-27
UQ. Write a program to swap two numbers using a function. Pass the values to be swapped to this function using
call-by-value method.MU - May 13, 2 Marks. ................................................................................................ 7-28
7.5.1(C) Difference between Call by Value and Call by Reference ............................................................................. 7-30
UQ. Explain difference between call by value and call by reference MU - May 13, 2 Marks. ............................. 7-30
UQ. Write program to swap to values by using call by reference concept MU - Dec. 17, 4 Marks. ..................... 7-31
7.6.1 Difference between Static and Dynamic Memory Allocation .......................................................................... 7-35
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-3)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-4)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-5)
Suppose the variable a stores at location 2000 and the 7.1.3 Dereferencing Pointer
pointer variable ptr is located at location 5000.
The statement ptr=&a; assigns the address of a to ptr UQ. Explain reference and de-reference operators
with example. MU - May 13, 3 Marks.
so in memory at location 5000 the 2000 is copied.
The dashed line says that the ptr points the value Ans. :
located at location 2000. Dereferencing Pointer
As variable declaration and initialization can be Dereferencing is used to access or manipulate data
combined in single statement, in the same way the contained in memory location pointed to by a pointer.
declaration of pointer and initialization of pointer can *(asterisk) is used with pointer variable when
be combined in one statement as follows: dereferencing the pointer variable, it refers to variable
being pointed, so this is called dereferencing of
int * b = & a;
pointers.
Consider a is an integer which holds an integer value 5.
In declaration and initialization of pointers two
So above statement states that the pointer variable b
operators are used .
holds the address of an integer variable a.
Pointer declaration is done with ‘*’ symbol and
Another examples of pointers are :
address of the variable can be assigned to it using ‘&’
char ch=’A’; symbol.
char *q;
C provides two pointer operators
q=&ch;
Here the first statement initializes the character A to
variable ch. In second statement char *q means q is a
pointer that will point the character value stored in
variable ch. It is represented in Fig. 7.1.4.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-6)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-7)
GQ. Write a program to demonstrate use of pointers. printf("\nNew address in ptr_a = %u", ptr_a);
(5 Marks) printf("\nNew address in ptr_b = %u", ptr_b);
printf("\nNew address in ptr_c = %u", ptr_c);
Ans. :
Prints value new values of
Program ptr_a, ptr_b, and ptr_c.
#include<stdio.h> return 1;
#include<conio.h> }
int main() Output :
{
int a, *ptr_a;
float b, *ptr_b;
char c, *ptr_c;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-8)
3. Increment
7.2 OPERATIONS ON POINTERS
Increment is unary operation. It increment the value of
operand by 1.There are two types: Prefix increment
GQ. With suitable example, list different pointer
and Postfix increment
arithmetic operations. (10 Marks)
(i) Prefix increment
Ans. :
When prefix ++ is used in an expression, the value
Operations on Pointer stored at location specified by pointer is incremented
Performing arithmetic operations with pointers is first and then the expression is evaluated using the new
known as pointer arithmetic. In pointer arithmetic the value pointed by the pointer.
basic arithmetic operations like, addition, subtraction, Example
multiplication, division has pointers as their operands.
Suppose *p is a pointer and variable a = 5 and c = 0.
Different pointer arithmetic operations p = &a;
c = 5 * ++(*p)
Here first the value stored at location specified by
pointer *p is incremented by 1 i.e. ++5 = 6. And then
the new value is used to calculate the expression so c
will be 5 * 6 = 30. So after performing the expression
c = 30 and a = 6.
(ii) Postfix increment
When postfix ++ is used with a pointer in an
expression ,the expression is evaluated first using the
original value located at the specified location by
pointer and then the value is incremented by one.
Example
Suppose *p is a pointer and variable a = 5 and c = 0.
p = &a;
c = 5*(*p)++
Fig. 7.2.1 : Pointer Arithmetic Operations
Here first the value stored at location specified by *p is
Suppose *p and *q are two pointers, and the variables used to solve the expression i.e. 5*5=25 is copied into
a = 20 and b = 10, c=0 then variable c and then value stored at location specified
1. Addition by *p is incremented by 1 i.e. a will be 5+1 = 6 now.
So after performing the expression c = 25 and a=6.
p = &a;
4. Decrement
q = &b;
c = *p + *q Decrement is unary operation. It decrement the value
of operand by 1.There are two types: Prefix decrement
After performing addition c has the value 30
and Postfix decrement
2. Subtraction
(i) Prefix decrement
p = &a;
When prefix -- is used in an expression, the value
q = &b; stored at location specified by pointer is decremented
c = *p - *q first and then the expression is evaluated using the new
After performing subtraction c has the value 10 value pointed by the pointer.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-9)
Ans. :
Program
#include<stdio.h> GQ. Write a program to find product of two numbers
#include<conio.h> using pointer. (5 Marks)
main()
{ Ans. :
int a, b, *ptr1, *ptr2, x, y, z; Program
a = 12; # include<stdio.h>
b = 4; int main()
ptr1 = &a; {
ptr2 = &b; int num1, num2;
x = *ptr1 * *ptr2 - 6; int *ptr1, *ptr2;
y = 4* - *ptr2 / *ptr1 + 10;
printf("The address of a = %u\n", ptr1); printf("\n Enter first number:");
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-10)
scanf("%d", &num1); GQ. Write a program to print terms of Fibonacci
printf("\n Enter second number:"); series using pointers. (5 Marks)
ptr1=&num1; #include<stdio.h>
ptr2=&num2; #include<conio.h>
printf("\n Product of two numbers: %d * %d = %d”, int main() Stores entered value in range variable
*ptr1,*ptr2, (*ptr1)*(*ptr2));
{
int range,i=0,j=1,k,f;
Prints value Prints result of
multiplication of value int *ptr_range,*ptr_i,*ptr_j;
pointed by ptr1
pointed by ptr1 and value ptr_range=⦥
Prints value pointed by ptr2.
ptr_i=&i;
pointed by ptr2
ptr_j=&j;
printf("\nEnter the number range of fibonacci series:\t");
return 1;
scanf("%d",* (& ptr_range);
}
printf("\nFIBONACCI SERIES: ");
Output
printf("%d %d",i,j); Prints “0 1”
for(k=2;k<*ptr_range;k++)
{
Calculates next number in
f=*ptr_i+*ptr_j; series and print it
printf(" %d",f);
*ptr_i=*ptr_j;
Explanation Assigns last two values in the
*ptr_j=f; series to ptr_i and ptr_j
Modified values are :
}
num1 num2 *ptr1 *ptr2
return 1;
User 12 10
inputs }
ptr1 = 12 10 12 Output
&num1
ptr2 = 12 10 12 10 Result
&num2
(*ptr1) * 12 10 12 10 = 120
(*ptr2)
Note
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-11)
Explanation
Modified values are :
i j K f Range *ptr_range *ptr_i *ptr_j
Initially 0 1
ptr_i = &i 0 1 0
ptr_j = &j 0 1 0 1
User input 15 15
Iteration 1 : 0 1 2 15 15 0 1
k < *ptr_range i.e.
2 < 15 is true
f=*ptr_i+*ptr_j 0 1 2 1 15 15 0 1
*ptr_i=*ptr_j 0 1 2 1 15 15 1 1
*ptr_j=f 0 1 2 1 15 15 1 1
k++ 0 1 3 1 15 15 1 1
Iteration 2 : k < *ptr_range i.e.
3 < 15 is true
f=*ptr_i+*ptr_j 0 1 3 2 15 15 1 1
*ptr_i=*ptr_j 0 1 3 2 15 15 1 1
*ptr_j=f 0 1 3 2 15 15 1 2
k++ 0 1 4 2 15 15 1 2
Iteration 3 : k < *ptr_range i.e.
4 < 15 is true
f=*ptr_i+*ptr_j 0 1 4 3 15 15 1 2
*ptr_i=*ptr_j 0 1 4 3 15 15 2 2
*ptr_j=f 0 1 4 3 15 15 2 3
k++ 0 1 5 3 15 15 2 3
Iteration 4 : k < *ptr_range i.e.
5 < 15 is true
f=*ptr_i+*ptr_j 0 1 5 5 15 15 2 3
*ptr_i=*ptr_j 0 1 5 5 15 15 3 3
*ptr_j=f 0 1 5 5 15 15 3 5
k++ 0 1 6 5 15 15 3 5
Iteration 5 : k < *ptr_range i.e.
6 < 15 is true
f=*ptr_i+*ptr_j 0 1 6 8 15 15 3 5
*ptr_i=*ptr_j 0 1 6 8 15 15 5 5
*ptr_j=f 0 1 6 8 15 15 5 8
k++ 0 1 7 8 15 15 5 8
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-12)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-13)
GQ. Write the value of d in the following component 7.3 USE OF POINTER IN ARRAY
of program (1 Mark)
int a = 20;
GQ. Explain use of pointer in array. (5 Marks)
int * b = & a
int * c = b Ans. : Use of pointer in array
int d = * b + * c; Array is collection of same type of elements. And they
are stored in memory in contiguous block. So to access
Ans. : elements easily pointers are very useful while handling
Errors array.
For statement 2 and 3 expected ; at the end. While dealing with array if the address of first element
is assigned to pointer then it will be easy to access all
Code after correcting the errors the element one by one by incrementing or
int a = 20; decrementing the pointer. Because all the elements
int * b = & a; have same data type so all uses same memory size.
int * c = *b; Any operation that can be accomplished by using array
int d = * b + * c; subscript is possible to accomplish by using pointers
Output also.
Address of first element is referred as the base address.
d = 20 + 20 = 40
Base address is used to assign the pointer to array.
GQ. The following is segment of a program : Let’s see the example to understand use of pointers in
void main ( ) array:
{ Suppose an x[] is defined and initialized as below :
int a, b, *p1, *p2, x, y; int x[ ]= {10,20,30,40,50};
a = 10; b = 5; memory map of x[] will be as follows.
p1 = & a;
p2 = & b;
x = * p1 * * p2 – 6;
y = * p1 * * p2 + 10;
printf (“a = %d, b = %d”, a, b);
printf (“x = %d, y = %d”, x, y);
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-14)
int *ptr = &x[0]; float *ptr;
This statement assigns the address of 0 th
array for(i=0;i<5;i++)
element(i.e. first element = 10) to pointer ptr. {
printf("\n Enter a float array element: ");
scanf("%f", &x[i]);
printf("\n Entered element is stored at %u\n",&x[i]);
}
Assigns address of x[0] to ptr. It also
ptr=&x; can be written as ptr=&x[0]
Fig. 7.3.1(b)
Ans. :
Program Explanation
# include<stdio.h> First for loop accepts elements from user and store
int main() them in x[] array.
{ ptr=x;
float x[5]; will assigns the address of x[0] to ptr. So now the ptr
int i=0; points to the first element of array x[].
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-15)
Loop will be executed 5 times and each time it prints Iteration 5 ptr = 2293428, i=4
the value pointed by ptr and then increments the ptr Prints *ptr and ptr i.e. 50.1 and 2293428
by 1.
As user enters five elements like follows and ptr is Increments ptr it will plus the size of float
pointing to first element i.e. x[0] like : into value stored in ptr i.e.
2293428+4 = 2293432
Increments i ; i.e. now i=i+1 = 4+1 = 5
Iteration 6 ptr = 2293432, i=5 While condition false
so it will exit the loop
Ans. :
Program
Fig. 7.3.2
#include<conio.h>
While loop will executes 5 times #include<stdio.h>
Iteration 1 ptr = 2293412, i=0 int main()
{
Prints *ptr and ptr i.e. 10.5 and 2293412
int *ptr, sum=0, number[5],i=0;
Increments ptr, it will plus the size of float
for(i=0;i<5;i++)
into value stored in ptr i.e.
{
2293412+4 = 2293416
printf("\n Enter %dth element ",i); Accepts array
Increments i ; i.e. now i=i+1 = 0+1 = 1 elements
scanf("%d", &number[i]); from user.
Iteration 2 ptr = 2293416, i=1 }
Prins *ptr and ptr i.e. 20.4 and 2293416 i=0;
Increments ptr, it will plus the size of float ptr=&number[0]; Calculates
into value stored in ptr i.e. for(i=0;i<5;i++) sum of all
2293416+4 = 2293420 { elements in
array
Increments i ; i.e. now i=i+1 = 1+1 = 2 sum=sum+(*ptr++);
Iteration 3 ptr = 2293420, i=2 }
printf("\n Sum of array elements = %d", sum);
Prints *ptr and ptr i.e. 30.3 and 2293420
return 1;
Increments ptr it will plus the size of float }
into value stored in ptr i.e.
2293420+4 = 2293424 Output
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-16)
Explanation
Elements f array are accepted for user so array will be number[] as follows and ptr points to first element of array i.e.
number[0].
Fig. 7.3.2(a)
So now the while loop will calculate the sum of all elements in array using pointer as follows :
number [0] number [1] number [2] number [3] number [4] i sum *ptr
Initially 0 0
User inputs 10 20 30 40 50 0 0
ptr = 10 20 30 40 50 0 0 10
&number [0]
while(0<5) is
true
sum = sum + 10 20 30 40 50 0 Sum = 20
(*ptr++) 0+10 = 10
i++ 10 20 30 40 50 1 10 20
while(1<5) is
true
sum = sum + 10 20 30 40 50 1 Sum = 30
(*ptr++) 10+20 =
30
i++ 10 20 30 40 50 2 30 30
while(2<5) is
true
sum = sum + 10 20 30 40 50 2 Sum = 40
(*ptr++) 30+30 =
60
i++ 10 20 30 40 50 3 60 40
while(3<5) is
true
sum = sum + 10 20 30 40 50 3 Sum = 50
(*ptr++) 60+40 =
100
i++ 10 20 30 40 50 4 100 50
while(4<5) is
true
sum = sum + 10 20 30 40 50 4 Sum = Garbage
(*ptr++) 100+50 = value
150
i++ 10 20 30 40 50 5 150
while(5<5) is
false
Last value of sum is printed i.e.150
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-17)
GQ. Write a program to accept array elements and Now i=0 and 0<5 is true
print them in reverse order. (5 Marks)
so prints 25,
Ans. : Program and decrements ptr so it will point to num[3]
#include<conio.h>
#include<stdio.h>
int main()
{
int num[5],i=0,j=0;
int *ptr;
for(i=0;i<5;i++)
{
printf("Enter %dth element : ", i);
scanf("%d", &num[i]); Accepts array
elements from user
Fig. 7.3.3(b)
}
Explanation
Elements of array are accepted from user so array
Fig. 7.3.3(c)
Increments i by 1
Now i=2 and 2<5 is true
so prints 15,
and decrements ptr so it will point to num[1]
Fig. 7.3.3(a)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-18)
Fig. 7.3.3(d)
Increments i by 1
Now i=3 and 3<5 is true
So prints 10 and decrements ptr so it will point to
num[0]
Fig. 7.3.4
In memory 2D array is stored like.
Fig. 7.3.3(e)
Increments i by 1.
Now i=4 and 4<5 is true
So prints 5, and decrements ptr so it will point to a Fig. 7.3.5
garbage value Here to access x[i][j] use *(p + i * size of column + j)
Increments i by 1 Example
Now i=5 and 5<5 is false so it will exit the loop To access x[3][2] use
GQ. How 2D array can be handle using pointers? *(p+3 * 3+2) = *(p + 9 +2) = *(p +11)
(3 Marks) = i.e. value at p + 11
Ans. : Handling 2D array with pointer As we know the p+1 will add size of data type into
Pointer can be used to manipulate the 2D arrays. In 1D value of p i.e. if p is integer pointer and p=2000 the
array that the statement p+1 will 2000+4=2004
ptr+i is the memory address of x[i], and *(ptr+i) is the Similarly, p+11 will be p+11*2 = p+22 = value at 2023
value of x[i]. location.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-19)
Prints value Considering the compiler who reserves 4 bytes for int ;
printf("x[2][0] = %d\n",*(p+2 * 3+0)); in x[2][0] 4*4=16 therefore 2001+16=2017 i.e. x[1][1] = 5
*(p+2 * 3+0) indicates *(p+6+0) = *(p+6) so it will
Prints value add 6*size of int
printf("x[3][2] = %d\n",*(p+3 * 3+2)); in x[3][2]
Considering the compiler who reserves 4 bytes for int ;
6*4=24 therefore 2001+24=2025 i.e. x[2][0] = 7
return 1;
} *(p+3 * 3+2) indicates *(p+9+2) = *(p+11) so it will
add 11*size of int
Output
Considering the compiler who reserves 4 bytes for int ;
11*4=44 therefore 2001+44=2045 i.e. x[3][2] = 12
Ans. : Program
#include<stdio.h>
#include<conio.h>
int main()
{ count is used to
calculate length of
char str[10],*ptr,count; string
printf("\n Enter the string: ");
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-20)
gets(str); Here ptr is not null so count is incremented by 1 so
count = 2
ptr=&str[0]; Base address of str[] is assigned to ptr.
ptr is incremented so now it points to third character in
count=0;
str i.e. o like :
While loop continues until
while(*ptr != NULL) *ptr points to end of string
{
count++;
ptr++; Points to next character in the string
} Fig. 7.3.10
printf("\n Length of string = %d",count);
return 1; Here ptr is not null so count is incremented by 1 so
} count = 3
Output ptr is incremented so now it points to fourth character
in str i.e. d like:
Accepts string from user and store it in str[] and the Here ptr is not null so count is incremented by 1 so
statement ptr = &str assigns address of first character count = 4
to ptr so *ptr points to first character of string i.e. G ptr is incremented so now it points to fifth character in
like: str i.e. a space character like :
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-21)
Ans. :
Program
#include<string.h>
#include<stdio.h>
Fig. 7.3.14
int main()
Here ptr is not null so count is incremented by 1 so
count = 7 {
ptr is incremented so now it points to eighth character char str[10];
in str i.e. e like : char *ptr;
int len,i=0;
Explanation
Program accepts string from user and store it in str[]
Fig. 7.3.17 and calculates the length of string by strlen(str) and
store the returned value in len.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-22)
The statement ptr = &str[len] assigns address of last now 2 < 7 is true and *ptr points to third last character
character to ptr. of string i.e. r like:
Prints *ptr i.e. r
Now decrements ptr by 1 so now it points to fourth last
character as follows
Increment the i by 1 so i = 3
Fig. 7.3.18
for loop will continue until i becomes equal to len=7
initially i=0
Now 0 < 7 is true so *ptr points to last character of
string i.e. m like : Fig. 7.3.22
Fig. 7.3.23
Fig. 7.3.24
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-23)
Fig. 7.3.25
Explanation
Now 6 < 7 is true and *ptr points to first character of This program accepts a sting from user and checks
string i.e. P like: whether m is present in entered string or not
Prints *ptr i.e. P
GQ. Write a program to find the number of vowels in
Now decrements ptr by 1 so now it points to garbage a string using pointer. (5 Marks)
value
Ans. : Program
Increment the i by 1 so i = 7
#include<stdio.h>
Now 7 < 7 is false so exit the loop.
#include<string.h>
GQ. Write a program to find a character in a string int main()
using pointer (5 Marks) {
char str1[10],*ptr;
Ans. :
int count=0,i;
Program printf("enter a string: ");
#include<stdio.h> scanf("%s",str1);
#include<string.h> for(ptr=str1;*ptr!='\0';ptr++)
int main() {
{ if(*ptr=='a'||*ptr=='A'||*ptr=='e'||*ptr=='E'||*ptr=
char str1[10],ch = 'm',*p; ='i'||*ptr=='I'||*ptr=='o'||*ptr=='O'||*ptr=='u'||*ptr
printf("enter a string: "); =='U')
Accepts a string from user count++;
scanf("%s",str1); and store it in str1
}
printf("number of vowels are: %d",count);
p=str1; Assigns address of first return 1;
character in str1 to ptr }
while(*p!=NULL) Output
{
If character pointed by ptr is same as
if(*p==ch) in ch then prints the position of that
{ character in str1.
Explanation
This program accepts a sting from user .
printf("character m is found at %d",p-str1);
break; For loop is used to check vowels in the string if
} character pointing by ptr is vowel then it increments
p++; Points to next character in str1 the count
} And at last the value of count is printed.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-24)
Fig. 7.4.1
and in memory it will reserve 3*10 = 30 bytes
Instead of reserving memory for strings of fixed length
we can use array of pointer to store strings of varying
lengths. Explanation
The dist_name [] has following strings.
Example 2
char *dist_name [3] = {"Mumbai", "Kolhapur", "Pune" };
The array will look like s:
Fig. 7.4.3
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-25)
GQ. Give the output of following code : (1 Mark) GQ. Explain concept of pointer to a pointer. (5 Marks)
# include <stdio.h> Ans. : Multiple Indirection (Pointer to Pointer)
void main ( )
Pointer variable can store address of another pointer. A
{ pointer points to another pointer which in turn points to
int * a [4]; another pointer, this forms a chain of pointer.
int i; Consider a variable var declared as below.
int m = 10, n = 20, p =30, q = 40; int var =10;
a [0] = & m;
in memory it reserves the space for integer as:
a [1] = &n;
a [2] = &p;
a [3] = &q;
for (i = 0; i < 4; i ++ )
Fig. 7.4.4
printf (“%d \n”, * a [1] );
Let’s declare a pointer to point 10
}
int *p1;
Ans. : Output p1 = &var;
Errors now link between var and p1 is created by copying the
address of var into p1 as:
It will print value stored at a[1] i.e. value of n=20 4
times due to for loop
Fig. 7.4.6
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-26)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-27)
Ans. : Program UQ. What are the different ways for parameter
passing to a function. Explain along with
#include<conio.h>
example. MU - Dec. 13, 10 Marks.
#include<stdio.h>
void display (int []); OR Explain the difference in using call by reference
int main() and call by value methods for argument passing,
{ for swapping 2 numbers. MU - Dec. 14, 8 Marks.
int num[4],i=0; OR Explain call by value and call by reference with
for(i=0;i<4;i++) necessary example. MU - May 15, 8 Marks.
{
OR With reference to parameter passing to function
printf("Enter element %d: ",i);
Accepts elements of explain call by value and call by reference with an
scanf("%d",&num[i]);
array from user example. MU - Dec. 15, 10 Marks.
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-28)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-29)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-30)
Output
7.5.1(C) Difference between Call by Value
and Call by Reference
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-31)
Ans. :
#include<stdio.h>
void swap(int *, int*);
int main()
{
int num1=50,num2=60;
printf("\n value of num1 and num2 before swapping:"); Fig. 7.5.6 : Initially Memory Map
printf("\n value of num1 :\t%d",num1); Prints values stored at num1 and num2 i.e. 50 and 60
printf("\n value of num1 :\t%d",num2); After swap(&num1.&num2) statement, control goes to
Call by reference: the function definition and copies the address of num1
swap(&num1,&num2); passes address of two to a i.e. now a contain 2000 and b contain 5000.
numbers to swap()
function
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-32)
int main()
Function call min()
{ accepts two
int m,num1=50,num2=60; parameters and
int *p; returns a pointer
back to calling
p = min(&num1,&num2); function
Explanation
Fig. 7.5.9
Ans. :
Program
#include<stdio.h>
#include<conio.h>
int* min(int *, int*); Fig. 7.5.10 : Initially Memory Map
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-33)
Here *a>*b is false i.e. 50>60 hence it returns It will tell the compiler that the ptr_name is a function
a (else part) to the main() function. So now the address and returns a pointer of type data_type.
stored at b is copied into p and p points to the value stored in The empty parenthesis indicates it points to a function.
num1.
Examples
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-34)
GQ. Write a program to multiply two numbers using Array is considered as an example of static memory
pointer to function. (5 Marks) allocation i.e. the size of array is fixed. While declaring
an array we have to compulsory mention the size.
Ans. : Program
Example
#include<stdio.h>
#include<math.h> Declares a pointer to int arr[5];
double mul(double, double); a function which
accepts two double
double(*p1) (double, double); values and return a
int main() double
{ This is an array arr of type int and size 5.
double x = 2.5, y = 3.4, z; Size indicates the maximum elements which can be
stored in the array.
Assign the address
p1 = mul; of function mul() In this array we can store maximum of 5 elements.
But in real life application, it is difficult to predict the
Calls the mul () function and maximum elements to be stored as the data is accepted
z = (*p1)(x,y); passes x to a and y to b and also from end user at run time.
printf("%lf",z); after function call assigns the
returned value to z Hence if there is requirement of storing elements more
return 1;
than size of the array, then memory shortage occurs
}
and we cannot store more elements than the size of an
double mul(double a, double b)
array.
{
return a * b ; Now in the above array, if only three elements are
} stored, then the memory will be wasted.
Output
precedence of ( ) is greater than *. This statement will Dynamic memory allocation means memory can be
call the function mul() which multiplies two values and allocated or de-allocated as per the requirement at run
returns the result back to calling function. time.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-35)
Examples Used in array. Used in linked list. GQ. Explain the use of free() function with syntax.
(2 Marks)
7.6.2 Functions for Dynamic Memory
Allocation Ans. :
free()
GQ. Explain functions for dynamic memory allocation.
Dynamically allocated memory created with either
(3 Marks) calloc() or malloc() doesn't get freed on its own. The
Ans. : free() function is used explicitly to release the space.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-36)
int cnt, i, *ptr, sum = 0; For example
printf("How many elements: ");
ptr = (float*) calloc(30, sizeof(float));
scanf("%d", &cnt);
This statement allocates contiguous space in memory
for an array of 30 elements each of size of float,
ptr = (int*) malloc(cnt * sizeof(int));
i.e, 4 bytes.
//memory allocated using malloc
if(ptr == NULL) GQ. Write a C program to find sum of n elements
{ entered by user. To perform this program,
printf("Error in allocating memory"); allocate memory dynamically using calloc()
exit(0); function. (5 Marks)
}
Ans. :
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-37)
GQ. Explain the use of realloac() function with syntax. GQ. Differentiate between malloc() and calloc()
(2 Marks)
(2 Marks)
Ans. :
Ans. :
realloc()
Difference between malloc() and calloc()
If the initially allocated memory is not sufficient or
Parameter calloc() malloc()
more than necessity, it is possible to change the
initially allocated memory size with the help of Initial calloc() initializes malloc() initializes
realloc(). value the allocated the allocated memory
memory with 0 with garbage value.
Syntax of realloc()
value.
ptr = realloc(ptr, newsize);
Number of Number of Number of argument
Here, ptr is reallocated with size newsize.
arguments arguments is 2 is 1
Example : Using realloc()
Syntax : (cast_type *) (cast_type *)
#include <stdio.h>
calloc(blocks, malloc(Size_in_bytes);
#include <stdlib.h>
size_of_block);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-38)
GQ. Write a program to find area of circle using printf(“\n value pointed by pointer variable *p is:\t%d”,*p);
pointer. (5 Marks)
return 1; Prints value pointed by p
Ans. : }
Program Output :
# include<stdio.h>
# include<math.h>
int main()
{
float r,area, *radius;
GQ. Write a program using pointers to compute the
printf("\n Enter radius of circle:");
sum of all elements stored in an array. (5 Marks)
scanf("%f", &r);
radius = &r; Ans. :
area = 3.14 * *radius * *radius;
Program
printf("\n Area of circle is : %f", area);
#include<conio.h>
return 1;
#include<stdio.h>
}
int main()
Output
{
int *ptr, sum=0, number[5],i=0;
for(i=0;i<5;i++)
{
printf("\n Enter %dth element ",i); Accepts array
elements
scanf("%d", &number[i]);
GQ. Write a program to demonstrate the concept of from user.
}
pointer. (5 Marks)
i=0;
Ans. : Program ptr=&number[0]; Calculates
#include<stdio.h> for(i=0;i<5;i++) sum of all
int main() { elements in
array
{ sum=sum+(*ptr++);
int no = 50; }
int *p; Pointer declaration printf("\n Sum of array elements = %d", sum);
return 1;
p = &no; Pointer intialzation }
Output
printf(“\n value store in variable no is:\t%d”,no);
Prints address of p
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (7-39)
GQ. Write a program to accept array elements and printf("\n %5.2f is stored at %u", *ptr, ptr);
print those using pointers. (5 Marks) ptr++;
i++;
Ans. : Program Prints address stored by ptr
}
# include<stdio.h>
return 1;
int main()
}
{
float x[5]; Output
int i=0;
float *ptr;
for(i=0;i<5;i++)
{
printf("\n Enter a float array element: ");
scanf("%f", &x[i]);
printf("\n Entered element is stored at %u\n",&x[i]);
}
Assigns address of x[0] to ptr. It also
ptr=&x; can be written as ptr=&x[0]
Chapter Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
Lab Manual
Assignment 1 : Basic data types and I/O operations Ans. : Program to convert distance
r = n1 - n2;
Distance_In_Meters = Distance_In_KiloMeters * 1000;
printf("\n Subtraction : %d",r);
Distance_In_Feet = Distance_In_KiloMeters * 3280.84;
r = n1 * n2; Distance_In_Inches = Distance_In_KiloMeters * 39370.1;
printf("\n Multiplcation : %d",r); Distance_In_Centimeters = Distance_In_KiloMeters *
100000.054;
r = n1 % n2;
printf("\n Modulo : %d",r); printf("\nDistance in meters : %.2f", Distance_In_Meters);
printf("\nDistance in feet : %.2f", Distance_In_Feet);
getch();
printf("\nDistance in inches : %.2f", Distance_In_Inches);
}
printf("\nDistance in centimeters : %.2f",
Output
Distance_In_Centimeters);
Soln. :
Program
getch() and putch()
# include<stdio.h> // including header file #include<stdio.h>
Includes header files
int main() #include<conio.h>
{ int main()
char ch=getch(); {
return 0; int n;
} Accepts number
printf("\n Enter a number : ");
If we press p then it will store the character in ch but from user
scanf("%d",&n);
will not display anything on the screen and exit from
the program.
And if we write the same program with putch(ch) as if(n>100) Checks whether number is greater than
100; If Yes then Message will be
follows : { display.
# include<stdio.h> // including header file
int main() printf("\n Number is greater than 100");
{ }
char ch=getch(); return 0;
putch(ch); }
return 0;
Output
}
And press P then due to putch ( ) function the output
will be :
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-3)
Program Output
#include<stdio.h>
Includes header files
#include<conio.h>
main()
{
int n;
GQ. Write a program to accept marks of 3 subjects
printf("\n Enter a number : "); Accepts number
from user from student. Calculate the total and average of
scanf("%d",&n);
marks. If the average is >= 40 then give the
remark as pass otherwise fail.
if(n>100) If the
condition Program
{ is true this
printf("\n Number is greater than 100"); message will #include<stdio.h>
} be displayed #include<conio.h>
else main()
{ If condition is {
false then this
printf("\n Number is less than 100"); message will be
int hindi,marathi,english,total,average;
} displayed.
} printf("\n Enter a marks of 3 subects : "); Accepts
marks
scanf("%d %d %d",&hindi,
Output from user
&marathi,&english);
}
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-4)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-5)
case 3: main()
Multiplicatio
result = n1 * n2; n if choice {
printf("\n Multiplication is %d",result); matches
with 3.
break; int n,n1,rem,sum;
sum = 0;
case 4: printf("\n Enter a number : ");
scanf("%d",&n);
if(n2!=0) n1 = n;
{ while(n>0)
result = n1 / n2; {
printf("\n Division is %d",result); rem = n % 10;
Division if
} choice matches sum = sum + (rem*rem*rem);
else with 4 n = n / 10;
{ }
Until the number becomes 0 it will repeat the loop statements. To get
printf("\n Cannot divide by zero"); digits from the number we calculate the remainder by dividing the
} number with 10
break;
if(sum==n1)
If none of the above case is
default: satisfied then this printf("\n Number is Armstrong");
printf("\n Invalid choice"); message else
} will be displayed. printf("\n Number is not Armstrong");
}
If given number is same as addition of cubes of digits
Output of the number then it is Armstrong number.
}
Output
UQ. Write a program to check if the entered number UQ. Write a program to check whether the given
is Armstrong or not. MU - Dec. 15, 10 Marks. number is palindrome or not. i.e. if no is 12421 it
is palindrome. MU - May 14 , 10 Marks.
Ans. :
e.g. 153 is Armstrong number. The summation of cubes
Ans. :
of all the digits should be exactly equal to the number Program
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-6)
while( n!=0 ) number++;
{ }
rem = n%10; }
reverse_no = reverse_no*10 + rem; Output
n = n/10;
}
if (original_no == reverse_no)
printf("The number is palindrome.");
Prints if the given number and the reverse are same.
else
UQ. Write a program to find GCD and LCM of 2 nos.
printf("The number is not palindrome.");
return 0; MU - Dec. 14, 6 Marks.
}
Ans. :
Output #include <stdio.h>
main()
{
int num1, num2, gcd, lcm, remainder, numerator,
UQ. Write a program to display Armstrong numbers denominator;
between 1 to 1000. MU - May 13, 6 Marks.
printf("Enter two numbers : ");
Ans. : scanf("%d %d", &num1, &num2);
#include <stdio.h> if (num1 > num2)
{
main() numerator = num1;
{ denominator = num2;
}
int number, temp, digit1, digit2, digit3;
else
{
printf("Print all Armstrong numbers between 1 and
numerator = num2;
1000:\n");
denominator = num1;
number = 001;
}
while (number <= 900) remainder = numerator % denominator;
{ while (remainder != 0)
digit1 = number - ((number / 10) * 10); {
digit2 = (number / 10) - ((number / 100) * 10); numerator = denominator;
digit3 = (number / 100) - ((number / 1000) * 10); denominator = remainder;
temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * remainder = numerator % denominator;
digit2) + (digit3 * digit3 * digit3); }
if (temp == number) gcd = denominator;
{ lcm = num1 * num2 / gcd;
printf("\n %d", temp); printf("GCD of %d and %d = %d\n", num1, num2, gcd);
} printf("LCM of %d and %d = %d\n", num1, num2, lcm);
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-7)
Output i = 1;
printf("1 2 ");
do
{
c = a + b; Loop will execute until i is
less than 5 In Fibonacci
printf (" %d ",c); series every number is
a = b; addition of its previous
two numbers.
b = c;
UQ. Write a program to find out binary equivalent of i = i + 1;
given decimal number. MU - May 15, 5 Marks. }while(i<5);
Ans. : }
#include<stdio.h> Output
int main()
{
int decimalnum, rem, temp = 1; UQ. Write a algorithm and program to generate a
long binarynum = 0; factor of given number MU - May 15, 8 Marks.
Program
UQ. Write a program to display the following :
#include<stdio.h>
*
#include<conio.h>
**
main()
***
{
****
int a,b,c,i;
***** MU - Dec. 15, 5 Marks.
a = 1;
b = 2;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-8)
Ans. : Output
Program
#include<stdio.h>
#include<conio.h>
main()
{
int i,j;
for(i=1;i<=5;i++)
Outer loop
{
for(j=1;j<=i;j++)
{
Inner loop
printf("* ");
}
printf("\n");
}
}
Ans. :
#include <stdio.h>
int main()
{
int i, Number, count;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-9)
Ans. : Output
#include<stdio.h>
int main() {
int i, j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%c ",'A' + j-1);
}
printf("\n"); UQ. Write a program to generate following patterns.
} 1
} 23
456
Output
7 8 9 10 MU - May 14, 5 Marks.
Ans. :
#include<stdio.h>
int main() {
int i,j, k=1;
for(i=1;i<=5;i++)
{
for(j=1;j<i;j++)
UQ. Write a program to generate following patterns. {
5 printf("%d ",k);
4 4 k++;
3 3 3 }
2 2 2 2 printf("\n");
1 1 1 1 1 MU - Dec. 13, 10 Marks. }
return 0;
Ans. :
}
#include<stdio.h>
int main() { UQ. Write a program to calculate summation of
int a, i; series. 1/2 – 3/4 + 5/6 – 7/8 + …….. upto n terms.
for(a = 5; a >= 1; a--) MU - May 14, 10 Marks.
{
for(i = a;i <= 5;i++) Ans. :
{ #include<stdio.h>
printf("%d ", a); int main() {
} int i,j,n;
printf("\n"); float sum = 0;
} printf("Enter the value of n : ");
return 0; scanf("%d",&n);
} for(i=1,j=1;i<=n; i++,j=j+2)
{
sum=sum+(float)(j)/(j+1);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-10)
} {
printf("Sum of series is %f",sum); for (j=1; j <=i-1; j++)
{
} printf (" ");
Output: }
for (j=1; j <=5-i; j++)
{
printf ("%c",(char)(j+64));
}
printf ("\n");
Q. Write a program to print the following pattern. }
(Note : Not only 4 lines, it should print n lines
taken from user) }
A
UQ. Write a Program to calculate summation of
B B
series. 1 – x2/2! + x4/4! – x6/6! + x8/8! upto n
C C C
terms. MU - Dec. 15, May 16, 10 Marks.
D D D D MU - Dec. 14, 8 Marks.
Ans. : Ans. :
#include<stdio.h>
#include<stdio.h>
int main() {
int main()
int i,j;
{
for(i='A';i<'E';i++)
{
int counter,f_coun;
for(j='A';j<=i;j++)
float sum=0,x,power,fact;
{
printf("%c ",i);
printf("\nEQUATION SERIES : 1- X^2/2! + X^4/4! -
}
X^6/6! + X^8/8! - X^10/10!");
printf("\n");
}
printf("\n\tENTER VALUE OF X : ");
}
scanf("%f",&x);
UQ. Write a program to display following pattern.
ABCD for(counter=0, power=0; power<=10;
ABC counter++,power=power+2)
AB {
A MU - May 15, 5 Marks. fact=1;
//Factorial of POWER value.
Ans. : for(f_coun=power; f_coun>=1; f_coun--)
#include<stdio.h> fact *= f_coun;
//The main equation for sum of series is...
int main() sum=sum+(pow(-1,counter)*(pow(x,power)/fact));
{ }
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-11)
else
{
++count1;
UQ. Generate the following pattern of digits using
printf("%d ", (i+k-2*count1));
nested loops. MU - Dec. 15, Dec. 17, 5 Marks.
}
1 ++k;
232 }
//reset all values to 0,except CurrentRow value and total
34543 row value
4567654 count1 = count = k = 0;
Ans. : printf("\n");
#include<stdio.h> }
return 0;
int main()
{ }
UQ. Write a program to generate following pattern.
int i, space, rows, k=0, count = 0, count1 = 0;
A
CB
printf("Enter number of rows: ");
FED
scanf("%d",&rows);
JIHG
ONMLK MU - May 16, 5 Marks.
for(i=1; i<=rows; ++i)
{ Ans. :
//print space until sapce value is not equal/less than #include<stdio.h>
(sapce-i), where
// i is current row Number
int main()
for(space=1; space <= rows-i; ++space)
{
{
printf(" ");
int n,i,j,m=65,k=64;
++count; //increment count after each space
n = 5;
}
for(i=1;i<=n;i++)
{
//after printing all spaces, let's start number printing loop
k=k+i;
// here while loop is used and it will print unless
m=k;
//k is not euqal to 2*CurrentRow-1
for(j=0;j<=n-i;j++)
while(k != 2*i-1)
printf(" ");
{
for(j=1;j<=i;j++)
//Now, looking at pattern formula is to print
printf("%c", m--);
I(CurrentRow)+ Current K
printf("\n");
// if Count is less than TotalRow -1
}
if (count <= rows-1)
}
{
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-12)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-13)
for(i=0;i<5;i++) {
{ if(array[j]<array[i]) Compare array[i] with array[j]
scanf("%d",&arr[i]); {
} temp=array[i]; If condition satisfies
printf("\nEnter number to search : "); array[i]=array[j]; Swap the array[i] and
array[j].
scanf("%d",&num); array[j]=temp;
}
for(i=0;i<5;i++) }
{ }
if(num==arr[i]) printf("\n ascending ordered array :\n");
{ for(i=0;i<10;i++)
printf("\nNumber found"); { Prints the sorted array in
break; printf("%d\t",array[i]); ascending order.
} }
} return 1;
}
if(i==5) Output
printf("\nNumber not found");
}
Output
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-14)
{
temp=array[i]; If condition satisfies
array[i]=array[j]; Swap the array[i] and for (i = 0; i < n; i++)
array[j].
array[j]=temp; {
} if (ARR[i] % 2 == 0)
} {
} EAR[j] = ARR[i];
printf("\n ascending ordered array :\n"); j++;
for(i=0;i<10;i++) }
{ Prints the sorted array in else
printf("%d\t",array[i]); ascending order. {
} OAR[k] = ARR[i];
return 1; k++;
} }
}
void main()
{
printf("Enter the size of array : "); UQ. Write a program which will accept 2 dimensional
scanf("%d", &n); square matrix and find out transpose of it.
Program should not make use of another matrix.
printf("Enter the elements of the array : "); MU - Dec. 13, May 14, Dec. 15, 10 Marks.
for (i = 0; i < n; i++)
{ Ans. :
scanf("%d", &ARR[i]); # include<stdio.h>
int main()
} {
int matrix[2][2],i=0,j=0;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-15)
for (i=0;i<2;i++) UQ. Write a C program to
{ i. Create a 2D array (Matrix) [in main function]
for(j=0;j<2;j++) ii. Write a function to read 2D array (Matrix)
{ iii. Write a function that will return true (1) if
printf("Enter matrix[%d][%d] element : ",i, j); entered matrix is symmetric or false (0) is not
symmetric.
scanf("%d", &matrix[i][j]); iv. Print whether entered matrix is symmetric or
} not [ in main function ]
} MU - May 18, 10 Marks.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-16)
r = is_symmetric(a,rows,cols); sum=0;
if(r==1) for(k=0; k<3; k++)
printf("Symmetric Matrix"); {
else sum = sum + mat1[i][k] * mat2[k][j];
printf("Not Symmetric Matrix"); }
mat3[i][j] = sum;
} }
Output: }
printf("\nMultiplication of two Matrices : \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%d ", mat3[i][j]);
UQ. Write a program to calculate matrix
}
multiplication and transpose for a matrix.
printf("\n");
MU - May 13, Dec.17,Dec.18, 8 Marks. }
getch();
Ans. :
}
Multiplication of Matrices
Output
#include<stdio.h>
#include<conio.h>
void main()
{
int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k;
printf("Enter first matrix element (3*3) : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&mat1[i][j]);
}
}
Transpose of matrix
printf("Enter second matrix element (3*3) : ");
# include<stdio.h>
for(i=0; i<3; i++)
int main()
{
for(j=0; j<3; j++)
{
{
int orign_matrix[3][3], trans_matrix[3][3],i=0,j=0;
scanf("%d",&mat2[i][j]);
for (i=0;i<3;i++)
}
}
{
printf("Multiplying two matrices...\n");
for(j=0;j<3;j++)
for(i=0; i<3; i++)
{
{
printf("Enter matrix[%d][%d] element ",i, j);
for(j=0; j<3; j++)
{
scanf("%d", &orign_matrix[i][j]);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-17)
trans_matrix[j][i] = orign_matrix[i][j]; Assignment 5 : Strings
Ans. : Program
# include<stdio.h>
#include<string.h>
int main()
{
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-18)
int len=0, i=0; while (s[count] != '\0')
char str[10]; count++;
int flag=0; end = count - 1;
printf("Enter string : ");
scanf("%s", str); Accept string from user and store for (begin = 0; begin < count; begin++) {
it in a character array str.
len = strlen(str); r[begin] = s[end];
end--;
Loop will continue until i become
while(i<len/2) }
half of the length of str array.
{
if(str[i]!=str[len-i-1]) r[begin] = '\0';
{
flag=1; If condition satisfies the flag is set to 1 printf("%s\n", r);
break; return 0;
} }
i++; Output
}
if(flag==0)
Prints if initial
printf("\n String is palindrome"); value of flag is
not changed.
else
Prints if initial
printf("\n String is not palindrome");
value of flag UQ. Implements string copy function STRCOPY (str1,
getch(); is changed.
str2) that copies a string str1 (source) to another
}
string str2 (destination) without using library
Output function. MU -May 18, 5 Marks.
Ans. :
Program
# include<stdio.h>
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-19)
{
second_str[i]=first_str[i]; Copies character at {
i++; first_str[i] into int i=0,j=0; Checks whether
second_str[i]. memory is
} if(l1+l2<20) sufficient to copy
{ a string or not
second_str[i]=’\0’; Copies null character at the end. for(i; i<l2;i++)
{
printf("\nAfter copy:\t First String=%s and Second s1[i]=s2[i];
String=%s", first_str,second_str); }
Specifies the end of
printf("\nNumber of characters copied are %d", i); s1[i]='\0'; string after copy
return 1; }
} else
Output {
printf("string is too large can't be copied.");
}
printf("\nAfter copy\nFirst string: \t%s”,s1);
printf(“\nSecond string:\t%s",s2);
}
Output
UQ. Write a user defined function to copy one string
to another. MU - Dec. 14, 5 Marks.
Ans. :
Program
#include <string.h>
UQ. Write user defined functions to implement
#include <stdio.h>
following string operations
void copy(char s1[],char s2[],int l1,int l2);
(i) strcat (ii) strlen
int main(void)
MU - May 16, Dec. 17, 10 Marks.
{
char org_string[20], new_string[20];
Ans. :
printf("Enter first string: \t"); Program
gets(org_string); #include <stdio.h>
printf("Enter second string:\t"); int main()
gets(new_string); {
getstrlen();
int l1 = strlen(org_string); strconcat();
int l2 = strlen(new_string);
}
copy(org_string,new_string,l1,l2);
void getstrlen()
return 1; {
char s1[20];
} int i = 0;
void copy(char s1[], char s2[], int l1, int l2) printf("\n\nEnter a string : ");
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-20)
gets(s1); Assignment 6 : Functions
while(s1[i]!='\0')
UQ. Write a program to calculate compound interest
{
and amount.
i++;
} Using formula A=P(1+R/100)^n, where
printf("\nLength of %s is %d",s1,i); P=Principal Amt., R is Rate of interest,
} n = number of years. Your program should make
use of user defined function to calculate power.
void strconcat() Program should accept P, R and N, Display
{ interest earned for each year.
int i,j; MU - May 16, 10 Marks.
char str1[20],str2[20];
Ans. : Program
printf("\n\nEnter first string : ");
#include<stdio.h>
gets(str1);
#include<math.h>
printf("\nEnter second string : ");
main()
gets(str2);
{
for(i=0; str1[i]!='\0'; ++i);
float R,P,CI;
int N;
/* This loop would concatenate the string str2 at
float comp_int_calc(float,float,int);
* the end of str1
*/
printf("ENTER THE PRINCIPAL AMOUNT : ");
for(j=0; str2[j]!='\0'; ++j, ++i)
scanf("%f",&P);
{
printf("ENTER THE NUMBER OF YEAR(S) : ");
str1[i]=str2[j];
scanf("%d",&N);
}
printf("ENTER THE RATE OF INTEREST(%) : ");
scanf("%f",&R);
// \0 represents end of string
R=R/100;
str1[i]='\0';
CI=comp_int_calc(P,R,N);
printf("\nOutput: %s",str1);
printf("THE CALCULATED SIMPLE INTEREST IS RUPEES
}
: %.2f",CI);
Output getch();
}
float comp_int_calc(float AMT,float RATE,int YEARS)
{
float COMP_INT=0;
COMP_INT=pow(1+RATE,YEARS);
COMP_INT=AMT*COMP_INT;
return COMP_INT;
}
Output
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-21)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-22)
OR Write a program using function to print first ‘n’ recursion. MU - May 16, 8 Marks.
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-23)
{
Ans. :
int pow, num;
Program long result;
#include <stdio.h>
long reverse(long); printf("Enter a number: ");
scanf("%d", &num);
int main() printf("Enter it's power: ");
{ scanf("%d", &pow);
long n, r; result = power(num, pow);
printf("\n Enter a number : "); printf("%d^%d is %ld", num, pow, result);
scanf("%ld", &n); return 0;
}
r = reverse(n);
long power (int num, int pow)
printf("Reverse number is : %ld\n", r); {
if (pow)
return 0; {
} return (num * power(num, pow - 1));
}
long reverse(long n) { return 1;
static long r = 0; }
Output
if (n == 0)
return 0;
r = r * 10;
r = r + n % 10;
reverse(n/10);
return r; Assignment 8 : Structure and Union
} UQ Define a structure cricket which consist following
Output members
(i) player name
(ii) country name
(iii) batting average
Input 20 player information of test playing
county. Write a program which will display detail
information of player with given player name.
y
UQ. Write a program to find x using recursion. MU - May 15, 6 Marks.
MU - Dec. 18, 4 Marks.
Ans. :
Ans. : Program Program
#include <stdio.h> #include<conio.h>
#include<stdio.h>
long power (int, int); struct cricket
{
int main() char player_name[20], country_name[20];
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-24)
float batting_average; for(i=0;i<5;i++)
}; {
int main () printf("Enter the emp_name, date of joing and salary :
{ ");
struct cricket c1[25]; scanf("%s %s %f",c1[i].emp_name,c1[i].DOJ, &c1[i].sal);
int i; }
for(i=0;i<20;i++) printf("\nDetails of employess with salary > 50000 : : \n");
{ for(i=0;i<5;i++)
printf("Enter the player_name, country_name and {
average runs scored : "); if(c1[i].sal > 50000)
scanf("%s %s %f",c1[i].player_name,c1[i].country_name, printf("%s\t%s\t%.2f\n",c1[i].emp_name,c1[i].DOJ,c1[i].s
&c1[i].batting_average); al);
} }
printf("\nDetails : \n");
for(i=0;i<20;i++) }
{ Output
printf("%s\t%s\t%f\n",c1[i].player_name,c1[i].country_na
me,c1[i].batting_average);
}
}
Output
UQ. A company needs to maintain data about their UQ. Write a program to read Title, Author and Price
employees. Details to be maintained are of 10 books using array of structures. Display the
Salary. Write a program which will store these MU - May 17, 6 Marks.
details and list the employees whose salary is
greater than Rs. 50000.00.
Ans. :
#include<conio.h>
MU - May 16, 6 Marks.
#include<stdio.h>
Ans. : struct book
{
Program
char title[20], author[20];
#include<conio.h>
float price;
#include<stdio.h>
};
struct company
int main ()
{
{
char emp_name[20], DOJ[20];
struct book c1[10],temp;
float sal;
int i,j,n;
};
n = 10;
int main ()
for(i=0;i<10;i++)
{
{
struct company c1[5];
printf("Enter title, author and price : ");
int i;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-25)
scanf("%s %s %f",c1[i].title,c1[i].author, &c1[i].price); UQ. Write a program using structure to create an
} Array of structure to store the details of N
students. The details are,
for(i=0;i<=n-1;i++) Student name
{ Student Roll no.
for(j=0;j<=n-2;j++) Marks of Physics, Chemistry, Maths.
{ Calculate the total of P-C-M. Display the data in
if(c1[j].price>c1[j+1].price) the format
{ Name Roll no Total marks
temp=c1[j];
MU - Dec. 17, 8 Marks.
c1[j]=c1[j+1];
c1[j+1]=temp; Ans. :
} Program
}
#include<stdio.h>
}
main()
{
printf("\nDetails of books in ascending order on price : \n");
struct student
for(i=0;i<10;i++)
{
{
int rno,Physics,Chemestry,Maths,total;
char name[20];
printf("%s\t%s\t%.2f\n",c1[i].title,c1[i].author,c1[i].price);
}s[3];
}
int i;
}
Output for(i=0;i<3;i++)
{
printf("\n Enter name, rollno and marks of
Physics,Chemestry,Maths : ");
scanf("%s %d %d %d %d",&s[i].name,
&s[i].rno,&s[i].Physics,&s[i].Chemestry,&s[i].Maths);
s[i].total = s[i].Physics + s[i].Chemestry + s[i].Maths;
}
printf("\n Name \t Rno \t Total");
for(i=0;i<3;i++)
{
printf("\n %s \t %d \t %d",s[i].name,s[i].rno,s[i].total);
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-26)
Output Output
strcpy(record2.subject, "Physics");
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-27)
printf(" Subject : %s \n", record2.subject); Assigns value pointed by a i.e.
int temp=*a; num1 =50 to temp
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage); Assigns value pointed by b i.e.
return 0; *a=*b; num2 =60 to *a
}
Output *b=temp; Assigns value of temp i.e. 50 to *b
}
Output
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-28)
Output i=0;
ptr=&number[0]; Calculates
for(i=0;i<5;i++) sum of all
{ elements in
array
sum=sum+(*ptr++);
}
GQ. Write a program using pointers to compute the printf("\n Sum of array elements = %d", sum);
sum of all elements stored in an array. (5 Marks) return 1;
}
Ans. :
Output
Program
#include<conio.h>
#include<stdio.h>
int main()
{
int *ptr, sum=0, number[5],i=0;
for(i=0;i<5;i++)
{
printf("\n Enter %dth element ",i); Accepts array
elements
scanf("%d", &number[i]); from user.
}
Chapter Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming
(M2-05)
Multiple Choice
Questions (MCQs)
Q. 1.4 The _______ provides pictorial representation of given Q. 1.11 What is an Algorithm?
problem. (a) flowchart
(a) Algorithm (b) Flowchart (b) Step by step instructions used to solve a problem
(c) Pseudocode (d) All of these Ans. : (b) (c) decision
Q. 1.7 _______ graphically represents how a problem solution Q. 1.14 The ______ symbol is used at the beginning of a flow
can be broken into subtasks. chart.
(a) A flowchart (b) Pseudocode (a) Circle (b) Rectangle
(c) An algorithm (d) A structure chart (c) Diamond (d) None of these Ans. : (a)
Ans. : (a)
C Programming (MU-FE-Sem II) (Introduction & Fundamentals of C Programming)….Page no. (M1-2)
Q. 1.24 The _______ symbol is used to represent process in
Q. 1.15 What are the three algorithm constructs?
flowchart.
(a) Sequence, selection, repetition
(a) Circle (b) Rectangle
(b) Input, output, process
(c) Diamond (d) None of these Ans. : (b)
(c) Input/output, decision, terminator
(d) Loop, input/output, process Ans. : (b) Q. 1.25 In a flowchart how are symbols connected?
(a) Symbols do not get connected together in a flowchart
Q. 1.16 When an algorithm is written in the form of a
(b) With lines and an arrow to show the direction of
programming language, it becomes a _________
flow
(a) Flowchart b) Program
(c) With dashed lines and numbers
(c) Pseudo code (d) Syntax Ans. : (b)
(d) With solid lines to link events Ans. : (b)
Q. 1.17 A box that can represent two different conditions :
_______ Part B - Fundamentals of C Programming
(a) Rectangle (b) Diamond
Q. 1.26 Who invented C Language?
(c) Circle (d) Parallelogram Ans. : (b)
(a) Bjarne Stroustrup (b) James (a) Gosling
Explanation : A diamond shape box denotes either a
truth value or a false value. It jumps onto two different (c) Dennis Ritchie (d) Dr. E.F. Codd
statements following it via flow lines. Ans. : (c)
Q. 1.18 The _______ symbol is used to represent decision in Q. 1.27 What will be the output of this program?
flowchart. main()
(a) Circle (b) Rectangle {
(c) Diamond (d) None of these Ans. : (c) printf("Phoenix InfoTech");
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction & Fundamentals of C Programming)….Page no. (M1-3)
Q. 1.36 C programs are converted into machine languages using
Q. 1.31 C Language is developed at____
____
(a) AT & T's Bell Laboratories of USA in 1972
(a) An Editor (b) A compiler
(b) AT & T's Bell Laboratories of USA in 1970
(c) An operating system (d) None of these.
(c) Sun Microsystems in 1973
Ans. : (b)
(d) Cambridge University in 1972 Ans. : (a)
Explanation : A compiler is a system software that
Q. 1.32 What is required in each C program? converts high level language into machine level
(a) The program must have one main function. language.
(b) The program does not require any function. Q. 1.37 What will this program print?
(c) Input data main()
(d) Output data Ans. : (a)
{
Explanation : Any C program must have one main
function. int i = 2;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction & Fundamentals of C Programming)….Page no. (M1-4)
Q. 1.42 What is the output of this statement "printf("%d",
Q. 1.50 What is the 16-bit compiler allowable range for integer
(a++))"?
constants?
(a) The value of (a + 1) (b) The current value of a
(a) -3.4e38 to 3.4e38 (b) -32767 to 32768
(c) Error message (d) Garbage Ans. : (b)
(c) -32668 to 32667 (d) -32768 to 32767
Q. 1.43 Which of the following is not a valid C variable name?
Ans. : (d)
(a) int number; (b) float rate;
(c) int variable_count; (d) int $main; Q. 1.51 C Language is a successor to which language.
Ans. : (d) (a) FORTRAN (b) D Language
Explanation : Since only underscore and no other (c) BASIC (d) B Language Ans. : (d)
special character is allowed in a variable name, it results Q. 1.52 C99 standard guarantees uniqueness of __________
in an error. characters for internal names.
Q. 1.44 BCPL Language is also called ________ (a) 31 (b) 63
(a) C Language (b) B Language (c) 12 (d) 14 Ans. : (b)
(c) D Language (d) None Ans. : (d) Q. 1.53 A name having a few letters, numbers and special
Explanation : B language is successor of BCPL (Basic character _(underscore) is called _____
Combined Programming Language). B language was (a) keywords (b) reserved keywords
invented by Ken Thomson.
(c) tokens (d) identifiers Ans. : (d)
Q. 1.45 Total keywords in C language are ________
Q. 1.54 Many features of C were derived from an earlier
(a) 32 (b) 24 language called _____.
(c) 36 (d) 40 Ans. : (a) (a) FORTRAN (b) B
Q. 1.46 In the C language, the constant is defined _______. (c) BCPL (d) PASCAL Ans. : (b)
(a) Before main Q. 1.55 C programs are converted into machine language with
(b) After main the help of _____
(c) Anywhere, but starting on a new line. (a) An Editor (b) A compiler
(d) None of the these. Ans. : (c) (c) An operating system (d) None of the above
Explanation : In the C language, the constant is defined Ans. : (b)
anywhere, but starting on a new line. Q. 1.56 Which data type is most suitable for storing a number
Q. 1.47 Comments are executed by compiler. 65000 in a 32-bit system?
(a) true (b) false Ans. : (b) (a) short (b) int
(c) long (d) double Ans. : (a)
Q. 1.48 In C language comment is given using ________
(a) @....@ (b) # …# Q. 1.57 What are the types of linkages?
(c) /*….*/ (d) None of the above (a) Internal and External
Ans. : (c) (b) External, Internal and None
(c) External and None
Q. 1.49 Which of the following is true for variable names in C?
(d) Internal Ans. : (b)
(a) They can contain alphanumeric characters as well as
Q. 1.58 The words if, else, auto, float et(c)have predefined
special characters
meaning and users cannot use them as variables. These
(b) It is not an error to declare a variable to be one of the words are called_______
keywords(like goto, static)
(a) constant (b) identifier
(c) Variable names cannot start with a digit (c) data types (d) keywords Ans. : (d)
(d) Variable can be of any length Ans. : (c)
Q. 1.59 Dennis Was Author of Famous Programming Book
Explanation : According to the syntax for C variable
_________ .
name, it cannot start with a digit.
(a) The C Programming Language
(b) C Programming and Techniques
(c) Thinking in C
(d) C Programming for Scientist Ans. : (a)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Introduction & Fundamentals of C Programming)….Page no. (M1-5)
Q. 1.60 A C variable cannot start with _____
Q. 1.68 Which of the following shows the correct hierarchy of
(a) An alphabet arithmetic operations in C
(b) A number
(a) / + * – (b) *–/+
(c) A special symbol other than underscore
(d) both (b) and (c) Ans. : (d) (c) + – / * (d) */+– Ans. : (d)
Q. 1.61 What is the size of an int data type? Q. 1.69 Is the following statement a declaration or definition
(d) Cannot be determined. Ans. : (c) (c) Function (d) Error Ans. : (a)
Q. 1.62 Which of the following special symbol allowed in a Q. 1.70 Which operators are used to compare the values of
variable name? operands to produce logical value in C language?
(a) * (asterisk) (b) | (pipeline) (a) Logical operator (b) Relational operator
(c) - (hyphen (d) _ (underscore) Ans. : (d) (c) Assignment operator (d) None of the above
Ans. : (b)
Q. 1.63 What is/are the type/types of numeric constant/constants
Q. 1.71 What is/are the number of operand/operands needed to
used in c programming language?
unary operator logical not(!)?
(a) Integer constant (b) Real constant
(a) 4 (b) 3
(c) Both (a) and (b) (d) None of the above
(c) 2 (d) 1 Ans. : (d)
Ans. : (c) Q. 1.72 What is C Tokens?
Q. 1.64 Which of the following is allowed in a C Arithmetic (a) The smallest individual units of c program
instruction ? (b) The basic element recognized by the compiler
(a) [] (b) {} (c) The largest individual units of program
(c) () (d) None of the above Ans. : (c) (d) Both (a) and (b) Ans. : (d)
Q. 1.65 What is short int in C programming? Q. 1.73 An operator used to check a condition and select a value
(a) Basic data type of C depending on the value of the condition is called _____
(b) Qualifier (a) Logical operator
(c) short is the qualifier and int is the basic datatype (b) Decrement operator
(d) All of the mentioned. Ans. : (c) (c) Conditional or Ternary operator
(d) Bitwise operator Ans. : (c)
Q. 1.66 By default a real number is treated as a _____
(a) float Q. 1.74 What is Keywords?
(b) double (a) Keywords have some predefine meanings and these
(c) long double meanings can be changed.
(d) far double Ans. : (b) (b) Keywords have some unknown meanings and these
meanings cannot be changed.
Q. 1.67 Which is/are the integer constant/constants?
(c) Keywords have some predefine meanings and these
(a) Decimal integer constant meanings cannot be changed.
(b) Octal integer constant (d) None of the above Ans. : (c)
(c) Hexadecimal integer constant
Q. 1.75 The size of a character variable in C is _____
(d) All of the above Ans. : (d)
(a) 8 bytes (b) 4 bytes
(c) 2 bytes (d) 1 byte Ans. : (d)
MCQ Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
MODULE II Control Structures
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (M2-3)
{ Q. 2.21 Which loop is faster in C Language, for, while or Do
case EVEN: printf("Even"); While.?
break; (a) for (b) while
case ODD: printf("Odd"); (c) do while (d) All work at same speed
break; Ans. : (d)
default: printf("Default"); Q. 2.22 Switch statement accepts.
} (a) int (b) char
return 0; (c) long (d) All of the above Ans. : (d)
}
Q. 2.23 The type of the controlling expression of a switch
(a) Even (b) Odd
statement cannot be of the type ______
(c) Default (d) Compile-time error Ans. : (b)
(a) int (b) char
Explanation : The expression i & 1 returns 1 if the
(c) short (d) float Ans. : (d)
rightmost bit is set and returns 0 if the rightmost bit is not
set. As all odd integers have their rightmost bit set, the Q. 2.24 What is the output of C Program.?
control goes to the block labeled ODD. int main()
Q. 2.17 Which of the following is an invalid if-else statement? {
(a) if (if (a == 1)){} (b) if (a){} while(true)
(c) if ((char) a){} (d) if (func1 (a)){} Ans. : (a) {
printf("RABBIT");
Q. 2.18 Which keyword is used to come out of a loop only for
that iteration? break;
(a) break (b) continue }
(c) return (d) None of the mentioned Ans. : (b) return 0;
}
Q. 2.19 What is the output of the following program?
(a) RABBIT
#include<stdio.h> (b) RABBIT is printed unlimited number of times.
int c[10] = {1,2,3,4,5,6,7,8,9,10}; (c) No output
main() (d) Compiler error. Ans. : (d)
{ Explanation : while(TRUE) or while(true) does not
int a, b=0; work. true is not a keyword.
for(a=0;a<10;++a) Q. 2.25 Which of the following statement about for loop is true ?
if(c[a]%2 == 1) (a) Index value is retained outside the loop
b+=c[a]; (b) Index value can be changed from within the loop
printf("%d", b); (c) Goto can be used to jump, out of the loop
} (d) All of these Ans. : (d)
(a) 20 (b) 24
Q. 2.26 Which of the following are fundamental control
(c) 25 (d) 30 Ans. : (c)
structures?
Q. 2.20 What will be the output of following code? (a) Iteration (b) Branching
void main() (c) Sequencing (d) All the above Ans. : (d)
{
Q. 2.27 What is the result after execution of the following code if
if(1 || 0)
a is 10, b is 5, and c is 10?
printf("C Programming");
If ((a > b) && (a <= c))
else
a = a + 1;
printf("learn C");
else
}
c = c+1;
(a) learn C (b) Compile Error
(a) a = 10, c = 10 (b) a = 11, c = 10
(c) C Programming (d) Error Ans. : (c) (c) a = 10, c = 11 (d) a = 11, c = 11 Ans. : (b)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (M2-4)
Q. 2.28 What is the output of given program if user enter value if(x < 5)
99? continue;
#include<stdio.h> else
void main() break;
{ printf("Phoenix InfoTech");
int i; }
printf("Enter a number:"); return 0;
scanf("%d", &i); // 99 is given as input. }
if(i%5 == 0){ (a) Infinite times (b) 11 times
printf("nNumber entered is divisible by 5"); (c) 0 times (d) 10 times Ans. : (c)
}
Q. 2.32 How many times PhoenixGlobe.com is printed?
}
int main()
(a) Enter a number:99
{
(b) Enter a number:99 Number is divisible by 5
int a = 0;
(c) Complier error
while(a++);
(d) Run time error Ans. : (a)
{
Q. 2.29 What is the output of the following code snippet? printf("PhoenixGlobe.com ");
#include<stdio.h> }
main()
{ return 0;
int x = 5; }
if(x=5) (a) 0 time (b) 1 time
{ (c) Compilation Error (d) Infinite times
if(x=5) printf("Hello"); Ans. : (b)
}
Q. 2.33 How many times will the following loop be executed if
printf("Hi");
the input data item is 0 1 2 3 4 ?
}
while (c = getchar ()! = 0)
(a) - HelloHi (b) - Hi
{}
(c) - Hello (d) - Compiler error Ans. : (a)
(a) Ininitely (b) never
Q. 2.30 Assume that i,j and k are integer variables and their (c) once (d) None of these Ans. : (a)
values are 8, 5 and 0 respectively. What will be the
Q. 2.34 Which of the following is a clause in the for loop
values of variables i and k after executing the following
structure?
expression?
(a) Assign (b) Alter
k=(j>5)?(i<5)?i-j:j-i:k-j;
(c) Logic (d) All the above Ans. : (d)
i-=(k)?(i)?(j)?:(i):(k);
What will be the result of execution? Q. 2.35 Which one of the following is a loop construct that will
(a) -3 and 3 (b) 3 and -5 always be executed at least once?
(c) 3 and -3 (d) -5 and 3 Ans. : (b) (a) for (b) while
(c) a and b (d) do while Ans. : (d)
Q. 2.31 How many times "Phoenix InfoTech" is get printed?
#include<stdio.h> Q. 2.36 What is the output of given program if user enter "xyz" ?
int main() #include
{ void main()
int x; {
for(x=-1; x<=10; x++) float age, AgeInSeconds;
{ int value;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (M2-5)
printf("Enter your age:");
Q. 2.41 What will be the output of the program?
value=scanf("%f", &age);
(a) Undefined symbol "grade"
if(value==0){
(b) switch statement cannot have more than three labels
printf("\\nYour age is not valid");
(c) case label cannot be numbers
}
(d) none of these Ans. : (a)
AgeInSeconds = 365 * 24 * 60 * 60 * age;
printf("\\n You have lived for %f seconds", AgeInSeconds); Q. 2.42 How many times the while loop will get executed if a
short int is 2 byte wide?
}
#include<stdio.h>
(a) Enter your age : xyz Your age is not valid
int main()
(b) Enter your age: xyz You have lived for 0 seconds
{
(c) Enter your age: xyz Your age is not valid
int j=1;
(d) Complier error Ans. : (c)
while(j <= 255)
Q. 2.37 Which of the following control structures is an exit- {
controlled loop?
printf("%c %d\n", j, j);
(a) For loop (b) While loop
j++;
(c) Const and Goto (d) Do-While loop Ans. : (d)
}
Q. 2.38 Which one of the following is a loop construct that will return 0;
always be executed once? }
(a) for (b) while (a) Infinite times (b) 255 times
(c) switch (d) do while Ans. : (d) (c) 256 times (d) 254 times Ans. : (b)
Q. 2.39 What will be the value of i and j after execution of Q. 2.43 How many times CppBuzz.com is printed on console?
following program? int main()
#include<stdio.h> {
void main() int a = 0;
{ while(a++)
int i, j; {
for(i=0,j=0;i<10,j<20;i++,j++){ printf("CppBuzz.com");
printf("i=%d %t j=%d", i, j); }
} return 0;
} }
(a) 10 10 (b) 10 20 (a) Nothing is printed on screen
(c) 20 20 (d) Run time error Ans. : (c) (b) 0 time
Q. 2.40 main() (c) 1 time
{ (d) Infinite times (Untill Stack overflow) Ans. : (a)
int m; Q. 2.44 What will be the output of the code below :
char g; #include <stdio.h>
switch(m) int a;
{ void main()
case 3: grade="P";break; {
case 2: grade="Q";break; if (a)
case 1: grade="R";break; printf("Hello");
default: grade="S";break; else
} printf("world");
} }
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (M2-6)
(a) Hello Q. 2.52 Trace the output.
(b) World void main()
(c) compile time error {
(d) none of the mentioned Ans. : (b) int i=2,j=2;
while(i+1?--i:j++)
Q. 2.45 Using _______ statement is how you test for a specific
condition. printf("%d",i);
(a) Select (b) If }
(c) Switch (d) For Ans. : (b) (a) 1 (b) 2
(c) ERROR (d) None of the above. Ans. : (a)
Q. 2.46 What should be the expression return value for a do-
while to terminate Q. 2.53 Which among the following is an unconditional control
(a) 1 (b) 0 (c) –1 (d) NULL Ans. : (b) structure
(a) do-while (b) if-else
Q. 2.47 Is the code snippet given below wrong?
(c) goto (d) for Ans. : (c)
if(a=b) {
Serial.print(“Yes”); Q. 2.54 Which one of the control structures is similar to the if-
else statement?
}
(a) Switch-case (b) For loop
(a) No (b) Yes Ans. : (a)
(c) While loop (d) Continue Ans. : (a)
Q. 2.48 What will be the output given program?
Q. 2.55 #include<stdio.h>
#include<stdio.h>
void main()
void main()
{
{
int i = -10; int value=0;
if(value)
for(;i;printf("%d ", i++));
printf("well done ");
}
printf("Try again");
(a) -10 to -1 (b) -10 to infinite
}
(c) -10 to 0 (d) Complier error Ans. : (a)
(a) well done examveda (b) Try again
Q. 2.49 Data type of the controlling statement of a SWITCH (c) complier error (d) None of these
statement cannot of the type : ______
Ans. : (b)
(a) int (b) char
(c) short (d) float Ans. : (d) Q. 2.56 How long the following loop runs?
for(x=0;x=3;x++)
Q. 2.50 Which of the following cannot be checked in a switch-
(a) Three times (b) Four times
case statement?
(c) Forever (d) Never Ans. : (d)
(a) Character (b) Integer
(c) Float (d) enum Ans. : (c) Q. 2.57 What will be the output of the program?
#include<stdio.h>
Q. 2.51 The output of the code below is ______
int main(){
#include <stdio.h>
int i=0;
void main()
for(; i<=5; i++);
{
printf("%d", i);
int a = 5;
return 0;
if (true);
}
printf("hello");
(a) 0, 1, 2, 3, 4, 5 (b) 5
}
(c) 1, 2, 3, 4 (d) 6 Ans. : (d)
(a) It will display hello (b) It will throw an error
(c) No Output (d) Depends on Compiler
Ans. : (b)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (M2-7)
Q. 2.58 The output of the code below is ______ Q. 2.62 The CONTINUE statement cannot be used with ______
#include <stdio.h> (a) for (b) switch
void main() (c) do (d) while Ans. : (d)
{
Q. 2.63 hat will be the output of the program?
int a = 0;
#include<stdio.h>
if (a == 0) int main()
printf("hi");
{
else
char str[]="C-program";
printf("how are u"); int a = 5;
printf("hello");
printf(a >10?"Ps\n":"%s\n", str);
}
return 0;
(a) hi (b) how are you
}
(c) hello (d) hihello Ans. : (d)
(a) C-program (b) Ps
Q. 2.59 Continue statement is used ______ (c) Error (d) None of above Ans. : (a)
(a) to go to the next iteration in a loop Q. 2.64 The following code ‘for(;;)’ represents an infinite loop. It
(b) come out of a loop can be terminated by ______.
(c) exit and return to the main function (a) break (b) exit(0)
d) restarts iterations from the beginning of the loop (c) abort() (d) all of the mentioned Ans. : (a)
Ans. : (a)
Q. 2.65 Which operator in C is called a ternary operator ?
Q. 2.60 What is the output of the code given below if there is a (a) if..then (b) ++
constant 5V supply to pin 10? (c) ?: (d) () Ans. : (c)
void setup() {
Q. 2.66 Can the break statement be used to abort a program?
Serial.begin(9600);
(a) Yes
}
(b) Yes, but only if it is used within the global scope
void loop() {
(c) No
int x=0;
(d) Yes, but only for some Arduino Boards Ans. : (c)
do {
x=analogRead(10); Q. 2.67 What will be the output of the given program?
Serial.println(x); #include
}while(x!=1023); void main()
} {
(a) 1023 (b) 1024 float num=5.6;
(c) null (d) 1029 Ans. : (a) switch(num){
case 5:printf("5");
Q. 2.61 What will be the output of the given program? case 6:printf("6");
#include<stdio.h> default : printf("0");
void main() break;
{ }
int value1, value2=100, num=100; printf("%d", num);
if(value1=value2%5) num=5; }
printf("%d %d %d", num, value1, value2); (a) 5 5.600000 (b) 6 5.600000
(c) 0 5.600000 (d) Complier error Ans. : (d)
}
(a) 100 100 100 (b) 5 0 20 Q. 2.68 How many times will the following loop be executed?
(c) 5 0 100 (d) 100 0 100 Ans. : (d) ch = ‘b’
while (ch > = ‘a’ && ch <= ‘z’)
(a) 20 (b) 25 (c) 26 (d) 0 Ans. : (b)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (M2-8)
Q. 2.69 What will be the output of the program? (a) complier error (b) no error no output
#include<stdio.h> (c) 0 (d) 1 Ans. : (b)
int main()
Q. 2.73 What will be the output of the program?
{
#include<stdio.h>
int a = 500, b = 100, c;
if(!a >= 400) int main()
b = 300; {
c = 200; unsigned int i = 65535; /* Assume 2 byte integer*/
printf("b = %d c = %d\n", b, c); while(i++ != 0)
return 0; printf("%d",++i);
} printf("\n");
(a) b = 300 c = 200 (b) b = 100 c = garbage return 0;
(c) b = 300 c = garbage (d) b = 100 c = 200 }
Ans. : (d) (a) Infinite loop (b) 0 1 2 ... 65535
Q. 2.70 The correct syntax for running two variable for loop (c) 0 1 2 ... 32767 - 32766 -32765 -1 0
simultaneously is ______. (d) No output Ans. : (a)
(a) for (i = 0; i < n; i++) Q. 2.74 Which for loop has range of similar indexes of ‘i’ used in
for (j = 0; j < n; j += 5) for (i = 0;i < n; i++)?
(b) for (i = 0, j = 0;i < n, j < n; i++, j += 5) (a) for (i = n; i>0; i--) (b) for (i = n; i >= 0; i--)
(c) for (i = 0; i < n;i++){} (c) for (i = n-1; i>0; i--) (d) for (i = n-1; i>-1; i--)
(d) d) for (j = 0; j < n;j += 5){} Ans. : (b) Ans. : (d)
Q. 2.71 The continue command cannot be used with ______ Q. 2.75 What will be the output of given program?
(a) for (b) switch #include<stdio.h>
(c) do (d) while Ans. : (a) void main()
{
Q. 2.72 What will be the output of given program?
int a=3;
#include<stdio.h>
for(;a;printf("%d ", a--);
void main()
}
{
(a) no output (b) 3210
int a=1;
(c) 3 2 1 (d) infinity loop Ans. : (c)
if("%d=hello", a);
}
MCQ Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
MODULE III Functions
Q. 3.1 The keyword used to transfer control from a function (c) By default, return 0 is added as the last statement of
back to the calling function is ______ a function without specific return type.
(a) switch (b) goto (d) All the above Ans. : (d)
(c) go back (d) return Ans. : (d)
Q. 3.6 The default parameter passing mechanism is _____
Explanation : The keyword return is used to transfer
(a) Call by value (b) call by reference
control from a function back to the calling function.
(c) call by value result (d) None Ans. : (a)
Q. 3.2 Choose correct statement about Functions in C
Language. Q. 3.7 It is necessary to declare the type of a function in the
calling program if the function _____
(a) A Function is a group of c statements which can be
reused any number of times. (a) Returns an integer
(b) Every Function has a return type. (b) Returns a non-integer value
(c) Every Function may no may not return a value. (c) Is not defined in the same file
(d) All the above. Ans. : (d) (d) None of these Ans. : (b)
Q. 3.3 What is the default return type if it is not specified in Q. 3.8 What is the output of this C code?
function definition? int main()
(a) void (b) int {
(c) float (d) short int Ans. : (b) void foo(), f();
f();
Q. 3.4 What error would the following function give on
compilation ? }
f(int a,int b) void foo()
{ {
int a; printf("2 ");
a = 20; }
return a; void f()
} {
(a) Missing parentheses in return statement printf("1 ");
(b) Function should be define as int f (int a,int b) foo();
(c) Redeclaration of a }
(d) No error Ans. : (c) (a) Compile time error as foo is local to main
(b) 1 2
Q. 3.5 Choose a correct statement about C Function.?
(c) 2 1
main()
(d) Compile time error due to declaration of functions
{ inside main Ans. : (b)
printf("Hello");
Q. 3.9 In C, if you pass an array as an argument to a function,
}
what actually gets passed?
(a) "main" is the name of default must and should
(a) Value of elements in array
Function.
(b) First element of the array
(b) main() is same as int main()
C Programming (MU-FE-Sem II) (Functions)….Page no. (M3-2)
(c) Base address of the array i++;
(d) Address of the last element of array Ans. : (c) if(i<=5)
{
Q. 3.10 A function which calls itself is called a ___ function.
printf("Phoenix InfoTech");
(a) Self Function (b) Auto Function
exit(1);
(c) Recursive Function (d) Static Function
main();
Ans. : (c)
}
Q. 3.11 Pick the correct statements. return 0;
I. The body of a function should have only one return }
statement
(a) Prints "Phoenix InfoTech" 5 times
II. The body of a function may have many return
(b) Function main() doesn't calls itself
statements under if else.
(c) Infinite loop
III. function can return only one value to the calling
environment. (d) Prints "Phoenix InfoTech" Ans. : (d)
IV. If return statement is omitted, then the function does Q. 3.16 What is the output of C Program with Functions.?
its job but returns no value to the calling int main()
environment.
{
(a) I and II (b) I and III
void show()
(c) II and III (d) II anf IV Ans. : (c) {
Q. 3.12 What is the output of this C code? printf("HIDE");
void m() }
{ show();
printf("hi"); return 0;
} }
void main() (a) No output (b) HIDE
{ (c) Compiler error (d) None of the above
m(); Ans. : (b)
}
Q. 3.17 Functions can return structure in c.
(a) hi (b) Run time error
(a) TRUE (b) FALSE
(c) Nothing (d) Varies Ans. : (a)
(c) May Be (d) Can't Say Ans. : (a)
Q. 3.13 Which is not a proper prototype? Explanation : Yes, functions can return structure
(a) int funct(char x, char y);
Q. 3.18 What is the return type of the function with prototype:
(b) double funct(char x)
"int func(char x, float v, double t);" ?
(c) void funct();
(a) char (b) int
(d) char x(); Ans. : (b)
(c) float (d) double Ans. : (b)
Q. 3.14 Recursive functions are executed in a?
Q. 3.19 Point out the error in the program.
(a) First In First Out Order
f(int a, int b)
(b) Load Balancing
{
(c) Parallel Fashion
int a;
(d) Last In First Out Order Ans. : (d)
a = 20;
Q. 3.15 What will be the output of the program? return a;
#include<stdio.h> }
#include<stdlib.h> (a) Missing parenthesis in return statement
int main() (b) The function should be defined as int f(int a, int b)
{ (c) Redeclaration of a
int i=0; (d) None of above Ans. : (c)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (M3-3)
Q. 3.20 In C, what is the meaning of following function Q. 3.24 In the following 'C' code, in which order the functions
prototype with empty parameter list would be called ?
void fun() a = ( f1(23,14 ) * f2 (12/14)) + f3 () ;
{ (a) f1,f2,f3
(b) f3,f2,f1
/* .... */
(c) The order may vary from compiler to compiler
}
(d) None of these Ans. : (a)
(a) Function can only be called without any parameter
(b) Function can be called with any number of Q. 3.25
parameters of any types #include<stdio.h>
(c) Function can be called with any number of integer main()
parameters. {
(d) Function can be called with one integer parameter. int a = 1;
Ans. : (b) float b = 1.3;
Explanation : Empty list in C mean that the parameter double c;
list is not specified and function can be called with any c = a + b;
parameters. In C, to declare a function that can only be printf("%.2lf", c);
called without any parameter, we should use "void
}
fun(void)" As a side note, in C++, empty list means
function can only be called without any parameter. In (a) - 2.30 (b) - 2.3
C++, both void fun() and void fun(voi(d) are same. (c) - Compile error (d) - 2.0 Ans. : (a)
Q. 3.21 Choose a correct statement about C Language Functions. Q. 3.26 Is it true that a function may have several declaration,
(a) A function name can not be same as a predefined C but only one definition ?
Keyword. (a) True (b) False Ans. : (a)
(b) A function name can start with an Underscore( _ ) or Q. 3.27 What does the following function print?
A to Z or a to z.
func(int i)
(c) Default return type of any function is an Integer. {
(d) All the above. Ans. : (d) if(i%2) return 0;
Q. 3.22 Why is a macro used in place of a function? else return 1;
(a) It reduces execution time. }
main()
(b) It reduces code size.
{
(c) It increases execution time.
int i=3;
(d) It increases code size. Ans. : (d)
i=func(i);
Q. 3.23 What will be the output of the following C code? i=func(i);
#include <stdio.h> printf("%d", i);
int main() }
{ (a) 3 (b) 1 (c) 0 (d) 2 Ans. : (b)
void foo(); Q. 3.28 What is the output of this C code?
printf("1 "); #include <stdio.h>
foo(); void main()
} {
void foo() m();
{ void m()
printf("2 "); {
} printf("SimpleWay2Code");
(a) 1 2 (b) Compile time error }
(c) 1 2 1 2 (d) Depends on the compiler
}
Ans. : (a)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (M3-4)
(a) SimpleWay2Code (b) Compile time error
Q. 3.32 A function that is prototype as _____
(c) Nothing (d) Varies Ans. : (b)
int calculate(int num);
Q. 3.29 What is the following function determining? may
int fn(int a, int b) (a) Receive an integer variable named num from the
{ main () program
if (b==0) return 0; (b) Receive any integer variable from the main()
if (b==1) return a; program
return a+fn(a, b-1); (c) Either (a) or (b)
} (d) None of these Ans. : (c)
(a) a+b where a and b are integers Q. 3.33 What is the following function determining?
(b) a+b where a and b are non-negative integers int fn(int a, int b)
(c) a*b where a and b are integers {
(d) a*b where a and b are non-negative integers if (b==0) return 0;
Ans. : (b) if (b==1) return a;
Q. 3.30 What is the following function determining? return a+fn(a, b-1);
int fn(int a, int b) }
{ (a) a+b where a and b are integers
if (b==0) return 0; (b) a+b where a and b are non-negative integers
if (b==1) return a; (c) a*b where a and b are integers
return a+fn(a, b-1); (d) a*b where a and b are non-negative integers
} Ans. : (b)
(a) a+b where a and b are integers Q. 3.34 The value obtained in the function is given back to main
(b) a+b where a and b are non-negative integers by using ________ keyword?
(c) a*b where a and b are integers (a) return (b) static
(d) a*b where a and b are non-negative integers (c) new (d) volatile Ans. : (a)
Ans. : (b) Q. 3.35 What is the output of the following code?
Q. 3.31 What will be the output of the following C code? main()
#include <stdio.h> {
void foo(); int a=1, b=10;
int main() swap(a,b);
{ printf("\n%d%d", a,b);
void foo(int); }
foo(); swap(int x, int y)
return 0; {
} int temp;
void foo() temp=x;
{ x=y;
printf("2 "); y=temp;
} }
(a) 2 (a) 1 1
(b) Compile time error (b) 1 10
(c) Depends on the compiler (c) 10 1
(d) Depends on the standard Ans. : (b) (d) None of these Ans. : (b)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (M3-5)
Q. 3.41 What will be the output of the program?
Q. 3.36 What is the output of C Program with functions.?
#include<stdio.h>
int main()
int fun(int i)
{
show(); {
i++;
printf("BANK ");
return i;
return 0;
} }
int main()
void show()
{
{
printf("CURRENCY "); int fun(int);
int i=3;
}
fun(i=fun(fun(i)));
(a) CURRENCY BANK (b) BANK CURRENCY
(c) BANK (d) Compiler error printf("%d\n", i);
Ans. : (d) return 0;
}
Q. 3.37 What will be the output of the following C code?
(a) 5 (b) 4
#include <stdio.h>
(c) Error (d) Garbage value Ans. : (a)
void m()
{ Q. 3.42 Which is not a proper prototype?
printf("hi"); (a) int funct(char x, char y);
} (b) double funct(char x)
void main() (c) void funct();
{ (d) char x(); Ans. : (b)
m(); Q. 3.43 How many values can a C Function return at a time.?
} (a) Only One Value
(a) hi (b) Run time error (b) Maximum of two values
(c) Nothing (d) Varies Ans. : (a) (c) Maximum of three values
Q. 3.38 A function that uses variable types is called _____ (d) Maximum of 8 values Ans. : (a)
(a) Overloaded (b) Template Function Q. 3.44 The declaration _____
(c) Variable function (d) Virtual function void function1(int)
Ans. : (c) indicates the function1 is a function which
Q. 3.39 What is the problem in the following declarations? (a) Has no arguments (b) Returns nothing
int func(int); (c) Both (a) and (b) (d) None of these Ans. : (b)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (M3-6)
(a) Missing parenthesis in return statement
Q. 3.47 What will be the output of the program?
(b) The function should be defined as int f(int a, int b)
#include<stdio.h>
(c) Redeclaration of a
int fun(int);
int main() (d) None of above Ans. : (c)
{ Q. 3.51 Which of the following is a complete function?
float k=3; (a) int funct();
fun(k=fun(fun(k))); (b) int funct(int x) {return x=x+1;}
printf("%f\n", k); (c) void funct(int) { printf( "Hello");
return 0; (d) void funct(x) { printf( "Hello"); } Ans. : (b)
}
Q. 3.52 What are types of Functions in C Language.?
int fun(int i)
(a) Library Functions
{
(b) User Defined Functions
i++;
(c) Both Library and User Defined
return i;
(d) None of the above Ans. : (c)
}
(a) 5.000000 (b) 3.000000 Q. 3.53 What is the output of C program with functions.?
(c) Garbage value (d) 4.000000 Ans. : (a) int show();
void main()
Q. 3.48 Which of the following is a valid function call (assuming
{
the function exists)?
int a;
(a) funct; (b) funct x, y;
a=show();
(c) funct(); (d) int funct(); Ans. : (c)
printf("%d", a);
Q. 3.49 What is the output of C Program with functions.? }
void main() int show()
{ {
int a; return 15.5;
printf("TIGER COUNT="); return 35;
a=show(); }
printf("%d", a); (a) 15.5 (b) 15
} (c) 0 (d) Compiler error Ans. : (b)
Q. 3.54 Point out the error in the program
int show()
#include<stdio.h>
{
int f(int a)
return 15;
{
return 35;
a > 20? return(10): return(20);
}
}
(a) TIGER COUNT=15 (b) TIGER COUNT=35
int main()
(c) TIGER COUNT=0 (d) Compiler error
{
Ans. : (a)
int f(int);
Q. 3.50 Point out the error in the program. int b;
f(int a, int b) b = f(20);
{ printf("%d\n", b);
int a; return 0;
a = 20; }
return a;
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (M3-7)
(a) Error: Prototype declaration int myshow(int b)
(b) No error {
(c) Error: return statement cannot be used with printf("Received %d, ", b);
conditional operators }
(d) None of above Ans. : (c) (a) Received 10, Received 10,
Q. 3.55 What is the output of C Program.? (b) Received 10, Received RANDOMNumber,
int myshow(int); (c) Received 10, Received RANDOMNumber, with a
void main() compiler warning
{ (d) Compiler error Ans. : (c)
myshow(5); Q. 3.58 Which of the following statements are correct about the
myshow(10); program?
} #include<stdio.h>
int myshow(int b) int main()
{ {
printf("Received %d, ", b); printf("%p\n", main());
} return 0;
(a) Received 5, Received 10, }
(b) Received 10, Received 5, (a) It prints garbage values infinitely
(c) Received 0, Received 0, (b) Runs infinitely without printing anything
(d) Compiler error Ans. : (a) (c) Error: main() cannot be called inside printf()
Q. 3.56 Point out the error in the program (d) No Error and print nothing Ans. : (b)
#include<stdio.h> Q. 3.59 ________ function can be used to read two words at a
int main() time.
{ (a) scanf( ) (b) gets( )
int a=10; (c) getch( ) (d) none of these Ans. : (b)
void f();
Q. 3.60 What is the default return type if it is not specified in
a = f();
function definition?
printf("%d\n", a);
(a) void (b) int
return 0;
(c) float (d) None of these Ans. : (b)
}
void f() Q. 3.61 Predict the output : _____
{ #include<string.h>
printf("Hi"); int main()
} {
(a) Error: Not allowed assignment char str1[50]="abc", str2[50];
(b) Error: Doesn't print anything strcpy(str2, strrev(str1));
(c) No error printf("Reverse string is : %s",str2);
(d) None of above Ans. : (a) return 0;
}
Q. 3.57 What is the output of C Program with functions ?
(a) abc (b) cba
in myshow(int);
(c) ABC (d) none of these Ans. : (b)
void main()
{ Q. 3.62 Every C Program should contain which function?
int a=10; (a) printf() (b) show()
myshow(a); (c) scanf() (d) main() Ans. : (d)
myshow(&a);
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Functions)….Page no. (M3-8)
Q. 3.63 There is a error in the below program. Which statement Q. 3.68 What is the return type of the function with declaration:
will you add to remove error? int func(char x, float v, double t);
#include<stdio.h> (a) char (b) int
int main() (c) float (d) double Ans. : (b)
{
int a; Q. 3.69 In C, function parameters are always _____
a = f(10, 3.14); (a) Passed by value (b) Passed by reference
printf("%d\n", a); (c) Passed by value result (d) None of these
return 0; Ans. : (a)
}
Q. 3.70 Arguments passed to a function in C language are called
float f(int aa, float bb)
____
{
(a) Formal arguments (b) Actual arguments
return ((float)aa + bb);
(c) Definite arguments (d) Ideal arguments
}
(a) Add prototype: float f(aa, bb) Ans. : (b)
(b) Add prototype: float f(int, float) Q. 3.71 Which one is the correct statement?
(c) Add prototype: float f(float, int) (a) The body of a function should have only one return
(d) Add prototype: float f(bb, aa) Ans. : (b) statement.
(b) Function can return only one value in call by value
Q. 3.64 Any C Program _____ environment.
(a) Must contain at least one function (c) Function can return multiple values.
(b) Need not contain any function (d) None of these Ans. : (b)
(c) Needs input data Q. 3.72 What is the output?
(d) None of these Ans. : (a) void show();
Q. 3.65 Which of the following statements are correct about the void main()
function? {
long fun(int num) show();
{ printf("WORLD ");
int i; }
long f=1; void show()
for(i=1; i<=num; i++) {
f = f * i; printf("HELLO ");
return f; }
} (a) WORLD HELLO (b) HELLO WORLD
(a) The function calculates the value of 1 raised to (c) WORLD (d) Error Ans. : (b)
power num
(b) The function calculates the square root of an integer Q. 3.73 What is the output?
(c) The function calculates the factorial value of an int show(int b)
integer {
(d) None of above Ans. : (c) printf("%d,",b);
}
Q. 3.66 Function have______
void main()
(a) Local scope (b) Block scope
{
(c) File scope (d) No scope Ans. : (c)
show(5);
Q. 3.67 Which is not a correct function declaration? show(10);
(a) int funct(char x, char y); (b) double funct(x) }
(c) void funct(); (d) char x(); Ans. : (b) (a) 10,5 (b) 5,10
(c) 0,0 (d) Error Ans. : (b)
MCQ Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
MODULE IV Arrays and Strings
Explanation : This is the syntax to initialize an array Q. 4.7 What is right way to initialize an array?
in C. (a) int num[6] = { 2, 4, 12, 5, 45, 5 };
Q. 4.3 What is meaning of following declaration ? (b) int n{} = { 2, 4, 12, 5, 45, 5 };
int arr[20]; (c) int n{6} = { 2, 4, 12 };
(a) Integer Array of size 20 (d) int n(6) = { 2, 4, 12, 5, 45, 5 }; Ans. : (a)
(b) None of these Explanation : option (b), (c) and (d) are incorrect
(c) Array of size 20 that can have integer address because array declaration syntax is wrong. Only square
brackets ([]) must be used for declaring an array.
(d) Array of Size 20 Ans. : (a)
Q. 4.8 Choose a correct statement about C language arrays.
Q. 4.4 What is the maximum number of dimensions an array in
C may have? (a) An array size cannot be changed once it is created.
(a) Two (b) Array element value can be changed any number of
times
(b) eight
(c) To access Nth element of an array students, use
(c) sixteen
students[n-1] as the starting index is 0.
(d) Theoretically no limit. The only practical limits are
(d) All the above Ans. : (d)
memory size and compilers Ans. : (d)
Explanation : The maximum size of an array is Q. 4.9 In C Programming, If we need to store word "INDIA"
determined by the amount of memory that a program can then syntax is as below -
access. On a 32-bit system, the maximum amount of (a) char name[6] = {'I','N','D','I','A','\0'}
memory that can be addressed by a pointer is 2^32 bytes (b) char name[6] = {"I","N","D","I","A"}
which is 4 gigabytes. The actual limit may be less,
(c) char name[]; name = "INDIA";
depending on operating system implementation details.
(d) char name[6] = {'I','N','D','I','A'} Ans. : (a)
Q. 4.5 Which of the following correctly declares an array?
Q. 4.10 A one dimensional array A has indices 1....75. Each
(a) int anarray[10];
element is a string and takes up three memory words.
(b) int anarray; The array is stored at location 1120 decimal. The starting
(c) anarray{10}; address of A[49] is ______
(d) array anarray[10]; Ans. : (a) (a) 1264 (b) 1164
(c) 1167 (d) 1267 Ans. : (a)
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (M4-2)
Explanation : Start address of the element = base
Q. 4.19 A string in C is _____
address of array + number of elements * size of each
(a) 1-D Array of Character
element = 1120 + 48 * 3 = 1264
(b) 2-D Array of Character
Q. 4.11 What is the index number of the last element of an array (c) Any of i & ii
with 29 elements?
(d) None of the above Ans. : (a)
(a) 29 (b) 28
(c) 0 (d) Programmer-defined Ans. : (b) Q. 4.20 What will be the output of the program ?
#include<stdio.h>
Q. 4.12 Which of the following is a two-dimensional array?
#include<string.h>
(a) array anarray[20][20]; (b) int anarray[20][20];
int main()
(c) int array[20, 20]; (d) char array[20];
{
Ans. : (b)
char str1[20] = "Hello", str2[20] = " World";
Q. 4.13 Which of the following function is more appropriate for printf("%s\n", strcpy(str2, strcat(str1, str2)));
reading in a multi-word string? return 0;
(a) scanf() (b) printf() }
(c) gets() (d) puts() Ans. : (c) (a) Hello (b) Hello
Explanation : The C library function gets() reads a line (c) Hello World (d) WorldHello Ans. : (c)
from stdin and stores it into the string pointed to by str.
Q. 4.21 Which standard library function will you use to find the
Q. 4.14 Which of the following correctly accesses the seventh last occurrence of a character in a string in C?
element stored in foo, an array with 100 elements? (a) strnchar() (b) strchar()
(a) foo[6]; (b) foo[7]; (c) strrchar() (d) strrchr() Ans. : (d)
(c) foo(7); (d) foo; Ans. : (a)
Q. 4.22 What is the Format specifier used to print a String or
Q. 4.15 What is the output of C program.? int main() { float
Character array in C printf or scanf function.?
marks[3] = {90.5, 92.5, 96.5}; int a=0; while(a<3)
(a) %c (b) %C
{ printf("%.2f,", marks[a]); a++; } }
(c) %s (d) %w Ans. : (c)
(a) 90.5 92.5 96.5 (b) 90.50 92.50 96.50
(c) 0.00 0.00 0.00 (d) Compiler error Ans. : (b) Q. 4.23 Which function will you choose to join two words?
Explanation : 0.2%f prints only two decimal points. It is (a) strcpy() (b) strcat()
allowed to use float values with arrays. (c) strncon() (d) memcon() Ans. : (b)
Explanation : The strcat() function is used for
Q. 4.16 Choose a correct statement about C String.
concatenating two strings, appends a copy of the string.
char ary[]="Hello..!";
char *strcat(char *s1,const char *s2);
(a) Character array, ary is a string.
Q. 4.24 A String constant in C terminated by
(b) ary has no Null character at the end
(a) '\O' (b) '\\O'
(c) String size is not mentioned
(c) " (d) "" Ans. : (a)
(d) String can not contain special characters. Ans. : (a)
Q. 4.25 What will be the address of the arr[2][3] if arr is a 2-D
Explanation : It is a simple way of creating a C String. long array of 4 rows and 5 columns and starting address
You can also define it like the below. \0 is mandatory in of the array is 2000?
this version. char ary[] = {'h','e','l','l','o','\0'};
(a) 2048 (b) 2056
Q. 4.17 Which among the following is Copying function?
(c) 2052 (d) 2042 Ans. : (c)
(a) memcpy() (b) strcopy()
Q. 4.26 What is a String in C Language.?
(c) memcopy() (d) strxcpy() Ans. : (a)
(a) String is a new Data Type in C
Explanation : The memcpy() function is used to copy n
(b) String is an array of Characters with null character as
characters from the object.
the last element of array.
Q. 4.18 If the two strings are identical, then strcmp() function (c) String is an array of Characters with null character as
returns the first element of array
(a) – 1 (b) 1 (d) String is an array of Integers with 0 as the last
(c) 0 (d) Yes Ans. : (c) element of array. Ans. : (b)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (M4-3)
Q. 4.27 What is an Array in C language.?
Q. 4.35 Array is an example of _______ type memory allocation.
(a) A group of elements of same data type.
(a) Compile time (b) Run time
(b) An array contains more than one element
(c) Both A and B (d) None of the above
(c) Array elements are stored in memory in continuous
Ans. : (a)
or contiguous locations.
(d) All the above. Ans. : (d) Q. 4.36 What is the output of C Program with Strings.?
int main()
Q. 4.28 Which among the following is Copying function?
{
(a) memcpy() (b) strcopy()
char str[]={'g','l','o','b','e'};
(c) memcopy() (d) strxcpy() Ans. : (a)
printf("%s",str);
Q. 4.29 Which of these best describes an array? return 0;
(a) A data structure that shows a hierarchical behavior }
(b) Container of objects of similar types (a) g (b) globe
(c) Arrays are immutable once initialised (c) globe\0 (d) None of the above Ans. : (d)
(d) Array is not a data structure Ans. : (b)
Q. 4.37 What are the Types of Arrays.?
Q. 4.30 Array can be considered as set of elements stored in (a) int, long, float, double (b) struct, enum
consecutive memory locations but having __________. (c) char (d) All the above
(a) Same data type (b) Different data type Ans. : (d)
(c) Same scope (d) None of these Ans. : (a)
Q. 4.38 What will strcmp() function do?
Q. 4.31 What is the output of C Program with Strings.? (a) compares the first n characters of the object
int main() (b) compares the string
{ (c) undefined function
char ary[]="Phoenix InfoTech"; (d) copies the string Ans. : (b)
printf("%s",ary);
Q. 4.39 Size of the array need not be specified, when
return 0;
(a) Initialization is a part of definition
}
(b) It is a formal parameter
(a) D (b) Phoenix InfoTech
(c) It is a declaratrion
(c) Phoenix (d) Compiler error Ans. : (b)
(d) All of the above Ans. : (a)
Q. 4.32 Choose a correct statement about C language arrays.
Q. 4.40 What is the output of C Program with Strings.?
(a) An array address is the address of first element of
array itself. int main()
(b) An array size must be declared if not initialized {
immediately. char str[]={'g','l','o','b','y','\0'};
(c) Array size is the sum of sizes of all elements of the printf("%s",str);
array. return 0;
(d) All the above Ans. : (d) }
Q. 4.33 The ______ function appends not more than n (a) g (b) globe
characters. (c) globe\0 (d) Compiler error Ans. : (b)
(a) strcat() (b) strcon() Q. 4.41 An array Index starts with.?
(c) strncat() (d) memcat() Ans. : (c) (a) – 1 (b) 0 (c) 1 (d) 2 Ans. : (b)
Q. 4.34 How do you initialize an array in C? Q. 4.42 Which of the following is the variable type defined in
(a) int arr[3] = (1,2,3); (b) int arr(3) = {1,2,3}; header string. h?
(c) int arr[3] = {1,2,3}; (d) int arr(3) = (1,2,3); (a) sizet (b) size
Ans. : (c) (c) size_t (d) size-t Ans. : (c)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (M4-4)
(a) First matching character is at 8
Q. 4.43 The information about an array used in program will be
stored in (b) First matching character is at 7
(a) Symbol Table (b) Activation Record (c) First matching character is at 9
(c) Dope Vector (d) Both (a) and (b) Ans. : (c) (d) First matching character is at 12 Ans. : (a)
Q. 4.44 How do you convert this char array to string.? Q. 4.51 Which of the following function is more appropriate for
reading in a multi-word string?
char str[]={'g','l','o','b','y'};
(a) scanf() (b) printf()
(a) str[5] = 0; (b) str[5] = '\0'
(c) gets() (d) puts() Ans. : (c)
(c) str[]={'g','l','o','b','y','\0'}; (d) All the above
Ans. : (d) Q. 4.52 What is the maximum length of a C String.?
Q. 4.45 Choose a correct statement about C language arrays. (a) 32 characters (b) 64 characters
(a) An array size can not changed once it is created. (c) 256 characters (d) None of the above
(b) Array element value can be changed any number of Ans. : (d)
times
Q. 4.53 What is the output of C Program.?
(c) To access Nth element of an array students, use
students[n-1] as the starting index is 0. int main() { int a[] = {1,2,3,4}; int b[4] = {5,6,7,8};
(d) All the above Ans. : (d) printf("%d,%d", a[0], b[0]); }
(a) 1,5 (b) 2,6
Q. 4.46 NULL is the macro defined in the header string. h.
(c) 0 0 (d) Compiler error Ans. : (a)
(a) true (b) false Ans. : (a)
Q. 4.47 A string that is a formal parameter can be declared Q. 4.54 Length of the string "Hi Kunal" is ______
_____ (a) 2 (b) 5 (c) 7 (d) 8 Ans. : (d)
(a) An array with empty braces Q. 4.55 What is the output of C program with strings.?
(b) A pointer to character int main()
(c) Both (a) and (b)
{
(d) None of the above Ans. : (c)
char str1[]="KUNAL";
Q. 4.48 What is the output of C Program.? char str2[20];
int main() str2= str1;
{ printf("%s",str2);
int str[]={'g','l','o','b','y'}; return 0;
printf("A%c ",str); }
printf("A%s ",str); (a) KUNAL (b) K
printf("A%c ",str[0]); (c) KUNAL\0 (d) Compiler error Ans. : (d)
return 0;
Q. 4.56 What is the output of C program.?
}
int main()
(a) A A A (b) A Ag Ag
{
(c) A*randomchar* Ag Ag (d) Compiler error
float marks[3] = {90.5, 92.5, 96.5};
Ans. : (c)
int a=0;
Q. 4.49 What is the output of C Program.? int main() { int a[]; while(a<3)
a[4] = {1,2,3,4}; printf("%d", a[0]); } {
(a) 1 (b) 2 printf("%.2f,", marks[a]); a++;
(c) 4 (d) Compiler error Ans. : (d) }
Q. 4.50 What will be the output of the following C code? }
const char str1[]="ABCDEF1234567"; (a) 90.5 92.5 96.5 (b) 90.50 92.50 96.50
const char str2[] = "269"; (c) 0.00 0.00 0.00 (d) Compiler error Ans. : (b)
len = strcspn(str1, str2);
printf("First matching character is at %d\n", len + 1);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (M4-5)
printf("%d ", a[i]);
Q. 4.57 int a[20]
i++;
What will be the size of above array element ?
}
(a) 22 (b) 21
}
(c) 20 (d) 19 Ans. : (c)
(a) 20 12 14 (b) 10 20 14
Q. 4.58 Which standard library function will you use to find the (c) 10 12 20 (d) Compiler error Ans. : (b)
last occurance of a character in a string in C?
(a) strnchar() (b) strchar() Q. 4.63 Below is an example of -
(c) strrchar() (d) strrchr() Ans. : (d) int RollNum[30][4];
(a) 3-D Array (b) 2-D Array
Q. 4.59 What will be the output of the program ?
(c) 1-D Array (d) 4-D Array Ans. : (b)
#include<stdio.h>
int main() Q. 4.64 What will be the output of the program ?
{ #include<stdio.h>
char p[] = "%d\n"; #include<string.h>
p[1] = 'c'; int main()
printf(p, 65); {
return 0; printf("%d\n", strlen("123456"));
} return 0;
(a) A (b) a (c) c (d) 65 Ans. : (a) }
(a) 6 (b) 12 (c) 7 (d) 2 Ans. : (a)
Q. 4.60 Which of the following statements are correct ?
1: A string is a collection of characters terminated by '. Q. 4.65 Strcat() function adds null character ____
2: The format specifier %s is used to print a string. (a) Only if there is space
3: The length of the string can be obtained by strlen(). (b) Always
4: The pointer CANNOT work on string. (c) Depends on the standard
(a) 1,2,3 (b) 1,2 (d) depends on the compiler Ans. : (b)
(c) 2,4 (d) 3,4 Ans. : (a) Q. 4.66 What is the output of C program with strings.?
Q. 4.61 What is the output of C Program with arrays.? int main()
int main() {
{ char str[2];
char str[25]; scanf("%s", str);
scanf("%s", str); printf("%s",str);
printf("%s",str); return 0;
return 0; }
} //Input: South
//input: South Africa (a) So (b) South
(a) South (b) South Africa (c) Compiler error (d) None of the above
(c) S (d) Compiler error Ans. : (a) Ans. : (b)
Q. 4.62 What is the output of C Program.? Q. 4.67 What is the output of C Program.?
int main() int main()
{ {
int a[3] = {10,12,14}; int a[3] = {20,30,40};
a[1]=20; a[0]++;
int i=0; int i=0;
while(i<3) while(i<3)
{ {
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Arrays and Strings)….Page no. (M4-6)
printf("%d ", i[a]); int a[3] = {20,30,40};
i++; int b[3];
} b=a;
} printf("%d", b[0]);
(a) 20 30 40 (b) 41 30 20 }
(c) 21 30 40 (d) None of the above Ans. : (c) (a) 20 (b) 30
Q. 4.68 What will be the output of the program ? (c) address of 0th element. (d) Compiler error
#include<stdio.h> Ans. : (d)
#include<string.h> Q. 4.72 What will be the output of the program ?
int main() #include<stdio.h>
{ int main()
char str[] = "Phoenix\0\InfoTech\0"; {
printf("%s\n", str); printf("Phoenix", "InfoTech\n");
return 0; return 0;
} }
(a) Phoenix (b) InfoTech (a) Phoenix (b) InfoTech
(c) Phoenix InfoTech (d) Phoenix\0InfoTech (c) Phoenix InfoTech (d) Phoenix\0InfoTech
Ans. : (a) Ans. : (a)
Q. 4.69 Which of the following function sets first n characters of Q. 4.73 The library function used to find the last occurrence of a
a string to a given character? character in a string is ______
(a) strset() (b) strnset() (a) strnstr() (b) laststr()
(c) strcset() (d) strinit() Ans. : (b) (c) strrchr() (d) strstr() Ans. : (c)
Q. 4.70 What is the output of C Program with strings.? Q. 4.74 How do you accept a Multi Word Input in C Language.?
int main() (a) scanf (b) gets
{ (c) getc (d) finds Ans. : (b)
char str[2]; Q. 4.75 What is an array Base Address in C language.?
int i=0; (a) Base address is the address of 0th index element.
scanf("%s", str); (b) An array b[] base address is &b[0]
while(str[i] != '\0') (c) An array b[] base address can be printed with
{ printf("%d", b);
printf("%c", str[i]); (d) All the above Ans. : (d)
i++; } Q. 4.76 What will be the output of the program ?
return 0; #include<stdio.h>
} #include<string.h>
//Input: KLMN int main()
(a) KL (b) KLMN {
(c) Compiler error (d) None of the above char str[] = "Phoenix\0\InfoTech\0";
Ans. : (b) printf("%d\n", strlen(str));
Q. 4.71 What is the output of C program with arrays.? return 0;
int main() }
{ (a) 15 (b) 16 (c) 17 (d) 7 Ans. : (d)
MCQ Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
MODULE V Structure and Union
Q. 5.2 Which of the following are themselves a collection of Q. 5.7 Which of the following cannot be a structure member?
different data types? (a) Another structure
(a) string (b) structures (b) Function
(c) char (d) all of the mentioned Ans. : (b) (c) Array
Q. 5.3 Which of the following accesses a variable in (d) None of the mentioned Ans. : (b)
structure b? Q. 5.8 Choose a correct statement about C structure.?
(a) b->var; (b) b.var; int main( )
(c) b-var; (d) b>var; Ans. : (b) {
Q. 5.4 User-defined data type can be derived by___________. struct ship
(a) struct (b) enum {
(c) typedef (d) All of the mentioned Ans. : (d)
};
Q. 5.5 What is the output of this program?
return 0;
#include <stdio.h>
}
struct test {
(a) It is wrong to define an empty structure
int x;
(b) Member variables can be added to a structure even
char y;
after its first definition.
} test;
(c) There is no use of defining an empty structure
int main()
(d) None of the above Ans. : (c)
{
test.x = 10; Q. 5.9 Which of the following structure declaration will throw
test.y = 'A'; an error?
(a) 0.416666666666667
(d) None of the mentioned Ans. : (d)
(b) garbage value garbage value Q. 5.10 Which properly declares a variable of struct foo?
(c) Compilation Error (a) struct foo; (b) struct foo var;
(d) None of these Ans. : (a) (c) foo; (d) int foo; Ans. : (b)
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (M5-2)
Q. 5.11 What is the output of this C code? Q. 5.15 Which of the following is a collection of different data
void main() types?
{ (a) String (b) Array
struct student (c) Structure (d) Files Ans. : (c)
{ Explanation : Structure is a user defined data type which
int no; contains the variables of different data types.
char name[20]; Q. 5.16 What will be the output of following program ?
}; #include <stdio.h>
struct student s; struct sample
s.no = 8; {
printf("%d", s.no); int a=0;
} char b='A';
(a) Nothing (b) Compile time error float c=10.5;
(c) Junk (d) 8 Ans. : (d) };
Q. 5.12 What is the similarity between a structure, union and int main()
enumeration? {
(a) All of them let you define new values struct sample s;
(b) All of them let you define new data types printf("%d,%c,%f",s.a,s.b,s.c);
(c) All of them let you define new pointers return 0;
(d) All of them let you define new structures }
Ans. : (b) (a) Error (b) 0,A,10.5
(c) 0,A,10.500000 (d) No Error , No Output
Q. 5.13 What are the uses of C Structures.?
Ans. : (a)
(a) structure is used to implement Linked Lists, Stack
Explanation : Cannot initialize members here. We can
and Queue data structures
only declare members inside the structure, initialization
(b) Structures are used in Operating System
of member with declaration is not allowed in structure
functionality like Display and Input taking.
declaration.
(c) Structure are used to exchange information with
peripherals of PC Q. 5.17 Most appropriate sentence to describe unions is ______
(d) All the above Ans. : (d) (a) Union is like structures
(b) Union contain members of different data types which
Q. 5.14 What is the output of this C code?
share the same storage area in memory
#include <stdio.h>
(c) Union are less frequently used in program
struct student
(d) Union are used for set operations Ans. : (b)
{
int no; Q. 5.18 What is the right way to access value of structure
variable book{ price, page }?
char name[20];
(a) printf("%d%d", book.price, book.page);
}
(b) printf("%d%d", price.book, page.book);
void main()
(c) printf("%d%d", price::book, page::book);
{
(d) printf("%d%d", price->book, page->book);
struct student s;
Ans. : (a)
s.no = 8;
printf("hello"); Q. 5.19
} #include <stdio.h>
(a) Compile time error (b) Nothing int main()
(c) hello (d) Varies Ans. : (a) {
struct sample{
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (M5-3)
int a; {
int b; int a[10];
sample *s; char p;
}t; };
printf("%d,%d",sizeof(sample),sizeof(t.s)); (a) 5 (b) 11
return 0; (c) 41 (d) 44 Ans. : (d)
} Q. 5.24 Size of the following union (assume size of int=2, size of
(a) 12,12 (b) 12,0 float=4 and size of char=1);
(c) Error (d) 12,4 Ans. : (d) union ABC
Q. 5.20 What will be the output of following program ? {
#include <stdio.h> int a;
struct sample float b;
{ char c;
int a; };
}sample; (a) 2 (b) 4 (c) 1 (d) 7 Ans. : (b)
int main() Q. 5.25 Can we declare function inside structure of C
{ Programming?
sample.a=100; (a) Yes (b) No
printf("%d",sample.a); (c) Depends on Compiler (d) Yes but run time error
return 0; Ans. : (b)
}
Q. 5.26 Which of the following is a properly defined struct?
(a) 0 (b) 100
(a) struct {int a;}
(c) ERROR (d) Warning Ans. : (b)
(b) struct a_struct {int a;}
Q. 5.21 Assume that size of an integer is 32 bit. What is the (c) struct a_struct int a;
output of following program? (d) struct a_struct {int a;}; Ans. : (d)
#include<stdio.h>
Q. 5.27 Consider the following C declaration
struct st
struct {
{
short s[5];
int x;
union {
static int y;
float y;
};
long z;
int main()
}u;
{
} t;
printf("%d", sizeof(struct st));
Assume that objects of the type short, float and long
return 0;
occupy 2 bytes, 4 bytes and 8 bytes, respectively. The
} memory requirement for variable t, ignoring alignment
(a) 4 (b) 8 considerations, is
(c) Compiler Error (d) Runtime Error Ans. : (c) (a) 22 bytes (b) 14 bytes
Q. 5.22 Which operator connects the structure name to its (c) 18 bytes (d) 20 bytes Ans. : (c)
member name? Q. 5.28 What is the correct syntax to declare a function foo()
(a) - (b) -> which receives an array of structure in function?
(c) . (d) both . and -> Ans. : (c) (a) void foo(struct *var);
Q. 5.23 What will be the size of the following structure? (b) void foo(struct *var[]);
#include <stdio.h> (c) void foo(struct var);
struct temp (d) none of the mentioned Ans. : (a)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (M5-4)
(c) struct Person Mother, Father; must be defined as
Q. 5.29 What is the output of this program?
struct Person *Mother, *Father;
#include <stdio.h>
(d) There is no error in the code Ans. : (c)
int main()
{ Q. 5.33
union demo { #include <stdio.h>
int x; #include <string.h>
int y; int main()
}; {
union demo a = 100; struct xyz
printf("%d %d",a.x,a.y); {
} char * n;
(a) 100 0 (b) 100 100 int eos;
(c) 0 0 (d) Compilation Error Ans. : (d) };
struct xyz x = {"Phoenix", 2017};
Q. 5.30 Which among the following is never possible in C when
struct xyz y=x;
members in a structure are same as that in a union?
printf("%d", printf("%s",y.n));
//Let P be a structure
return 0;
//Let Q be a union
}
(a) sizeof(P) is greater than sizeof(Q)
(a) Phoenix (b) 7Phoenix
(b) sizeof(P) is equal to sizeof(Q)
(c) 8Phoenix (d) Phoenix7 Ans. : (d)
(c) sizeof(P) is less than to sizeof(Q)
Q. 5.34 Which of the following accesses a variable in
(d) None of the above Ans. : (c)
structure *b?
Q. 5.31 hat is the output of this C code? (a) b->var; (b) b.var;
#include <stdio.h> (c) b-var; (d) b>var; Ans. : (a)
struct student Q. 5.35
{ #include<stdio.h>
char *name; struct st
}; {
void main() int x;
{ struct st next;
struct student s, m; };
s.name = "st"; int main()
{
m = s;
struct st temp;
printf("%s%s", s.name, m.name);
temp.x = 10;
} temp.next = temp;
(a) Compile time error (b) Nothing printf("%d", temp.next.x);
(c) Junk values (d) st st Ans. : (d) return 0;
Q. 5.32 What is wrong with the following code? }
struct Person{ (a) Compiler Error (b) 10
char *name; (c) Runtime Error (d) Garbage Value Ans. : (a)
struct Person Mother, Father; Q. 5.36 Union differs from structure in the following way ____
}Anita; (a) All members are used at a time
(a) The ; should appear after the } and Anita be defined (b) Only one member can be used at a time
later (c) Union cannot have more members
(b) name should be defined as an array (d) Union initialized all members as structure
Ans. : (b)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (M5-5)
Q. 5.37 What is the output of this program?
Q. 5.40 What will be the output of the following code?
#include <stdio.h>
struct abc{int a; int b;} v[3], *p;
int main(){
main()
struct simp {
{
p=v;
int i = 6;
p->a=3;
char city[] = "chennai"; p->b=p->a;
};
printf("\n%d\t%d", v[0].a, v[0].b);
struct simp s1;
}
printf("%d",s1.city);
(a) 3 4 (b) 43
printf("%d", s1.i);
(c) Any garbage value (d) 33 Ans. : (d)
return 0;
} Q. 5.41
(a) chennai 6 (b) Nothing will be displayed #include "stdio.h"
(c) Runtime Error (d) Compilation Error #include "string.h"
Ans. : (d) int main()
{
Q. 5.38 Which among the following is never possible in C when
members are different in a structure and union? struct xyz{
//Let P be a structure char * n;
//Let Q be a union int eos;
(a) sizeof(P) is greater than sizeof(Q) };
(b) sizeof(P) is less than sizeof(Q) struct xyz x = {"Kunal", 2017};
(c) sizeof(P) is equal to sizeof(Q) struct xyz y=x;
(d) None of the above Ans. : (d) printf("%i", printf("%s",y.n));
Q. 5.39 What’s the output of the following code? return 0;
#include <stdio.h> }
struct temp (a) Kunal7 (b) 7Kunal
{ (c) Kunal8 (d) 8Kunal Ans. : (a)
int a; Q. 5.42 Which of the following is a properly defined struct?
} s; (a) struct {int a;} (b) struct a_struct {int a;}
void func(struct temp) (c) struct a_struct int a; (d) struct a_struct {int a;}
{ Ans. : (d)
s.a = 10; Q. 5.43 Which of the following operators can be applied on
printf("%d\t", s.a); s structure variables?
} (a) Equality comparison ( == )
main() (b) Assignment ( = )
{ (c) Both of the above
func(s); (d) None of the above Ans. : (b)
printf("%d\t", s.a); Q. 5.44 The size of the following union, where an int occupies 4
} bytes of memory is
(a) 10 (Garbage Value) union demo
(b) 0 10 {
(c) 10 0 float x;
(d) (Garbage Value) 10 Ans. : (c) int y;
char z[10];
};
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (M5-6)
(a) 8 byte (b) 4 byte Q. 5.49
(c) 10 byte (d) 18 byte Ans. : (c) include "stdio.h"
#include "string.h"
Q. 5.45 What is the output of this program?
#include <stdio.h> int main()
{
struct
struct xyz{
{
int i; char * n;
int eos;
float ft;
};
}decl;
int main(){ struct xyz x = {"Kunal", 2017};
struct xyz y=x;
decl.i = 4;
printf(printf("%s",y.n), printf("%s",y.n));
decl.ft = 7.96623;
printf("%d %.2f", decl.i, decl.ft); return 0;
}
return 0;
(a) Kunal
}
(b) KunalKunal
(a) 4 7.97 (b) 4 7.96623
(c) Kunal7
(c) Compilation error (d) None of the above
(d) None of the above Ans. : (d)
Ans. : (a)
Q. 5.50 Which properly declares a variable of struct foo?
Q. 5.46 What is the similarity between a structure, union and
enumeration? (a) struct foo;
(a) All of them let you define new values (b) struct foo var;
(b) All of them let you define new data types (c) foo;
(c) All of them let you define new pointers (d) int foo; Ans. : (b)
(d) All of them let you define new structures Q. 5.51
Ans. : (b) union test
Q. 5.47 Which of the following operation is illegal in structures? {
(a) Typecasting of structure int x;
(b) Pointer to a variable of same structure char arr[8];
(c) Dynamic allocation of memory for structure int y;
(d) All of the mentioned Ans. : (a) };
int main()
Q. 5.48 What will be the output of the following program?
{
main()
printf("%d", sizeof(union test));
{
return 0;
struct emp
}
{
Predict the output of above program. Assume that the
char name[20]; size of an integer is 4 bytes and size of character is 1
int age; byte. Also assume that there is no alignment needed.
float sal; (a) 12 (b) 16
}; (c) 8 (d) 7 Ans. : (c)
struct emp e={"Tiger"};
Q. 5.52 Members of a union are accessed as____
printf("\n%d%f"),e.age, e.sal;
(a) union-name.member
}
(b) union-pointer->member
(a) 0 0.000000 (b) Garbage values
(c) Both (a) and (b)
(c) Error (d) None of the above
(d) None of the mentioned Ans. : (c)
Ans. : (a)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (M5-7)
Q. 5.53 What is the output of this program?
Q. 5.59 union test
void main()
{
{
int x;
struct bitfields { char arr[4];
int bits_1: 2;
int y;
int bits_2: 9;
};
int bits_3: 6; int main()
int bits_4: 1;
{
}bit;
union test t;
printf("%d", sizeof(bit)); t.x = 0;
}
t.arr[1] = 'G';
(a) 2 (b) 3 (c) 4 (d) 0 Ans. : (b) printf("%s", t.arr);
Q. 5.54 Presence of code like “s.t.b = 10” indicate _____ return 0;
(a) Syntax Error }
(b) structure Predict the output of above program. Assume that the
(c) double data type size of an integer is 4 bytes and size of character is 1
(d) An ordinary variable name Ans. : (b) byte. Also assume that there is no alignment needed.
(a) Nothing is printed
Q. 5.55 What will be the output of the following code?
(b) G
struct
(c) Garbage character followed by 'G'
{
(d) Garbage character followed by 'G', followed by more
int a; garbage characters Ans. : (a)
double d;
Q. 5.60 It is not possible to create an array of pointer to
float cp;
structures.
}s;
(a) TRUE (b) FALSE
void main()
(c) May Be (d) Can't Say Ans. : (b)
{
printf("%d\t%d\t%d\t%d", sizeof(s.a), sizeof(s.d), Q. 5.61 What is the output of this program?
sizeof(s.cp), sizeof(s)); #include <stdio.h>
} int main(){
(a) 4, 8, 4, 24 (b) 8, 2, 4, 12 struct leader
(c) 10, 4, 6, 4 (d) 4, 8, 4, 14 Ans. : (a) {
char *lead;
Q. 5.56 What is important difference between structure & union?
int established;
(a) There is no difference
};
(b) Union takes less memory
struct leader l1 = {"Phoenix-InfoTech", 2006};
(c) Union is faster
struct leader l2 = l1;
(d) Structure is faster Ans. : (b)
printf("%s %d", l2.lead, l1. established);
Q. 5.57 Which keyword is used to define a new structure? }
(a) struct (b) structure (a) Compilation error
(c) typedef (d) none of the above Ans. : (a) (b) Garbage value 2006
Q. 5.58 If a variable is a pointer to a structure, then which of the (c) Phoenix-InfoTech 2006
following operator is used to access data members of the (d) None of the above Ans. : (c)
structure through the pointer variable?
(a) . (b) $ (c) & (d) -> Ans. : (d)
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (M5-8)
(a) Segmentation Fault (b) Shoenix-InfoTech
Q. 5.62 What is the output of this C code?
(c) Phoenix-InfoTech (d) Compiler Error
#include <stdio.h>
struct point Ans. : (c)
{ Q. 5.66 Size of union is size of the longest element in the union
int x; (a) Yes (b) No
int y; (c) May Be (d) Can't Say Ans. : (a)
};
int main() Q. 5.67 What is the output of this program?
{ #include <stdio.h>
struct point p = {1}; struct student
struct point p1 = {1}; {
if(p == p1) int no = 5;
printf("equal\n"); char name[20];
else };
printf("not equal\n");
void main()
}
{
(a) Compile time error (b) equal
struct student s;
(c) depends on the standard (d) not equal
s.no = 8;
Ans. : (a)
printf("hello");
Q. 5.63 Is it necessary that all elements of structure should be }
different in size? (a) Nothing (b) Compile time error
(a) Yes (b) No Ans. : (b) (c) hello (d) Varies Ans. : (b)
Q. 5.64 Which of the following is not true about a structure? Q. 5.68 What is the output of this C code?
(a) Structure are used to construct a complex data type #include <stdio.h>
in a meaningful way
struct point
(b) We can also declare an array of Structure.
{
(c) A Structure can be nested inside under Structure.
int x;
(d) We cannot pass a structure as a function argument
int y;
Ans. : (d)
};
Q. 5.65 struct notpoint
# include <iostream> {
# include <string.h> int x;
using namespace std; int y;
struct Test };
{ int main()
char str[20]; {
}; struct point p = {1};
int main() struct notpoint p1 = p;
{ printf("%d\n", p1.x);
struct Test st1, st2; }
strcpy(st1.str, "Phoenix-InfoTech"); (a) Compile time error (b) 1
st2 = st1; (c) 0 (d) Undefined
st1.str[0] = 'S'; Ans. : (a)
cout << st2.str;
Q. 5.69 Are self referential structures are possible in C?
return 0;
(a) Yes (b) No Ans. : (a)
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Structure and Union)….Page no. (M5-9)
Q. 5.70 _______ is a keyword used in C language to assign int x;
alternative names to existing types? int y;
(a) struct (b) typedef };
(c) union (d) none of the above Ans. : (b) struct notpoint
Q. 5.71 {
#include<stdio.h> int x;
struct Point int y;
{ };
int x, y, z; void foo(struct point);
}; int main()
int main() {
{ struct notpoint p1 = {1, 2};
struct Point p1 = {.y = 0, .z = 1, .x = 2}; foo(p1);
printf("%d %d %d", p1.x, p1.y, p1.z); }
return 0; void foo(struct point p)
} {
(a) Compiler Error (b) 201 printf("%d\n", p.x);
(c) 1 2 (d) 210 Ans. : (b) }
(a) Compile time error (b) 1
Q. 5.72 Which of the following share a similarity in syntax?
(c) 0 (d) Undefined
1. Union 2. Structure
Ans. : (a)
3. Arrays 4. Pointers
(a) 3 and 4 (b) 1 and 2 Q. 5.75
(c) 2 and 3 (d) All of the above Ans. : (b) #include <stdio.h>
int main()
Q. 5.73 What is the output of this program?
{
#include <stdio.h>
struct xyz{
void main()
int a;
{
};
struct number
struct xyz obj1={1};
{
struct xyz obj2 = obj1;
int no;
printf("%d", obj2.a);
char name[20];
obj2.a = 100;
};
printf("%d", obj1.a);
struct number s;
return 0;
s.no = 50;
}
printf("%d", s.no);
(a) 1100 (b) 11
}
(c) 0100 (d) 10 Ans. : (b)
(a) Nothing (b) Compile time error
(c) Junk (d) 50 Ans. : (d) Q. 5.76 Which operator connects the structure name to its
member name?
Q. 5.74 What is the output of this C code? (a) - (b) .
#include <stdio.h> (c) Both (b) and (c) (d) None of the above
struct point Ans. : (b)
{
MCQ Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
MODULE VI Pointers
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (M6-3)
foo(&p); Q. 6.21 What will be the output of the following C code?
printf("%d ", *p); #include <stdio.h>
printf("%d ", *p); void foo(int*);
} int main()
void foo(int **const p) {
{ int i = 10, *p = &i;
foo(p++);
int j = 11;
}
*p = &j;
void foo(int *p)
printf("%d ", **p); {
} printf("%d\n", *p);
(a) 11 11 11 }
(b) 11 11 Undefined-value
(a) 10 (b) Some garbage value
(c) Compile time error
(c) Compile time error (d) Segmentation fault
(d) Segmentation fault/code-crash Ans. : (b)
Ans. : (a)
Q. 6.19 What is the output of this C code?
int *f(); Q. 6.22 What is (void*)0?
{ char(*ptr)[4] = wer;
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (M6-4)
Q. 6.27 Which among the following is right? (a) 10.000000 (b) 0.000000
(a) sizeof(struct stemp*) > sizeof(union utemp*) > (c) Compile time error (d) Undefined behaviour
sizeof(char *) Ans. : (b)
(b) sizeof(struct stemp*) < sizeof(union utemp*) <
Q. 6.31 Combine the following two statements into one?
sizeof(char *)
char *p;
(c) sizeof(struct stemp*) = sizeof(union utemp*) =
sizeof(char *) p = (char*) malloc(100);
(d) The order Depends on the compiler Ans. : (c) (a) char p = *malloc(100);
Q. 6.28 Given the following code fragment: (b) char *p = (char) malloc(100);
main() (c) char *p = (char*)malloc(100);
{ (d) char *p = (char *)(malloc*)(100);
int row[20],i,sum=0; Ans. : (c)
int *p=row;
Q. 6.32 Comment on the following?
for(i=0;i<20;i++)
const int *ptr;
*(p+i)=1;
(a) You cannot change the value pointed by ptr
for(i=0;i<20;i+=sizeof(int))
sum+=*(p+i); (b) You cannot change the pointer ptr itself
printf("sum=%d\n",sum); (c) Both (a) and (b)
} (d) You can change the pointer as well as the value
What will be the result of execution? pointed by it Ans. : (a)
(a) sum=10 (b) sum=40
Q. 6.33 Address stored in the pointer variable is of type _____.
(c) sum=60 (d) sum=190 Ans. : (a)
(a) Integer (b) Float
Q. 6.29 Assume that float takes 4 bytes, predict the output of
following program.
(c) Array (d) Character Ans. : (a)
#include <stdio.h> Q. 6.34 Consider the following program fragment.
int main() static char wer[3][4] = {"bag", "let", "bud"};
{ char(*ptr)[4] = wer;
float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5}; The possible output of printf ( "%d %d", wer, wer +1); is
float *ptr1 = &arr[0];
(a) 262 262 (b) 262 266
float *ptr2 = ptr1 + 3;
(c) 262 263 (d) 262 265 Ans. : (a)
printf("%f ", *ptr2);
printf("%d", ptr2 - ptr1); Q. 6.35 What is the output of the program ?
return 0; #include<stdio.h>
} int main()
(a) 90.500000 3 (b) 90.500000 12 {
(c) 10.000000 12 (d) 0.500000 3 Ans. : (a) int a[5] = {2, 3};
Q. 6.30 printf("%d, %d, %d\n", a[2], a[3], a[4]);
#include <stdio.h> return 0;
void foo(float *); }
int main() (a) Garbage Values (b) 2, 3, 3
{ (c) 3, 2, 2 (d) 0, 0, 0 Ans. : (d)
int i = 10, *p = &i; Q. 6.36 What do the following declaration signify?
foo(&i); char **argv;
} (a) argv is a pointer to pointer.
void foo(float *p) (b) argv is a pointer to a char pointer.
{ (c) argv is a function pointer.
printf("%f\n", *p); (d) argv is a member of function pointer. Ans. : (b)
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (M6-5)
Q. 6.37 What is the missing statement in the following function (a) 2 97 (b) 22
which copies string x into string y? (c) Compile time error
void strcpy (char *x, char *y) (d) Segmentation fault/code crash Ans. : (a)
{
Q. 6.40 In which header file is the NULL macro defined?
while (*y!='\0')
(a) stdio.h (b) stddef.h
................./*missing statement*/
(c) stdio.h and stddef.h (d) math.h Ans. : (c)
*x='\0';
} Q. 6.41 Which of the following does not initialize ptr to null
What will be the result of execution? (assuming variable declaration of a as int a=0)?
(a) x=y (b) *x++=*y++ (a) int *ptr = &a; (b) int *ptr = &a – &a;
(c) (*x)++=(*y)++ (d) none of these Ans. : (b) (c) int *ptr = a – a; (d) All of the mentioned
Ans. : (a)
Q. 6.38 include<stdio.h>
int main() Q. 6.42 In order to fetch the address of the variable we write
preceding _________ sign before variable name.
{
(a) Percent(%) (b) Comma(,)
int arr[] = {10, 20, 30, 40, 50, 60};
(c) Ampersand(&) (d) Asteric(*) Ans. : (c)
int *ptr1 = arr;
int *ptr2 = arr + 5; Q. 6.43 The operators > and < are meaningful when used with
printf("Number of elements between two pointer are: %d.", pointers, if ______
(ptr2 - ptr1)); (a) the pointers point to data of similar type
printf("Number of bytes between two pointers are: %d", (b) the pointers point to structure of similar data type
(char*)ptr2 - (char*) ptr1); (c) the pointers point to elements of the same array
return 0; (d) none of these Ans. : (c)
} Q. 6.44 Combine the following two statements into one?
Assume that an int variable takes 4 bytes and a char char *p;
variable takes 1 byte p = (char*) malloc(100);
(a) Number of elements between two pointer are: 5. (a) char p = *malloc(100);
Number of bytes between two pointers are: 20
(b) char *p = (char) malloc(100);
(b) Number of elements between two pointer are: 20.
(c) char *p = (char*)malloc(100);
Number of bytes between two pointers are: 20
(d) char *p = (char *)(malloc*)(100); Ans. : (c)
(c) Number of elements between two pointer are: 5.
Number of bytes between two pointers are: 5 Q. 6.45 What do the following declaration signify?
(d) Compiler Error Ans. : (a) int (*pf)();
Q. 6.39 What will be the output of the following C code? (a) pf is a pointer to function.
#include <stdio.h> (b) pf is a function pointer.
int main() (c) pf is a pointer to a function which return int
{ (d) pf is a function of pointer variable. Ans. : (c)
int i = 97, *p = &i; Q. 6.46
foo(&i); char *ptr;
printf("%d ", *p); char myString[]="abcdefg";
} ptr=myString
void foo(int *p) ptr+=5;
{ The pointer ptr points to which string?
int j = 2; (a) fg (b) efg
p = &j; (c) defg (d) cdefg Ans. : (a)
printf("%d ", *p);
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (M6-6)
Q. 6.52 What would be the equivalent pointer expression for
Q. 6.47
referring the array element a[i][j][k][l]
#include<stdio.h>
(a) ((((a+i)+j)+k)+l)
int main()
(b) *(*(*(*(a+i)+j)+k)+l)
{
(c) (((a+i)+j)+k+l)
int a;
(d) ((a+i)+j+k+l) Ans. : (b)
char *x;
x = (char *) &a; Q. 6.53 How will you free the memory allocated by the
a = 512; following program?
x[0] = 1; #include<stdio.h>
x[1] = 2; #include<stdlib.h>
printf("%dn",a); #define MAXROW 3
return 0; #define MAXCOL 4
} int main()
What is the output of above program? {
(a) Machine dependent (b) 513 int **p, i, j;
(c) 258 (d) Compiler Error p = (int **) malloc(MAXROW * sizeof(int*));
Ans. : (a) return 0;
}
Q. 6.48 If a variable is a pointer to a structure, then which of the
(a) memfree(int p); (b) dealloc(p);
following operator is used to access data members of the
structure through the pointer variable?
(c) malloc(p, 0); (d) free(p); Ans. : (d)
(a) . (b) & Q. 6.54 Output of the following program will be ______
(c) * (d) -> Ans. : (d) main()
{
Q. 6.49 What is the output of this C code?
int a[]={1,2,9,8,6,3,5,7,8,9};
int x = 0;
void main() int *p=a+1;
int *q=a+6;
{
printf("\n%d",q-p);
int *ptr = &x;
printf("%p\n", ptr); }
(a) 9 (b) 5
x++;
printf("%p\n ", ptr); (c) 2 (d) None of these Ans. : (b)
} Q. 6.55
(a) Same address (b) Different address int main()
(c) Compile time error (d) Varies Ans. : (a) {
char *ptr = "GeeksQuiz";
Q. 6.50 Comment on this const int *ptr;
printf("%cn", *&*&*ptr);
(a) You cannot change the value pointed by ptr
return 0;
(b) You cannot change the pointer ptr itself
}
(c) Both (a) and (b)
(a) Compiler Error (b) Garbage Value
(d) You can change the pointer as well as the value
pointed by it Ans. : (a) (c) Runtime Error (d) G Ans. : (d)
Q. 6.51 Choose the best answer. Prior to using a pointer variable Q. 6.56 What is the output of this C code?
(a) it should be declared int x = 0;
(b) it should be initialized void main()
(c) it should be both declared and initialized {
(d) none of the above Ans. : (c) int *const ptr = &x;
printf("%p\n", ptr);
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (M6-7)
ptr++;
Q. 6.61 Given float *pf; int *pi; Which of the following is true?
printf("%p\n ", ptr);
(a) sizeof(pf) > sizeof(pi)
}
(b) sizeof(pi) < sizeof(pf)
(a) 0 1
(c) sizeof(pf) == sizeof(pi)
(b) Compile time error
(d) None of these above Ans. : (c)
(c) 0xbfd605e8 0xbfd605ec
(d) 0xbfd605e8 0xbfd605e8 Ans. : (b) Q. 6.62
#include<stdio.h>
Q. 6.57 Which of the following statements are correct about the
void fun(int arr[])
given program?
{
#include <stdio.h>
int i;
int main()
int arr_size = sizeof(arr)/sizeof(arr[0]);
{
for (i = 0; i < arr_size; i++)
printf("%p", main());
printf("%d ", arr[i]);
return 0;
}
}
int main()
(a) Prints garbage value infinite times
{
(b) Error
int i;
(c) Runs infinite times without printing anything
int arr[4] = {10, 20 ,30, 40};
(d) None of the above Ans. : (c)
fun(arr);
Q. 6.58 Consider the two declarations return 0;
void *voidPtr; }
char *charPtr; (a) 10 20 30 40 (b) Machine Dependent
Which of the following assignments are syntactically (c) 10 20 (d) Nothing Ans. : (c)
correct?
Q. 6.63 What is the output of this C code?
(a) voidPtr = charPtr (b) charPtr = voidPer
void main()
(c) *voidPtr = *charPtr (d) *charPtr = voidPtr
{
Ans. : (a)
int x = 0;
Q. 6.59 The operator used to get value at address stored in a int *ptr = &5;
pointer variable is
printf("%p\n", ptr);
(a) * (b) & (c) && (d) || Ans. : (a)
}
Q. 6.60 What is x in the following program? (a) 5 (b) Address of 5
#include<stdio.h> (c) Nothing (d) Compile time error Ans. : (d)
int main()
Q. 6.64 What is the output of this program?
{
#include <stdio.h>
typedef char (*(*arrfptr[3])())[10];
void fun(int a, ...)
arrfptr x;
{
return 0;
printf("%d ", a);
}
}
(a) x is a pointer
int main()
(b) x is an array of three pointer
{
(c) x is an array of three function pointers
fun(1,2,3,4);
(d) Error in x declaration Ans. : (c)
fun(5,6,7,8,9);
return 0;
}
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture
C Programming (MU-FE-Sem II) (Pointers)….Page no. (M6-8)
(a) 1 5 (b) 25 (a) Address of x (b) Junk value
(c) 5 1 (d) Compilation Error Ans. : (a) (c) 0 (d) Run time error Ans. : (c)
Q. 6.65 A pointer variable can be ______ Q. 6.70 Consider the following program.
(a) passed to a function as argument main()
(b) changed within a function {
(c) returned by a function char x[10], *ptr = x;
(d) can be assigned an integer value Ans. : (c) scanf("%s", x);
change(&x[4]);
Q. 6.66 What will be the output of the program ?
#include<stdio.h> }
change ( char a[ ] )
int main()
{
{
static char *s[] = {"black", "white", "pink", "violet"}; puts(a);
}
char **ptr[] = {s+3, s+2, s+1, s}, ***p;
If abcdefg is the input, the output will be
p = ptr;
(a) abcd (b) abc
++p;
printf("%s", **p+1); (c) efg (d) garbage Ans. : (c)
return 0; Q. 6.71 What will be the output of the program ?
} #include<stdio.h>
(a) ink (b) ack int main()
(c) ite (d) let Ans. : (a) {
int i=3, *j, k;
Q. 6.67 In the following code what is 'P'?
j = &i;
typedef char *charp;
const charp P; printf("%d\n", i**j*i+*j);
return 0;
(a) P is a constant
}
(b) P is a character constant
(a) 30 (b) 27
(c) P is character type
(c) 9 (d) 3 Ans. : (a)
(d) None of the above Ans. : (a)
Q. 6.72 How will you free the allocated memory?
Q. 6.68 The reason for using pointers in a C program is_____
(a) remove(var-name);
(a) Pointers allow different functions to share and
modify their local variables. (b) free(var-name);
(b) To pass large structures so that complete copy of the (c) delete(var-name);
structure can be avoided. (d) dalloc(var-name) Ans. : (b)
(c) Pointers enable complex “linked" data structures like Q. 6.73 Output of the following program will be
linked lists and binary trees.
main()
(d) All of the above Ans. : (d)
{
Q. 6.69 What is the output of this C code? int a[]={1,2,9,8,6,3,5,7,8,9};
void main() int *p=a+1;
{ int *q=a+6;
int x = 0; printf("\n%d",q-p);
int *ptr = &x; }
printf("%d\n", *ptr); (a) 9 (b) 5 (c) 2 (d) None of these
} Ans. : (b)
MCQ Ends…
(MU-New Syllabus w.e.f academic year 19-20)(M2-05) Tech-Neo Publications...A SACHIN SHAH Venture