0% found this document useful (0 votes)
20 views300 pages

c Programming

The document outlines the syllabus and structure for the C Programming course (FEC205) at the University of Mumbai for first-year engineering students, effective from the academic year 2019-2020. It includes course objectives, outcomes, assessment methods, and detailed content modules covering fundamental programming concepts. The authors, Er. Manoj S. Kavedia and Pankaj B. Brahmankar, express gratitude to contributors and emphasize the importance of feedback for continuous improvement.

Uploaded by

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

c Programming

The document outlines the syllabus and structure for the C Programming course (FEC205) at the University of Mumbai for first-year engineering students, effective from the academic year 2019-2020. It includes course objectives, outcomes, assessment methods, and detailed content modules covering fundamental programming concepts. The authors, Er. Manoj S. Kavedia and Pankaj B. Brahmankar, express gratitude to contributors and emphasize the importance of feedback for continuous improvement.

Uploaded by

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

University of Mumbai

C Programming
(Course Code : FEC205)
First Year Engineering (Common to All Branches)
(Semester II) (Mumbai University)

Strictly as per the New Syllabus (REV-2019 ‘C’ Scheme) of


Mumbai University w.e.f. academic year 2019-2020

Er. Manoj S. Kavedia Pankaj B. Brahmankar


Assistant Professor Director, Phoenix InfoTech,
Department of Electronics and Pune,
Telecommunication
Maharashtra, India.
Pursing PHD in Internet of Things
Thadomal Shahani Engineering College
(TSEC), Bandra, Mumbai

.
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 glad to present the New Edition of this book titled

“C Programming”. This book covers the new Syllabus of First Year

Engineering (Semester-2) course of “Mumbai University” which has been

effective since the academic year 2019-2020.

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

arranged in a proper sequence to ensure smooth flow of the subject.

We are thankful to Shri. Sachin Shah for the encouragement and

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,

because that will help us to improve further.

We are also thankful to our family members and friends for their

patience and encouragement.

- 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

Test 1 Test 2 Avg. Sem. (in Hrs)


Exam.
FEC205 C Programming 15 15 15 60 2 - - 75
Objectives :
To provide exposure to problem-solving by developing an algorithm, flowchart and implement the logic
using C programming language.
Outcomes : Learners will be able to…
1. Formulate simple algorithms for arithmetic, logical problems and translate them to programs in C
language
2. Implement, test and execute programs comprising of control structures.
3. Decompose a problem into functions and synthesize a complete program.
4. Demonstrate the use of arrays, strings and structures in C language.
5. Understand the concept of pointers
Module Detailed Contents Hrs.
Introduction
 Introduction to components of a Computer System
 Introduction to Algorithm and Flowchart (Refer chapter 1)
Fundamentals of C Programming
1  Keywords, Identifiers, Constants and Variables
5
 Data types in C
 Operators in C
 Basic Input and Output Operations
 Expressions and Precedence of Operators
 In-built Functions (Refer chapter 2)
Control Structures
 Introduction to Control Structures
Branching and looping structures
2  If statement, If-else statement, Nested if-else, else-if Ladder 7
 Switch statement
 For loop, While loop, Do while loop
 break and continue (Refer chapter 3)
Functions
 Introduction to functions
4
3  Function prototype, Function definition, Accessing a function and parameter passing.
 Recursion. (Refer chapter 4)
Module Detailed Contents Hrs.

4 Arrays and Strings 4

 Introduction to Arrays

 Declaration and initialization of one dimensional and two-dimensional arrays.

 Definition and initialization of String

 String functions (Refer chapter 5)

Structure and Union

 Concept of Structure and Union

 Declaration and Initialization of structure and union


5 4
 Nested structures

 Array of Structures

 Passing structure to functions (Refer chapter 6)

Pointers

 Fundamentals of pointers

6  Declaration, initialization and dereferencing of pointers 4

 Operations on Pointers

 Concept of dynamic memory allocation (Refer chapter 7)

Assessment: Internal Assessment Test:

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.

End Semester Theory Examination:

1. Question paper will comprise of total 06 questions, each carrying 15marks.

2. Total 04 questions need to be solved.

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

 Chapter 1 : Introduction to Computer, Algorithm and Flowchart ...........1-1 to 1-25

 Chapter 2 : Fundamentals of C Programming ......................................2-1 to 2-34

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

 LAB MANUAL ......................................................................................... L-1 to L-28


 MULTIPLE CHOICE QUESTIONS


Module I
Chapter… 1
Introduction to Computer,
Algorithm and Flowchart
University Prescribed New Syllabus w.e.f Academic Year 2019-2020

 Introduction to components of a Computer System


 Introduction to Algorithm and Flowchart

1.1 Introduction to Computer System .................................................................................................................................. 1-2


1.1.1 Introduction to Components of a Computer System ........................................................................................ 1-3
1.1.2 Input Devices ................................................................................................................................................... 1-4
1.1.3 Output Devices ................................................................................................................................................ 1-5
1.1.4 Hardware ......................................................................................................................................................... 1-7
1.1.5 Software ........................................................................................................................................................... 1-8
1.1.6 Machine Level Programming ........................................................................................................................... 1-9
1.1.7 Assembly Level Programming ....................................................................................................................... 1-10
1.1.8 High Level Programming................................................................................................................................ 1-11
1.1.9 Compiler and Interpreter ................................................................................................................................ 1-12
1.1.10 Defining Problem ........................................................................................................................................... 1-13
UQ. Explain how problem is defined with a help of suitable example. MU - May 13, 4 Marks............................. 1-13
1.2 Introduction to Algorithm .............................................................................................................................................. 1-14
UQ. What do you mean by algorithm ? Which points you should consider while developing the algorithm ?
MU - Dec. 13, May 14, May 16, 4 Marks. ..................................................................................................... 1-14
OR Define term algorithm. MU - Dec. 17, 2 Marks. ............................................................................................ 1-14
UQ. An algorithm is a graphical representation of the logic of a program. MU - May 18, 1 Mark. ....................... 1-14
1.2.1 Characteristics of Algorithm ........................................................................................................................... 1-14
1.2.2 Basic Conventions of Algorithm ..................................................................................................................... 1-15
1.2.3 Keywords in Algorithm ................................................................................................................................... 1-16
1.2.4 Steps to implement Algorithm ........................................................................................................................ 1-16
1.2.5 Examples of Algorithm ................................................................................................................................... 1-17
UQ. Write Algorithm to check whether given number is Armstrong Numbers or not also mention input and output
specifications to algorithm. MU - Dec. 17, 8 Marks........................................................................................ 1-19
1.3 Introduction to Flowchart ............................................................................................................................................. 1-19
UQ. Explain need of flowchart.MU - May 15, 2 Marks. ......................................................................................... 1-19
1.3.1 Symbols used in Flowchart ............................................................................................................................ 1-20
1.3.2 Rules of Flowchart Construction .................................................................................................................... 1-20
1.3.3 Examples of Flowchart................................................................................................................................... 1-21
1.3.4 Advantages and disadvantages of Flowchart................................................................................................. 1-25
 Chapter Ends .................................................................................................................................................... 1-25
C Programming (MU-FE-Sem II) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-2)

 1.1 INTRODUCTION TO COMPUTER


SYSTEM

GQ. Write note on Computer System. (10 Marks)

 Ans. : Computer System


 Computer is an electronic device that can be instructed
to carry out sequences of arithmetic or logical
operations automatically via computer programming.
 Modern computers have the ability to follow Fig. 1.1.1 : First Generation of Computers
generalized sets of operations, called programs. These  First generation : 1937 - 1946 – First electronic
programs enable computers to perform an extremely digital computer was built by Dr. John V. Atanasoff
wide range of tasks. and Clifford Berry during 1937.
 Computers are used as control systems for a wide  It was named as the Atanasoff-Berry Computer
variety of industrial and consumer devices. i.e. ABC. Development of other computers continued
until in 1946.
 This includes simple special purpose devices like
microwave ovens and remote controls, factory devices  Further Electronic Numerical Integrator and Computer
(ENIAC) were built which weighed 30 tons, and had
such as industrial robots and computer-aided design,
18,000 vacuum tubes. Vacuum tubes were used for
and also general purpose devices like personal
processing. Computers of first generation had no
computers and mobile devices such as smart-phones.
operating system and could able to perform only single
 Early computers were only conceived as calculating task at a time.
devices.  Second generation : In second generation first
 Since ancient times, simple manual devices like the computer was introduced in 1951 for commercial
abacus helps people in doing calculations. purpose. In the computer world International Business
Machine which is also known as IBM made their mark.
 Early in the Industrial Revolution, some mechanical
Many computer programming languages were
devices were built to automate long tedious tasks, such
developed and computers had memory and operating
as guiding patterns for looms.
systems.
 More sophisticated electrical machines did specialized
analog calculations in the early 20th century.
 The first digital electronic calculating machines were
developed during World War II. The speed, power, and
versatility of computers have been increasing
dramatically ever since then.
 The history of computer begins in the 19th century.
Charles Babbage was an English mathematics
professor, he designed the Analytical Engine. Design
made by him was the basic framework of the today’s
computer. Fig. 1.1.2 : Second Generation of Computers
 Computers can be classified into three generations.  Third generation : 1963 - present - Integrated circuit
 Computer of every generation lasted for specific period was developed in third generation. Due to this,
of time, after some time it lead to invention of new and computer became more dominant and more
improved computer. trustworthy and they are able to run many different
programs at the same 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) (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

 1.1.1 Introduction to Components of


understand.
o Supply the converted data to the computer system
a Computer System
for further processing.
GQ. Explain the major components of computer (B) Storage Unit
system and give their function. ( 10 Marks)
 The storage unit of the computer holds data and
 Ans. : instructions that are entered through the input unit,
Components of computer system
before they are processed.
 It preserves the intermediate and final results before
 A computer can process data, pictures, sound and
these are sent to the output devices.
graphics. They can solve highly complicated problems
quickly and accurately.  It also saves the data for the later use. The various
storage devices of a computer system are divided into
 A computer as shown in Fig. 1.1.4 performs basically
two categories.
five major computer operations or functions
irrespective of their size and make. These are : 1. Primary Storage
(1) It accepts data or instructions by way of input,  Stores and provides very fast. This memory is
(2) It stores data, generally used to hold the program being currently
executed in the computer, the data being received from
(3) It can process data as required by the user,
the input unit, the intermediate and final results of the
(4) It gives results in the form of output, and program.
(5) It controls all operations inside a computer.  The primary memory is temporary in nature. The data
is lost, when the computer is switched off. In order to
store the data permanently, the data has to be
transferred to the secondary memory.
 The cost of the primary storage is more compared to
the secondary storage. Therefore most computers have
limited primary storage capacity.
2. Secondary Storage
 Secondary storage is used like an archive. It stores
several programs, documents, data bases etc.
Fig. 1.1.4 : Block Diagram of Computer

(MU-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)

 To produce some symbols, it requires pressing and  1.1.3 Output Devices


holding of several keys concurrently or in sequence.
GQ. Explain various output devices in detail. (5 Marks)
2. Mouse
 A computer mouse is an input device which is also  Ans. :
known as hand control device. Nowadays two types of Output Devices
mouse are available; wireless and wired mouse.
 Output devices are used to provide output to user.
 Mouse controls cursor in GUI (Graphical User There are number of output devices such as Monitor,
Interface). Mouse can perform actions such as move printer, speaker, plotter etc.
and select text, icons, files, and folders.
1. Monitor
 Mouse is placed on a plane surface for desktop
 Monitor is an output device which is used to display
computers, such as a mouse pad or desk. Due to mouse
the information. Monitor is a computer display. A
pointer it allows a smooth control of the graphical user
monitor typically consists of many parts such as the
interface.
display device, casing and power supply.
 Mouse consists of one or more buttons. User can move
 In the modern monitors there is display device which is
the mouse to move the cursor in the same direction.
typically Liquid Crystal Display (LCD). Cathode Ray
 To select something, the user can move the cursor on Tube (CRT) was used in older monitors. By using
the screen. The right mouse button is used to open Digital Visual Interface (DVI) monitors are connected
menus. Touch surfaces and "wheels" are other features to the computer.
of mouse which enables dimensional input additional
control.

Fig. 1.1.6 : Mouse


3. Scanner
 An image scanner often abbreviated to just scanner is a
device that optically scans images, printed text, Fig. 1.1.8 : Monitor
handwriting or an object and converts it to a digital
 Displaying video and graphical information which is
image.
developed by the computer’s graphics adapter is the
main function of the computer.
2. Printer
 "A printer is an external output device that takes data
from a computer and generates output in the form of
graphics / text on a paper".
 There various types of printers available in market :
(i) Dot-Matrix Printers
 The dot-matrix printer uses print heads containing from
Fig. 1.1.7 : Scanner 9 to 24 pins.

(MU-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.

Fig. 1.1.10 : Ink-Jet Printer


(iii) Laser printers
 A laser printer works like a photocopy machine. Laser
printers produce images on paper by directing a laser
Fig. 1.1.9 : Dot-Matrix Printer beam at a mirror which bounces the beam onto a drum.
(ii) Ink-jet printers  The drum has a special coating on it to which toner
 Ink-jet printers work in the same fashion as dot-matrix (an ink powder) sticks.
printers in the form of images or characters with little  Using patterns of small dots, a laser beam conveys
dots. However, the dots are formed by tiny droplets of information from the computer to a positively charged
ink. drum to become neutralized.
 From all those areas of drum which become
 Ink-jet printers form characters on paper by spraying
neutralized, the toner detaches. As the paper rolls by
ink from tiny nozzles through an electrical field that
the drum, the toner is transferred to the paper printing
arranges the charged ink particles into characters at the
the letters or other graphics on the paper. A hot roller
rate of approximately 250 characters per second. bonds the toner to the paper.
 The ink is absorbed into the paper and dries instantly.  Laser printers use buffers that store an entire page at a
Various colors of ink can also be used. time. When a whole page is loaded, it will be printed.
 One or more nozzles in the print head emit a steady  The speed of laser printers is high and they print
stream of ink drops. Droplets of ink are electrically quietly without producing much noise.
charged after leaving the nozzle.  Many home-use laser printers can print eight pages per
 The droplets are then guided to the paper by minute, but faster printers print approximately 21,000
electrically charged deflecting plates [one plate has lines per minute or 437 pages per minute if each page
positive charge (upper plate) and the other has negative contains 48 lines.
charge (lower plate)].

(MU-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

4. Plotter GQ. Explain concept of Hardware in detail. (5 Marks)


 The plotter is a computer printer for printing vector  Ans. : Hardware
graphics.
 Hardware refers to the physical elements of a
 In the past, plotters were used in applications such as
computer. This also sometimes called the machinery or
computer-aided design, though they have generally
the equipment of the computer.
been replaced with wide-format conventional printers.
 Examples of hardware in a computer are the keyboard,
 A plotter gives a hard copy of the output. It draws
the monitor, the mouse and the central processing unit.
pictures on a paper using a pen. Plotters are used to
 However, most of a computer's hardware cannot be
print designs of ships and machines, plans for
seen; in other words, it is not an external element of the
buildings and so on.
computer, but rather an internal one, surrounded by the
computer's casing (tower).
 A computer's hardware is comprised of many different
parts, but perhaps the most important of these is the
motherboard. The motherboard is made up of even
more parts that power and control the computer.
 In contrast to software, hardware is a physical entity.
Hardware and software are interconnected, without
software, the hardware of a computer would have no
Fig. 1.1.11 : Plotter 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) (Introduction to Computer, Algorithm & Flowchart)….Page no. (1-8)

 However, without the creation of hardware to perform


tasks directed by software via the central processing
 1.1.5 Software

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)

 Application software allows users to perform various  5. Content Access Software


tasks for example creation of documents, worksheets,
Used to access content and examines a need for
databases and also creating graphics.
published digital content and entertainment.
 Application software includes programs intended to
 6. Educational Software
complete particular tasks. These software can make
users work done easily. This software can give all the necessary educational
information that user may require.
 Examples of application software are Word processing
software, database programs, educational software,  7. Media Development Software
CAD software, Spreadsheet software etc. It can examine requirements to produce and print
 There are various types of application software, some electronic media.
of them are listed below :
 1.1.6 Machine Level Programming

GQ. Write note on Machine Level Programming


(5 Marks)

 Ans. : Machine Level Programming


 Machine code is a computer program written
in machine language instructions that can be executed
directly by a computer's central processing unit (CPU).
 Each instruction causes the CPU to perform a very
specific task, such as a load, a jump, or an ALU
operation.
 Machine code is a strictly numerical language which is
intended to run as fast as possible, and may be
regarded as the lowest-level representation of a
compiled or assembled computer program.
 While it is possible to write programs directly in
Fig. 1.1.13: Types of Application software machine code, it is tedious and error prone to manage
individual bits and calculate numerical addresses and
 1. Application Suite constants manually.
Application suite can have multiple applications that  For this reason, programs are very rarely written
can be grouped together. It can contain functions, directly in machine code in modern contexts.
features and user interfaces which can interact with  The overwhelming majority of practical programs
each other in the program. today are written in higher-level languages or assembly
 2. Enterprise Software language.
This kind of software is used for big organization  The source code is then translated to executable
which is widely distributed through network. machine code by utilities such as compilers,
assemblers.
 3. Enterprise Infrastructure Software :
 Below is an example of machine language (binary) for
This software can have the ability to provide support
the text "Hello World".
for enterprise software systems.
 4. Information Worker Software 01001000 01100101 01101100 01101100 01101111
00100000 01010111 01101111 01110010 01101100
Finds human needs necessary to manage and create
01100100
information for individual projects within departments.

(MU-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

Assembly Level Programming 1. It requires small amount of memory as well as


execution time.
 An assembly (or assembler) language, often
abbreviated asm, is any low-level programming 2. It helps to perform hardware-specific complex jobs in
language in which there is a very strong an easier way.
correspondence between the program's statements and 3. It is also appropriate for time-critical jobs.
the architecture's machine code instructions. 4. It is considered as compatible for writing interrupt
 Each assembly language is specific to a particular service routines and other memory resident programs.
computer architecture and operating system.
GQ. Write disadvantages of Assembly Level
 Assembly language may also be called symbolic Programming. (2 Marks)
machine code.
 Assembly code is converted into executable machine
 Ans. :
code by a utility program referred to as an assembler. Disadvantages of Assembly Level Programming
The conversion process is referred to as assembly, or 1. Similar to machine language, assembly language is also
assembling the source code. machine dependent.
 Assembly language uses a mnemonic to represent each 2. As it is machine dependent, the programmer should
low-level machine instruction. have knowledge of hardware.
 Many operations require one or more operands in order
to form a complete instruction.

(MU-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)

 (3) Object-Oriented Programming Language


 1.1.8 High Level Programming
In OOP, the application (program) is group of objects.
GQ. Write note on High Level Programming (5 Marks)
Examples are :
 Ans. : o C++
High Level Programming o Java
 The formats used in High-level computer languages are  (4) Visual Programming Language
similar to English. The important aim of developing The functionality of these languages is to design
high-level languages was to help users to develop Windows-based applications.
programs without problems.
Examples are :
 High-level languages are generally considered as
o Visual Basic
symbolic languages which use English words and/or
mathematical symbols instead of mnemonic codes. o Visual Java

 All the instructions in the high-level language are o Visual C


transformed into multiple machine language GQ. Write advantages of High Level Programming.
instructions which the computer can understand. (2 Marks)
 There are various types of High level languages :
 Ans. :
Advantages of High Level Programming
1. High-level languages are considered as user-friendly.
2. They are same as of English language and use English
vocabulary and well-known symbols.
3. Learning them is easy.
4. Maintenance is easy.
5. They are problem-oriented instead of machine
dependent.
Fig. 1.1.14 : Types of High level languages 6. The language is not dependent on the machine on
which it is running.
 (1) Business Data Processing
These languages are useful in the process of GQ. Write disadvantages of High Level Programming.
maintaining data processing procedures and problems (2 Marks)
which are involved in handling files.  Ans. :
Examples are :
Disadvantages of High Level Programming
o COBOL (Common Business Oriented Language)
1. There is need to transform high-level language into the
o RPG (Report Program Generator)
machine language by a translator, which leads to
 (2) String and List Processing wastage of time.
The functionality of these languages is string 2. The object code which has been created by a translator
manipulation, including search patterns and inserting might not be efficient when compared with an
and deleting characters. equivalent assembly language program.
Examples are :
o LISP (List Processing)
o Prolog (Program in Logic)

(MU-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)

Following are some interesting facts about interpreters


 1.1.9 Compiler and Interpreter and compilers.
GQ. Explain compiler and interpreter. (5 Marks) (i) Both compilers and interpreters covert source code
(text files) into tokens, both may generate a parse tree,
 Ans. : and both may generate immediate instructions. The
Compiler and Interpreter basic difference is that a compiler system, including a
(built in or separate) linker, generates a stand alone
Compiler and Interpreter are two different ways to machine code program, while an interpreter system
execute a program written in a programming or scripting instead performs the actions described by the high
language. level program.
Compiler (ii) Once a program is compiled, its source code is not
 A compiler is a computer program which transforms useful for running the program. For interpreted
programs, the source code is needed to run the program
the code written in a high-level programming language
every time.
into the machine code.
(iii) In general, interpreted programs run slower than the
 A compiler takes entire program and converts it into
compiled programs.
object code which is typically stored in a file. The
object code is also refereed as binary code and can be GQ. Differentiate between compiler and interpreter.
directly executed by the machine after linking. (5 Marks)

 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)

 1.1.10 Defining Problem 1. Define the Problem


UQ. Explain how problem is defined with a help of  A situation or issue or condition which needs to solve
suitable example. MU - May 13, 4 Marks. to achieve the goal is called problem.
 Ans. : Defining Problem  In addition to getting clear on what the problem is,
 Computer is a multi-purpose electronic machine which defining the problem also helps in finding a target for
is used for storing, organizing, and processing the data what you want to achieve.
by using set of programs. 2. Data Gathering
 Computer is not able to find solution of a problem
 This step involves the process to create a list of
rather the computer is a machine which follows the
required data to solve the problem.
instructions given by programmer to solve any
problem. So all the efforts needed to understand the  Gathering of data may contain key terms, some
problem and define procedure to solve that problem is assumptions, previous experience, and also opinions of
done by programmer (a human being). other peoples towards the problem.
 First thing in problem solving is to understand the
3. Decide Effective Solution
problem properly and then define proper steps to
produce a perfect solution for that problem.  After getting the details about the problem and their
Problem Definition symptoms, finding the list of solutions is the main
 Before a program is written for solving a problem, it is goal.
important to define the problem clearly.  Among the list of solutions, choose a solution which is
 Definition : Problem is defined as a situation or issue effective, efficient and has fewest side effects.
or condition which needs to solve to achieve the goal.
For most software projects the system-analysts According to the hardness of the problem list of
approach system users to collect user requirements and solutions may increase.
define the problem that the system aims to solve. 4. Implement and Evaluate the Solution
System-analysts typically look at the following issues :
 The selected solution must be implemented and then
o What the problem is?
evaluate to check whether the expected output is
o What input is required for achieving expected
output? generated or not.
o Expected output of the problem.  The implementation of a solution involves planning
o Current method of solving the problem. and execution of that task. It is an iterative process
o Can the problem or part of the problem be more until desired solution is not getting.
effectively solved by a software solution?
 Evaluation is process of checking whether the solution
GQ. What are the steps in problem solving ? (5 Marks)
is as per expectations or not. The solution is evaluated
 Ans. : Steps in problem solving by all means.
5. Review the Results
 It is important to cross-verify the result by applying
variant inputs to know the success of the problem
solution. It also helps you to improve long-term
problem solving skills and keeps you from re-inventing
the wheel.
 Until we get expected results all the steps will be
executed again and again as shown in Fig. 1.1.17.

Fig. 1.1.17: Steps in Problem Solving

(MU-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.

 1.2 INTRODUCTION TO ALGORITHM

UQ. What do you mean by algorithm ? Which points


you should consider while developing the
algorithm ?
Fig. 1.2.1 : Characteristics of algorithm
MU - Dec. 13, May 14, May 16, 4 Marks.

OR Define term algorithm. MU - Dec. 17, 2 Marks.  1. Input


 An algorithm should accept zero or more inputs.
 Ans. : Algorithm
In some problem definitions, algorithm can have zero
In 825 A.C. a Persian mathematician wrote a book inputs for example, displaying welcome message on
“Al-jabr wa’l muqabala” which contains the generic the screen.
methods for solving certain category of problems. He is the
 Some problems require user interaction during
one who presented this type of methods first time. His name
execution of the program, at this situation number of
was Abu Ja’far Mohamed Ibn Musa Al Khowarismi. The
inputs may be accepted from users to generate output.
term algorithm comes from his name. The definition for

(MU-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)

 2. Output  1. Algorithm Name


An algorithm must generate some output. The aim of Each algorithm should have a name so that
algorithm is to provide sequence of steps to achieve user/programmer will know for which problem the
goal, so every algorithm must provide output at the algorithm is. That’s why the header contains the name
end. of that algorithm.

 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)

 9. End of Algorithm For Example


Every algorithm’s last line should be End.  Step 5 : SUM  NUM1 + NUM2.
 1.2.3 Keywords in Algorithm 6. Conditional Statements in Algorithm

GQ. What are the keywords which should be used


Conditional statements are the statement which causes
while writing an Algorithm (5 Marks) to change the sequence of flow of an algorithm
according to the condition satisfied.
 Ans. : Use “If” and “Else” keyword to define the condition
Keywords which should be used while writing an and their operations.
Algorithm
For Example
Each effective statement of an algorithm should be
 Step 6 : If condition 1
declared as a separate step. Each step starts with the
keyword “Step” followed by its number and colon (:). Display condition 1 is True
Else
1. Starting of Algorithm
Display condition 1 is False
First step of every algorithm should be written as
follows with the “Start” Keyword. 7. Repeat-Until Statements in Algorithm
For Example The set of statements will be executed repeatedly until
 Step 1 : Start given condition is satisfying. To specify the repeat-
until statements in an algorithm, use “Repeat” and
2. Variable Declaration in Algorithm
“Until” keywords.
Variables are used to hold the data entered by users
For Example
used for further operations. So it is necessary in
algorithm to declare variables.  Step 7 : Repeat Step 6 until condition 1
While declaring variables it is good to use the keyword 8. Displaying Outputs of Algorithm
“Declare” followed by list of variables. Every algorithm produces at least one output. To
For Example display that output use of “Display” keyword in
 Step 2 : Declare variables NUM1, NUM2 algorithm is a good practice.

3. Variable Initialization in Algorithm For Example

While initializing variables, use the keyword  Step 8 : Display SUM.


“Initialize” followed by the variable and the value to be 9. Displaying Outputs of Algorithm
initialized to it.
Every algorithm should end after finite number of
For Example
steps. To indicate the end of an algorithm use keyword
 Step 3 : Initialize COUNT  1 “Stop”.
4. Accepting Inputs form User in Algorithm
For Example
In some problems the input of an algorithm is given by
users. To indicate the process of accepting input from
 Step 9 : Stop
user for variables we use “Read” keyword.
 1.2.4 Steps to implement Algorithm
For Example
GQ. What are the steps which should be followed
 Step 4 : Read values NUM1 and NUM2.
while writing an Algorithm (5 Marks)
5. Processing Statements in Algorithm
Processing statements may include some mathematical
expressions and formulas.

(MU-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)

 Ans. :  Step 1 : Start


 Step 2 : Declare variables NUM1, NUM2, ADD, SUB,
Steps which should be followed while writing an
DIV, and MUL.
Algorithm
 Step 3 : Read values for NUM1 and NUM2.
 Step 4 : Add NUM1 and NUM2 and assign the result to
ADD.
ADD ← NUM1 + NUM2
 Step 5 : Display value of ADD
 Step 6 : Subtract NUM1 from NUM2 and assign the
result to SUB.
SUB ← NUM2 - NUM1
 Step 7: Display value of SUB
 Step 8 : Divide NUM1 and NUM2 and assign the result
to DIV.
DIV ← NUM1 / NUM2
Fig. 1.2.3 : Steps in Algorithm Development  Step 9 : Display value of DIV
 Step 1 : Define the problem  Step 10 : Multiply NUM1 and NUM2 and assign the
result to MUL.
The problem which is going to be solved must be first
MUL ← NUM1 * NUM2
defined in clear words.
 Step 11 : Display value of MUL
 Step 2 : Identifying Inputs
 Step 12 : Stop
The data required to solve the problem supplied to an
algorithm called as input. Inputs are given externally to GQ. Write an algorithm to calculate square of given
the algorithms. number. (4 Marks)
 Step 3 : Identifying Outputs  Ans. : Algorithm : Square
The result produced by an algorithm is called as output Input : A number
of the algorithm. At least one output should be
Output : Square of the number
generated from an algorithm.
 Step 1 : Start
 Step 4 : Identifying the sequence of steps to be
processed  Step 2 : Declare variable NUM, SQUARE

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)

 Ans. : Algorithm : Arithmetic  Ans. : Algorithm : Cube


Input : A number
Input : Two numbers
Output : Cube of the number
Output : Addition of two numbers

(MU-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)

 Step 1 : Start GQ. Write an algorithm to calculate area of triangle.


 Step 2 : Declare variable NUM, CUBE (4 Marks)

 Step 3 : Read value for NUM  Ans. :


 Step 4 : Multiply NUM to itself twice and assign the Algorithm : Area of Triangle
result to CUBE
Input : Height and Base of the triangle
CUBE ← NUM * NUM * NUM
Output : Area of the triangle
 Step 5 : Display value of NUM
 Step 1 : Start
 Step 6 : Stop
 Step 2 : Declare variable HEIGHT, BASE and AREA
GQ. Write an algorithm to calculate area of circle.
 Step 3 : Read values for HEIGHT and BASE
(4 Marks)
 Step 4 : Calculate area of the triangle and assign the
 Ans. : result to AREA
Algorithm : Area of Circle AREA ← 0.5 * HEIGHT * BASE
Input : Radius of the circle  Step 5 : Display value of AREA
Output : Area of the circle  Step 6 : Stop.
 Step 1 : Start GQ. Write an algorithm to find largest number among
 Step 2 : Declare variable RADIUS and AREA three numbers. (4 Marks)

 Step 3 : Read value for RADIUS  Ans. : Algorithm : Greatest Number


 Step 4 : Calculate area of the circle and assign the result Input : Three numbers
to AREA
Output : The greatest number among three numbers
AREA ← 3.14 * RADIUS * RADIUS
 Step 1 : Start
 Step 5 : Display value of AREA  Step 2 : Declare variables NUM1, NUM2, and NUM3.
 Step 6 : Stop  Step 3 : Read values for NUM1, NUM2, and NUM3.
GQ. Write an algorithm to calculate area of rectangle.  Step 4 :
(4 Marks) if NUM1 > NUM2
 Ans. : if NUM1 > NUM3
Display NUM1 is the largest number.
Algorithm : Area of Rectangle
else
Input : Length and Width of the rectangle Display NUM3 is the largest number.
Output : Area of the rectangle else
 Step 1 : Start if NUM2 > NUM3
Display NUM2 is the largest number.
 Step 2 : Declare variable LENGTH, WIDTH and AREA
else
 Step 3 : Read values for LENGTH and WIDTH Display NUM3 is the greatest number.
 Step 4 : Calculate area of the rectangle and assign the  Step 5 : Stop
result to AREA
GQ. Write an algorithm to check whether given
AREA ← LENGTH * WIDTH
number is even or odd. (2 Marks)
 Step 5 : Display value of AREA
 Step 6 : Stop.
 Ans. : Algorithm : Even or Odd
Input : A number
Output : Display message 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-19)

 Step 1 : Start  Step 3 : Read num from User


 Step 2 : Declare variable Num.  Step 4 : Initialize Variable sum=0 and temp=num
 Step 3 : Read values for NUM  Step 5 : Repeat Until num>=0
 Step 4 : If NUM / 2 == 0 5.1 sum=sum + cube of last digit
Display NUM is the Even number i.e. [(num%10)*(num%10)*(num%10)]

Else 5.2 num=num/10

Display NUM is the Odd number  Step 6 : IF sum==temp


 Step 5 : Stop Print "Armstrong Number"
ELSE
GQ. Write an algorithm to check whether given
number is prime or not. (4 Marks) Print "Not Armstrong Number"
 Step 7 : Stop
 Ans. :
GQ. Give advantages of algorithm. (2 Marks)
Algorithm : Prime Number
Input : A number  Ans. :
Output : Display message Prime or not Advantages of Algorithm
 Step 1 : Start 1. Algorithms are user friendly as use of English
 Step 2 : Declare variables NUM, I, FLAG. language.

 Step 3 : Initialize variables 2. Algorithms are easy to write.

FLAG ← 1 3. It is easy to understand logic.

I←2 4. Every step has got its own logical sequence, so it is


easy to debug.
 Step 4 : Read value for NUM
5. Since the logical sequence is given with simple English
 Step 5 : Repeat the steps until I < (NUM/2)
language it is easy to convert into flowchart and then
5.1 If remainder of NUM / I equals 0
into programs.
FLAG ← 0
GQ. Give disadvantages of algorithm. (2 Marks)
Go to step 6
5.2 I ← I + 1
 Ans. : Disadvantages of Algorithm
 Step 6 : If FLAG == 0 1. It is time consuming.

Display NUM is not prime 2. It is difficult to write algorithms for Complex


problems.
Else
3. Branching and looping is difficult to show.
Display NUM is prime
 Step 7 : Stop  1.3 INTRODUCTION TO FLOWCHART
UQ. Write Algorithm to check whether given number
UQ. Explain need of flowchart.
is Armstrong Numbers or not also mention input
and output specifications to algorithm. MU - May 15, 2 Marks.

MU - Dec. 17, 8 Marks.  Ans. : Need of flowchart

 Ans. : Algorithm : Armstrong Number  Flowchart is graphical representation of algorithm. The


 Step 1 : Start sequence of steps in algorithm is maintained and
represented in the flowchart by using some standard
 Step 2 : Declare Variable sum, temp, num
symbols such as rectangles and directed lines.

(MU-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)

 As flowchart uses the pictorial representation of an Symbols Name Description


algorithm, it becomes easier to understand what is
Flowline Indicates the flow of
going on.
algorithm. Represented as
 Processing and finding errors occurred during problem an arrowline. It will
solving become quicker and accurate as compared to connected two symbols in
working with algorithms. some order.
 As we know to solve big problems one way is to divide Decision Indicates the decision
it into smaller pieces to make it simpler, same thing is making statements. It
applied in flowchart construction also. includes a condition on
 The flowchart allows breaking the complex problems which decisions are made.
Represented as diamond.
into parts and at last connects them to represent
solution for whole problem. On-page To connect parts of
connector flowchart this symbol is
 1.3.1 Symbols used in Flowchart used if the parts are drawn
on same page. To simplify
GQ. Explain different symbols used in flowchart. the complex or confusing
(5 Marks) parts of the flowchart
labelled connectors are
 Ans. : Symbols used in flowchart used.
 It is constructed using standard shapes commonly Represented as a small
known as flowchart symbols. These symbols are given circle with a letter as its
in this section. label.

 Description about the symbols used to construct a Off-page To connect parts of


flowchart is given in Table 1.3.1. connector flowchart which are
located on different pages.
Table 1.3.1 : Symbols of Flowchart
Represented as pentagon.
Symbols Name Description Predefined Indicates a set of
 Start/End Indicates the start or end Process operations performed by
terminal of the algorithm. (function) one process which is
Represented as rounded defined elsewhere. It uses
rectangle. to make a function call.
 Process Represented as rectangle
Indicates set of operations
like assignment, with double vertical lines
increment/decrement at the end.
initialization and
calculations. It is  1.3.2 Rules of Flowchart Construction
represented as rectangle.
GQ. State the rules of flowchart construction.
 Input/Output Indicates the inputs (2 Marks)
provided to the algorithm
and outputs produced by  Ans. :
algorithm. It is used to Rules of flowchart construction
signify reading of data
 Each flowchart starts with the Start Symbol (a rounded
from user and displaying
rectangle labeled as “Start”). All the symbols are
results on the screen.
Represented as connected with flowline (an arrow line).
parallelogram.

(MU-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

Fig. 1.3.1 : Flowlines in the Flowchart

 Note : This rule is not applicable for Flowline used for


Decision symbols.
 In decision symbols the FlowLines should be labelled
as True or False. Each flowchart ends with End
Symbol.

 1.3.3 Examples of Flowchart

GQ. Draw flowchart for accepting two numbers and


performing addition, subtraction, division and
multiplication on them. (4 Marks)

 Ans. : Fig. 1.3.3 : Flowchart of finding square of given number


Solve Simple Arithmetic Expression
GQ. Draw flowchart for calculating cube of given
number. (4 Marks)

 Ans. :
Calculate cube of Given Number

Fig. 1.3.2 : Flowchart of accepting two numbers and


Fig. 1.3.4 : Flowchart of finding cube of given number
doing arithmetic operations on it

(MU-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

Fig. 1.3.6 : Flowchart of calculating area of rectangle


Fig. 1.3.5 : Flowchart of calculating area of circle

GQ. Draw flowchart for calculating area of triangle. (4 Marks)

 Ans. :
Calculate area of triangle

Fig. 1.3.7 : Flowchart of calculating 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

Fig. 1.3.9 : Flow chart of finding 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)

 Ans. :  Ans. : Fibonacci Series

Determine Whether a Given Number is Prime

Fig. 1.3.10 : Flowchart for checking


number prime or not

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.

 1.3.5 Difference between Algorithm and


Flowchart

GQ. State the difference between algorithm and


flowchart. (5 Marks)

 Ans. : Difference between Algorithm and Flowchart


Parameter Algorithm Flowchart
Definition An algorithm is a set Flowchart is
Fig. 1.3.14 of ordered graphical
 1.3.4 Advantages and disadvantages of
instructions in simple
English language
representation of
algorithm.
Flowchart designed to solve
GQ. State any four advantages of using flow-chart. certain problems
(4 Marks)
Understanding Algorithm is more Less detailed but
 Ans. : Advantages of Flowchart detailed but difficult easy to
to understand by understand by
1. It is a suitable method of communication between everyone. everyone.
users/programmers.
Use of Specific instructions Standard symbols
2. As it is based on pictorial representation, it become are used. are used for
easier to understand what actually is going on. specific tasks.
3. It becomes easier to trace the faults and correct them. When it is Algorithms get Flowcharts are
created created first. created later on
4. In the process of planning and designing completely a
using algorithms.
new system, flowchart will be a good tool.
Branching and Branching and Branching and
5. Flowcharts can be recorded and stored for later use so it looping looping is difficult to looping is easy to
saves the inconveniences in future. show show
6. It can be used for documentation of a system. Big Problems Managing big Big problems can
7. It express the relationship between the steps specified problems is difficult be managed
easily
in an algorithm and helps to provide correct logic.
Chapter Ends…


(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

 Keywords, Identifiers, Constants and Variables


 Data types in C
 Operators in C
 Basic Input and Output Operations
 Expressions and Precedence of Operators
 In-built Functions

2.1 Introduction to C Programming ...................................................................................................................................... 2-3


2.1.1 History of C ...................................................................................................................................................... 2-3
2.1.2 Features of C ................................................................................................................................................... 2-4
2.1.3 Applications of C .............................................................................................................................................. 2-5
2.1.4 Concept of Data in C........................................................................................................................................ 2-6
2.1.5 Concept of Character in C................................................................................................................................ 2-6
2.1.6 C Tokens.......................................................................................................................................................... 2-7
2.1.7 C Keywords...................................................................................................................................................... 2-8
UQ. Which of the following is not a keyword of ‘C’ ? ............................................................................................... 2-8
(A) auto (B) register (C) int (D) function MU - May 18, 1 Mark. ...................................................................... 2-8
2.1.8 Identifiers ....................................................................................................................................................... 2-10
2.1.9 Structure of C Program .................................................................................................................................. 2-11
UQ. Comments in the program make debugging of the program easier. MU - May 18, 1 Mark. ......................... 2-14
2.2 Data Types in C ........................................................................................................................................................... 2-14
UQ. Enlist all the data types in C language along with their memory requirements. MU - May 17, 4 Marks. ....... 2-14
2.2.1 Variables ........................................................................................................................................................ 2-15
UQ. Which of these is a valid variable declaration ?
(A) in temp salary; (B) float marks_student; (C) float roll-no; (D) int main; MU - May 18, 1 Mark. ............. 2-16
2.2.2 Constants ....................................................................................................................................................... 2-17
2.2.3 Difference between Variable and Constant .................................................................................................... 2-19
2.3 Operators in C ............................................................................................................................................................. 2-19
2.3.1 Arithmetic Operators ...................................................................................................................................... 2-19
2.3.2 Increment and Decrement Operators ............................................................................................................. 2-20
C Programming (MU-FE-Sem II) (Fundamentals of C Programming)….Page no. (2-2)
UQ. Write a output for following program : ............................................................................................................ 2-21
int main ( )
{
int x=10,y,z;
z=y=x;
y-=--x;
z-=x--;
x-=--x-x--;
printf("x = %d y = %d z = %d",x,y,z); MU - May 13, 6 Marks......................................................................... 2-21
UQ. Predict output of following program segment.
main( )
{
int x=4, y=9, z;
z = x+++ --y + y;
printf(“\n %d %d %d” , x, y, z);
z= --x + x + y --;
printf(“\n %d %d %d”, x, y, z);
} MU - May 18, 4 Marks. ................................................................................................................................ 2-21
2.3.3 Relational Operators ...................................................................................................................................... 2-21
2.3.4 Logical Operators........................................................................................................................................... 2-22
UQ. Evaluate following expression :
(i) ! (5 + 5 > = 10) (ii) 5 + 5 = = 10 || 1 + 3 = = 5
(iii) 5.10 || 10 < 20 && 3 < 5 MU - Dec. 14, 5 Marks. ................................................................................... 2-22
2.3.5 Bitwise Operators........................................................................................................................................... 2-22
UQ. Explain with example bitwise operators in C language. MU - Dec. 14, 5 Marks. ......................................... 2-22
OR Explain following bitwise operator with example :
(I) Bitwise right shift operator (II) Bitwise X-OR operator MU - May 15, 5 Marks.................................. 2-22
OR Explain any two bitwise operators in C with example. MU - Dec. 15, 4 Marks. ............................................ 2-22
OR Enlist bitwise operators in C language. Explain any 2 with examples. MU - May 17, 5 Marks.............. 2-22
n
UQ. Which bitwise operator is used to multiply the number by 2 where n is number of bits.
(A) Bitwise-OR (B) Bitwise-AND
(C) Bitwise Left shift (D) Bitwise Right Shift MU - May 18, 1 Mark. ..................................................... 2-23
2.3.6 Assignment Operators ................................................................................................................................... 2-23
2.3.7 Conditional / Ternary Operator....................................................................................................................... 2-24
UQ. Explain : ? operator in C. MU - May 16, 2 Marks......................................................................................... 2-24
UQ. Write a program to find the biggest of given 3 no’s using conditional operator.
MU - Dec. 14, May 16, 5 Marks. ................................................................................................................... 2-24
2.4 Expressions ................................................................................................................................................................. 2-25
2.5 Precedence of operators ............................................................................................................................................. 2-25
2.6 Basic Input and Output Operations.............................................................................................................................. 2-26
UQ. Which operator has the lowest priority ? (A) ++ (B) % (C) + (D) || MU - May 18, 1 Mark............................... 2-26
2.7 Inbuilt Functions .......................................................................................................................................................... 2-26
2.7.1 scanf() and printf() Functions ......................................................................................................................... 2-27
UQ. scanf ( ) function is used to input string having multiple words. MU - May 18, 1 Mark. ................................ 2-27
2.7.2 getchar() and putchar() Functions .................................................................................................................. 2-29
2.7.3 getch() and putch() Functions ........................................................................................................................ 2-30
2.7.4 gets() and puts() Functions ............................................................................................................................ 2-30
UQ. Explain gets() and puts() functions of C language. Comment on their parameters and return values.
MU - May 17, 5 Marks. ............................................................................................................................... 2-30
2.7.5 Formatted Input and Output Statements ........................................................................................................ 2-30
2.8 Storage Class .............................................................................................................................................................. 2-31
UQ. What is storage class? Explain extern storage class with example. MU - Q. 1(B), May 14, 4 Marks. ........... 2-31
UQ. Explain storage class with example MU - Q. 6(A), May 19, 10 Marks.......................................................... 2-31
2.8.1 Automatic Storage Class................................................................................................................................ 2-32
2.8.2 Static Storage Class ...................................................................................................................................... 2-32
2.8.3 Register Storage Class .................................................................................................................................. 2-33
2.8.4 External Storage Class .................................................................................................................................. 2-33
2.8.5 Comparision of Storge Classes...................................................................................................................... 2-34
 Chapter Ends .................................................................................................................................................... 2-34

(MU-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

GQ. What is C ? (2 Marks)

 Ans. :
C Language

 It is good to begin the journey of learning


programming with the C Language. Because
C language is the one which survived from last four
decades in the environment where every day new
languages are emerges and gone.
 To become a good programmer, learning C is the first
step because it will help you to perfect the basics
required to learn any advance programming tools and
technologies.
 C Programming helps you to understand working of a
program and to enhance your programming logic. It
Fig. 2.1.1 : History of C
also helps to visualize working of the computer.
 Before C language there were some languages like
 Before starting programming in C let’s know about
BASIC, COBOL, FORTRAN etc.
what is C and its history.
 These languages were developed for specific purpose.
 C is a general purpose structured programming
For example BASIC was used by beginners whereas
language designed and written by Dennis Ritchie at
COBOL was used for commercial purpose. And all
AT & T’s Bell Laboratories of USA in 1972.
engineering applications use FORTRAN.
 C is a middle level language because it combines the  In 1960 ALGOL was developed by an International
features of both high-level language as well as low- Committee to provide a single solution to all these
level language (like Assembly Language). purposes. ALGOL introduces the structured
 C is very powerful programming language as well as it programming. But because of some of its drawbacks it
is more popular and widely used language. Since last 4 would not be able to popular.
decades the popularity of C exists because it is reliable,  To reduce the drawbacks of ALGOL, a new language
simple and easy to use. called Combined Programming Language (CPL)
was developed at Cambridge and London universities
 2.1.1 History of C in 1963.

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)

 Like other languages BCPL also get vanished as it was


developed for specific application domains only.
 Many features of BCPL are inherited in language
called ‘B’ which was developed by Ken Thompson in
1970.
 In AT and T Bell laboratory, the process of developing
UNIX Operating System is the Origin of C language.
 Initially the UNIX operating system was being
developed with BCPL.
 In 1972, due to dissatisfaction of some requirements in
development process of UNIX, new language is
invented by Dennis Ritchie called the ‘C’ language.
UNIX is then re-implemented with C language.
 C provides “strut” type due to which most of the UNIX
kernel developed in C.
 C is influenced by BCPL and B. So as the next version
of B, name given to newly created language as C.
 Up to 1977, further modifications in C are done by
Ritchie and Stephen C. Johnson.
 After this, In 1978 Brian Kernighan and Dennis Ritchie
Fig. 2.1.2 : Features of C
add some more features like long int and unsigned int
data type in C.  1. Simple
 This language is then referred as K&R C.  C uses English language to write the code, that’s why it
 In 1989 C has been standardize by ANSI (American is very easy to write code in C.
National Standard Institute) committee known as  Also the syntaxes used in C coding are simple which
ANSI C. can be easily understood by the programmer.
 Later it has been standardized by ISO (International  2. General purpose language
Organization for Standardization) committee for  Unlike COBOL and PASCAL, C is used for
further improvements and named as ISO C. developing applications for all the purposes.
 In 1999 Standardization committee introduces C99.  C can be used for several domains of applications like,
business and scientific applications.
 2.1.2 Features of C
 It has the ability to operate the bits, bytes and addresses
GQ. Explain features of C. (5 Marks) means it can manipulate the memory hence it is used
for system programming also.
 Ans. :  3. Block structured language
Features of C
 As compare to other languages C is well structured
The C language is popular because it is reliable, simple language.
and easy to use.
 The program code can be divided into several
functions or blocks.

(MU-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)

 The block structure approach helps to simplify the


complexity of program by splitting it into smaller
parts.
 To clearly understand the complex code, it is divided
into blocks which can be manipulated by using control
structure.
Fig. 2.1.4 : C is portable
 4. Middle level language
 7. Powerful
 C combines features of both high-level language and
 C has rich function library with built-in functions.
low-level language, so it is called as middle level
 Wide range of operators and data types are available in
language.
C. Also C provides various keywords.
 C is near to machine as well as human as it deals with
 These all things make the C language more powerful.
bit level operations and also uses English language
while coding.  8. Case sensitive
 5. Platform dependent C language is the case sensitive language so it consider
int and INT as two different terms.
 C is a platform dependent language.
 9. Syntax based
 Platform dependent means the program runs on same
operating system where it is developed and compiled, C provides elegant syntax. While coding, the
and cannot be executed on another operating system. programmer should follow the syntax.

 The compiled version of a program file is platform  10. Compiler based


dependent. Every program written in C should be compiled first
before execution. Without compilation the code will
not execute because C is compiler based programming
language.
 11. Fast and Efficient
Due to the large set of data types and operators, C is
Fig. 2.1.3 : C is Platform Dependent
faster and efficient than other languages like BASIC,
 6. Portable etc.

 Portability means executing the same application on  12. Easily Extendable


different systems. C allows the programmer to use library functions and
 In C Language three files are generated; the source also add their own functions in library so as to extend
code file (has .c extension), the compiled file (has .obj and reuse the functions.
extension) and the executable file (has .exe extension).
 2.1.3 Applications of C
.exe file is not editable like .c file.
 The programs written and compiled on one operating GQ. What are the applications of C programming?
system say Windows can be able to run on other (3 Marks)
windows based systems. This much portability is
 Ans. :
supported by C.
Applications of C programming
 Note that this .exe file will not execute on other than
windows operating system.  As the C is close to machine level languages, it is used
in system programming to develop System software
and also to develop desktop support software.

(MU-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

) Right parenthesis See following statement in C program.


_ Underscore printf ( "Phoenix InfoTech" );
- Minus sign Here in this statement there are 5 tokens as follows :
+ Plus sign printf
= Equal to sign (
| Vertical bar “Phoenix Infotech”
\ Backslash )
;
{ Left brace
} Right brace That means each and every valid unit of a C program is
considered as a token by C compiler.
[ Left bracket
] Right bracket GQ. Give suitable examples of C tokens. (2 Marks)
: Colon  Ans. : Examples of C tokens
" Double Quotation mark
 C tokens can be classified in six types as follow :
; Semicolon
1. Keywords 2. Identifiers
‘ Single Quotation Mark
3. Constants 4. Operators
< Opening angle bracket/ Less
than sign 5. Strings 6. Special symbol
> Closing angle bracket/ greater
than sign

(MU-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

Data types Loop


int for
char while
float do
double Decision
Qualifiers if
signed else
unsigned Switch
short Case
long Default
User-defined Jump
typedef Goto
enum continue
Storage Classes break
auto Function Fig. 2.1.6 : Keywords used 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)

 1. Data type Keywords  4. User-defined type keywords

Fig. 2.1.10 : User-defined type keywords

(i) typedef : typedef is used to rename the existing data


Fig. 2.1.7 : Data type keywords
type.
(i) int : It indicates that the variable holds an integer (ii) enum : enum is used to define a new data type and the
value. values used by variable of that data type.
(ii) char : It indicates that the variable holds a character  5. Jumping Control Keywords
value.
(iii) float : It indicates that the variable holds a float value
(iv) double : It indicates that the variable holds a double
value.
 2. Qualifier Keywords

Fig. 2.1.11 : Jumping control keywords

(i) break : break is used to terminate the loop. It can be


used with any loop or switch case.
(ii) continue : continue is used to restart the loop.
(iii) goto : goto is used to pass the control to specified
Fig. 2.1.8 : Qualifier keywords location in the program.

(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

Fig. 2.1.12 : Storage class keywords

(i) auto : It indicates that the variable is stored in memory


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
Fig. 2.1.9 : Loop control structure keywords where it is defined.

for, while, do while : It is used for looping.

(MU-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.16 : Other 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.

Fig. 2.1.14 : Decision keywords  2.1.8 Identifiers

(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

Rules for naming an identifier Made up of Combination of Combination of


 Each identifier should start with an alphabet or alphabetic characters alphanumeric
underscore and then followed by any number of characters and
alphabets, digits or underscores. underscore symbol

 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)

 A C program basically consists of the following parts.  6. Comments


The comment is ignored by the compiler and it is used
to add additional information about the program or its
statements. It can be written anywhere in the program.
It always good practice to write comments.
Let’s see the structure of C program :
//HelloWorld.c
/*Developed by : Phoenix InfoTech Date: 9/7/2017*/
Documentation Section

#include <stdio.h> Pre-processor Commands

Fig. 2.1.17 : Parts of C Program


int main() {
 1. Documentation Section /* my first program in C */ Function Section
 Documentation Section contains the information about // Declaration Section
the program and its author which is provided in
comments. printf("Hello, World! \n"); Statements
 It contains the name and other details of program and return 0;
name of the programmer. }
 This section can be skipped by learners.
 Rules in C Programming
 But it is good practice to include this section by
programmers while working on projects in team.  Execution of every C program starts with the main()
function.
 2. Pre-processor Commands
 Each C Program contains exactly one main() function.
The pre-processor command tells a C compiler to
include required library files. These files are included  Every statement in C program ends with semicolon (;)
before compiling the code.  Most of the statements in C program are in lowercase
 3. Function Section except some symbolic names and outputs.
 As mentioned earlier the C is block structured  Each opening brace should have its closing brace.
language. It uses functions to divide the code into Braces are used to define the blocks in coding.
blocks.  C can contain comments anywhere in the program.
 Each C program should contain exactly one main()  The execution of program starts with the opening brace
function from where the program execution begins. So of main() function and ends with the closing brace of
we can say that each C program has at least one the main() function.
function.
GQ. List the header files used in C Programming with
 Below main() function, other user defined functions their properties. (4 Marks)
can be defined.
 Ans.. :
 4. Declaration Section Header files used in C Programming
If C program uses any data variables then those will be  The C program includes some header files in include
declared in this section. section. Header files contain the library functions
 5. Statements and Expressions which are required by program to execute properly.
Statements and expressions are usually written in the  The # include<file_name> statement is used to
function block. Each statement ends with the include the header files. This statement is written
semicolon ( ; ). always at the beginning of the 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-13)

 Stdio.h header file is used to perform standard input


output operations.
 To deal with console related operations the conio.h file
is included in the program.
 Math.h file is used to perform the mathematical
operations like sqrt().

GQ. Explain main() function in C (3 Marks)

 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.

GQ. Write a simple C program


If you are using Turbo C or Turbo C++ compiler, you
 Ans. : need to follow steps listed below :
Simple C Program Step 1 : Start the compiler TC.EXE from C:\TC\BIN
directory.
 We can use any available complier to run the
C programs. There are number of editors like Turbo, Step 2 : Select New from the File menu.
ANSI, Borland etc. Now a day number of applications Step 3 : Type the program
are available to write and run C programs. Step 4 : Save the program using F2
 We will use Dev to run C Program. Step 5 : Use Ctrl + F9 to compile and execute the
program.
Step 1 : Download dev CPP 5.11 for windows
GQ. Explain comments used in C Program. (5 Marks)
Step 2 : Install dev CPP 5.11
Step 3 : Open dev CPP 5.11  Ans. : Comments used in C Program

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)

 C supports two types of comments

Fig. 2.1.19 : Types of Comments

 1. Single line comment


Single line comment starts with the double forward
slash // and it will continue up till the end of the line. Fig. 2.2.1 : Data types in C
 2. Multiline comment  Several data types are broadly divided into two
categories.
Multiline comments starts with /* and ends with */.

 Example of comments
/* Program name: Program1.c
Date modified: 15-8-2018 Multiline comment
Author: Phoenix InfoTech */

# include<stdio.h> Fig. 2.2.2 : Categories of data types


int main()
{  1. Primary data types
printf(“This is program1 ”); These are basic data types. int, char, float, void are the
//prints data on screen Single line comment primary data types.
}
 2. Derived data types
UQ. Comments in the program make debugging of Derived data types are derived from primary data types.
the program easier. MU - May 18, 1 Mark. Array, functions, structure, union and pointers are the
 Ans. : True derived data types.
UQ. Enlist all the data types in C language along with
 2.2 DATA TYPES IN C their memory requirements.
MU - May 17, 4 Marks.
GQ. Explain basic data types of C. (3 Marks)
 Ans. :
 Ans. : Various data types along with their memory sizes
Data types of C
 A program may use different types of data for
example, digit, character, real numbers, etc.
 Data types are used to specify the compiler which
types of data the program manipulates.
 C language has some predefined set of data types to
handle various kinds of data that we use in our
program. These data types have different storage
capacities. Fig. 2.2.3 : Primary data types

(MU-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)

 1. Integer type  Converting a value from one data type to another is


Integers are used to store whole numbers like 1, 0, 15, called as type conversion or type casting.
3049, etc.  Types of data conversion
Table 2.2.1 : Size and range of Integer type on 16-bit There are two types of data conversions.
machine

Type Size(bytes) Range


int or signed int 2 – 32, 768 to 32767
unsigned int 2 0 to 65535
short int or signed 1 – 128 to 127
short int
Fig. 2.2.4 : Types of data conversion
unsigned short int 1 0 to 255
long int or signed 4 – 2, 147, 483, 648 to 2,  1. Implicit conversion
long int 147, 483, 647 It is done internally by compiler
unsigned long int 4 0 to 4, 294, 967, 295
 2. Explicit conversion
 2. Floating type It is done by the user explicitly.
Floating types are used to store real numbers.  This conversion is temporary and not permanent in the
Table 2.2.2 : Size and range of Integer type on 16-bit program.
machine
 Type cast
Type Size(bytes) Range
 This means if in a statement, type cast is provided, then
Float 4 3.4E-38 to 3.4E+38 only at the time of execution of the statement the
double 8 1.7E-308 to 1.7E+308 values will get converted and after the execution of the
long double 10 3.4E-4932 to 1.1E+4932 statement the original data type remains same.

 3. Character type  The conversion of one data type to other is known as


type cast.
Character types are used to store characters value.
 Table 2.2.4 showing some examples of type casting.
Table 2.2.3 : Size and range of Integer type on 16-bit
machine Table 2.2.4

Type Size(bytes) Range Example Action


a = 2 * int(5.5) 5.5 is converted to integer (i.e. 6) by
char or signed char 1 –128 to 127 truncating it. So a will hold 2*6=12
unsigned char 1 0 to 255 b=(int) 22.3 will be converted to 22
 4. void type
 2.2.1 Variables
void type means no value. This is usually used to
specify the type of functions. GQ. State the variables with example. (2 Marks)

GQ. What do you mean by type conversion? Why is it  Ans. : Variables


necessary? (3 Marks)  During program execution number of operations are
 Ans. : performed on the data.
 The data is stored in the memory. It is difficult to
Conversion
remember the memory address where the data is going
 C language allows us to manipulate the information of to be stored, so to simplify this, C allows to refer these
various data types. memory locations by particular name.

(MU-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)

Rules for assigning variable name  Ans. :


 Each variable name starts with an alphabet or Initializing variable
underscore and then followed by any number of  Variable initialization means assigning a value to the
alphabets, digits or underscore. variable.
 Other than underscore no special symbol is allowed to  While assigning a value to the variable it is necessary
form the variable name. to keep the value to be placed in right-hand side of the
 Variable name should not start with digit. equal to sign and keep the variable name to which the
 In a program variable name must be unique. value is going to be placed at left hand side of the
 Variables are case sensitive so the area, AREA and equal to sign as given in example.
Area considered as different variables.  Syntax of initializing variable
 A variable should not contain any comma or blank data_type variable_name = value;
space.
 Variable name should not same as of the keywords
 Example

otherwise compiler will generate an error. int a =10;


 The length of a variable varies from compiler to  Valid statement because LHS contains the variable
compiler say 31 characters or more. But it is a good name (a) and RHS contains the value (10) to be
practice to keep the variable name short and specific. assigned.

(MU-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)

 And the closed box is referred as constant as we cannot


change the contents of this box.
 Let’s see the definition of constant
Fig. 2.2.5
 Definition of constant
GQ. Enlist types of variable. (2 Marks)
Constant is a value (For example : 11, 20.05,”Hello
 Ans. : World”, etc.) or a variable whose value is fixed during
Types of variable program execution. To declare a variable as a constant C
provides a keyword const.
There are following types of variables in c program :
 Syntax of constant
const data_type variable_name = value;

 Example of constant

const float PRICE = 495.75;


 It is good practice to write the constants in uppercase
Fig. 2.2.6 : Types of variables
as shown in example.
 1. Local variable Declaration Explanation
The local variables are declared and initialized within const int MAX = 1; read as “MAX is an integer which is
function. The scope of these variables is within the constant”
function where it is declared and initialized and cannot int const MAX = 1; read as “MAX is a constant integer”
be accessed outside of the function.
Both are valid.
 2. Global variable
GQ. Explain the types of constants. (5 Marks)
The global variables are declared outside the main
function. The scope of these variables is throughout the  Ans. :
program. Every function in the program can access
Types of constants
them.

 2.2.2 Constants

GQ. State the constants with example. (2 Marks)

 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)

 3. Character and string constants in C


Rules for constructing Character constants
 A character constant is a single alphabet, a single digit
or a single special symbol enclosed within single
quotes.
 The maximum length of a character constant is
1 character.
 String constants are enclosed within double quotes.
Fig. 2.2.9 : Primary Constants
Example
 1. Integer Constants in C Character Constants : ‘Z’, ‘M’, etc.
Rules for constructing Integer constants String Constants : “Kunal”, “Hello”, etc.
 An integer constant must have at least one digit. Here we can use char data type to declare character or
 It must not have a decimal point. string constant.
 It can either be positive or negative.  4. Backslash character constants in C
 No commas or blanks are allowed within an integer Rules for constructing Backslash constants
constant.
 There are some characters which have special meaning
 If no sign precedes an integer constant, it is assumed to in C language.
be positive.
 These characters are preceded by backslash symbol to
 The allowable range for integer constants is –32768 make use of special function of them.
to 32767.
 Table 2.2.5 is the list of special characters and their
Example purpose.
 10, –578, 5000, etc. Table 2.2.5
 Here we can use following data types to declare integer
Backslash_character Meaning
constant :
\b Backspace
int, long int, long long int, signed int, unsigned int.
\f Form feed
 2. Real constants in C
\n New line
Rules for constructing Real constants
\r Carriage return
 A real constant must have at least one digit.
\t Horizontal tab
 It must have a decimal point.
\” Double quote
 It could be either positive or negative.
\’ Single quote
 If no sign precedes an integer constant, it is assumed to
\\ Backslash
be positive.
\v Vertical tab
 No commas or blanks are allowed within a real
constant. \a Alert or bell

Example \? Question mark

 10.456789 \N Octal constant (N is an octal


constant)
 Here we can use following data types to declare real
\XN Hexadecimal constant
constant :
(N – hex.dcml cnst)
float

(MU-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)

 2.2.3 Difference between Variable and  Ans. : Types of operators


Constant  C programming has collections of operators to perform
various operations. These operators can be classified as
GQ. Distinguish between variable and constant. follows :
(4 Marks)

 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)

Operator Description Example UQ. Evaluate following expression :


>= Determines whether the left side (M >= N) is (i) ! (5 + 5 > = 10)
operand has value greater than or not true. (ii) 5 + 5 = = 10 || 1 + 3 = = 5
equal to the right side operand. If it (iii) 5.10 || 10 < 20 && 3 < 5
is, then the condition is true. MU - Dec. 14, 5 Marks.
<= Determines whether the left side (M <= N) is (i) ! (5 + 5 > = 10)
operand has value less than or true.
equal to the right side operand. If it
 Ans. : False
is, then the condition is true. (ii) 5 + 5 = = 10 || 1 + 3 = = 5

 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

Logical operators UQ. Explain with example bitwise operators in C


language. MU - Dec. 14, 5 Marks.
 Logical operators are used to check the conditions.
These operators are used in decision making OR Explain following bitwise operator with example :
statements. (I) Bitwise right shift operator
 It returns true or false according to the condition (II) Bitwise X-OR operator MU - May 15, 5 Marks.
satisfaction. OR Explain any two bitwise operators in C with
 Table 2.3.3 shows all the logical operators supported example. MU - Dec. 15, 4 Marks.
by C language. OR Enlist bitwise operators in C language. Explain
 Here we consider two variables M=10 and N=20 any 2 with examples. MU - May 17, 5 Marks.
Table 2.3.3
 Ans. :
Operator Description Example Bitwise operators
&& Logical AND operator. (M == 10) && (N !=  As we know that the C language has the features of
Used to check multiple M) both conditions are low-level language so it can perform bit level
conditions. If all the true so result of && operations. C provides Bitwise operators to perform bit
conditions get satisfy operation is true. level operations.
then returns true.
 Bitwise operators work on bits and perform bit-by-bit
|| Logical OR operator. (M > 20) || (N > M)
operation.
Used to check multiple here first condition is
conditions. If either of false and second  The truth tables for &(Bitwise AND), |(Bitwise OR),
the condition get satisfy condition is true so and ^(Bitwise XOR) is as follows :
then returns true. result of || operation is M N M&N M|N M^N
true.
0 0 0 0 0
! Logical NOT Operator. !(M < N) : here M<N
This operator reverses produces true but 0 1 0 1 1
the logical state of the because of NOT 1 1 1 1 0
operand. If a condition operator it is converted
1 0 0 1 1
is true, then false or to false.
vice versa.

(MU-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)

The truth tables ~(Bitwise NOT) is as follows : Operator Description Example


~M | Binary OR Operator copies a (M | N) = 28,
z
bit to the result if a bit of either i.e., 0001 1100
0 1 the operand is set (1);
1 0 otherwise it copies zero to the
result.
Assume M = 28 and N = 12 in binary format, they will
be as follows : ^ Binary XOR Operator copies (M ^ N) = 16,
the bit if it is set in either i.e., 0010 0000
M = 0001 1100 operand, if bits of both the
N = 0000 1100 operands are set then it will
copy zero into the result;
Now let’s perform Bitwise AND on M and N
otherwise one will be copied in
M = 0001 1100 the result set.
& N = 0000 1100 ~ Binary Ones Complement (~M ) = 28, i.e,
0000 1100 Operator also called as NOT 1110 0011 in
operator. It is unary operator. If 1's complement
Now let’s perform Bitwise AND on M and N the bit of the operand is set (1) form.
M = 0001 1100 it will copy zero in the result
and if the bit is set (0) then it
| N = 0000 1100 will copy one in the result.
0001 1100 << Binary Left Shift Operator. The M << 2 = 112
Now let’s perform Bitwise XOR on M and N bits of the left operand are i.e., 0111 0000
moved left by the number of
M = 0001 1100
bits specified by the right
^ N = 0000 1100 operand.
0001 0000 >> Binary Right Shift Operator. M >> 1 = 14
Now let’s perform Bitwise NOT on M The bits of the left operand are i.e., 0000 1110
moved right by the number of
M = 0001 1100 bits specified by the right
~M = 1110 0011 operand.
Now let’s perform Bitwise Left Shift on M UQ. Which bitwise operator is used to multiply the
n
M = 0001 1100 number by 2 where n is number of bits.
M << 2 = 0111 0000 (A) Bitwise-OR
(B) Bitwise-AND
Now let’s perform Bitwise Right Shift on M
(C) Bitwise Left shift
M = 0001 1100
(D) Bitwise Right Shift MU - May 18, 1 Mark.
M >> 1 = 0000 1110
 Ans. : (C)
Table 2.9.4 lists the bitwise operators supported by C.
Here consider two variable M = 28 i.e. in binary 0001  2.3.6 Assignment Operators
1100 and variable N=12 i. e. in binary 0000 1100.
GQ What are the assignment operators? (5 Marks)
Table 2.3.4
Operator Description Example  Ans. :
& Binary AND Operator copies a (M & N) = 12, Assignment operators
bit to the result if bits of both i.e., 0000 1100  Assignment operators are used to assign the values to
the operands are set (1); the variables.
otherwise it copies zero to the
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-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.

Table 2.3.5  Ans. : Conditional operator

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

 As we have seen C supports wide range of operators.


 2.4 EXPRESSIONS
Precedence means the priority. Each operator has some
priority.
GQ. Explain mathematical expression of C language
with example. (2 Marks)
 If we use multiple operators in a single expression;
operator precedence helps us to solve the sequence of
 Ans. : operations to be performed in the expression.
Expression  So in the expression, operator which has highest
 An expression in a programming language is a precedence will be evaluated first and the lowest
combination of one or more constants, variables, precedence operator will be evaluated at last.
operators, and functions that the programming  Associativity
language interprets (according to its particular rules of
precedence and of association) and computes to  When multiple operators in an expression have same
produce ("to return", in a stateful environment) another priority, then the sequence of operations to be
value. performed is decided by their associativity. It may be
either left to tight or right to left.
 This process, as for mathematical expressions, is called
evaluation of expression. Example

 In simple settings, the resulting value is usually one of x = 7 + 3 - 2;


various primitive types, such as numerical, string, and

(MU-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)

GQ. What is the use of printf() function? (2 Marks) printf("%d", a);


printf("%c", b);
 Ans : Use of printf() function printf("%f", c);
 This function is used to display any type of output  With printf statement back slash characters are used as
(e.g. number, character, or string) on output device like shown in Table 2.7.2.
monitor. Table 2.7.2
 The displayed output can be of two types :
Back slash character Use of black clash
\a For alert
\b For back space
\f For form feed
\n For new line
\r For carriage return
Fig. 2.7.1 : Types of displayed output \t For horizontal tab
\V For vertical tab
 1. Simple text as Output
\’ For single quote
In this case the string written in double quotes is
\” For double quote
displayed on the screen as it is.
\? For question mark
Syntax
\\ For back slash
printf("String to be displayed on monitor”);
\0 Null used with string
Example
 If we want to print “Beginning of C” on the screen then GQ. Write a program that reads two numbers from
we use following statement. key board and gives their addition, subtraction,

printf( “ Beginning of C”); multiplication, division and modulo. (5 Marks)

 2. Text with values of variables as output  Ans. :


 In this case values of program variables are displayed Program on arithmetic operations
on the screen with the simple text. #include <stdio.h>
Syntax main()
printf("format specifier", variable_name); {
int n1,n2,r;
Example printf("Enter two numbers : ");
 Consider n is a variable of type integer and holds scanf("%d %d",&n1,&n2);
5 then,
printf("%d", n); r = n1 + n2;
 This statement prints 5 on the screen. printf("\n Addition : %d",r);

 We can display more than one outputs using single


r = n1 - n2;
printf() statement as follows:
printf("\n Subtraction : %d",r);
 Consider a is a variable of integer type, b is variable of
character type and c is variable of float type then
r = n1 * n2;
printf(“%d %c %f”, a,b,c); printf("\n Multiplcation : %d",r);
 Another way is to use different printf() functions for
each output as shown below. r = n1 % n2;

(MU-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

printf("\nDistance in meters : %.2f", Distance_In_Meters);


printf("\nDistance in feet : %.2f", Distance_In_Feet);
printf("\nDistance in inches : %.2f", Distance_In_Inches);
printf("\nDistance in centimeters : %.2f",
Distance_In_Centimeters);

(MU-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)

 2.7.3 getch() and putch() Functions  Ans. :


gets() and puts()
GQ. Explain following functions : getch(), putch() and
with suitable example. (3 Marks)  gets( ) function accepts and stores the sequence of
characters into an character array and also echo the
 Ans. : pressed key on the screen.
getch() and putch()  puts() function takes an character array as argument
 getch( ) function accepts an character and doesn’t echo like gets( ) and print the value stored in the character
it on the screen. array on the screen.
 putch( ) function takes an Ascii int value as argument For Example : If we write a code like :
and then prints the corresponding character. # include<stdio.h> // including header file
For Example, int main()
# include<stdio.h> // including header file {
int main() puts("Hello");
{ return 0;
char ch=getch(); }
return 0;
}
 If we press p then it will store the character in ch but
will not display anything on the screen and exit from
the program.
 And if we write the same program with putch(ch) as  2.7.5 Formatted Input and Output
follows : Statements
# include<stdio.h> // including header file
int main() GQ. Explain formatted input and formatted output
{ statement. (5 Marks)
char ch=getch();
 Ans. :
putch(ch);
return 0; Formatted input and output statement
}  We have seen earlier that the scanf( ) and printf( )
 And press P then due to putch ( ) function the output functions are used to formatting input and output.
will be :  Formatted input

 Formatted input data is an input data which has been


arranged in a particular format.
 scanf( ) function takes two arguments; format specifier
and variable.

 2.7.4 gets() and puts() Functions
The format specifier again divided into sub parts as
follows :
UQ. Explain gets() and puts() functions of % data_specifier width_number
C language. Comment on their parameters and o conversion character ‘%’
return values. MU - May 17, 5 Marks.
o width number : optional.
o data specifier

(MU-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)

 For example : To accept integer values with maximum A


width following statement is used:
The statement printf(“%-4c”, ch); will print
scanf(“%2d”);
 Here % is the conversion character, 2 is width number A
which specifies maximum number of digits to be
accepted and d is data specifier which tells compiler
 Printing the strings

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

 Printing the real numbers printf(“%5.4s”, str); //will print

 printf ( ) statement is also able to print floating point C P r


numbers. To format the output, following pattern of printf(“%-5.4s”, str); //will print
format specifier is used %w.p f
0 0 0 C P r
where ‘w’ is the number of positions to display the
number and’ p’ is the number of digits after the printf(“%07.4s”, str); //will print
decimal point.
 2.8 STORAGE CLASS
 Example of printing real numbers

 Suppose a float variable stores 25.331 Then The UQ. What is storage class? Explain extern storage
following statement class with example .

printf(“% 5.2f”, a); will print : MU - Q. 1(B), May 14, 4 Marks.

2 5 . 3 3 UQ. Explain storage class with example

MU - Q. 6(A), May 19, 10 Marks.


 Printing the character or strings
 A storage class defines the scope (visibility) and life-
 To format the output while displaying single character time of variables and/or functions within a C Program.
on the screen, we use following pattern of format They precede the type that they modify. There are four
specifier %wc different storage classes in a C programming Langauge
 where ‘w’ is the width of input to be displayed on the 1. automatic
screen.
2. Register
 For example of Printing the character or strings 3. static
 Consider ch is a character variable which has value ‘A’ 4. extern
printf(“%2c”,ch);

(MU-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)

Output  2.8.4 External Storage Class

 The external storage class is used to tell the compiler


that the variable defined as extern is declared with an
When program is executed it is seen that even if external linkage elsewhere in the program.
varables are not initialized the default value for int os ‘0’ ,  The variables declared as extern are not allocated any
char is initialized to ’0’ , float is ‘0.000000’ and string is memory. It is only declaration and it specify that the
initialized to null. variable is declared elsewhere in the program.

 2.8.3 Register Storage Class
The default initial value of external integral type is 0
otherwise null.
 The variables defined as the register is allocated the  We can only initialize the extern variable globally, i.e.,
memory into the CPU registers depending upon the we can not initialize the external variable within any
size of the memory remaining in the CPU. block or method.
 We can not dereference the register variables, i.e., we  An external variable can be declared many times but
can not use &operator for the register variable. can be initialized at only once.
 The access time of the register variables is faster than  If a variable is declared as external then the compiler
the automatic variables. searches for that variable to be initialized somewhere
 The initial default value of the register local variables in the program which may be extern or static. If it is
is 0. not, then the compiler will show an error.
 The register keyword is used for the variable which  Example
should be stored in the CPU register. However, it is
compiler?s choice whether or not; the variables can be Program to demonstrate external storage class
stored in the register. #include <stdio.h>
#include <conio.h>
 We can store pointers into the register, i.e., a register
extern int x = 32; // x is declared and defined
can store the address of a variable.
int b = 8;
 Static variables can not be stored into the register since
void main()
we can not use more than one storage specifier for the
{
same variable.
extern int b;
 Example // b is redeclared but not assigned with value
printf("Extern variables x : %d\n",x);
Program to demonstrate static storage class
printf("Extern variables b : %d\n",b);
#include <stdio.h>
#incude <conio.h>
x = 15; // x is assigned with new value
int main()
printf("Modified extern variable x : %d\n",x);
{
getch();
register int a=100;
}
// variable a is allocated memory in the
CPU register. The initial default value of a is 0. Output
printf("%d",a);
getch();
}
Output
 In the above code variable ‘x’ is declared once and
asgined value twice, where as variable ‘b’ is declared
twice.

(MU-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)

 2.8.5 Comparision of Storge Classes

Storage Declaration Storage Default Initial Scope Lifetime


Class Value

auto Inside a Memory Unpredictable Within the Within the function/block


function/block function/block

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

Static Inside a Memory Zero Within the program runtime


(local) function/block function/block

Static Outside all Memory Zero Global program runtime


(global) functions
Chapter Ends…


(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

3.1 Introduction to Control Structures .................................................................................................................................. 3-3


UQ. Explain switch control statement with the help of example. MU - May 14, 2 Marks. ...................................... 3-3
3.2 Branching Structures ..................................................................................................................................................... 3-3
3.2.1 if Statement ...................................................................................................................................................... 3-3
3.2.2 if else Statement .............................................................................................................................................. 3-4
UQ. Draw flowchart for 'if else' statement of C language. MU - May 17, 2 Marks........................................... 3-5
3.2.3 else if ladder..................................................................................................................................................... 3-7
UQ. Explain if-else ladder with example.MU - Dec. 17, 2 Marks. ........................................................................... 3-7
3.2.4 Nested if-else ................................................................................................................................................... 3-9
3.2.5 Switch Statement ........................................................................................................................................... 3-11
UQ. Explain syntax of switch case? Discuss what is need of break statement in switch case?
MU - May 15, 5 Marks. .................................................................................................................................. 3-11
OR Explain switch case with example.MU - Dec. 17, 2 Marks. ........................................................................... 3-11
Program 3.2.9 MU - May 14, 2 Marks........................................................................................................................ 3-12
Program 3.2.11 MU - Dec. 14, 6 Marks. .................................................................................................................... 3-15
3.2.6 Difference between if else and switch Statement........................................................................................... 3-16
UQ. Explain difference between switch statement, ladder of if else and nested if else. MU - May 13, 6 Marks. .. 3-16
3.3 Looping Structures ...................................................................................................................................................... 3-17
3.3.1 while Loop ...................................................................................................................................................... 3-17
UQ. Draw flowchart for 'while' statement of C language. MU - May 17, 2 Marks. ......................................... 3-17
Program 3.3.4 (MU - May 15, 2 Marks) ...................................................................................................................... 3-19
Program 3.3.7 (MU - Dec. 15, 10 Marks).................................................................................................................... 3-22
Program 3.3.9 (MU - May 14 , 10 Marks). .................................................................................................................. 3-24
Program 3.3.14 (MU - May 13, 6 Marks) .................................................................................................................... 3-27
UQ. Write a program to find GCD and LCM of 2 nos.MU - Dec. 14, 6 Marks. ...................................................... 3-28
UQ. Write a program to find out binary equivalent of given decimal number. MU - May 15, 5 Marks. ................. 3-28
3.3.2 do while Loop ................................................................................................................................................. 3-28
3.3.2(A) Difference between while and do while Loop ................................................................................................. 3-32
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (3-2)
UQ. Explain difference between while and do while loop.MU - May 13, Dec. 13, May 15, Dec. 15, 4 Marks. ..... 3-32
3.3.3 for Loop .......................................................................................................................................................... 3-32
UQ. Write a algorithm and program to generate a factor of given number MU - May 15, 8 Marks. ..................... 3-34
3.3.4 Nested Loops ................................................................................................................................................. 3-34
Program 3.3.22 (MU - Dec. 15, 5 Marks).................................................................................................................... 3-35
UQ. Write a program to generate prime numbers between 1 to 100. MU - Dec. 13, 10 Marks. ......................... 3-41
UQ. Write a program to display pascal triangle. MU - May 13, 6 Marks. .............................................................. 3-42
UQ. Write a program to generate following patterns.
1
23
456
7 8 9 10 MU - May 14, 5 Marks. ................................................................................................................... 3-42
UQ. Write a program to calculate summation of series. 1/2 – 3/4 + 5/6 – 7/8 + …….. upto n terms
MU - May 14, 10 Marks. ................................................................................................................................ 3-42
UQ. Write a program to print the following pattern.
(Note : Not only 4 lines, it should print n lines taken from user)
A
B B
C C C
D D D D MU - Dec. 14, 8 Marks. .............................................................................................................. 3-43
UQ. Write a program to display following pattern.
ABCD
ABC
AB
A MU - May 15, 5 Marks............................................................................................................................... 3-43
2 4 6 8
UQ. Write a Program to calculate summation of series. 1 – x /2! + x /4! – x /6! + x /8! upto n terms.
MU - Dec. 15, May 16, 10 Marks. ................................................................................................................ 3-43
UQ. Generate the following pattern of digits using nested loops.
1
232
34543
4 5 6 7 6 5 4 MU - Dec. 15, Dec. 17, 5 Marks. ............................................................................................. 3-44
UQ. Write a program to generate following pattern.
A
CB
FED
JIHG
O N M L K MU - May 16, 5 Marks. ............................................................................................................... 3-44
UQ. Write a program to generate following pattern.
5
54
543
5432
5 4 3 2 1 MU - May 17, 5 Marks................................................................................................................... 3-45
UQ. Write a program for finding sum of series, 1 + 2 + 3 + 4 upto n terms. MU- Dec. 17, 5 Marks. .................... 3-45
3.3.5 Break Statement ............................................................................................................................................ 3-45
UQ. Explain break statement with the help of suitable examples.MU - May 17, Dec. 17, 2 Marks. .............. 3-45
3.3.6 Continue Statement ....................................................................................................................................... 3-46
UQ. Explain following statement with example.(i) continue MU - May 15, May 17, Dec. 17, 2 Marks. ................. 3-46
3.3.7 Difference between Break and Continue Statement ...................................................................................... 3-47
UQ. Difference between break and continue with example. MU - May 16, 4 Marks. .......................................... 3-47
 Chapter Ends .................................................................................................................................................... 3-47

(MU-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)

 3.1 INTRODUCTION TO CONTROL


 Ans. :
STRUCTURES Use of Decision making Statements
The decision making statements are used to check
UQ. Explain switch control statement with the help of different given conditions depending upon which the flow of
example. MU - May 14, 2 Marks. control can be decided.
 Ans. : Control Structures / Statements GQ. State any four decision making statements.
 Statements in a program are normally executed (2 Marks)
sequentially in the order in which they appear in the
program. But number of times it is necessary to change
 Ans. :
the sequence of program, or to repeat some statements List of decision making statements
number of times. There are four decision making statements: if, if-else,
 C language allows the user for decision making and else if ladder and nested if else.
change the sequence of the program using control or
decision making statements.
 Before studying decision making statements
understand the relational and logical operators which
we are going to use in control or decision making
statements.
Control statements
Control statements are used to control the sequence of
statement’s execution.
 Classification of control statements
Fig. 3.2.1 : Decision making statements
These statements are broadly divided into four
categories: Decision Making Statements, Selection
Statements, Looping Statements, and Jump Statements as
 3.2.1 if Statement
shown in Fig. 3.1.1. UQ. Explain if statement with the help of flowchart.

(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.

Fig. 3.1.1 : Various control statements


 Syntax of if statement

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

 Now in this example user enters 110 which is greater


Fig. 3.2.2 : Flowchart of if statement than 100, so the program prints message.

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.

 3.2.2 if else Statement

GQ. Explain use of if else statement with syntax and


example. (5 Marks)

Fig. P. 3.2.1 : Flowchart of Program 3.2.1


 Ans. :
if else statement
Program
#include<stdio.h>
 Use
Includes header files
#include<conio.h>  The if else statement is used to tell the compiler what
int main() to do in both the situations:
{ 1) if the given condition satisfy
int n;
2) And if the given condition does not satisfy.

printf("\n Enter a number : ");


Accepts number  If the given condition is true, then the “if” block of
from user
scanf("%d",&n); code will be executed, otherwise “else” block of code
will be executed.
 In C programming language any non-zero and non-null
if(n>100) Checks whether number is greater value is considered as true, and for false either zero or
than 100; If Yes then Message
{ will be display. null value is considered.

(MU-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)

 Syntax of if else Statement Program


if(Condition 1) #include<stdio.h>
Includes header files
{ #include<conio.h>
Statement 1; main()
} {
else int n;
{ printf("\n Enter a number : "); Accepts number
Statement 2; from user
scanf("%d",&n);
}
if(n>100) If the
UQ. Draw flowchart for 'if else' statement of condition
{
C language. MU - May 17, 2 Marks. is true this
printf("\n Number is greater than 100"); message will
 Ans. : } be displayed

Flowchart of if else Statement else


{ If condition is
false then this
printf("\n Number is less than 100");
message will be
} displayed.
}
Output

Fig. 3.2.3 : Flowchart of if else statement


 Explanation
Program 3.2.2  Here program accepts a number from user.
Write a program accept a number from user and check  If the number is greater than 100, it will print the
whether it is more than 100. If the given number is greater message – “Number is greater than 100”.
than 100 then print one message and if it is less than 100  If number is less than 100, it will print the message –
then print another message. “Number is less than 100”.
 Soln. : Flowchart Program 3.2.3
Write a program to accept a number from user and check
whether it is even or odd.
 Soln. : Flowchart

Fig. P. 3.2.2 : Flowchart of Program 3.2.2

Fig. P. 3.2.3 : Flowchart of Program 3.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-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);

total = hindi + marathi + english; Calculates total


average = total / 3; and average of
Explanation marks.
 Here program accepts a number from user.
printf("\n Total marks : %d",total);
 Program checks whether the number is even by printf("\n Average : %d",average);
dividing it by 2 and checking whether the remainder is
zero or not Checks whether average
if(average>=40)
is greater than 40
 If the remainder is zero then it will print the message {
“Number is even”
 If the remainder is not zero then it will print the
message “Number is odd”. printf("\n Pass"); If average is greater than or equal to
40 then this message will be displayed.
Program 3.2.4 }
else
Write a program to accept marks of 3 subjects from student.
Calculate the total and average of marks. If the average {
If average is less than 40 then this
is >= 40 then give the remark as pass otherwise fail. printf("\n Fail"); 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-7)

Output  Flowchart of else if ladder

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

 3.2.4 Nested if-else

GQ. Explain nested if-else. (5 Marks)

 Ans. : Nested if-else statement

 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

Fig. P. 3.2.7 : Flowchart of Program 3.2.7

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)

 Flowchart of switch statement

Fig. 3.2.6 : Flowchart of switch case statement


Program 3.2.9 MU - May 14, 2 Marks.
Write a program to display the user entered single digit number in words.
 Soln. : Flowchart

Fig. P. 3.2.9 : Flowchart of Program 3.2.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) (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

break; Prints if n matches with 2


case 2:
printf("\n Two");
break; Prints if n matches with 3
case 3:
printf("\n Three");
Prints if n matches with 4
break;
case 4:
printf("\n Four");
Prints if n matches with 5
break;
case 5:
printf("\n Five");
break;
default:
printf("\n Invalid number"); Prints if none of the above cases satisfied.
}
}
Output

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

Fig. P. 3.2.10 : Flowchart of Program 3.2.10

Program case 'D':


#include<stdio.h> printf("\n Character is d or D"); Prints if ch matches
with ‘d’ or ‘D’
#include<conio.h> break;
main() case 'e':
{ case 'E':
char ch; printf("\n Character is e or E"); Prints if ch matches
with ‘e’ or ‘E’
printf("\n Enter a character from a / A to e / E : "); break;
scanf("%c",&ch); default:
Accepts a character from user and
switch(ch) store it in ch. printf("\n Invalid character"); If none of the above case
} is satisfied then this
{ message will be displayed
case 'a': }
case 'A': Output

printf("\n Character is a or A"); Prints if ch matches


with ‘a’ or ‘A’
break;

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

Fig. P. 3.2.11 : Flowchart of Program 3.2.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) (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)

 3.3 LOOPING STRUCTURES UQ. Draw flowchart for 'while' statement of


C language. MU - May 17, 2 Marks.

GQ. Write use of looping statements with example.  Ans. : Flowchart of while loop
(2 Marks)

 Ans. : Looping statements / Structures


 Use : Loops are used to execute specific task
repeatedly in our program. Rather than writing the code
again and again we can use the concept of loop. There are
various situations when we may want to execute specific
task multiple times. For example student mark sheet. Here
Fig. 3.3.2 : Flowchart of while loop
we want to accept details from student and want to generate
Program 3.3.1
the marks sheet. This task is obviously repeated for number
Write a program to print a message 10 times
of students. In such situations we use the loops.
 Soln. : Flowchart
 Looping statement in ‘C’

C provides three types of loops as shown in Fig. 3.3.1.

Fig. 3.3.1 : Types of loops in C

 3.3.1 while Loop

GQ. Explain while loop with syntax. (5 Marks)


Fig. P. 3.3.1 : Flowchart of Program 3.3.1
 Ans. : while loop
Program
 Use : while loop is used when we want to execute the #include<stdio.h>
set of statements repeatedly until the given condition is #include<conio.h>
satisfying. main()
while loop is considered as an entry controlled loop. {
That means the condition is given at the beginning of loop. int i;
If the given condition does not satisfy, the loop statements i = 1;
never get executed. while(i<=10)
If the condition is satisfied, then loop statements are {
repeatedly executed until the condition is satisfying. Once printf("\n Welcome To C Programming”);
the condition becomes false, the control exits the loop.
Message will be printed repeatedly until the condition
 Syntax of while loop satisfies.
while(Condition 1)
i = i + 1;
{
Statement 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) (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

Fig. P. 3.3.2 : Flowchart of Program 3.3.2


Program
#include<stdio.h>
#include<conio.h>
main()
{
int i;
i = 1;

while(i<=10) 10 times loop will be executed.


Fig. P. 3.3.3 : Flowchart of Program 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-19)

Program Iteration 4 : (2>0) is true so


#include<stdio.h> f = 60 & n=2
#include<conio.h> f = 60*2 = 120
main() n = 2-1 = 1
{
Iteration 5 : (1>0) is true so
int n,f; Declares n and f and initializes f to 1 f =120 & n=1
f = 1;
printf("\n Enter a number : "); f = 120*1 = 120
scanf("%d",&n); Accepts n from user n = 1-1 = 0
while(n>0) Iteration 6 : (0>0) is false so it exits the while loop.
{ And prints Factorial is 120
Until n becomes 0 n will be multiplied
f = f * n; with f repeatedly to calculate factorial.
Program 3.3.4
n =n -1;
Write a program to find whether the entered number is
}
prime or not.
printf("\n Factorial is %d",f);
Program 3.3.4 MU - May 15, 2 Marks.
}
Draw a flowchart to check enter no. is prime or not.
Output
 Soln. : (Prime number is the one which is divisible
by 1 and itself only)
Flowchart

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)

Program O/p will be 3


#include<stdio.h> n= n/10 = 123/10 = 12
#include<conio.h> Iteration 2 : now n= 12
main()
(12>0) is true so
{
int n,rem; rem = n%10 = 12%10 = 2
printf("\n Enter a number : "); Prints value of rem
scanf("%d",&n); O/p will be 32
printf("\n Reverse number is : ");
n= n/10 = 12/10 = 1
Until the value of n becomes 0 the loop will Iteration 3 : now n= 1
while(n>0) be continue.
{ (1>0) is true so
rem = n % 10; rem = n%10 = 1%10 = 1
printf("%d",rem); Prints value of rem
n = n / 10;
O/p will be 321
}
n= n/10 = 1/10 = 0
While dividing a number by 10 we get last digit of the number as a
reminder and remaining digits as the quotient. So here we print the Iteration 4 : now n= 0
reminder and assign the quotient to the number. And repeat
the loop again. Reversing the number involves dividing number (0>0) is false so it will exit the loop
by 10 and storing reminder.
Program 3.3.6
} Write a program to find the sum of digits of an integer
(e.g. input = 1453 sum = 1 + 4 + 5 + 3 = 13).
Output
 Soln. : Flowchart

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)

Program Iteration 1 : now n= 123


#include<stdio.h> (123>0) is true so
rem = n%10 = 123%10 = 3
#include<conio.h>
sum = sum + rem = 0 + 3 = 3
main()
n= n/10 = 123/10 = 12
{
Iteration 2 : now n= 12
int n,rem,sum; (12>0) is true so
sum = 0; rem = n%10 = 12%10 = 2
sum = sum + rem = 3 + 2 = 5
printf("\n Enter a number : "); n= n/10 = 12/10 = 1
scanf("%d",&n); Iteration 3 : now n= 1
while(n>0) (1>0) is true so
{ rem = n%10 = 1%10 = 1
rem = n % 10; sum = sum + rem = 5 + 1 = 6
sum = sum + rem; n= n/10 = 1/10 = 0
n = n / 10; Iteration 4 : now n= 0
(0>0) is false so it will exit the loop, Sum (6) is printed.
}
Program 3.3.7 MU - Dec. 15, 10 Marks.
Until the value of n becomes 0 the loop statements will be Write a program to check if the entered number is
repeated. While dividing a number by 10 we get last digit of
Armstrong or not.
the number as a remainder and remaining digits as the
quotient. So here we add the remainder in the sum and  Soln. : e.g. 153 is Armstrong number. The summation
assign the quotient to the number. And repeat the loop again. of cubes of all the digits should be exactly equal to the
Reversing the number involves dividing number by 10 and number
storing reminder.
153 = (1*1*1) + (5*5*5) + (3*3*3) = 1 + 125 + 27 =153
printf("\n Summation of digits %d",sum); Flowchart
getch();
}
Output

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)

Program (15>0) is true so


#include<stdio.h> rem = n%10 = 15 %10 = 5
#include<conio.h> sum = sum + (rem*rem*rem) = 27+(5*5*5)
main() = 27+125 = 152
{ n= n/10 = 15/10 = 1
int n,n1,rem,sum; Iteration 3 : now n= 1 and sum= 152
sum = 0; (1>0) is true so
printf("\n Enter a number : "); rem = n%10 = 1%10 = 1
scanf("%d",&n); sum = sum + (rem*rem*rem) = 152+(1*1*1)
n1 = n; = 152+1 = 153
while(n>0) n= n/10 = 1/10 = 0
{ Iteration 4 : now n= 0
rem = n % 10; is false so it will exit the loop and goes to the next
statement after while loop
sum = sum + (rem*rem*rem);
Now sum=153 and n1 = 153
n = n / 10;
(153 == 153) is true so it will print Number is
}
Armstrong
Until the number becomes 0 it will repeat the loop statements. To get
digits from the number we calculate the remainder by dividing the Program 3.3.8
number with 10 Write a program to accept a number from user and check
whether it is perfect or not
if(sum==n1) (Perfect number is the number where summation of all the
printf("\n Number is Armstrong"); factors is exactly equal to the number). e.g. 6
else 1+2+3=6
printf("\n Number is not Armstrong");  Soln. : Flowchart
If given number is same as addition of cubes of digits
of the number then it is Armstrong number.
}
Output

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)

Program Iteration 2 : now n = 6, i = 2, sum = 1


#include<stdio.h> (2<=3) is true so
#include<conio.h>
(6%2 ==0) is true so
main()
{ sum = sum +i = 1+2 = 3
int n,i,sum; i= i+1 = 2+1 = 3
i = 1; Iteration 3 : now n = 6, i = 3, sum = 3
sum = 0; (3<=3) is true so
printf("\n Enter a number : ");
(6%3 ==0) is true so
scanf("%d",&n);
sum = sum +i = 3+3 = 6
while(i<=n/2) i= i+1 = 3+1 = 4
Until the value of i becomes
{ half of the number the loop Iteration 4 : now n = 6, i = 4, sum = 6
if(n%i==0) statements will be repeated (4<=3) is false so it will exit the loop and goes
{ Numbers which divides the n
completely are added in sum. to the next statement after while loop
sum = sum + i;
(sum = = n) i.e. (6 = = 6) is true so it will print
}
Number is Perfect
i = i + 1;
} Program 3.3.9 MU - May 14 , 10 Marks.
if(sum==n) Write a program to check whether the given number is
Prints if the sum is palindrome or not. i.e. if no is 12421 it is palindrome.
printf("\n Number is Perfect"); equal to the given
else number .  Soln. : Flowchart
printf("\n Number is not Perfect");
}
Output

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)

Program Program 3.3.10


#include <stdio.h> Write a program which will count number of digit in entered
int main() number.
{  Soln. : Program
int n, reverse_no = 0, rem, original_no;
#include<stdio.h>
printf("Enter a a number : "); #include<conio.h>
scanf("%d", &n); main()
original_no = n;
{
while( n!=0 ) int n,rem,count;
{ count = 0; Declares a count = 0;
rem = n%10;
printf("\n Enter a number : ");
reverse_no = reverse_no*10 + rem; scanf("%d",&n);
n = n/10; while(n>0)
} Until the value of
{
n become 0 loop
Until the value of n is not 0 loop will be executed rem = n % 10; statements will
repeatedly Loop reverses the given number. count = count + 1; be executed repeatedly
Counter is increments
n = n / 10; on every iteration
if (original_no == reverse_no) }
printf("The number is palindrome.");
Prints if the given number and the reverse are same. printf("\n Number of digits are %d", count);
}
else Output
printf("The number is not palindrome.");
return 0;
}
Output

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

Initially 121 0 - 121

Iteration 1 while( 121 != 0) is true 12 1 1

Iteration 2 while( 12 != 0) is true 1 12 2

Iteration 3 while( 1 != 0)is true 0 121 1

Iteration 4 while( 0 != 0) is false - -

Finally 121 121

121 is palindrome number because reverse_no


matches with original_no.
Fig. P. 3.3.10 : Flowchart of Program 3.3.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-26)

Explanation while(i<=100) 100 times the loop will


{ be executed.
See the updated values of n, rem and count by Each time updated value
sum = sum + i;
considering the initial value of n as 135 of i will be added in sum
i = i + 1;
while( n > 0) n rem count }
Initially 135 - 0 printf("\n Sum of numbers from 1 to 100 is %d",sum);
Iteration 1 while( 135 >0) is 13 5 1 getch();
true }
Iteration 2 while( 13 >0) is 1 3 2 Output
true
Iteration 3 while( 1 >0)is true 0 1 3
Iteration 4 while( 0 >0) is false - -
Finally 3
Print the value of count i.e. 3 Explanation

Program 3.3.11 Initial value of i = 1 and sum = 0


Write a program to find out sum of numbers from 1 to 100. i <= 100 is true
sum = sum + I = 0+1 = 1
 Soln. :
i = i+1 = 1+1 = 2
Flowchart
Now value of i = 2 and sum = 1
i <= 100 is true
sum = sum+ i = 1+2 = 3
i=i+1=2+1=3
According to above explanation updated values of i and
sum are given in following table:
while( i <= 100) sum i
Initially 0 1
Iteration 1 while( 1 <= 100) is true 0 + 1 = 1 1+1=2
Iteration 2 while( 2 <= 100) is true 1 + 2 = 3 2+1=3
Iteration 3 while( 3 <= 100) is true 3 + 3 = 6 3+1=4
Iteration 4 while( 4 <= 100) is true 6 + 4 = 10 4+1=5
. . . .
Fig. P. 3.3.11 : Flowchart of Program 3.3.11 . . . .
. . . .
Program
Iteration 99 while( 99 <= 100) is true 4851 + 99 = 4950 99 + 1 = 100
#include<stdio.h>
Iteration 100 while( 100 <= 100) is 4950 + 100 = 100 + 1 =
#include<conio.h>
true 5050 101
Finally while( 101 <= 100) is - -
main()
false
{
int i,sum; Print the value of sum i.e. 5050
i = 1;
sum = 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-27)

Program 3.3.12 Output

Write a program to accept a number from user and print it’s


cube. Ask user for continuity , if user says yes repeat the
process.

 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

UQ. Write a program to find out binary equivalent of


given decimal number. MU - May 15, 5 Marks.

 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)

Program 3.3.14 Output

Write a program to accept a number from user and print it’s


cube. Ask user for continuity, if user says yes repeat the
process.

 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

Fig. P. 3.3.14 : Flowchart of Program 3.3.14


Program
#include<stdio.h>
#include<conio.h>
main()
{
int n,cube;
char ch;
do
{
printf("\n Enter a number : ");
scanf("%d",&n);
cube = n * n * n;
printf(" Cube is %d",cube);
printf("\n\n Do u want to continue?(y/n) : ");
scanf("%s",&ch);
} while(ch=='y');
If user enter ‘y’ for continuity then loop will be repeated.

getch(); Fig. P. 3.3.15 : Flowchart of Program 3.3.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) (Control Structures)….Page no. (3-30)

Program  Soln. : Flowchart


#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,i;
a = 1;
b = 2;
i = 1;
printf("1 2 ");
do
{
Loop will execute until i is
c = a + b; less than 5 In Fibonacci
series every number is
printf (" %d ",c); addition of its previous
a = b; two numbers.

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

Iteration 1 while(1< 5) is true 2 2 3 3 1 2 3 i++;


Loop will execute until i
}while(i<=n);
become equal to n
Iteration 2 while(2< 5)is true 3 3 5 5 1 2 3 5 }

Iteration 3 while(3< 5)is true 4 5 8 8 1 2 3 5 8 Output

Iteration 4 while(4< 5)is true 5 8 13 13 1 2 3 5 8 13

Finally while(5< 5)is false Explanation


See the updated values of i and n by considering the
Program 3.3.16
initial value of n as 6
Write a program to display all even numbers from 1 to 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-31)

while( i <= n) if(i%2 == 0) i n O/P on screen Explanation


Initially 16
It will print addition of 1+3+5+7+9+11+13+15+17+19
Iteration 1 while(1<= 6) is true if(1%2 == 0) is false 2 6
which is 100.
Iteration 2 while(2<= 6) is true if(2%2 == 0) is true 3 6 2
Iteration 3 while(3<= 6) is true if(3%2 == 0) is false 4 6 2 Program 3.3.18
Iteration 4 while(4<= 6) is true if(4%2 == 0) is true 5 6 2 4
Write a program to accept ten numbers and print average of
Iteration 5 while(5<= 6) is true if(5%2 == 0) is false 6 6 2 4
it.
Finally while(6<= 5) is false if(6%2 == 0) is true 7 6 2 4 6
Program 3.3.17  Soln. : Flowchart
Write program to sum all the odd numbers between 1 to 20.
 Soln. : Program
#include<stdio.h>
#include<conio.h>
main()
{
int i,sum;
i = 1;
sum = 0;
do
{
if(i%2!=0) 20 times loop will be
sum = sum + i; executed
}while(i<=20);
printf(“\n Sum of odd numbers : %d ”,sum);
}
Output

Fig. P. 3.3.18 : Flowchart of Program 3.3.18

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);

Calculate and print the average of ten numbers.

Fig. P. 3.3.17 : Flowchart of Program 3.3.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) (Control Structures)….Page no. (3-32)

Output  3.3.2(A) Difference between while and do


while Loop
UQ. Explain difference between while and do while
loop.
MU - May 13, Dec. 13, May 15, Dec. 15, 4 Marks.
 Ans. : Difference between while loop and do-while
loop
Parameters while loop do while loop
Known as It is an entry It is an exit controlled
controlled loop loop
Position of Condition is given at Condition is given at
condition the beginning of loop the end of loop
Execution of Loop statement never Loop statement
loop executes if condition executes once even if
statement does not satisfy condition does not
satisfy
Syntax while(condition) do
{ {
Statements; Statements;
} } while(condition);

 3.3.3 for Loop


Explanation GQ. Describe use of for loop with syntax and
flowchart. (5 Marks)
The updated values of i, sum and n are given in
following table :  Ans. : for loop

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.

Iteration 2 while(2<= 10)is true 2 1+2=3 3  Syntax


for(Initialization; Condition 1; Increment/Decrement)
Iteration 3 while(3<= 10)is true 3 3+3=6 4 {
Iteration 4 while(4<= 10)is true 4 6 + 4 = 10 5 Statement 1;
}
Iteration 5 while(5<= 10)is true 5 10 + 5 = 15 6
 Flowchart
Iteration 6 while(6<= 10)is true 6 15 + 6 = 21 7
Iteration 7 while(7<= 10)is true 7 21 + 7 = 28 8
Iteration 8 while(8<= 10)is true 8 28 + 8 = 36 9
Iteration 9 while(9<= 10)is true 9 36 + 9 = 45 10
Iteration 10 while(10<= 10)is true 10 45 + 10 = 55 11
Finally while(11<= 10)is false

So the updated value of sum is 55 and


avg = sum / 10 = 55 / 10 = 5
So value of avg i.e. 5 is printed on the screen.
Fig. 3.3.4 : Flowchart of for 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-33)

Program 3.3.19 ( i <= 10) O/P on screen i


Write a program to print 1 to 10 numbers using for loop. Initially 1
 Soln. : Iteration 1 (1<= 10)is true 1 2

Flowchart Iteration 2 (2<= 10)is true 2 3


Iteration 3 (3<= 10)is true 3 4
Iteration 4 (4<= 10)is true 4 5
Iteration 5 (5<= 10)is true 5 6
Iteration 6 (6<= 10)is true 6 7
Iteration 7 (7<= 10)is true 7 8
Iteration 8 (8<= 10)is true 8 9
Iteration 9 (9<= 10)is true 9 10
Iteration 10 (10<= 10)is true 10 11
Finally (11<= 10)is false

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;

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


{
printf("\n %d ",i); Loop will be repeated until i
remains <=10
}
}
Output

Fig. P. 3.3.20 : Flowchart of Program 3.3.20

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)

Program UQ. Write a algorithm and program to generate a


#include<stdio.h> factor of given number MU - May 15, 8 Marks.
#include<conio.h>
main()
 Ans. :
{ #include <stdio.h>
int n,f; int main() {
f = 1; int num, i;
printf("Enter a positive integer: ");
n = 10;
scanf("%d", &num);
for(;n>0;n--) printf("Factors of %d are: ", num);
Initialization part is
{ optional we can skip for (i = 1; i < num; ++i) {
f = f * n; this part
if (num % i == 0) {
F is multiplied with n
} until n becomes 0 printf("%d ", i);
printf("\n Factorial is %d",f);
getch(); }
} }
Output return 0;
}
Output

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

Iteration 5 (6 > 0)is true 5040 * 6 = 30240 5 for(initialization 1; condition 1; increment/decrement)


Iteration 6 (5 > 0)is true 30240 * 5 = 151200 4 {
Statement 1;
Iteration 7 (4 > 0)is true 151200 * 4 = 604800 3
for(initialization 2; condition 2; increment/decrement)
Iteration 8 (3 > 0)is true 604800 * 3 = 1814400 2
{
Iteration 9 (2 > 0)is true 1814400 * 2 = 3628800 1 Statement 2;
Iteration 10 (1 > 0)is true 3628800 * 1 = 3628800 0 }
Finally (0 > 0)is false Statement 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-35)

Flowchart of nested looping Flowchart

Fig. 3.3.4 : Flowchart of nested looping


Program 3.3.21 MU - Dec. 15, 5 Marks.
Write a program to display the following : Fig. P. 3.3.21 : Flowchart of Program 3.3.21
*
Explanation
**
*** Let’s consider the pattern in row and column format we
**** require five rows and five columns.
***** Here the outer loop is used for rows ( i ) and inner loop
 Soln. : Program is used for columns ( j ).
#include<stdio.h>
#include<conio.h>
main()
{
int i,j;

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)

Flowchart 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 i is incremented therefore 2 <= 5 is true
And j = 1 so 1 <=2 is true so value of j i.e. 1 is printed
as shown below

Then j is incremented therefore 2 <= 2 is true so value


of j i.e. 2 is printed as shown below

1 2

Fig. P. 3.3.22 : Flowchart of Program 3.3.22


Then j is incremented therefore 3 <= 2 is false and
Explanation control goes out from inner loop and cursor goes to the next
Let’s consider the pattern in row and column format we line due to printf (“\n”) statement
require five rows and five columns. The i is incremented therefore 3 <= 5 is true
Here the outer loop is used for rows ( i ) and inner loop And again the inner loop will be executed 3 times as
is used for columns ( j ). j = 1 to 3 and it will print value of j i.e. 1, 2, and 3 as shown
below.

1 2

1 2 3

Initially, i = 1 so 1 <= 5 is true


And j = 1 so 1 <=1 is true so value of j i.e. 1 is printed
as shown below: Then j is incremented therefore 4 <= 3 is false and
1 control goes out from inner loop and cursor goes to the next
line due to printf (“\n”) statement
The i is incremented therefore 4 <= 5 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) (Control Structures)….Page no. (3-38)

And again the inner loop will be executed 4 times as  Soln. :


j = 1 to 4 and it will print value of j i.e. 1, 2, 3, and 4 as
Flowchart
shown below.

1 2

1 2 3

1 2 3 4

Then j is incremented therefore 5 <= 4 is false and


control goes out from inner loop and cursor goes to the next
line due to printf (“\n”) statement
The i is incremented therefore 5 <= 5 is true
And again the inner loop will be executed 5 times as
j = 1 to 5 and it will print value of j i.e. 1, 2, 3, 4, and 5 as
shown.

1 2

1 2 3

1 2 3 4

1 2 3 4 5 Fig. P. 3.3.23 : Flowchart of Program 3.3.23


Then j is incremented therefore 6 <= 5 is false and Program
control goes out from inner loop and cursor goes to the next
#include<stdio.h>
line due to printf (“\n”) statement
#include<conio.h>
The i is incremented therefore 6 <= 5 is false and
control goes out from outer loop. main()
The pattern is printed. {
int i,j;
Program 3.3.23
Write a program to print following pattern for(i=1;i<=5;i++) 5 times loop will be executed
1 {
22 for(j=1;j<=i;j++) Loop will executes until j
333 { becomes equal to i

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)

Explanation  Then j is incremented therefore 3 <= 2 is false and


 Let’s consider the pattern in row and column format control goes out from inner loop and cursor goes to the
we require five rows and five columns. next line due to printf (“\n”) statement.

 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

 Initially, i = 1 so 1 <= 5 is true


 And j = 1 so 1 <=1 is true so value of i i.e. 1 is printed
as shown below.  Then j is incremented therefore 4 <= 3 is false and
control goes out from inner loop and cursor goes to the
1 next line due to printf (“\n”) statement.
 The i is incremented therefore 4 <= 5 is true.
 And again the inner loop will be executed 4 times as
j = 1 to 4 and it will print value of i (i.e. 4) 4 times as
shown below.
1

 Then j is incremented therefore 2 <= 1 is false and 2 2


control goes out from inner loop and cursor goes to the 3 3 3
next line due to printf (“\n”) statement 4 4 4 4
 The i is incremented therefore 2 <= 5 is true
 And j = 1 so 1 <=2 is true so value of i i.e. 2 is printed  Then j is incremented therefore 5 <= 4 is false and
as shown below. control goes out from inner loop and cursor goes to the
1 next line due to printf (“\n”) statement.
 The i is incremented therefore 5 <= 5 is true.
2
 And again the inner loop will be executed 5 times as
j = 1 to 5 and it will print value of i (i.e. 5) 5 times as
shown below.
1
2 2
 Then j is incremented therefore 2 <= 2 is true so value
3 3 3
of i i.e. 2 is printed as shown.
4 4 4 4
1
5 5 5 5 5
2 2  Then j is incremented therefore 6 <= 5 is false and
control goes out from inner loop and cursor goes to the
next line due to printf (“\n”) 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-40)

 The i is incremented therefore 6 <= 5 is false and Explanation


control goes out from outer loop. Let’s consider the pattern in row and column format we
 The pattern is printed. require four rows and four columns.
Program 3.3.24 Here the outer loop is used for rows ( i ) and inner loop
Write a program to print following pattern is used for columns ( j ).
****
***
**
*
 Soln. : Program Initially, i = 4 so 4 >= 1 is true
#include<stdio.h> And j = 1 so 1 <=4 is true so one * is printed as shown
main() below.
{
*
int i,j;
clrscr();
for(i=4;i>=1;i--)
Loop will executes 4 times
{
for(j=1;j<=i;j++)
{ Loop will executes until j Then j is incremented therefore 2 <=4 is true so again
becomes equal to i
printf("* "); one * is printed as shown below.
} * *
printf("\n");
}
}
Flowchart

Then j is incremented therefore 3 <=4 is true so again


one * is printed as shown below.
* * *

Then j is incremented therefore 4 <=4 is true so again


one * is printed as shown below.
* * * *

Then j is incremented therefore 5 <= 4 is false and


control goes out from inner loop and cursor goes to the next
line due to printf (“\n”) statement
The i is decremented therefore 3 >= 1 is true
And again the inner loop will be executed 3 times as
Fig. P. 3.3.24 : Flowchart of Program 3.3.24 j = 1 to 3 and it will print 3 * as shown below.

(MU-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.

UQ. Write a program to generate prime numbers


between 1 to 100. MU - Dec. 13, 10 Marks.

 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)

UQ. Write a program to display pascal triangle. {


printf("%d ", a);
MU - May 13, 6 Marks.
}
A printf("\n");
A B }
A B C return 0;
A B C D }

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)

 Soln. : UQ. Write a program to display following pattern.

#include<stdio.h> ABCD

int main() { ABC

int i,j,n; AB

float sum = 0; A MU - May 15, 5 Marks.

printf("Enter the value of n : ");  Soln.


scanf("%d",&n);
#include<stdio.h>
for(i=1,j=1;i<=n; i++,j=j+2)
{
int main()
sum=sum+(float)(j)/(j+1);
{
}
printf("Sum of series is %f",sum);
int i, j;

}
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!");

printf("\n\tENTER VALUE OF X : ");


scanf("%f",&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) (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()
{ }

UQ. Write a program to generate following pattern.


int i, space, rows, k=0, count = 0, count1 = 0;
A
printf("Enter number of rows: "); CB
scanf("%d",&rows);
FED

for(i=1; i<=rows; ++i) JIHG


{ ONMLK MU - May 16, 5 Marks.
//print space until sapce value is not equal/less than
(sapce-i), where
// i is current row 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-45)

 Ans. : UQ. Write a program for finding sum of series, 1 + 2

#include<stdio.h> + 3 + 4 upto n terms. MU- Dec. 17, 5 Marks.

 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.

 Ans. :  3.3.5 Break Statement


#include<stdio.h> UQ. Explain break statement with the help of
int main() suitable examples.
{ MU - May 17, Dec. 17, 2 Marks.
int i,j,k;
 Ans. : break statement
for(i=1;i<=5;i++)  Use : The break statement is used to exit from the loop
{ for a particular condition.
for(j=1;j<=5-i;j++)
{
 Syntax of break Statement
for(Initialization ; Condition 1; Increment/
printf(" ");
Decrement)
}
{
for(j=1,k=5;j<=i;j++)
Statement 1;
{
if (Condition 2)
printf("%d ",k--);
break;
}
Statement 2;
printf("\n");
}
}
Statement 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-46)

 Flowchart of break Statement Program

#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

Fig. 3.3.5 : Flowchart of break statement


Explanation : When the value of I becomes 5 , the control

Program 3.3.25
come out of the loop because of break statement.

Write a program to demonstrate use of break statement.  3.3.6 Continue Statement


 Soln. : Flowchart
UQ. Explain following statement with example.
(i) continue
MU - May 15, May 17, Dec. 17, 2 Marks.

 Ans. : continue Statement

 Use : The continue statement sets the control at the


beginning of loop for particular condition. That means for
the given condition, the statements below the continue
statement are skipped.
 Syntax of continue Statement
for(Initialization ; Condition 1; Increment/
Decrement)
{
Statement 1;
if (Condition 2)
continue;
Statement 2;
}
Fig. P. 3.3.25 : Flowchart of Program 3.3.25 Statement 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-47)

 Flowchart of continue Statement {

When i =5 , the prinf


if(i==5) statement will not execute
continue; and control sets at the
printf(" %d ",i); beginning of loop
}
getch();
}
Output

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.

 3.3.7 Difference between Break and


Continue Statement

UQ. Difference between break and continue with


example. MU - May 16, 4 Marks.

 Ans. : Difference between break and continue


statement
Parameters Break continue

Use A break can be used in A continue can be used in


switch and loops loops only.

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

University Prescribed New Syllabus w.e.f Academic Year 2019-2020

 Introduction to functions
 Function prototype, Function definition, Accessing a function and parameter passing.
 Recursion.

4.1 Introduction to Functions ............................................................................................................................................... 4-3

4.1.1 Function Definition / Elements of Function ....................................................................................................... 4-3

4.1.2 Function Prototype ........................................................................................................................................... 4-4

4.1.3 Accessing or Calling Function .......................................................................................................................... 4-5

4.1.4 Parameter Passing .......................................................................................................................................... 4-5

4.1.5 Advantages of Function ................................................................................................................................... 4-6

4.2 Types of Function .......................................................................................................................................................... 4-6

4.2.1 Function with no Return Type and no Argument .............................................................................................. 4-6

4.2.2 Function with Arguments and no Return Type ................................................................................................. 4-7

4.2.3 Function with Return Type and no Arguments ................................................................................................. 4-8

4.2.4 Function with Return Type and with Arguments............................................................................................... 4-9

4.3 Library Functions ......................................................................................................................................................... 4-10

UQ. Explain the purpose of following standard library functions :

(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

UQ. Write a program to calculate compound interest and amount.

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

4.4 Scope of Variables ...................................................................................................................................................... 4-19

4.5 Recursive Functions .................................................................................................................................................... 4-20

UQ. Explain recursion concept. MU - May 13, 2 Marks. ...................................................................................... 4-20

OR What do you mean by recursion ? MU - Dec. 13, May 14, Dec. 15, May 16, Dec. 18, 2 Marks. ................. 4-20

OR Explain recursive function MU - Dec.17, 2 Marks......................................................................................... 4-20

4.5.1 Advantages of Recursive Functions ............................................................................................................... 4-20

UQ. What are advantages of recursion? MU - May 17, 2 Marks. ......................................................................... 4-20

4.5.2 Disadvantages of Recursive Functions .......................................................................................................... 4-20

UQ. What are disadvantages of recursion? MU - May 17, 2 Marks ..................................................................... 4-20

4.5.3 Programs on of Recursive Functions ............................................................................................................. 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.

MU - Dec. 14, May 17, 4 Marks. ................................................................................................................... 4-21

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

 Chapter Ends .................................................................................................................................................... 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)

 Prototype declaration is not essential but if it is not {


declared before it is used, then compiler assumes that if (a>b)
details of that functions will be available at linking {
time. printf("\n\t%d is greater number", a); Function
} definition
 4.1.3 Accessing or Calling Function else
{
GQ. Explain with the proper syntax : function call.
printf("\n\t%d is greater number", b);
(4 Marks) }
}
 Ans. :
Output
Accessing / calling a Function
 We have learned how to define the function. To use
defined function we must call it.
Syntax
 Following syntax is used to call a function.
Function_name (list of actual parameters); Explanation
 Before calling any function it should be either declared  In this program main() is the calling function and
or defined first and then function call can be made, greater() is called function. While the function
otherwise compiler will generate an error. greater ( ) gets called by main() further execution of
Calling function and called function main() is suspended and the control goes to the
 The function which calls another function is referred as definition of greater() function and the values of x and
calling function and the function which gets called is y are mapped to a and b respectively.
referred as called function.  After finding the greater number the control goes back
to the calling function i.e. main ( ) again and continues
Actual and formal parameters
its further execution.
 Parameters used in function call are referred as actual
parameters whereas parameters used in the function  4.1.4 Parameter Passing
definition and function declaration referred as formal
parameters. GQ. Explain concept of parameter passing in function.
(2 Marks)
GQ. Write a program to find greater number using
function. (5 Marks)  Ans. :
 Ans. : Parameter Passing

Program  When a function gets called there are two possibilities


#include<stdio.h> of order in which the actual parameters are passed to
#include<conio.h> the function definition and maps with formal
void greater(int , int ); Function prototype parameters. The possibilities are:
int main() o Parameters are passed from left to right.
{ o Parameters are passed from right to left.
int x=4, y=5;  In C, parameters are passed from right to left. The
greater(x,y); Function call order of parameter passing doesn’t much essential for
getch(); certain examples like following function call:
} sum(m,n,o,p);
void greater(int a, int 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. (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);

 4.1.5 Advantages of Function

GQ. State the advantages of function. (2 Marks)

 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)

GQ. State types of function on the basis of parameter


 Ans. : Program

passing and return type. (2 Marks) # include<stdio.h>


void message(void);
 Ans. : int main()
Types of Function {
printf("\nBefore function call\n");
 A function may fall in one of the categories given
below. To which category the function belongs to is 1. Function call passes the control to function
decided based on the absence or presence of arguments definition.
2. After end of the function execution, it returned
and whether the function returns any value or not. back to next statement of calling 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-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)

GQ. Explain with-Argument-No-Return Value  Ans. :


function type with example. (4 marks)
Program
 Ans. : Function with Argument and No Return
# include<stdio.h>
Type
void cube(int a);
 When the function doesn’t return any value void is
int main()
written at the place of return type. And when a
{
function has arguments, these arguments are written
int num = 5;
within parenthesis. So general form of declaring the
function with no return type but with arguments is printf(“\nThe number is:%d”, num);
given below : 1. Function call to cube()
Syntax cube(num); 1 transfer the control to its
return 1; function definition.
void function_name (argument list); 2. Value of num i.e. 5 copied
} 2
 To call the function with no return type but with into a.
void cube (int a)
arguments following format is used:
{
function_name ( list of actual parameters );
printf("\nCube of the number is :%d \n", a*a*a);
 Every parameter is separated by comma in the list.
Parameter list should match the order, type and number After function execution control returned back to main().
of parameters as given in function prototype or }
definition.

(MU-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)

Output  %d is used if the return type is int. otherwise


corresponding modifier is used to print the return
value.
2. If prototype of function is like :
int mul(void);

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)

GQ. Explain Return type and no arguments function  Ans. : Program


type with example. (4 Marks) # include<stdio.h>
 Ans. : int square();
int main()
Function with Return Type and No Arguments
{
 When the function does not have any arguments we
Function call to square() leads to
use void in the parenthesis. And when the function
transfer the control to its definition.
returns a value, the data type for that value is written in
the place of return type. So general form of declaring
the function with return type but no arguments is given int result = square ();
below.
Syntax
return_type function_name (void); printf(“\nThe square is:%d”, result);
return 1;
 To call the function with return type but no arguments
}
following format is used :
int square()
variable_name = function_name ();
{
 variable_name is used to hold the value returned by the int s,num; return s;
function. Empty parenthesis indicates that the function statement
return back the
doesn’t have arguments. printf(“\nEnter a number:\t\t”); control to
Examples main() and
assign the
scanf(“%d”, &num); value of s to
1. If the function returns meaningful value it can be stored
result.
in the variable or can be printed directly on the screen
s=num*num;
like:
return s;
printf(“%d”, function_name());
}

(MU-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)

 Ans. :  Ans. : Program


Function with Return Type and with Arguments # include<stdio.h>
 When the function has arguments and also returns a double pow(double, double);
value, then it uses following general form to declare int main()
the function {
double x,y,z;
Syntax
printf("\nEnter value of x and y for the expression
return_type function_name (argument list); z=(x^4)+(y^-
 To call the function with return type and with 3)+3:\n");
arguments following format is used: scanf("%lf %lf", &x,&y);
The function pow() is
variable_name = function_name (list of actual parameters);
called twice and returned
 variable_name is used to hold the value returned by the z = pow (x,4)+pow(y,-3)+3; values are passed to
function. The type of variable should match the type of printf("\nz = %lf", z); expression to evaluate z.

returned value. return 1;


}
 The function parameters in list are separated by
double pow(double n, double p)
comma. Parameters in the list have same order, type
{
and number of parameters as in the prototype.
double result = 1;
Example if(p>=0)
 If prototype of function is like. {
while (p--) Calculates the positive
int sub(int a, int b); powers .At first call to
{
 then, the following all are the valid function calls pow() p is 4 so if block
result*=n; will be executed.
1. int result= sub(4,7);
}
}
2. int x=4, y=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) (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

 In this program we called the function pow() twice void clrscr(void);


with different inputs. getch() and getche()
 The value of x and y are given by user so 2 is stored in  getch() reads a single character from the console
x and next 2 is stored in y variable. without echoing to the screen. Whereas getche() reads
 At the first time we call the function with input x and 4 a single character from the console and echoes to the
4 screen.
i.e. the function calculates the 2 to power 4 i.e. 2 =16.
 And at second time the pow() function is called with y Declaration
and -3 as its arguments so the function calculates 2 to int getch(void);
-3 int getche(void);
power -3 i.e. 2 = 0.125.
 So each time the pow() function calculates the result Both are used for accepting a character from user.
and send it back to the expression in main(). cgets() : Reads string from console.
4 –3 4 -3
Therefore z = x + y + 3 = 2 +2 +3 Declaration

= 16.000 + 0.125 + 3 = 19.125 is printed as result. char *cgets(char *str);


 cgets() will read string of characters from the console
 4.3 LIBRARY FUNCTIONS and stores the string (and the string length) in the
location *str.
GQ. Enlist different library functions (2 Marks) cputs()

 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)

 Ans. : Difference between getch() and getche() Function Description


putchar() writes a character to screen
Parameters getch() getche()
clearerr() clears the error indicators
Concept It accepts the entered It accepts the
character but doesn’t entered character fopen() Opens file
echo it on the screen. and also echos it on fclose() closes an opened file
the screen. getw() reads an integer from file
Example int main() int main() putw() writes an integer to file
{ { fgetc() reads a character from file
char ch; char ch;
putc() writes a character to file
printf("\nEnter a printf("\nEnter
character: "); a character: "); fputc() writes a character to file
ch = getch(); ch = getche(); fgets() reads string from a file, one line at a
printf("\nEntered printf("\n Entered time
character is %c", ch); character is %c", fputs() writes string to a file
return 1; ch); feof() finds end of file
} return 1; fgetchar reads a character from keyboard
}
fgetc() reads a character from file
Output of Output of the above Output of the
fprintf() writes formatted data to a file
example program is; above program is;
Enter character : T Enter character: T fscanf() reads formatted data from a file
Entered character is T Entered character fgetchar reads a character from keyboard
is T fputchar writes a character from keyboard
fseek() moves file pointer position to given
GQ. List any five library functions under stdio.h location
header file. (2 Marks)
SEEK_SET moves file pointer position to the
 Ans : beginning of the file
SEEK_CUR moves file pointer position to given
Functions under stdio.h Header File location
 The stdio.h header file is referred as standard input SEEK_END moves file pointer position to the end of
output header file. This file includes standard macros file.
definition, constants and functions. ftell() gives current position of file pointer
 To perform all types of input output operations it also rewind() moves file pointer position to the
includes the required data type. beginning of the file
putc() writes a character to file
 The most frequently used functions in stdio.h file are:
sprint() writes formatted output to string
printf(),scanf(),putchr(),getchar().
sscanf() Reads formatted input from a string
 Inbuilt C functions in stdio.h file
remove() deletes a file
Function Description
fflush() flushes a file
printf() print the character, string, float, integer,
octal and hexadecimal values on the GQ. List any five library functions under ctype.h
output screen header file. (2 Marks)
scanf() reads a character, string, numeric data
from keyboard.  Ans. :
getc() reads character from file Functions under ctype. h header file
gets() reads line from keyboard ctype.h file includes the functions which are used to
getchar() reads character from keyboard manipulate characters. Some of them are explained below :
puts() writes line to o/p screen

(MU-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. : Purpose of math functions printf("original number %5.2lf\n", number);


printf("number rounded down %5.2lf\n", down);
Function Purpose
printf("number rounded up %5.2lf\n", up);
ceil(number) rounds up the given number. It printf("square root of th number %5.2lf is : %5.5lf", down,
returns the integer value which is sqrt(down));
greater than or equal to given
return 0;
number.
}
floor(number) rounds down the given number. It
returns the integer value which is Output
less than or equal to given number.
sqrt(number) returns the square root of given
number.
pow(base, returns the power of given number.
exponent)
abs(number) returns the absolute value of given
number.
Explanation
GQ. Write a program which does following
1. Calculate absolute value of an integer number  Here, x = -12345678L and num = -1234; So to find
and a long number absolute value of both following functions are used :
2. Round down the number (i.e. if input is  labs(x) finds absolute value for long i.e.=12345678 and
125.740, then the output should be 125.00) abs(num) finds absolute value for integer i.e.=1234
3. Round up a number (i.e. if input is 125.740,
 floor() will round the number 625.54 to 625 whereas,
then the output should be 126.00) (5 Marks)
ceil() will round up the number 625.54 to 626.
 Ans. : Program
GQ. List any four library functions under stdlib.h
#include <stdio.h>
header file. (2 Marks)
#include <math.h>
int main(void)  Ans. : Functions under stdlib.h Header File
{  stdlib.h header file include general library functions
long result; long x = -12345678L; for example:
int num = -1234;
1. rand() 2. swab() 3. div() 4. min()
printf("%d is the absolute value of integer: %d\n",
abs(num),num); GQ. Write a program to swap the characters in a
string e.g. if input string is abcd then output will
abs() returns absolute value of an integer be badc. (4 Marks)

 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()

ctime() converts time and date to string. The format of


converted string is like.
DDD MMM dd hh:mm:ss YYYY
Fig. 4.3.1
where:
GQ. Write a program to generate five random DDD = Day(Mon, Tue, Wed, Thu, Fri, Sat, Sun)
numbers from 0 to 99. (3 Marks) MMM = Month(Jan, Feb, Mar, Apr, May, Jun, Jul,
 Ans. : Program Aug, Sep, Nov, Dec)

#include <stdlib.h> dd = date (01,02,03,04,……31)


#include <stdio.h> hh = Hour (01,02,03,04,……12)
int main(void) mm = Minutes(01,02,03,04 ,… 59)
{
ss = Seconds(01,02,03,04 ,… 59)
int i;
YYYY = year
printf("five random numbers from 0 to 99 are :\n\n");
Example
for(i=0; i<5; i++) 5 times loop will be executed Thu Oct 05 05:20:34 2017
{ _strdate ()
printf("%d\n", rand() % 100); Prints random It is used to convert the current date into string. The
} numbers between
standard format of strdate() is:
return 0; 0 to 99
} _strdate(date);
Output This statement converts the current date into string and
stores it into date. The length of date should be 9
characters long.
The string date has following format:
MM /DD/ YY
Where:
MM = Month (01,02,….12)
DD = Day (01,02,…..31)
YY = Year(last two digits of year)

(MU-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)

Example GQ. Write a program to perform addition,


01/02/17 subtraction, multiplication and division of two

time() integer numbers using function. (10 Marks)

time( ) is used to get time of day in seconds elapsed  Ans. :


since January 1, 1970 Program
GQ. Write a program to illustrate use of library #include <string.h>
functions in time.h header file (5 Marks) #include <stdio.h>
int add(int,int);
 Ans. : int sub(int,int);
Program int mul(int,int);
#include <stdio.h> int div(int, int);
#include <time.h> int main(void)
{
int main(void) int a,b,result;
{ printf("\nEnter two inegers:\n");
scanf("%d%d",&a,&b);
time_t t;
char date[9]; result=add(a,b);
t = time(NULL); printf("\na + b = %d\n",result);
Flow of control is
Converts the date into string and store changed according to
_strdate(date); it in date result=sub(a,b); the function calls.
printf("a - b = %d\n",result); Here First add() is
called(1) after
performing defined
printf("Current date and time is %s”, ctime(&t)); result=mul(a,b); operation the result is
printf(“\n todays date is %s", date); printf("a * b = %d\n",result); send back to main()
(2). Then sub() gets
Returns system’s current date and time. called (3) and
result=div(a,b); performs defined
return 0; printf("a / b = %d",result); operation then result
is send back to
} return 0;
main() (4). Then
Output } mul() gets called (5)
int div(int a,int b) and performs defined
operation then result
{ is send back to
if(b!=0) main() (6) . Then
return a/b; div() gets called (7)
and performs defined
else operation then result
Explanation
printf("Can't divisible by zero"); is send back to
 Time(NULL) provides the elapsed seconds from } main() (8)
January 1 1970 till current time int mul(int a,int b)
 _strdate(date) will convert the current date into string {
and stores the string into following format in date: return a*b;
10/05/2017. }
 ctime(&t) will convert the system’s current date and int add(int a,int b)
time into string the string will be in the form of: Thu {
Oct 05 04:39:22 2017 return a+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. (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)

 Ans. : rev = rev * 10 + (n%10) = 7 * 10 +(68%10)


= 70+8 = 78
Program
#include <stdio.h> n= n/10 = 68/10 = 6
int revrse (int a); Iteration 1 : Now rev=70, n=6
while(6!=0) ) is true so
int main(void)
rev = rev * 10 + (n%10) = 78 * 10 +(6%10)
{
= 780+6 = 786
int num;
printf("\nEnter an integer:\t\t"); n= n/10 = 6/10 = 0
scanf("%d",&num); Iteration 4 : now n= 0
printf("\nreverse of entered number is : %d", revrse(num)); (0>0) is false so it will exit the loop
return 0;
 return rev will return the control back to main() and
} Value of num is
copied into n. prints the result i.e. 786

UQ. Write a program to calculate compound interest


int revrse(int n) and amount.
{ Using formula A=P(1+R/100)^n, where
int rev=0; P=Principal Amt., R is Rate of interest,
Loop will execute n = number of years. Your program should make
until n becomes 0. use of user defined function to calculate power.
while (n!=0)
Program should accept P, R and N, Display
{ interest earned for each year.
rev=rev*10 + (n%10); Returns the reversed MU - May 16, 10 Marks.
n=n/10; number to main().
}  Ans. :
return rev;
Program
}
#include<stdio.h>
Output #include<math.h>
main()
{
float R,P,CI;
int N;
float comp_int_calc(float,float,int);
Explanation
 User enters value for num = 687 printf("ENTER THE PRINCIPAL AMOUNT : ");
 Revrse(num) passes the control to function definition. scanf("%f",&P);
And copies value of num i.e. 687 into n. printf("ENTER THE NUMBER OF YEAR(S) : ");
Iteration 1 : Now rev=0, n=687 scanf("%d",&N);
printf("ENTER THE RATE OF INTEREST(%) : ");
while(687!=0) ) is true so
scanf("%f",&R);
rev = rev * 10 + (n%10) = 0 * 10 +(687%10) = 0+7 = 7 R=R/100;
n= n/10 = 687/10 = 68 CI=comp_int_calc(P,R,N);
Iteration 2 : Now rev=7, n=68 printf("THE CALCULATED SIMPLE INTEREST IS RUPEES
: %.2f",CI);
while(68!=0) ) is true so
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) (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;

UQ. Write a menu driven program to perform


while(choice!=5)
arithmetic operations on two integers. The menu
{
should be repeated until the user selects 'STOP'
printf("\n--------Menu---------");
option. Program should have independent user
printf("\n 1 : Addition");
defined function for each case.
printf("\n 2 : Subtraction");
MU - May 17, 10 Marks. printf("\n 3 : Multiplication");
 Ans. : printf("\n 4 : Division");
printf("\n 5 : STOP");
Program
printf("\n Select your choice : ");
#include<stdio.h> scanf("%d",&choice);
#include<conio.h> if(choice>= 1 && choice<=4)
{
int result; printf("\n Enter two numbers :" );
add(int n1,int n2) scanf("%d %d",&n1,&n2);
{ }
result = n1 + n2; switch(choice)
printf("\n Addition is %d",result); {
} case 1:
sub(int n1,int n2) add(n1,n2);
{ break;
result = n1 - n2; case 2:
printf("\n Subtraction is %d",result); sub(n1,n2);
} break;
mul(int n1,int n2) case 3:
{ mul(n1,n2);
result = n1 * n2; break;
printf("\n Multiplication is %d",result);
} case 4:
div(n1,n2);
div(int n1,int n2) break;
{

(MU-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

Fig. 4.4.1 : Types of variables

 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()

 4.4 SCOPE OF VARIABLES


printf("In main() function \n a= %d\n i=%d",a,i);
display(i);
GQ. Explain scope of variables with suitable example.
return 1;
(5 Marks) }

 Ans. : void display( int j )


Scope of variables {
int k = 35; Local variables of display()
 In C variables are used to store data. Every variable has
its scope means it can be used only by the block in
which it is declared. Other codes can’t access that printf("\nIn display() function \n a=%d\n j= %d\n k=%d",
variable. This is referred as scope and lifetime of that a,j,k);
variable in the 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) (Functions)….Page no. (4-20)

Output  It helps in code reusability.


 Reduce unnecessary calling of function.
 Through Recursion one can solve problems in easy
way while its iterative solution is very big and
complex.

 4.5.2 Disadvantages of Recursive Functions


Explanation
 In this program, a is global variable so it can be UQ. What are disadvantages of recursion?
accessed by both main() and display() functions. MU - May 17, 2 Marks.
 i is local variable of main() function so it is only
accessible by main() itself. We pass value of i to
 Ans. :
display() function. Disadvantages of recursion

 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.

 It helps to reduce the length of program. }


int fact (int 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

UQ. Write a program to display Fibonacci series using Explanation


recursion. MU - May 13, 6 Marks.
main()
OR Write a program using function to print first ‘n’ n i c
numbers in Fibonacci series.
10 0 1
MU - Dec. 14, May 17, 4 Marks. c < = n is true.
 Ans. : Program Fibbo(0)
#include <stdio.h> So prints 0. Fibbo(0)
#include<conio.h> if(0==1) true
Returns 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-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

c < = n is true. i++


Fibbo(4) Now
So prints 3. Fibbo(4) n i c
(4==0) and (4==1)both are false so 10 8 9
Else c < = n is true.
Returns Fibbo(4-1) + Fibbo(4-2) Fibbo(8)
= Fibbo(3) + Fibbo(2) i.e. 2 + 1 = 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) (Functions)….Page no. (4-23)

So prints 21. Fibbo(8) Output


(8==0) and (8==1)both are false so
Else
Returns Fibbo(8-1) + Fibbo(8-2)
= Fibbo(7) + Fibbo(6) i.e. 13 + 8 = 21
i++
Now UQ. Write a program to reverse a number using
n i c recursion. MU - May 16, 8 Marks.

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.

UQ. Write a program which will add first n natural return 0;


numbers using recursion MU - Dec. 15, 8 Marks. }

 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)

GQ. Write a program to find the GCD of a number by  Ans. : Program


using recursive function. #include <stdio.h>
 Ans. : long power (int, int);
int main()
Program
{
#include <stdio.h> int pow, num;
long result;
int calGCD(int n1, int n2) {
if (n2 != 0) printf("Enter a number: ");
return calGCD(n2, n1 % n2); scanf("%d", &num);
else printf("Enter it's power: ");
return n1; scanf("%d", &pow);
} result = power(num, pow);
int main() { printf("%d^%d is %ld", num, pow, result);
int n1, n2; return 0;
printf("Enter two positive integers: "); }
scanf("%d %d", &n1, &n2); long power (int num, int pow)
printf("G.C.D of %d and %d is %d.", n1, n2, calGCD(n1, {
n2));
if (pow)
return 0;
{
}
return (num * power(num, pow - 1));
Output }
return 1;
}
Output

y
UQ. Write a program to find x using recursion

MU - Dec. 18, 4 Marks.

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

University Prescribed New Syllabus w.e.f Academic Year 2019-2020

 Introduction to Arrays
 Declaration and initialization of one dimensional and two-dimensional arrays.
 Definition and initialization of String
 String functions

5.1 Introduction to Arrays .................................................................................................................................................... 5-3

5.1.1 Characteristics of Array .................................................................................................................................... 5-4

5.2 Declaration and Initialization of One Dimensional Arrays .............................................................................................. 5-4

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

5.3 Declaration and Initialization of Two Dimensional Arrays ............................................................................................ 5-13

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)

UQ. Write a C program to

i. Create a 2D array (Matrix) [in main function]

ii. Write a function to read 2D array (Matrix)

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

5.4 Declaration and Initialization of Multi-Dimensional Arrays .......................................................................................... 5-18

UQ. Write a program to calculate matrix multiplication and transpose for a matrix.

MU - May 13, Dec. 17, Dec. 18, 8 Marks. ..................................................................................................... 5-19

UQ. Write a program to calculate sum of list by passing array to a function.MU - May ,13, 5 Marks.................... 5-22

UQ. Write a program to validate whether accepted string is palindrome or not.

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.

MU - May 15, 5 Marks. .................................................................................................................................. 5-23

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

OR State any 4 library function in string.h along with its uses.

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

UQ. Write user defined functions to implement following string operations

(i) strcat (ii) strlen MU - May 16, Dec. 17, 10 Marks. .................................................................................... 5-29

 Chapter Ends .................................................................................................................................................... 5-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) (Arrays and Strings)….Page no. (5-3)

printf ( “\n**** Weights of children ****”);


 5.1 INTRODUCTION TO ARRAYS printf (“\n Suvrna = %d \n Chitra = %d \n Rajesh = %d
\n Pritesh = %d \n Surya = %d ", suvrna, chitra, rajesh,
GQ. Describe array ? (2 Marks) pritesh, surya ) ;
}
 Ans. :  If count of variables is small then this idea will work.
Arrays Similarly to store weight of 100, 1000, or more
 Let’s consider a situation where a program needs children, programmer should declare that much
number of similar types of data elements to be stored. number of variables which is a bad idea. Also it is
A variable is used to store one data element at a time. difficult to retrieve particular child’s weight as the
So to store multiple data elements; multiple variables programmer needs to remember all the variables.
are required. This solution has many problems : Second Scenario
o As the list of variables increases, the length of  Another idea is to use single variable to store these
program also increases. information as shown in following program.
o To manipulate those variables, several assignment void main( )
statements also needed. {
o Programmer needs to remember names of all the int weight ;
variables. weight = 25 ;
weight = 20 ;
 An alternate solution to above situation is to store
printf ( "\n weight of child = %d", weight) ;
similar type of data elements is create an array.
}
Definition
 No doubt, this program will print the most recently
 Array is a collection of elements of similar data type updated value of the variable i.e. 20. Because initially
referred by the same variable name. Contiguous the variable weight is assigned to 25; and when 20 is
memory block is allocated to all these array elements. assigned to weight, previous value of weight i.e. 25 is
 Array elements are of same data type i.e. once array is lost and new value i.e. 20 is assigned to weight. A
declared as integer, then all values which are present in situation in which more than one values needs to be
an array will be of type integer only. stored at a time, this idea will not work.

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)

 Memory arrangement after declaring one dimensional  Ans. :


array shown in Fig. 5.2.1.
Entering or Writing Data into One Dimensional Array
 We can enter data into array by array initialization or
by accepting array elements from user. We have seen
Fig. 5.2.1 how to initialize data, now we are going to study how
to accept array element from user and store it in array.
Initialization of one dimensional array
 The following code is used to accept ten elements from
Syntax user and store into one dimensional array :
 Syntax for initializing one dimensional array is given for ( i = 0 ; i <10 ; i++ )
below : {
array_name [subscript] = value; printf ( "\nEnter Percentage of student %d :\t ", i+1 ) ;
Example
scanf ( "%f", &percentage[i] ) ;
}
 Here we initialize an array to store percentage of 10
 In this example for loop is used to repeat the
students
statements 10 times.
percentage[0] = 99.07;
 printf() function is used to request user to enter the
percentage[1] = 79.47;
data.
percentage[2] = 60.60;
 scanf() function is used to accept input from user.
percentage[3] = 54.04;
 &percentage[i] tells the compiler the location where
percentage[4] = 80.60; the entered value to be stored. The value of i varies
percentage[5] = 91.70; from 0 to 9 so percentage[i] specifies the position
percentage[6] = 90.30; where the entered elements are stored in the array.

percentage[7] = 85.27; GQ. How element of 1-D array can be accessed ?


percentage[8] = 99.70; (2 Marks)
percentage[9] = 94.50;
 Ans. :
 Using the subscript we can assign value to specific
Accessing or Reading Data from an One Dimensional
array element. The order of assignment statement
Array
doesn’t matter in above example. It will form
following structure in memory.  While accessing array elements we can use loop just
like used in writing the data into array. Only difference
 Memory arrangement after declaring one dimensional
is that reading data from array doesn’t require the
array shown in Fig. 5.2.2.
scanf () function. The following code is used to access
elements of one dimensional array :
for ( i = 0 ; i <10 ; i++ )
{
printf ( "\n Percentage of student %d :\t %f", i+1,
Fig. 5.2.2 percentage[i] ) ;
}
GQ. How elements are inserted in 1D array ?
 The for loop is used to repeat the statements 10 times.
(5 Marks)
 printf() function is used to display the array elements
on screen.
 The %f specifies the compiler that the data which is
going to be accessed is of type float type.

(MU-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)

 The value of i varies from 0 to 9 so percentage[i] printf("%d\n", array[i]);


specifies which array element to be read. }
}
GQ. Write a program to accept the position from user
return 0;
and delete the element at that position from
}
array. (5 Marks)
Output
 Ans. :
Program for deleting Array elements
 The deletion of elements of array doesn’t affect array
size.
 Following program shows the example of deleting the
element at specified location in array. And also checks
whether the given position is less than the array size or
not.
#include <stdio.h>
int main()
{
int array[20], pos, i, n; GQ. Write a program to declare array to store
percentage of 10 students. Accept percentage
printf("Enter number of elements want to insert in the
array\n"); from user and print on the screen. (5 Marks)

 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

scanf("%d", &pos); int i;


Accepts the position from user to
if ( pos >= n+1 ) for deletion for ( i = 0 ; i <10 ; i++ )
{ {
printf ( "\nEnter Percentage of student %d :\t ", i+1 ) ;
printf("Deletion not possible.\n"); scanf ( "%f", &percentage[i] ) ;
} } Accepts array elements from user
Prints if the position is greater
else than the array size
{
for ( i = pos - 1 ; i < n - 1 ; i++ ) for ( i = 0 ; i <10 ; i++ )
{ {
Shifts the elements to left
array[i] = array[i+1]; from given position printf ("\n Percentage of student %d :\t %4.2f", i+1,
} percentage[i] ) ;
}
printf("After deleting element at %d location the array return 1;
is\n",pos); }
for( i = 0 ; i < n - 1 ; 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-7)

Output printf("\n smallest number in 5-element integer array


is:\t%d",min);
return 1;
}
Output

UQ. Write a program to search a number within the


array. MU - Dec.15, 10 Marks.

 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:

for(j=1;j<5;j++) Loop will continue 5 times


{
if(array[j]<min)
{
Finds smallest element and
min=array[j]; store it in min variable.
}
}

(MU-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)

GQ. Write a program to find out the largest of an int marks[20] ;


array. (5 Marks) for ( i = 0 ; i < 20 ; i++ ) Accepts marks of 20
{ students from user and
 Ans : Program printf ( "\n Enter marks " ) ;
store them in an array
marks.
#include<stdio.h> scanf ( "%d", &marks[i] ) ;
#include<conio.h> }
int main() for ( i = 0 ; i < 20 ; i++ ) Calculates the total
{ { marks of the class
int array[5]={33,30,34,31,32},j; sum = sum + marks[i] ; of 20 students
printf("\n array elements are:\t"); }
for(j=0;j<5;j++) printf ( "\n sum of marks = %d", sum ) ;
{
Calculates average marks
printf("%d\t",array[j]); avg = sum / 20 ; obtained by a class of 20 students.
}
Sets the maximum number as
int max=array[0]; the first element of array. printf ( "\n Average marks = %d", avg ) ;
}
Output
for(j=1;j<5;j++) Loop will continue 5 times.
{
if(array[j]>max)
{ Finds the largest
max=array[j]; element and store it in
} max variable.
}
printf("\n largest number in 5-element integer array is:\t%d”,
max);

return 1;
}
Output

GQ. Write a program to find sum and average marks


obtained by a class of 20 students in a test.

(5 Marks)

 Ans : Program
#include<stdio.h>
#include<conio.h> GQ. Write a program to find out number of positive,

int main( ) negative and zero elements from an array.


{ (5 Marks)
int avg, sum = 0 ;
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) (Arrays and Strings)….Page no. (5-9)

 Ans. : Program GQ. Write a program to accept values for 2 integer

# include<stdio.h> arrays and add and multiply them and print the

int main() result of addition and multiplication. (5 Marks)


{  Ans : Program
int numbers[5];
# include<stdio.h>
int i=0,cnt_pos=0,cnt_neg=0,cnt_zero=0;
main()
cnt_pos, cnt_neg, cnt_zero are used to count number of negative {
values, zero values, and positive values in the array. int array1[5], array2[5], array3[5];
int i=0;
printf("\n Enter elements for first array");
for(i=0;i<5;i++) Condition to check for
negative number
{
for(i=0;i<5;i++)
printf("\n Enter a number:"); Accepts
{ elements
scanf("%d", &numbers[i]); for 1st
printf("\nEnter number for array1[%d]:",i);
if (numbers[i]<0) array.
scanf("%d",&array1[i]);
{
cnt_neg++; }
} printf("\n Enter elements for second array");
if (numbers[i]==0) Condition to check for zero
{ for(i=0;i<5;i++)
Accepts
cnt_zero++; Condition to check for { elements
nd
} positive number printf("\nEnter number for array1[%d]:",i); for 2
array.
if (numbers[i]>0) scanf("%d",&array2[i]);
{ }
cnt_pos++; printf("\n addition of array1 and array2");
}
} for(i=0;i<5;i++)
printf("\n Number of positive numbers= %d",cnt_pos);
{
printf("\n Number of zeros=%d", cnt_zero);
array3[i]=array1[i]+array2[i];
printf("\n Number of negative numbers= %d", cnt_neg);
printf("\n array1[%d]+array2[%d]=array3[%d]=%d",
return 1; i,i,i, array3[i]);
} } Adds both arrays and store result in an array.
Output

printf("\n multiplication of array1 and array2");


for(i=0;i<5;i++)
{
array3[i]=array1[i]*array2[i];
printf("\n array1[%d] * array2[%d] = array3[%d]=%d",
i,i,i, array3[i]);
}
Multiplies both arrays and store result in an 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-10)

Output printf("\n subtraction of array1 and array2");


for(i=0;i<5;i++)
{
array3[i]=array1[i]-array2[i];
printf("\n array1[%d]-array2[%d]=array3[%d]=%d",
i,i,i, array3[i]);
} Subtract both arrays and store result in an array.

printf("\n division of array1 and array2");


for(i=0;i<5;i++)
{
array3[i]=array1[i]/array2[i];
printf("\n array1[%d] / array2[%d] = array3[%d]=%d",
i,i,i, array3[i]);
}
Divides both arrays and store result in an array.

}
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)

GQ. Write a program to find largest number in }


th
5-element integer array. (5 Marks) for(i=0;i<9;i++) Used to compare i element
with all the remaining elements
{ in the array.
 Ans. : Program for(j=i+1;j<10;j++)
#include<stdio.h> {
#include<conio.h> if(array[j]<array[i]) Compare array[i] with array[j]
int main()
{ {
int array[5]={33,30,34,31,32},j; If condition satisfies
printf("\n array elements are:\t"); temp=array[i]; Swap the array[i] and
array[j].
for(j=0;j<5;j++) array[i]=array[j];
{ array[j]=temp;
printf("%d\t",array[j]); }
} Sets the maximum number as }
int max=array[0]; the first element of array. }
printf("\n ascending ordered array :\n");
for(j=1;j<5;j++) Loop will continue 5 times. for(i=0;i<10;i++)
{ {
Prints the sorted array in
if(array[j]>max) printf("%d\t",array[i]); ascending order.
{ Finds the largest }
max=array[j]; element and store it in return 1;
} max variable. }
}
Output
printf("\n largest number in 5-element integer array is:\t%d”,
max);
return 1;
}
Output

UQ. Write a program to sort given numbers in


ascending order.
UQ. Write a program to sort list elements in
MU - May 14, Dec. 17, 10 Marks.
descending order. MU - May 13,8 Marks.
 Ans. : Program
OR Write a program to sort given nos in descending
#include<stdio.h> order. MU - Dec. 13, 10 Marks.
#include<conio.h>
int main()  Ans. : Program

{ #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++;
} }
}

printf("\nThe elements of OAR are : ");


for (i = 0; i < k; i++)
{
printf("%d ", OAR[i]);
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
printf("\nThe elements of EAR are : ");
numbers and C contains Even numbers. i.e. if
for (i = 0; i < j; i++)
ARRAY A contains A={3,2,4,2,5,7,8} then
{
B={3,5,7} and C={2,4,2,8}.
printf("%d ", EAR[i]);
MU - May 16, 10 Marks. }
}
 Ans. :
Output
Program
#include <stdio.h>
void main()
{

long int ARR[10], OAR[10], EAR[10];


int i, j = 0, k = 0, 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) (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

Syntax Fig. 5.3.3


Syntax for declaring two dimensional array is given below :
data_type array_name [ row size ][ column size ];  In memory initialized values are stored in sequential
row as shown in Fig. 5.3.4.
Example
matrix[0][0] 7 3000
 Declare an array to store a 2 × 2 matrix
matrix[0][1] 6 3004
int matrix[2][2];
matrix[1][0] 5 3008
The 2 × 2 matrix stores 2*2=4 values. In our example
matrix[1][1] 9 3012
data type of array is integer means the four values are
of int type. Fig. 5.3.4
 In user’s view the matrix looks like:
GQ. How to add elements in 2D array (5 Marks)

 Ans. :
Entering or Writing Data into Two Dimensional Arrays

Fig. 5.3.1  We can enter data in array by array initialization or by


accepting array elements from user.
 But in memory it will form different structure.
 We have seen how to initialize data, now we are going
 Memory arrangement after declaring two dimensional to study how to accept array elements from user and
array shown in Fig. 5.3.2. store into 2D array.
matrix[0][0] 3000  The following code is used to accept values for 2 × 2
matrix[0][1] 3004 matrix from user and store into 2D array.
matrix[1][0] 3008 printf ( "\nEnter data for 2D matrix\n” );
matrix[1][1] 3012 for ( i = 0 ; i <2 ; i++ ) Outer for loop
{
Fig. 5.3.2 for ( j = 0 ; j <2 ; j++ ) Inner for loop
Initialization of two dimensional array {
printf ( "\n matrix [%d] [%d] :\t ", i, j ) ;
Syntax
scanf ( "%d", &matrix[i][j] ) ;
 Syntax for initializing 2D array is given below: }
array_name [row_number] [column_number] = 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) (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.

GQ. How element of 2-D array can be accessed ?


printf(“\nThe matrix is:\n”);
(2 Marks)
for ( i = 0 ; i <2 ; i++ )
 Ans. : {
Prints 2D
Accessing or Reading Data from Two Dimensional Array for ( j = 0 ; j <2 ; j++ )
array
{ elements
 As we use two for loops for writing the data into 2D
printf ( " %d ", matrix[i][j] ) ;
array, likewise we can use two for loops to read the
}
data from 2D array.
printf(“\n”);
 Only difference is that in reading data from array }
doesn’t require the scanf () function. The following return 1;
code is used to access elements of two dimensional }
array :
Output
printf(“\nThe matrix is:\n”);
for ( i = 0 ; i <2 ; i++ )
{
for ( j = 0 ; j <2 ; j++ )
{
printf ( " %d ", matrix[i][j] ) ;
}
printf(“\n”);
}

GQ. Write a program to accept values for 2 × 2 matrix


and print them. (5 Marks)

 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.

int main()  Ans. :


# include<stdio.h>
{
int main()
int matrix[2][2],i,j;
{
int matrix[2][2],i=0,j=0;
printf ( "\nEnter data for 2D matrix\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) (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);

scanf("%d", & matrix2[i][j]);


Accepts element of 2nd matrix from user and store it in
matrix2.

}
}
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)

{ UQ. Write a C program to


for(j=0;j<2;j++) i. Create a 2D array (Matrix) [in main function]
{ ii. Write a function to read 2D array (Matrix)
matrix3[i][j]=matrix1[i][j] - matrix2[i][j]; iii. Write a function that will return true (1) if
entered matrix is symmetric or false (0) is not
Subtracts the second matrix from first matrix and stores
symmetric.
result in third matrix and display it.
iv. Print whether entered matrix is symmetric or
not [ in main function ]
MU - May 18, 10 Marks.
printf("%d\t",matrix3[i][j]);
}  Ans. : Program
printf("\n\t\t"); #include<stdio.h>
#include<conio.h>
}
void accept(int a[10][10], int rows, int cols)
printf("\n division of two 2 X 2 matrix is:\n\t\t"); {
for (i=0;i<2;i++) int i,j;
for(i=0;i<=rows-1;i++)
{
{
for(j=0;j<2;j++) printf("Enter elements : ");
{ for(j=0;j<=cols-1;j++)
matrix3[i][j]=matrix1[i][j] / matrix2[i][j]; {
scanf("%d",&a[i][j]);
printf("%d\t",matrix3[i][j]);
}
} Divides the second matrix from first }
printf("\n\t\t"); matrix and stores result in third
}
} matrix and display it.
int is_symmetric(int a[10][10],int rows,int cols)
{
}
int i,j;
Output if(rows!=cols) return 0;
for(i=0;i<=rows-1;i++)
{
for(j=0;j<=cols-1;j++)
{
if(a[i][j]!=a[j][i]) return 0;
}
}
return 1;
}
main()
{
int a[10][10],rows,cols,r;

printf("Enter the number of rows and columns : ");


scanf("%d %d",&rows,&cols);
accept(a,rows,cols);
r = is_symmetric(a,rows,cols);

(MU-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

Output Array[0][0][1] 1004


Array[0][1][0] 1008
Array[0][1][1] 1012
Array[1][0][0] 1016
Array[1][0][1] 1020
Array[1][1][0] 1024
 5.4 DECLARATION AND Array[1][1][1] 1028
INITIALIZATION OF
Initialization of multidimensional array
MULTI-DIMENSIONAL ARRAYS
Syntax
GQ. Write syntax to declare and initialize 3D arrays.  Syntax for initializing multidimensional array is given
(5 Marks) below.
array_name [row_number] [row_number] [column_number] =
 Ans. : Multi-dimensional Arrays value;
 An array with more than two subscripts is called as Example
multidimensional array.
 Initialize the multidimensional array
Declaration of multidimensional array
array[0][1][1]= 9;
 For simplicity we will study 3D array which has 3
array[0][0][0]= 7;
subscripts.
array[0][0][1]= 6;
Syntax
array[0][1][0]= 5;
 Syntax for declaring multidimensional array is given
array[1][0][0]= 2;
below :
data_type array_name [size1][size2][size3]; array[1][1][1]= 3;
array[1][0][1]= 4;
Example
array[1][1][0]= 8;
 Declare an multidimensional array
 Using the subscript we can assign value to specific
int array[2][2][2];
array element. The order of assignment statement
 This array stores 2*2*2 =8 values. In this example data doesn’t matter in above example. It will assign the
type of array is integer means the values should be of values given Bellow Fig. 5.4.2.
int type.
 In user’s view the multidimensional array looks like :

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)

 In memory initialized values are stored in sequential for(j=0; j<3; j++)


row by row manner as shown in Fig. 5.4.3. {
sum=0;
Array[0][0][0] 7 1000
for(k=0; k<3; k++)
Array[0][0][1] 6 1004 {
sum = sum + mat1[i][k] * mat2[k][j];
Array[0][1][0] 5 1008
}
Array[0][1][1] 9 1012 mat3[i][j] = sum;
}
Array[1][0][0] 2 1016
}
Array[1][0][1] 4 1020 printf("\nMultiplication of two Matrices : \n");
for(i=0; i<3; i++)
Array[1][1][0] 8 1024
{
Array[1][1][1] 3 1028 for(j=0; j<3; j++)
Fig. 5.4.3 {
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;
{ for (i=0;i<3;i++)
scanf("%d",&mat2[i][j]);
} {
} for(j=0;j<3;j++)
printf("Multiplying two matrices...\n"); {
for(i=0; i<3; i++) printf("Enter matrix[%d][%d] element ",i, 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) (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”);
}

GQ. Write a program to accept values for 3D array


and print them. (5 Marks)

 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)

 And for displaying entered character array as output


following code will be used:
printf ( "\nEntered array is:”);
for (i = 0 ; i < 10 ; i++)
{
printf ("%c", array[i]) ;
Fig 5.5.1 }
Initializing String GQ. Write a program to declare a character array to
 Syntax for initializing a string is given below: accept and store 10 characters and print it.
str1[subscript] = value; (5 Marks)
 For example: Initialize an array to store “Hello” word.
str1[0] = ‘H’;
 Ans. :
str1[1] = ‘e’; Program

str1[2] = ‘l’; #include <conio.h>


str1[3] = ‘l’; #include <stdio.h>
str1[4] = ’o’; int main()
{
str1[5] = ‘\0’
char array[10]; Array declaration
 It will form following structure in memory.
int i;
 Memory arrangement after declaring string is shown in printf ( "\nEnter 10 characters:\t " ) ;
Fig. 5.5.2 for ( i = 0 ; i <10 ; i++ )
Accepting array
{ elements from
scanf ( "%c", &array[i] ) ; user
}
printf ( "\nEntered array is:”);
for ( i = 0 ; i < 10 ; i++ )
{
printf ( "%c", array[i] ) ;
}
Fig. 5.5.2
return 1;
GQ. How to display string? (2 Marks) }
 Ans. : Output

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)

 Ans. : Loop will continue until i become


while(i<len/2) half of the length of str array.
Program
{
cal(int arr1[])
{ if(str[i]!=str[len-i-1])
int sum,i; {
sum = 0; flag=1; If condition satisfies the flag is set to 1
for(i=0;i<5;i++) break;
{ }
sum = sum + arr1[i];
i++;
}
}
printf("\nSum of array elements : %d",sum);
} if(flag==0)
main() Prints if initial
{ printf("\n String is palindrome"); value of flag is
not changed.
int arr[5], i;
printf("\nEnter 5 els : "); else
for(i=0;i<5;i++)
scanf("%d",&arr[i]); Prints if initial
printf("\n String is not palindrome");
cal(arr); value of flag is
} getch(); changed.
}
Output
Output

UQ. Write a program to find reverse of given string


without using string library function.
UQ. Write a program to validate whether accepted
string is palindrome or not. MU - May 15, 5 Marks.

MU - May 13, 5 Marks, Dec. 13,  Ans. :


May 14, Dec. 18, 10 Marks.
Program
 Ans. : Program int main()
# include<stdio.h> {
#include<string.h> char s[1000], r[1000];
int main() int begin, end, count = 0;
{
int len=0, i=0; printf("Input a string\n");
char str[10]; gets(s);
int flag=0;
printf("Enter string : "); // Calculating string length
Accept string from user and store
scanf("%s", str); it in a character array str. while (s[count] != '\0')
len = strlen(str);
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) (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

5.6 String Functions

UQ. Explain any three string standard library


functions. MU - May 13, 3 Marks.
UQ. Implements string copy function STRCOPY (str1,
str2) that copies a string str1 (source) to another OR State any 4 library function in string.h along with
string str2 (destination) without using library its uses.
function. MU - May 18, 5 Marks.
MU - Dec. 13, Dec. 15,May 17,
 Ans. : Dec. 17, Dec. 18, 5 Marks.

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);

Second call to strcat() appends “Ritchie” to int main(void)


“Dennis “ and stores result back in string1. {
char string[15];
printf("\nfirst + second :\t %s\n", string1);
int pos;
return 0;
}
char ch = 'o';
Output printf("Enter a string: \t");
gets(string);
if (strchr(string, ch))
printf("The character %c is at position: %d\n",
ch, strchr(string, ch)-string+1);

Explanation Prints position of found character in string.

 strcat(string1,string3) joins string3 to the end of else


string1 and stores combined string in string1.
 So now string1 will be “Dennis “ printf("The character was not found\n");
return 0;
 strcat(string1,string2) joins string2 to the end of
}
string1 and stores combined string in string1.

(MU-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 }

 The function call strcpy(dest_string, src_string will Output


copy C Programming into dest_string

UQ. Write a user defined function to copy one string


to another. MU - Dec. 14, 5 Marks.

 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)

Iteration3 : Now i=2,l2=4 {


char string1[] = "pens", string2[] = "pen";
So i<l2 i.e. 2<4 is true so
int d;
S1[2]=s2[2]=”n”
i++ d = strcmp(string2, string1);
Iteration4 : Now i=3,l2=4 if(d<0)
So i<l2 i.e. 3<4 is true so {

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)

Syntax of calling strlwr() function Syntax of calling strlwr() function

Char *lowerstring = strlwr(str1 ); Char *lowerstring = strupr(str1 );


strlwr() returns the string in lowercase  strupr() returns the string in uppercase

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)

} /* This loop would concatenate the string str2 at


* the end of str1
void getstrlen() */
{ for(j=0; str2[j]!='\0'; ++j, ++i)
char s1[20]; {
int i = 0; str1[i]=str2[j];
printf("\n\nEnter a string : "); }
gets(s1); // \0 represents end of string
while(s1[i]!='\0') str1[i]='\0';
{ printf("\nOutput: %s",str1);
i++; }
} Output
printf("\nLength of %s is %d",s1,i);
}

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

University Prescribed New Syllabus w.e.f Academic Year 2019-2020

 Concept of Structure and Union


 Declaration and Initialization of structure and union
 Nested structures
 Array of Structures
 Passing structure to functions

6.1 Concept of Structure...................................................................................................................................................... 6-3

UQ. Explain structures in C ? MU - May 16, 2 Marks. ........................................................................................... 6-3

OR What are structures? MU - May 17, 2 Marks. ................................................................................................ 6-3

6.2 Declaration and Initialization of Structure ...................................................................................................................... 6-4

UQ. What do you mean by struct ? MU - May 13, 2 Marks. ................................................................................... 6-4

6.3 Nested Structures .......................................................................................................................................................... 6-5

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

OR Comment on nested structures.MU - May 17, 2 Marks. .................................................................................. 6-5

6.4 Array of Structures / Array of Structure Variables .......................................................................................................... 6-7

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)

UQ Define a structure cricket which consist following 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. MU - May 15, 6 Marks.................................................................................... 6-9

6.5 Difference between Array and Structure ........................................................................................................................ 6-9

6.5.1 More Programs on Structure .......................................................................................................................... 6-10

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

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. ................................................................................. 6-11

UQ. Define a structure consisting of following elements.

(1) Student roll_no (2) Student name (3) student percentage

Write a program to read records of 5 students and display same. MU - Dec. 18, 10 Marks. ....................... 6-12

6.6 Passing Structure to Function...................................................................................................................................... 6-12

6.6.1 Passing Structure by Value ............................................................................................................................ 6-13

6.6.2 More Examples on Structure.......................................................................................................................... 6-13

6.7 Concept of Union : Declaration and initialization of Union ........................................................................................... 6-15

UQ. Define union. MU - Dec. 17, 2 Marks. .......................................................................................................... 6-15

6.7.1 Difference between Structure and Union ...................................................................................................... 6-16

UQ. Differentiate between structure and union. MU - May 17, May 18, 4 Marks. ................................................ 6-16

OR Compare structure and union.MU - Dec. 17, 2 Marks. .................................................................................. 6-16

UQ. When is union preferred over struct ? MU - May 18, 1 Mark. ........................................................................ 6-17

 Chapter Ends .................................................................................................................................................... 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)

 The program becomes more difficult to handle as the Example of structure


number of arrays go on increasing. To solve this struct student
problem, C provides a special data type called {
structure. int roll_no;
Second approach char name[25];
float percentage;
 Structure is user defined data type which holds
};
elements of dissimilar data types together.
 All the elements in the structure are known as structure  Student is the name of structure.
members. To access these structure members outside  The variables roll_no, name and percentage are
the structure, structure variables are used. structure members.
 This approach works properly and used to keep records  Only declaration of these variables is done in structure
of entities like : declaration.
 Employee, student, date, product, etc. Initializing Structure Members
 The program of structure has two main parts.  We can initialize the members of structure by
1. Declaration of structure accessing them.
2. Accessing members of structure  To access these variables in program we have to
declare a variable of this structure type.
 6.2 DECLARATION AND  This can be declared as below :
INITIALIZATION OF STRUCTURE struct student
{
GQ. Explain with example how to declare a structure int roll_no;
and how to initialize it. (5 Marks) char name[25];
float percentage;
UQ. What do you mean by struct ?
}s;
MU - May 13, 2 Marks. OR
struct student s;
 Ans.
s is structure variable which is used to access Structure
Declaration and initialization of structure
members. The data type of s is student.
Syntax of the structure declaration
 Following form is used to access and initialize the
struct structure_name structure members :
{
struct_variable.member-name
data_type1 variable_name1;
 Example of initializing structure members :
data_type2 variable_name2;
…. s.roll_no = 1;
}; s.name = “Neelam”;
s.percantage = 97.60;
 Where struct is the keyword used to declare the
GQ. Write a program to declare structure book having
structures.
data member as book_name, book pages,
 Structure_name is an identifier which is formed by book_price. Accept this data for 3 books and
using letters, digits and underscore. display it. (5 Marks)

 The structure body is indicated by { and } brackets.  Ans. : Program


 Structure body contains number of variables. #include <stdio.h>
 Semicolon (;) indicates end of structure definition. #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) (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.

OR What do you mean by nested structures ?


MU - May 16, 2 Marks.

OR Comment on nested structures.


MU - May 17, 2 Marks.

 Ans. : Nested Structures


 A structure can be declared within another structure
known as nested structure.
structure tagname_1
{
member1;
member2;
member3;
...
membern;
structure tagname_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) (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

MU - May 18, 5 Marks. #include <stdio.h>


#include <string.h>
 Ans. :
int main( )
Array of Structures / Array of Structure Variables
{
 Consider a situation where details of 5 books need to int i;
stored. In such situation declaring 5 structure variables struct employee
is not good idea so we can create array of structure {
variables : char name[10] ; Structure definition
struct student char street[20] ;
{ char city[20] ;
int roll_no; };
char name[25]; struct employee emp[3]; Declaring array of structure.
float percentage;
}s[5];
printf ( "\nEnter details of employees\n" ) ;
 s[5] will hold details of 5 books, each record contains for(i=0;i<3;i++)
roll_no, name and percentage as given in Fig. 6.4.1.
{
printf ("\nname :\t");
scanf("%s", emp[i].name); Accepts details of 3
printf("\nstreet:\t"); employees using
array of structure.
scanf("%s",emp[i].street);
printf("\ncity:\t");
scanf("%s", emp[i].city );
}
printf ( "\n\n\tEmployee detail:\n" ) ;
printf(“\n Name \tStreet \tCity\n”);
for(i=0;i<3;i++)
{
printf ("\n%s \t %s \t %s",emp[i].name,emp[i].street,
emp[i].city );
}
Prints details of three employees

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)

Output printf ("\n Enter name,cost and quantity :");


scanf("%s %d %d",&s[i].name,&s[i].cost,&s[i].qty);
}
Accepts details of stationary and store it in
structure using array of structure.

printf ( "\n\n\tStationary detail:\n" ) ;


printf ("\n\n Name \tCost \tQantity :");
for(i=0;i<5;i++)
{
printf("\n%s \t%d \t%d",s[i].name,s[i].cost,s[i].qty);
}
Prints details stored in structure using
array of structure.
getch();
}
Output :

GQ. Write a program to declare a structure stationery


having data member, name quantity and cost.
Accept and display this information for five
items. (5 Marks)

 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

UQ Define a structure cricket which consist following


members
(i) player name (ii) country name
 6.5 DIFFERENCE BETWEEN ARRAY AND

(iii) batting average


STRUCTURE
Input 20 player information of test playing
county. Write a program which will display detail GQ. State the difference between array and structure.
information of player with given player name.
(5 Marks)
MU - May 15, 6 Marks.
 Ans :
 Ans. :
Difference between array and structure
Program
Parameters Array Structure
#include<conio.h>
Type of Array is Structure is
#include<stdio.h>
elements collection of same collection of
struct cricket type of data different types of
{ elements. data elements
char player_name[20], country_name[20]; Simplicity Arrays are simple Structures are
float batting_average; to store values complicated as
and access compare to array.
}; elements.
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) (Structure and Union)….Page no. (6-10)

Parameters Array Structure printf("%s\t%s\t%.2f\n",c1[i].emp_name,c1[i].DOJ,c1[i].s


al);
Memory Array elements Structure elements }
allocation are stored are also stored in a
continuously in continuous manner
}
the memory one with different bytes
after other. required for every Output
element.
Declaration Array declaration Structure needs
does not need any "struct" keyword
specific keyword while declaration.
except data type.

 6.5.1 More Programs on Structure

UQ. A company needs to maintain data about their


employees. Details to be maintained are UQ. Write a program to read Title, Author and Price
Employee name, Department, Date of joining, of 10 books using array of structures. Display the
Salary. Write a program which will store these records in ascending order of Price.
details and list the employees whose salary is
MU - May 17, 6 Marks.
greater than Rs. 50000.00.

MU - May 16 6 Marks.  Ans. :


Program
 Ans. :
#include<conio.h>
Program
#include<stdio.h>
#include<conio.h>
struct book
#include<stdio.h>
{
struct company
char title[20], author[20];
{
float price;
char emp_name[20], DOJ[20];
float sal; };
}; int main ()
int main () {
{ struct book c1[10],temp;
struct company c1[5]; int i,j,n;
int i; n = 10;
for(i=0;i<5;i++) for(i=0;i<10;i++)
{ {
printf("Enter the emp_name, date of joing and salary : printf("Enter title, author and price : ");
");
scanf("%s %s %f",c1[i].title,c1[i].author, &c1[i].price);
scanf("%s %s %f",c1[i].emp_name,c1[i].DOJ, &c1[i].sal);
}
}
printf("\nDetails of employess with salary > 50000 : : \n");
for(i=0;i<5;i++) for(i=0;i<=n-1;i++)
{ {
if(c1[i].sal > 50000) for(j=0;j<=n-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) (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)

UQ. Define a structure consisting of following


elements.
 6.6 PASSING STRUCTURE TO FUNCTION

(1) Student roll_no (2) Student name


GQ. Write note on Structure with function. (5 Marks)
(3) student percentage
Write a program to read records of 5 students  Ans. :
and display same. MU - Dec. 18, 10 Marks.
Structure with function
 Ans. : Program  Same as of all other types, it is possible to pass
#include<stdio.h> structures as arguments to a function. It is possible to
main() pass individual members, structure variables, a pointer
{ to structures etc to the function.
struct student
 Further, functions can return either an individual
{
member or structures variable or pointer to the
int rno;
structure.
float per;
char name[20];  We will see how to pass individual structure members
}s[5]; as arguments to a function.
int i;  Passing Structure Members as arguments to Function
 We can pass individual members to a function just like
for(i=0;i<5;i++) ordinary variables.
{
 The given example demonstrates the way to pass
printf("\n Enter name, rollno and percentage : ");
structure members as arguments to the function.
scanf("%s %d %f",&s[i].name, &s[i].rno,&s[i].per);
#include<stdio.h>
}
/*
printf("\n Name \t Rno \t Percentage");
structure is defined above all functions so it is global.
for(i=0;i<5;i++)
*/
{
struct student
printf("\n %s \t %d \t %.2f",s[i].name,s[i].rno,s[i].per);
{
}
char Stud_name[20];
int Stud_roll_no;
int Stud_marks;
}
};
Output void print_struct(char sname[], int sroll_no, int smarks);
main()
{
struct student stu = {"Kunal", 1, 98};
print_struct(stu.Stud_name, stu.Stud_roll_no,
stu.Stud_marks);
getch();
}
void print_struct(char sname[], int sroll_no, int smarks)
{
printf("\n Student Name: \t\t %s", sname);
printf("\n Student Roll no: \t %d", sroll_no);
printf("\n Student Marks: \t %d", smarks);
}

(MU-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)

Output printf("\n Student Name: \t\t %s", s.Stu_name);


printf("\n Student Roll no: \t %d", s.Stu_roll_no);
printf("\n Student Marks: \t %d", s.Stu_marks);

printf("\n");
}
Output
 6.6.1 Passing Structure by Value

GQ. Explain concept of passing structure by value


with suitable example? (5 Marks)

 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)

printf ( "\t2.\n\tname: \t%s \n\tprice: \t%d \n\tno. of pages: {


\t%d\n", b2.name[1], b2.price, b2.pages ); printf("\n Enter name, DOB and salary of emplyee : ");
printf ( "\t3.\n\tname: \t%s \n\tprice: \t%d \n\tno. of pages: scanf("%s %s %d",&p[i].pname,&p[i].dob,&p[i].sal);
\t%d\n", b3.name[2], b3.price, b3.pages ); }
return 1;
} printf("\n\n Name \t DOB \t\t Salary");
for(i=0;i<5;i++)
Output
{
printf("\n %s \t %s \t %d",p[i].pname,p[i].dob,p[i].sal);
}

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;

int i; printf("\n Enter hour : ");


scanf("%d",&t.hour);
for(i=0;i<5;i++) printf("\n Enter minute : ");

(MU-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

GQ. Design a structure student_record to contain


name, branch and total marks obtained. Develop
a program to read data for 10 students in a class
and print them. (5 Marks)

 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

int i; GQ. Explain : Union in C. (5 Marks)

UQ. Define union. MU - Dec. 17, 2 Marks.


for(i=0;i<10;i++)
{  Ans. : Union
printf("\n Enter name, Branch and total marks : ");  C Union is also like structure, i.e. collection of
scanf("%s %s different data types which are grouped together. Each
%d",&p[i].name,&p[i].branch,&p[i].total); element in a union is called member.
}
 Union and structure in C are same in concepts, except
allocating memory for their members.
printf("\n\n Name \t Branch \t Total 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-16)

 Structure allocates storage space for all its members


separately whereas, Union allocates one common printf("Union record1 values example\n");
storage space for all its members. printf(" Name : %s \n", record1.name);
 We can access only one member of union at a time. printf(" Subject : %s \n", record1.subject);
We can’t access all member values at the same time in
printf(" Percentage : %f \n\n", record1.percentage);
union.
 Below syntax illustrates how to declare a union,
// assigning values to record2 union variable
initialize it and access the members of the union.
printf("Union record2 values example\n");
Syntax
strcpy(record2.name, "Mani");
union tag_name
printf(" Name : %s \n", record2.name);
{
data type var_name1;
data type var_name2; strcpy(record2.subject, "Physics");
data type var_name3; printf(" Subject : %s \n", record2.subject);
};
Example record2.percentage = 99.50;
union student printf(" Percentage : %f \n", record2.percentage);
{ return 0;
int mark; }
char name[10];
Output
float average;
};
Program on Union

#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

union student record1; UQ. Differentiate between structure and union.


union student record2;
MU - May 17, May 18, 4 Marks.

OR Compare structure and union.


// assigning values to record1 union variable
strcpy(record1.name, "Raju"); MU - Dec. 17, 2 Marks.

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)

 Ans. Parameter STRUCTURE UNION


Difference between Structure and Union Memory Structures will
Union will occupy less
Occupied occupy more
Parameter STRUCTURE UNION memory space. memory space
compared to structure.
Keyword Struct keyword is
Union keyword is used
used to declare the
to declare the Union Member It allows us to
structure It allows us to access
Access access any or all
only one union
Memory Structure variable the members at
Union variable will member at a time.
Allocation will allocate any time.
allocate common
memory for all the
memory for all the UQ. When is union preferred over struct ?
structure members
union members.
separately.
MU - May 18, 1 Mark.
Example: struct Employee union Employee
 When there is need to store value in a single member at
{ {
a time, then union is preferred over struct.
int age; int age;
char name[50]; char name[50];
float salary; float salary;
}; };

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

University Prescribed New Syllabus w.e.f Academic Year 2019-2020

 Fundamentals of pointers
 Declaration, initialization and dereferencing of pointers
 Operations on Pointers
 Concept of dynamic memory allocation

7.1 Fundamentals of Pointers .............................................................................................................................................. 7-3

UQ. Define pointer and its use.MU - Dec. 17, 2 Marks. .......................................................................................... 7-3

OR What is a pointer? MU - Dec. 18, 2 Marks...................................................................................................... 7-3

7.1.1 Declaration of Pointer ...................................................................................................................................... 7-4

UQ. Explain how the pointer variable declared and initialized. MU - Dec. 18, 2 Marks. ........................................ 7-4

7.1.2 Initialization of Pointer ..................................................................................................................................... 7-4

7.1.3 Dereferencing Pointer ...................................................................................................................................... 7-5

UQ. Explain reference and de-reference operators with example. MU - May 13, 3 Marks. .................................. 7-5

7.2 Operations on Pointers .................................................................................................................................................. 7-8

7.3 Use of Pointer in Array ................................................................................................................................................ 7-13

7.4 Array of Pointers .......................................................................................................................................................... 7-24

UQ. Explain array of pointers with example. MU - Dec. 17, 4 Marks. ................................................................... 7-24

7.5 Passing Array to Function ........................................................................................................................................... 7-26

7.5.1 Parameters in Function Call ........................................................................................................................... 7-27

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.

MU - Dec. 13, 10 Marks. .............................................................................................................................. 7-27

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

7.5.1(A) Call by Value .................................................................................................................................................. 7-28

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(B) Call by Reference .......................................................................................................................................... 7-29

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.5.2 Function Pointer ............................................................................................................................................. 7-33

7.6 Concept of Dynamic Memory Allocation ...................................................................................................................... 7-34

UQ Comment on dynamic memory allocation MU - May 17, 4 Marks. ................................................................ 7-34

7.6.1 Difference between Static and Dynamic Memory Allocation .......................................................................... 7-35

7.6.2 Functions for Dynamic Memory Allocation ..................................................................................................... 7-35

 Chapter Ends .................................................................................................................................................... 7-39

(MU-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)

program ends its execution. Next time the 5 might be


 7.1 FUNDAMENTALS OF POINTERS stored at another location. To know the location where
5 is stored &n is used. The “address of” (&) symbol
GQ. Explain the concept of address. (5 Marks) gives the address of variable.
Ans. : Address  To access the value 5, we can use variable name or the
 Memory is collection of contiguous cells and each cell memory address as follows :
has a number called as address of the cell. The int main( )
numbers are from zero to the memory size, usually last {
address is 65,635 for size of 64K. A 64K Computer int n = 5 ;
Memory is organized as shown in Fig. 7.1.1. printf ("\n Accessing value of n using its address :n= %d",
*(&n)) ;
printf ("\n Accessing value of n using its name : n= %d", n) ;
return 1;
}
Output

 Here to indicate the value stored at specific address


*(&n) is used. “point to”(*) operator is used to
indicate the value stored at memory address given by
&n.
Fig. 7.1.1  C provides the ability to store the memory address of a
variable into another variable and store it in memory.
 When a variable is declared, it is stored somewhere in
memory. Consider following declaration, UQ. Define pointer and its use.
int n = 5 ; MU - Dec. 17, 2 Marks.
 This statement instructs the C compiler to :
OR What is a pointer? MU - Dec. 18, 2 Marks.
1. Find a location in the memory to store an integer
Ans. : Pointer
number.
2. Assign n as the name of this location.  Pointer is a variable which is used to store memory
address of another variable.
3. Put 5 in that memory location.
 Pointer in C is a user defined data type. It is build by
 Memory map for this declaration is as shown in
using primary data types. Variables hold values and
Fig. 7.1.2.
pointers hold their memory addresses where these
variables are located in memory.
 A pointer variable is therefore nothing but, a variable
that holds address of another variable in memory.
Fig. 7.1.2
Memory address is a positive number so its type is
 Here the computer has selected 2000 as memory unsigned integer. Since pointer is a variable it is also
location to store the value of n i.e. 5. So the location stored at some location in memory and the values
number 2000 is referred as memory address of n. This stored in it are of unsigned integer type.
memory location is reserved to store value 5 until 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) (Pointers)….Page no. (7-4)

 The values whose addresses are stored in a pointer Example of character


variable can be of type char, int, float, double, etc.
 Other examples of pointers are as follow.
 7.1.1 Declaration of Pointer char *cptr;
float *fptr;
UQ. Explain how the pointer variable declared and  Here char *ptr specifies that cptr points to character
initialized. MU - Dec. 18, 2 Marks. type of value. This cptr pointer will be stored at a
specific memory location.
Ans. :
float *fptr;
Declaration of Pointer
 This pointer will going to point a float value and will
 Same as of variable, to use pointer in program it should be stored at a specific memory location.
be declared and initialized first.
 In the program pointers are declared at same location  7.1.2 Initialization of Pointer
where we declare variables i.e. in declaration section.
GQ. How to initialize pointer? Explain in brief.
Declaring a pointer is somewhat similar to declaring a
variable. (5 Marks)
 To indicate which type of value is stored in a variable Ans. :
we use data type while declaring a variable. e.g to hold
Initializing pointer
integer type of value the data type of variable should
be integer, to hold a character the data type of variable  After declaring the pointer, the next step is to assign
should be char and to hold real number the data type of the address of certain variable to it. This is called as
variable should be float or double. pointer initialization. It connects variables and
pointers.
 Similarly while declaring a pointer; we should know
the data type of the value to which it is going to point, Syntax
so that we can declare a pointer of that data type. This  Syntax for initializing a pointer.
means suppose a pointer stores address of a variable of pointer_name = &variable_name;
type integer then we declare pointer as integer.
 Here the unary operator “address of” (& (called as
Syntax ampersand)) is used to find out memory location of a
 The syntax of pointer declaration is as follows. variable. variable_name is the name of that variable to
data_type *pointer_name; which the pointer pointer_name will point.
where * specifies that it is pointer variable. Example

Example of integer  Suppose variable a is an integer. Then initializing the


int *ptr; address of a to a pointer can be done in the following
way :
 Here int is the data_type of pointer and ptr is the name
int *ptr;
of pointer. While declaring the pointer, same
int a;
guidelines and rules should be followed for
ptr = &a;
pointer_name as given for variable_name in variable
declaration.  In above statements, the first line we have declared
 The above example tells that the pointer ptr is of type pointer ptr of integer type.
integer which means it stores the address of an integer  In second line we have declared an integer variable a.
variable in memory.  And in the third line, the address of a is assigned to the
pointer ptr . That’s why now the pointer ptr is
pointing to the variable a as shown in Fig. 1.2.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) (Pointers)….Page no. (7-5)

Fig. 7.1.3 Fig. 7.1.4

 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.

Fig. 7.1.5 : Two pointer 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) (Pointers)….Page no. (7-6)

1. The Address of Operator & (ampersand)


p = &no; Pointer intialzation
 The & is a unary operator means it has only one
operand. The address of operator is used to access the
printf(“\n value store in variable no is:\t%d”,no);
memory address of operand.
 For example, if variable num is an integer, then Prints value of num
&num
 will be said as “address of num” and it will return the printf(“\n address of variable no is :\t%u”,&no);
memory location (address) of num.
Prints Address of num
 Like other unary operators the “Address of (&)
operator has same precedence and right-to-left
associativity. printf(“\n value store in pointer variable p is :\t%u”,p);

Example Prints address of p


ptr=&m;
printf(“\n value pointed by pointer variable *p is:\t%d”,*p);
2. The Indirection Operator *(asterisk)
 The * operator is also unary operator and is used to return 1; Prints value pointed by p
access the value of variable located at specified address }
given in operand. We can say that it is totally opposite Output
of & operator.
 For example, address of variable num is assigned to the
pointer variable *p by the statement :
p = &num;
 So to access the value stored at the address specified
by p we use * operator as :
*p
Explanation
It points to the value stored at location specified in p. And it
also returns the value stored at location given in p.  This program demonstrates how to access the data
using pointers.
Example
 In this program a variable no stores value 50. And the
*ptr = m;
pointer variable *p is declared and initialized to the
 As we know * operator is used to display original
address of no.
value of the variable, here *ptr indicates the value
 That means the pointer variable p stores address of 50.
stored in variable m.
 To access the value hold by variable no, we use %d as
GQ. Write a program to demonstrate the concept of
access specifier and variable name no in printf(). It will
pointer. (5 Marks)
print 50 as the result of the printf() statement.
Ans. :  To access the address of variable no using & operator,
Program we have use &no in printf () statement and the access
specifier %u as the address is an unsigned integer
#include<stdio.h>
value. It will print current location of 50 in memory, at
int main()
this point it is 2293432 as the result of the printf()
{
statement.
int no = 50;
int *p; Pointer declaration  Whereas, to access the address stored in pointer
variable p we have used %u as access specifier and 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-7)

in the printf(). It will print current location of 50 in


Adds sizeof (int) i.e. 4 to the
memory. Here it is 2293432 as the result of the printf() ptr_a++; values stored at ptr_a ,
statement.
 To access the value 50 using pointer we use *p and the Adds sizeof (float) i.e. 4 to
ptr_b++; the values stored at ptr_b
access specifier %d. It will print value stored at
location specified by the pointer p i.e. value at location
2293432 is 50 so prints 50 as the result of the printf() Adds sizeof (char) i.e. 1 to the
ptr_c++; values stored at ptr_c
statement.

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;

printf ( "\nEnter a character for c : ") ;


scanf("%c", &c);

printf ( "\nEnter an integer value for a : ") ;


scanf("%d", &a);

printf ( "\nEnter a float value for b : ") ;


scanf("%f", &b);

printf ( "\nValue of a = %d", a ) ; Explanation


printf ( "\nValue of b = %f", b ) ;
 As shown in output when the integer pointer
printf ( "\nValue of c = %c", c ) ;
(i.e. ptr_a) is incremented by size of integer
ptr_a = &a ;
Now ptr_a points to a, ptr_b (i.e. 2 bytes or 4 bytes depending on operating system)
ptr_b = &b ; points to b and ptr_c poins to c so new value stored in ptr_a is
ptr_c = &c ;
2293424 + 4 = 2293428.
printf("\nOriginal address in ptr_a = %u", ptr_a );  And also when the float pointer(i.e. ptr_b) is
printf("\nOriginal address in ptr_b = %u", ptr_b ); incremented it will plus the size of float(i.e. 4 bytes) in
printf("\nOriginal address in ptr_c = %u", ptr_c ); original address, so new value stored in ptr_b is
2293420 + 4 = 2293424.
Prints value stored at ptr_a, ptr_b, and ptr_c. i.e.  And while incrementing the character pointer
addresses of a, b, and c respectively. (i.e. ptr_c) it will plus the size of character (i.e. 1
bytes) to original address, so new value stored in ptr_c
is 2293419 + 1 = 2293420.

(MU-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)

Example printf("The address of b = %u\n", ptr2);


printf("\n");
 Suppose *p is a pointer and variable a = 5 and c = 0.
printf("a = %d, b = %d\n", a, b);
p = &a;
printf("x = %d, y = %d\n", x, y);
c = 5 * - -(*p) *ptr2 = *ptr2 + 3;
 Here first the value stored at location specified by *ptr1 = *ptr2 - 5;
pointer *p is decremented by 1 i.e. --5 = 4. And then z = *ptr1 * *ptr2 - 6;
the new value is used to calculate the expression so c printf("\na = %d, b = %d,", a, b);
will be 5 * 4 = 20. So after performing the expression printf(" z = %d\n", z);
c = 20 and a = 4.
ptr1++;
(ii) Postfix decrement
printf(" The address in p1 = %u\n", ptr1);
 When postfix -- is used with a pointer in an expression,
printf(" *ptr1 = %d\n", *ptr1);
the expression is evaluated first using the original
value located at the specified location by pointer and ptr1--;
then the value is decremented by one.
printf(" The address in ptr1 = %u\n", ptr1);
Example printf(" *ptr1 = %d\n", *ptr1);
 Suppose *p is a pointer and variable a = 5 andd c = 0.
getch();
p = &a;
c = 5*(*p)-- }
 Here first the value stored at location specified by *p is
Output
used to solve the expression i.e. 5*5=25 is copied into
variable c and then value stored at location specified
by *p is decremented by 1 i.e. a will be 5-1 = 4 now.
So after performing the expression c = 25 and a=4.
 Let’s study following programs to understand the
pointer arithmetic.

GQ. Write a program to demonstrate the pointer


arithmetic operations. (5 Marks)

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)

scanf("%d", &num2); Ans. : Program

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=&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)

Iteration 6 : k < *ptr_range i.e.


7 < 15 is true
f=*ptr_i+*ptr_j 0 1 7 13 15 15 5 8
*ptr_i=*ptr_j 0 1 7 13 15 15 8 8
*ptr_j=f 0 1 7 13 15 15 8 13
k++ 0 1 8 13 15 15 8 13
Iteration 7 : k < *ptr_range i.e.
8 < 15 is true
f=*ptr_i+*ptr_j 0 1 8 21 15 15 8 13
*ptr_i=*ptr_j 0 1 8 21 15 15 13 13
*ptr_j=f 0 1 8 21 15 15 13 21
k++ 0 1 9 21 15 15 13 21
Iteration 8 : k < *ptr_range i.e.
9 < 15 is true
f=*ptr_i+*ptr_j 0 1 9 34 15 15 13 21
*ptr_i=*ptr_j 0 1 9 34 15 15 21 21
*ptr_j=f 0 1 9 34 15 15 21 34
k++ 0 1 10 34 15 15 21 34
Iteration 9 : k < *ptr_range i.e.
10 < 15 is true
f=*ptr_i+*ptr_j 0 1 10 55 15 15 21 34
*ptr_i=*ptr_j 0 1 10 55 15 15 34 34
*ptr_j=f 0 1 10 55 15 15 34 55
k++ 0 1 11 55 15 15 34 55
Iteration 10 k < *ptr_range i.e.
: 11 < 15 is true
f=*ptr_i+*ptr_j 0 1 11 89 15 15 34 55
*ptr_i=*ptr_j 0 1 11 89 15 15 55 55
*ptr_j=f 0 1 11 89 15 15 55 89
k++ 0 1 12 89 15 15 55 89
Iteration 11 k < *ptr_range i.e.
: 12 < 15 is true
f=*ptr_i+*ptr_j 0 1 12 144 15 15 55 89
*ptr_i=*ptr_j 0 1 12 144 15 15 89 89
*ptr_j=f 0 1 12 144 15 15 89 144
k++ 0 1 13 144 15 15 89 144
Iteration 12 k < *ptr_range i.e.
: 12 < 15 is true
f=*ptr_i+*ptr_j 0 1 13 233 15 15 89 144
*ptr_i=*ptr_j 0 1 13 233 15 15 144 144
*ptr_j=f 0 1 13 233 15 15 144 233
k++ 0 1 14 233 15 15 144 233

(MU-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)

Iteration 13 k < *ptr_range i.e.


: 12 < 15 is true
f=*ptr_i+*ptr_j 0 1 14 377 15 15 144 233
*ptr_i=*ptr_j 0 1 14 377 15 15 233 233
*ptr_j=f 0 1 14 377 15 15 233 377
k++ 0 1 15 377 15 15 233 377
Iteration 14 k < *ptr_range i.e.
: 15 < 15 is false so
exits the loop

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);
}

GQ What will be the output of program ? (1 Mark)


Output Fig. 7.3.1

 Now to assign pointer to an array following statement


is used

(MU-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]

printf("\n Array elements and their locations: \n");


i=0; Prints value stored at
Fig. 7.3.1(a) while (i<5) location value stored in
ptr
{
 To access x[1] just we need to increment the pointer printf("\n %5.2f is stored at %u", *ptr, ptr);
like: ++ptr so that the new address in ptr will be ptr++;
2001 + size of integer i.e. 2001 + 2 = 2003. i++;
Prints address stored by ptr
}
return 1;
}
Output

Fig. 7.3.1(b)

 We can say that, if *ptr points to a particular element


of an array, then
 ptr+1 points to the next element,
 ptr+i points ith elements after ptr,
 and ptr-i points ith elements before ptr.
 *(ptr+1) refers to the value of x[1],
 ptr+i is the memory address of x[i], and *(ptr+i) is the
value of x[i].

GQ. Write a program to accept array elements and


print those using pointers. (5 Marks)

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

GQ. Write a program using pointers to compute the


sum of all elements stored in an array. (5 Marks)

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

Increments i ; i.e. now i=i+1 = 2+1 = 3


Iteration 4 ptr = 2293424, i=3
Prints *ptr and ptr i.e. 40.2 and 2293424
Increments ptr it will plus the size of float
into value stored in ptr i.e.
2293424+4 = 2293428
Increments i ; i.e. now i=i+1 = 3+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-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)
}

Assigns address of last element to  Increments i by 1


ptr=&num[4]; pointer ptr  Now i=1 and 1<5 is true
so prints 20,
printf("array elements in reverse order are:");
and decrements ptr so it will point to num[2]
for (i=0;i<5;i++)
{ Prints elements of array in
printf("\t %d", *ptr--); reverse order one by one
}
return 1;
}
Output

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)

 Similarly, an element in 2D array is represented as:


(ptr+i)+j is the memory address of x[i][j], and
*(*(ptr+i)+j) is the value of x[i][j].
 In two dimensional array, p is a pointer to first row. *p
points first element in 2D array i.e. element in x[0][0].
 p + i is a pointer to ith row.*(p + i) points first element
th
in i row of 2D array i.e. element in x[i][0] and
th th
*(p + i) + j points j element in i row of 2D array
i.e. element in x[i][j]
th th
 *(*(p+i)+j) points the element in i row and j
column of 2D array i.e. element in x[i][j]
Let’s consider a 2D array x[4][3] and if
int *p;
p = x;
then 2D array is shown in Fig. 7.3.4.

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)

GQ. Program to print particular element in 2D array Explanation


using pointer. (5 Marks)
 Suppose the base address of array x[] is 2001 then 2D
Ans. : Program array will be as shown in Fig. 1.4.8(a) logically.
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,*p,x[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
p=&x[0][0];
Fig. 7.3.6
printf("2D array is:\n");
for(i=0;i<4;i++) In memory 2D array is stored like as shown in
{ Fig. 1.4.8(b).
for(j=0;j<3;j++)
{
printf("%d\t",x[i][j]);
}
printf("\n"); Fig. 7.3.7
} p = &x[0][0]
printf("Element at:\n");
Prints value this statement assigns 2001 to ptr
printf("x[0][0] = %d \n",*p,p); in x[0][0]
 *ptr will point the value stored at location 2001 i.e.
x[0][0] = 1
printf("x[1][1] = %d \n",*(p+1 * 3+1)); Prints value  *(p+1 * 3+1) indicates *(p+3+1) = *(p+4) so it will
in x[1][1]
add 4*size of int

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

GQ. Write a program in C using pointers to determine


length of a string. (5 Marks)

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:

Explanation Fig. 7.3.11

 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 :

Fig. 7.3.8 Fig. 7.3.12


 Here ptr is not null so count is incremented by 1 so  Here ptr is not null so count is incremented by 1 so
count = 1 count = 5
 ptr is incremented so now it points to second character  ptr is incremented so now it points to sixth character in
in str i.e. o like: str i.e. B like:

Fig. 7.3.9 Fig. 7.3.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) (Pointers)….Page no. (7-21)

 Here ptr is not null so count is incremented by 1 so  So exits from loop


count = 6  And prints the value of count as length of string
 ptr is incremented so now it points to seventh character str i.e. 9.
in str i.e. y like:
GQ. Write a program to print reverse of an entered
string using pointer. (5 Marks)

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;

printf("\n Enter a string: ");

Accepts a string from user


scanf("%s", str); and store it in str

Fig. 7.3.15 strlen(str) returns the length of


len=strlen(str); str and it is stored in len
 Here ptr is not null so count is incremented by 1 so
count = 8
Assigns address of last
 ptr is incremented so now it points to ninth character in ptr=&str[len]; character in str to ptr
str i.e. ! like.
printf("\n reverse of string: ");
for(i=0;i<=len;i++)
{ Prints elements of
array in reverse
printf("%c", *(ptr)--); order one by one
}
return 1;
Fig. 7.3.16 }
 Here ptr is not null so count is incremented by 1 so Output
count = 9
 ptr is incremented so now it points to end of str like.

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

 Now 3 < 7 is true and *ptr points to fourth last


character of string i.e. g like:
Prints *ptr i.e. g
 Now decrements ptr by 1 so now it points to fifth last
character as follows
Fig. 7.3.19
Increment the i by 1 so i = 4
Prints *ptr i.e. m
 Now decrements ptr by 1 so now it points to second
last character as follows
Increment the i by 1 so i = 1

Fig. 7.3.23

 Now 4 < 7 is true and *ptr points to fifth last character


of string i.e. o like:
Prints *ptr i.e. o
Fig. 7.3.20
 Now decrements ptr by 1 so now it points to second
 now 1 < 7 is true and *ptr points to second last character as follows
character of string i.e. a like : Increment the i by 1 so i = 5
 Prints *ptr i.e. a
 Now decrements ptr by 1 so now it points to third last
character as follows
 Increment the i by 1 so i = 2

Fig. 7.3.24

 Now 5 < 7 is true and *ptr points to second character


of string i.e. r like:
Prints *ptr i.e. r
Fig. 7.3.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) (Pointers)….Page no. (7-23)

 Now decrements ptr by 1 so now it points to first if(*p== NULL)


character as follows printf("Character not found");
return 1;
Increment the i by 1 so i = 6
}
Output

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)

 And in memory it will reserve 6 + 8 + 4 = 18 bytes.


 7.4 ARRAY OF POINTERS
 To access a character h in Kolhapur we can use
th th
UQ. Explain array of pointers with example. *(dist_name[1]+3) i.e. j character in i name here
MU - Dec. 17, 4 Marks. i = 1 and j = 3.
 Array of pointers saves the memory space.
Ans. :
GQ. Write a program to demonstrate the array of
Array of pointer
pointers. (5 Marks)
 As an array of int contains integer values, and an array
of floats contains float values, the array of pointer Ans. : Program
contains the addresses which points to values of similar #include<conio.h>
data type. #include<stdio.h>
int main()
 All guidelines and rules followed to construct and
{
handle an ordinary array are applied to the array of
pointers as well. Array of pointers is declared as shown char *dist_name[5] = {"Mumbai", "Pune", "Sangali",
"Satara", "Kolhapur" };
below:
int i=0;
 Syntax Declares array of pointers

 Syntax of declaring array of pointers.


printf("\nElements of array *dist_name[ ] are : \n");
data_type *array-name[size];
for(i=0;i<5;i++)
 Array of pointers are used in handling the collection of {
strings. printf("\n Element %d = %s",i,dist_name[i]);
 Example 1
Displays the strings stored in array of pointers
 For example to store three strings in character array
}
following declaration is used :
return 1;
char str[3][10];
}
 The array will look like.
Output

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

Fig. 7.4.2 The for loop is used to print values in 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) (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

 To print all the value stored in array of pointer *a[] put


*a[i] instead of *a[1] in printf() statement. Fig. 7.4.5
Code after correcting the errors  To point to the pointer p1, declare another pointer and
# include <stdio.h> assign p1 to it as follow:
void main ( ) int **p2;
{ p2 = p1;
int * a [4];  Now link between p2 and p1 is created by copying the
int i; address of p1 into p2 as shown in Fig. 7.4.6.
int m = 10, n = 20, p =30, q = 40;
a [0] = & m;
a [1] = &n;
a [2] = &p;
a [3] = &q;
for (i = 0; i < 4; i ++ )
printf (“%d \n”, * a [i] );
}
Output

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)

 Now we can access the value 10 by : Output


printf(“%d”,var);
printf(“%d”,*&var);
printf(“%d”,*p1);
printf(“%d”,**p2);
 7.5 PASSING ARRAY TO FUNCTION
 Here all the printf statements print 10. The ** indicates
that it hold address of another pointer.
GQ. How to pass an array to the function explain with
**p2 indicates that p2 is a pointer to a pointer of int example? (5 Marks)
type.
Ans. :
 Example
Passing Array to the Function
int i=10, *p1, **p1, ***p3;
 Function is collection of statements combined in a
p1=&I;
block to perform specific task. It helps to achieve
p2=&p1;
reusability.
p3=&p2;
 And pointer stores address of a variable or address of
Here we can access 10 by following statements.
another pointer. Pointers can be passed to function.
printf(“%d”,var);
Also pointer can points to the function.
printf(“%d”,*&var);
printf(“%d”,*p1);  While passing a variable as parameter of function the
printf(“%d”,**p2); value of variable is copied into formal parameter. But
printf(“%d”,***p2); while passing an array as parameter of function only
the address of first element gets copied into formal
GQ. Write the output of the following program parameter.
(1 Mark)
 Following general form is used to declare the function
void main ( ) which accepts an array.
}
int ***r, **q, *p, i = 7;  Syntax
p = & i; return_type function_name (data_type [ ]);
q = & p;  Here all the syntax is same as declaring simple
r=&q function but the difference is of [ ] brackets. They are
print f (‘‘%d%d%d’’, *p, **q, ***r); used to indicate that we are dealing with an array.
}
For example
Ans. : Errors
float calculate_avg(float [ ]);
void instead of Void
 To call the function which passes an array:
{ of main function missing
function_name (array_name);
remove space between print and f
 Here the array_name is the name of array to be passed.
Code after correcting the errors
void main() For example

{ float avg = calculate_avg (marks);


int ***r,**q,*p,i=7;  marks is the float array. While function call is made the
p=&i; base address of marks array gets passed to the function
q=&p; calculate_avg().
r=&q;
printf(“%d%d%d”,*p,**q,***r);
}

(MU-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)

GQ. Write a program for passing array as function


 7.5.1 Parameters in Function Call
parameter. (5 Marks)

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.
}

num is equal to num[0] so it passes Ans. :


display(num); address of num[0] to display() Parameters in Function Call
return 1;
}  When a function gets called there are two possibilities
void display(int n[]) of order in which the actual parameters are passed to
{ the function definition and maps with formal
int i; parameters. The possibilities are:
printf("entered array is: "); Parameters are passed from left to right.
for(i=0;i<4;i++) Parameters are passed from right to left.
{ Prints values
stored in n[]  In C, parameters are passed from right to left. The
printf("%d \t",n[i]);
order of parameter passing doesn’t much essential for
}
certain examples like following function call:
}
sum(m,n,o,p);
Output
 It doesn’t matter in which order the m, n, o and p are
passed after encountering this function call. but order
of passing parameters matters a lot for certain
examples like following:
Power(x,y);
 Parameters in a function call can be passed in two
ways.
Explanation
 The method of passing data between functions is called
 This program accepts elements of an array from user as parameter passing. It can be done in two ways.
then pass the array to a function to display the values
stored in that array. But passing the array to a function
means passing just address of first element i.e.
&num[0] to formal parameter n[].
 So if any modifications are done with the formal
parameter i.e. n[] it will reflect into the passed array
i.e. num[].
Fig. 7.5.1 : Methods of parameter passing

(MU-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)

 7.5.1(A) Call by Value Explanation


 Here compiler copies value of actual parameter num
GQ. State call by value with example. (5 Marks)
i.e.10 into formal parameter num.
Ans. :  Even though actual and formal parameter has same
Call by Value names, compiler treats both as different variables.
Different spaces are allocated to both parameters. It
 The method of calling function by passing values to it
leads wastage of memory.
is referred as call by value.
 Memory structure after function is called and
 In this method only values of the actual parameters are
parameters are passed to function definition :
copied into formal parameters. So if any changes are
done with formal parameters it can’t affect the actual
parameters.
 Function call made by using call by value method can’t
able to reflect the changes done inside the functions on
actual parameters.
Program
Fig. 7.5.2
 Write a program to print number using call by value
 The scope of formal parameter num is limited within
Soln. :
the fun ( ) function only.
Program
 So the formal parameter num is incremented by 10 and
# include<stdio.h> prints modified value i.e. 20. The } brace of function
void fun(int); fun ( ) leads the control back to the called function i.e.
int main() main ( ) and continue the execution from next
{ statement after function call.
int num=10; num of main() = 10
 Memory structure after function called and return back
to the main ( ) function :
fun(num); 10 passes to fun()

printf(“value after function call: %d”, num);


} Prints value of num of main()

10 copied into formal


void fun (int num) parameter num
{ Fig. 7.5.3
num= num +10;
 After function call, the printf ( ) function in main will
printf(“value inside function: %d”, num);
print value of actual parameter num i.e. 10 because
Prints updated value of num of fun() modifications can’t get replicated on actual parameter.
}
Output 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.

(MU-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)

Ans. : parameters. So all the changes done within the function


are reflected in the actual parameters also.
Program
 Function call made by using call by reference method
#include<stdio.h>
is able to reflect the changes done inside the functions
void swap(int , int);
on actual parameters.
int main()
{  Syntax
int num1=50,num2=60;
 To call a function using call by reference we use
printf("\n Values of num1 and num2 before swapping:");
following syntax:
printf("\n Value of num1 :\t%d",num1);
function_name (&argument_name1, &argument_name2,
printf("\n Value of num1 :\t%d",num2);
….. );
swap(num1,num2);
 Here each parameter/argument name prefixed by the
printf("\n Values of num1 and num2 after swapping:");
address of (&) sign. Rest all is same as the function
printf("\n Value of num1 :\t%d",num1);
call using call by value method. Also the function
printf("\n Value of num1 :\t%d",num2);
definition has some little changes as follows:
return 1;
} return_type function_name (type1 *argument_name1, type2
*argument_name2,…)
void swap(int a,int b)
{  The * sign is used to indicate it holds only memory
int temp=a; location.
a=b; Program
b=temp;  Write a program to demonstrate call by reference.
}
Soln. :
Output
Program
# include<stdio.h>
void fun(int *);
int main()
{
int num=10; num of main() = 10

fun(&num); Address of num passes to fun()

 Result : Values are not swapped


printf("\nvalue after function call: %d", num);
 7.5.1(B) Call by Reference Prints value of num modified by fun()
return 1;
GQ. Explain call by reference with example. (5 Marks) }
Address of num copied into
void fun (int *p)
Ans. : Formal parameter *p
{
Call by Reference
*p = *p + 10;
 The method of calling function by passing reference of
variable to it is referred as call by reference. printf("\nvalue inside function: %d", *p);
 Here reference indicates the memory address of Calculations are done at memory location of num
variable where it is stored.
}
 In this method instead of values, location number of
actual parameter in the memory is passed to formal

(MU-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

UQ. Explain difference between call by value and call


by reference MU - May 13, 2 Marks.
Explanation
Ans. :
 Here compiler passes address of actual parameter num
Difference between Call by Value and Call by Reference
(let’s say 1002) to formal parameter *p.
Parameters Call by value Call by reference
 Memory structure after function is called and
Definition The method of The method of
parameters are passed to function definition. calling a function calling a function
by passing actual by passing
values of addresses (location
parameters is called numbers) of
as call by value. parameters is
called as call by
reference.
Syntax Syntax of function Syntax of function
function header in definition: header in
Fig. 7.5.4 declaration return_type definition:
function_name return_type
 The parameter p stores address of num. *p denotes the ( type1 argument1, function_name
value stored at location given in p (i.e. value stored at type2 argument2, … (type1 *argument1,
location 1002 which is 10). ); type2 *argument2,
…);
 So the statement *p = *p + 10 will add 10 to the value
Syntax of Syntax of function Syntax of function
10 of variable num. So the value at location 1002 function call call: call:
becomes 20. function_name function_name
 So printf ( ) statement in the function fun ( ) prints ( argument1, (&argument1,
modified value i.e. 20. The } brace of function fun ( ) argument2, … ); &argument2, …);
leads the control back to the called function i.e. Complexity If program is large Even though the
then there may be program is large no
main ( ) and continue the execution from next possibility of confusion will
statement after function call. conflicting or occur during
 Memory structure after function called and return back interchanging the calling of the
values while calling function by using
to the main ( ) function.
the function by call by reference.
using call by value.
Modifications Inside the function As while calling
definition if any function, pointer to
changes are done the location where
with the value of the data is stored is
parameter which passed to the
was passed to it; it function so all the
will not affect the modifications are
Fig. 7.5.5 actual parameter. done directly to
that location
 As the modifications are made directly to the location therefore all
where num is stored, the printf ( ) statement after modification
function call will print modified value i.e. 20. reflects on the
actual parameter.

(MU-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)

Parameters Call by value Call by reference Output


Efficiency The Call-by-value Call-by-reference
functions are less functions are more
efficient than call efficient than call
by reference by value.
functions.
GQ. How to pass a address of variable to the function,
explain with example? (5 Marks)

Ans.: Passing address of variable to Function


Explanation
 While passing the array to function, the address of first
element is passed as an argument. Similarly it is
possible to pass the address of variable as parameter of
function using pointers.
Example
UQ. Write program to swap to values by using call by
reference concept. MU - Dec. 17, 4 Marks.

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

printf("\n value of num1 and num2 after swapping:");


printf("\n value of num1 :\t%d",num1);
printf("\n value of num1 :\t%d",num2);
return 1;
}
Address of num1 stored in a
void swap(int *a,int *b) and address of num2 stored in
{ b

Assigns value pointed by a i.e.


int temp=*a; num1 =50 to temp

Fig. 7.5.7 : Memory Map


Assigns value pointed by b i.e.
*a=*b; num2 =60 to *a  temp = *a will assign the value pointed by *a i.e. 50
 *a = *b will assign the value pointed by *b to the
*b=temp; Assigns value of temp i.e. 50 to *b location specified by a i.e. now 60 will be at location
} 2000.

(MU-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

printf("\n The minimum between num1 and num2 is:


%d",*p);
getch();
}
int* min(int *a,int *b)
If value pointed by a is less than
{
value pointed by b then b is
if(*a > *b) returned back otherwise a is
{ return back to main()
return b;
Fig. 7.5.8
}
 *b=temp will assign the value of temp i.e. 50 to the else
location specified by b i.e. now 50 will be in location {
5000 return a;
}
}
Output

Explanation

Fig. 7.5.9

 After function call the control return to the main() and


prints values stored in num1(i.e. 60) and num2(i.e.50)
which are swapped just now.

GQ. Write a program to find minimum of two


numbers using pointer and function.

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)

 7.5.2 Function Pointer

GQ. Explain the concept of pointers to function.


(3 Marks)

Ans. : Function Pointer


 Like a variable, function also has data type and
memory location. So it is possible to point the function
like the variable.

 Syntax of pointer to a function :

 A pointer to a function is declared as follows :


data_type (*ptr_name)();
 Here the data type should be same as the return type of
function to which it is going to point. The data type
acts as the return type of ptr_name when it calls the
function.
 The ptr_name is the name of pointer and it should be
always written within brackets because if we write it
like
Fig. 7.5.11 : After function call the memory map data_type *ptr_name();

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

 Now assign the name of function to the pointer as


below.
int min(int.int);
int(*ptr_name) ();
ptr_name = min;
 First statement declare a function min having two
parameters.
 The second statement declares a function pointer
ptr_name.
 In third statement make ptr_name to point to the
function min.
 To call the function min we use the pointer ptr_name
as :
(*ptr_name) (x,y);
 It is same as
min(x,y);
Fig. 7.5.12
 Let’s see an example to understand the use of pointers
Now value pointed by *p is printed i.e. 50. to functions.

(MU-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

 Here the total memory wastage is 2+2 = 4 bytes.


 Array has both memory shortage as well as memory
Explanation
wastage problems.
 (*p1)(x,y); statement is same as the mul(x,y);
 The ( ) around *p1 are necessary because the  Definition of dynamic memory allocation

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.

 7.6 CONCEPT OF DYNAMIC MEMORY  Importance of dynamic memory allocation

ALLOCATION  No need to initially occupy large memory.


 Memory can be allocated as well as de-allocated as per
UQ Comment on dynamic memory allocation. necessity. It avoids the memory shortage as well as
MU - May 17, 4 Marks. memory wastage problems.

Ans. : Concept of Dynamic Memory Allocation


 Dynamic memory management is considered as
manual memory management. This concept helps to
 Array is a group of elements with same data type.
obtain more memory when required as well as release
it when not necessary.

(MU-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)

 7.6.1 Difference between Static and Dynamic


Ans. :

Memory Allocation malloc()


 The name malloc stands for "memory allocation".
GQ. Differentiate between static and dynamic
 The function malloc() reserves a block of memory of
memory allocation. (4 Marks)
specified size and return a pointer of type void which
Ans. : can be casted into pointer of any form.
Difference between Static and Dynamic Memory  Syntax of malloc()
Allocation
ptr = (cast-type*) malloc(byte-size)
Parameter Static memory Dynamic memory  Here, ptr is pointer of cast-type.
allocation allocation
 The malloc() function returns a pointer to an area of
Allocation Memory is allocated Memory is allocated memory with size of byte size. If the space is
time at compile time. at run time. insufficient, allocation fails and returns NULL pointer.
Memory Memory size can't Memory size can be ptr = (int*) malloc(15 * sizeof(int));
size be changed while changed while  This specified statement will allocate either 30 or 60
executing program. executing program. based on the size of int 2 or 4 bytes respectively and
Wastage or Memory shortage or No memory shortage the pointer points to the address of first byte of
shortage wastage may occur or wastage memory.

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.

Functions for dynamic memory allocation  Syntax of free()

 C provides four library functions defined under free(ptr);


<stdlib.h> for dynamic memory allocation.  This specified statement frees the space allocated in the
Function Use of Function memory pointed by ptr.
malloc() Allocates requested size of bytes and returns GQ. Write a C program to find sum of n elements
a pointer to first byte of allocated space entered by user. To perform this program,
calloc() Allocates space for an array elements, allocate memory dynamically using malloc()
initializes to zero and then returns a pointer function. (5 Marks)
to memory
Ans. :
free() De-allocate the previously allocated space
Program
realloc() Change the size of previously allocated
#include <stdio.h>
space
#include <stdlib.h>
GQ. Explain the use of malloc() function with syntax.
int main()
(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) (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. :

printf("Enter elements : "); Program


for(i = 0; i < cnt; ++i) #include <stdio.h>
{ #include <stdlib.h>
scanf("%d", ptr + i);
sum += *(ptr + i); int main()
} {
printf("Sum of elements : %d", sum); int cnt, i, *ptr, sum = 0;
free(ptr); printf("How many elements: ");
getch(); scanf("%d", &cnt);
}
Output ptr = (int*) calloc(cnt, sizeof(int));
if(ptr == NULL)
{
printf("Error in allocating memory");
exit(0);
}
printf("Enter elements : ");
GQ. Explain the use of calloc() function with syntax. for(i = 0; i < cnt; ++i)
(2 Marks) {
scanf("%d", ptr + i);
Ans. : sum += *(ptr + i);
calloc() }

 The name calloc stands for "contiguous allocation".


printf("Sum of elements : %d", sum);
 The most important difference in between malloc() and free(ptr);
calloc() is that, malloc() allocates single block of getch();
memory whereas calloc() allocates multiple blocks of }
memory each of same size and sets all bytes to zero.
Output
 Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
 This statement will allocate contiguous space in
memory for an array of n elements.

(MU-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);

int main() GQ. Write a program to add two integer numbers


{ using pointer. (5 Marks)
int *ptr, i , size1, size2;
printf("Enter the initial size : "); Ans. :
scanf("%d", &size1); Program
ptr = (int*) malloc(size1 * sizeof(int)); # include<stdio.h>
printf("Address of previously allocated memory: "); int main()
for(i = 0; i < size1; ++i) {
printf("%u ",ptr + i); int num1, num2;
printf("\n Enter new size : "); int *ptr1, *ptr2;
scanf("%d", &size2); printf("\n Enter first number:");
ptr = realloc(ptr, size2); scanf("%d", &num1);
printf("Address of newly allocated memory: "); printf("\n Enter second number:");
for(i = 0; i < size2; ++i) scanf("%d", &num2);
printf("%u ", ptr + i); ptr1=&num1;
ptr2=&num2;
getch(); printf("\n Addition of two numbers: %d + %d = %d",
} *ptr1,*ptr2, (*ptr1)+(*ptr2));
Output return 1;
}
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-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 value of num

printf(“\n address of variable no is :\t%u”,&no);

Prints Address of num

printf(“\n value store in pointer variable p is :\t%u”,p);

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]

printf("\n Array elements and their locations: \n");


i=0;
Prints value stored at
while (i<5) location value stored in
{ ptr

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

GQ. Write a program that reads two numbers from


#include <stdio.h>
key board and gives their addition, subtraction,
void main()
multiplication, division and modulo.
{
 Ans. :
Program on arithmetic operations float Distance_In_KiloMeters = 0;
#include <stdio.h> float Distance_In_Meters = 0;
main() float Distance_In_Feet = 0;
{ float Distance_In_Inches = 0;
int n1,n2,r; float Distance_In_Centimeters = 0;
printf("Enter two numbers : ");
scanf("%d %d",&n1,&n2); printf("Enter the distance between write cities in kilometers
: ");
r = n1 + n2; scanf("%f", &Distance_In_KiloMeters);
printf("\n Addition : %d",r);

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);

printf("\n\nPress any key to exit.");


getch();
}
Output
GQ. Develop an application program to convert and
print distance between two cities in meters, feet,
inches & centimeters. The distance between two
cities (In KM) is input through key board.
C Programming (MU-FE-Sem II) (Lab Manual)….Page no. (L-2)

GQ. getchar() and putchar() with suitable example int main()


{
Example
puts("Hello");
# include<stdio.h> //including header file return 0;
int main() }
{
int a= getchar();
putchar(a);
return 0;
}
Output
 Assignment 2 : Branching Statements

GQ. Write a program to accept a number from user


and check whether it is more than 100.

 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 :

GQ. Write a program accept a number from user and


check whether it is more than 100. If the given
number is greater than 100 then print one
gets() and puts() message and if it is less than 100 then print
# include<stdio.h> // including header file another message. (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) (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);

total = hindi + marathi + english;


Calculates total
average = total / 3; and average of
marks.
printf("\n Total marks : %d",total);
GQ. Write a program to accept a number from user
printf("\n Average : %d",average);
and check whether it is even or odd. (5 Marks)

Program Checks whether average


if(average>=40)
is greater than 40
#include<stdio.h> {
#include<conio.h> If average is greater than or equal to
main() printf("\n Pass"); 40 then this message will be displayed.
{ }
int n; else
printf("\n Enter a number : "); { If average is less than 40 then this
scanf("%d",&n); Checks whether number is printf("\n Fail"); message will be displayed
if(n%2==0) completely divisible by 2. }
{ }
printf("\n Number is even"); This statement is Output
} executed if number is
exactly divisible by 2.
else
{
This statement is executed
printf("\n Number is odd"); if number is not exactly
divisible by 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-4)

GQ. Write a program to accept marks of 3 subjects Switch Statement


from student. Calculate the total and average of
GQ. Write a menu driven program which should
marks. If the average is >= 80 then give the
accepts two numbers from user and print the
grade as “A” , if average>= 60 then give the grade
result of addition, subtraction, multiplication or
as “B”, if average>= 40 then give the grade as “C”
division as per user’s choice. (5 Marks)
and below 40 “Fail”. (5 Marks)
 Note : In division case if the second number entered by
Program user is zero then print an error message.
#include<stdio.h>
UQ. Write an program to implement calculator with
#include<conio.h>
following operations.
main()
(i) Add two numbers
{
(ii) Subtract two numbers.
int hindi,marathi,english,total,average;
(iii) Division two numbers
printf("\n Enter marks marathi, hindi and english : ");
(iv) Multiply two numbers.
scanf("%d %d %d",&marathi,&hindi,&english);
MU - Dec. 14, 6 Marks.

Accepts marks from user  Ans. :


Program
total = marathi + hindi + english;
Calculate total #include<stdio.h>
average = total / 3; and average
of marks
#include<conio.h>
main()
if(average>=80)
{
{
If average>= 80 then this int n1,n2,result,choice;
printf("\n Grade - A"); message will be printf("\n--------Menu---------");
} displayed.
printf("\n 1 : Addition"); Accepts user’s
else if(average>=60)
If above condition is not printf("\n 2 : Subtraction"); choice from
{ given menu and
satisfied instead of that printf("\n 3 : Multiplication");
printf("\n Grade - B"); average>= 60 condition is then store it in
printf("\n 4 : Division"); choice variable.
} this message will be displayed
printf("\n Select your choice : ");
scanf("%d",&choice);
else if(average>=40)
If both the above conditions if(choice>= 1 && choice<=4)
{ are not satisfied and {
printf("\n Grade - C"); average >=40 condition is
satisfied then this message printf("\n Enter two numbers :" );
} Only if user
will be displayed scanf("%d %d",&n1,&n2); choice is in
} between 1 to 4
else then only two
switch(choice)
{ numbers will be
If all of the above conditions are { accepted.
printf("\n Fail..."); unsatisfied then this message will
case 1:
} be displayed Addition if
result = n1 + n2; choice
printf("\n Addition is %d",result); matches with 1.
}
break;
Output case 2: Subtraction if
choice
result = n1 - n2; matches
printf("\n Subtraction is %d",result); with 2
break;

(MU-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

 Assignment 3 : Loop Statements

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

153 = (1*1*1) + (5*5*5) + (3*3*3) = 1 + 125 + 27 =153 #include <stdio.h>


int main()
 Soln. :
{
Program int n, reverse_no = 0, rem, original_no;
#include<stdio.h> printf("Enter a a number : ");
#include<conio.h> scanf("%d", &n);
original_no = 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) (Lab Manual)….Page no. (L-6)
while( n!=0 ) number++;
{ }
rem = n%10; }
reverse_no = reverse_no*10 + rem; Output
n = n/10;
}

Until the value of n is not 0 loop will be executed


repeatedly Loop reverses the given number.

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.

printf("Enter a Decimal Number: ");


 Ans. :
scanf("%d", &decimalnum); #include <stdio.h>
while (decimalnum!=0) int main() {
{ int num, i;
rem = decimalnum%2; printf("Enter a positive integer: ");
decimalnum = decimalnum / 2; scanf("%d", &num);
binarynum = binarynum + rem*temp; printf("Factors of %d are: ", num);
temp = temp * 10; for (i = 1; i < num; ++i) {
} if (num % i == 0) {
printf("%d ", i);
printf("Equivalent Binary Number is: %ld", binarynum); }
} }
return 0;
Output:
}
Output:

GQ. Write a program to print Fibonacci series.

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");
}
}

UQ. Write a program to generate prime nos between


1 to 100. MU - Dec. 13, 10 Marks.

 Ans. :
#include <stdio.h>
int main()
{
int i, Number, count;

printf(" Prime Number from 1 to 100 are: \n");


for(Number = 1; Number <= 100; Number++)
{
count = 0;
for (i = 2; i <= Number/2; i++)
{
if(Number%i == 0)
{
count++;
break;
}
} UQ. Write a program to display pascal triangle.
if(count == 0 && Number != 1 ) A
{ A B
printf("\n %d ", Number); A B C
} A B C D
} A B C D E
return 0; MU - May 13, 6 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-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));
{ }

int i, j; printf("\nSUM : %f",sum);

for (i=1; i <=4; 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-11)

Output printf("%d ", i+k);


++count;
}

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)

UQ. Write a program to generate following pattern. Output


5
54
543
5432
54321 MU - May 17, 5 Marks.  Assignment 4 : Arrays

 Ans. : UQ. Write a program in C to find minimum number in


an array. MU - Dec. 15, 10 Marks.
#include<stdio.h>
int main()  Ans. : Program
{ #include<stdio.h>
int i,j,k; #include<conio.h>
int main()
for(i=1;i<=5;i++) {
{ int array[5]={33,30,34,31,32},j;
for(j=1;j<=5-i;j++) printf("\n array elements are:\t");
{ for(j=0;j<5;j++)
printf(" "); {
} printf("%d\t",array[j]);
for(j=1,k=5;j<=i;j++) } Sets the minimum number is
{ int min=array[0]; the first element of array.
printf("%d ",k--);
} for(j=1;j<5;j++) Loop will continue 5 times
printf("\n"); {
} if(array[j]<min)
} {
Finds smallest element and
UQ. Write a program for finding sum of series, 1 + 2 min=array[j]; store it in min variable.
+ 3 + 4 upto n terms. MU - Dec. 17, 5 Marks. }
}
 Ans. : printf("\n smallest number in 5-element integer array
#include<stdio.h> is:\t%d",min);
int main() return 1;
{ }
int n,i; Output
int sum=0;
printf("Enter the n i.e. max values of series: ");
scanf("%d",&n);
sum = (n * (n + 1)) / 2;
printf("Sum of the series: "); UQ. Write a program to search a number within the
for (i =1;i <= n;i++) { array. MU - Dec. 15, 10 Marks.
if (i!=n)
printf("%d + ",i); else  Ans. : Program
printf("%d = %d ",i,sum); int main()
} {
return 0; int arr[5],num,i;
} printf("\nEnter 5 array eles : ");

(MU-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

UQ. Write a program to sort list elements in


descending order. MU - May 13, 8 Marks.

OR Write a program to sort given nos in descending


order. MU - Dec. 13, 10 Marks.
UQ. Write a program to sort given numbers in
ascending order.  Ans. : Program
MU - May 14, Dec. 17, 10 Marks. #include<stdio.h>
#include<conio.h>
 Ans. : Program int main()
#include<stdio.h> {
#include<conio.h> int array[10],i, j,temp;
int main() printf("enter 10 elements for array:");
{ for(i=0;i<10;i++)
int array[10],i, j,temp; { Accepts 10 elements from
printf("enter 10 elements for array:"); scanf("%d",&array[i]); user and store it in array.
for(i=0;i<10;i++) }
{ Accepts 10 elements from
for(i=0;i<9;i++)
th
Used to compare i element
user and store it in array.
scanf("%d",&array[i]); {
with all the remaining elements
in the array.
} for(j=i+1;j<10;j++)
th
for(i=0;i<9;i++) Used to compare i element
{
with all the remaining elements
{ in the array. if(array[j]>array[i]) Compare array[i] with array[j]
for(j=i+1;j<10;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-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++;
} }
}

printf("\nThe elements of OAR are : ");


for (i = 0; i < k; i++)
{
UQ. Write a program in C to accept an ARRAY A with printf("%d ", OAR[i]);
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 printf("\nThe elements of EAR are : ");
ARRAY A contains A = {3,2,4,2,5,7,8} then for (i = 0; i < j; i++)
B = {3,5,7} and C = {2,4,2,8}. {
printf("%d ", EAR[i]);
MU - May 16, 10 Marks.
}
 Ans. :
}
Program
#include <stdio.h> Output

void main()
{

long int ARR[10], OAR[10], EAR[10];


int i, j = 0, k = 0, n;

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.

printf("\n Original matrix:\n\t");  Ans. :


for (i=0;i<2;i++) Program
{ #include<stdio.h>
for (j=0;j<2;j++) #include<conio.h>
{ void accept(int a[10][10], int rows, int cols)
printf("%d\t",matrix[i][j]); {
} int i,j;
printf("\n\t"); for(i=0;i<=rows-1;i++)
} {
printf("\n Transposed matrix:\n\t"); printf("Enter elements : ");
for (i=0;i<2;i++) for(j=0;j<=cols-1;j++)
{ {
for (j=0;j<2;j++) scanf("%d",&a[i][j]);
{ }
printf("%d\t",matrix[j][i]); }
} }
printf("\n\t"); int is_symmetric(int a[10][10],int rows,int cols)
} {
} int i,j;
Output if(rows!=cols) return 0;
for(i=0;i<=rows-1;i++)
{
for(j=0;j<=cols-1;j++)
{
if(a[i][j]!=a[j][i]) return 0;
}
}
return 1;
}
main()
{
int a[10][10],rows,cols,r;

printf("Enter the number of rows and columns : ");


scanf("%d %d",&rows,&cols);
accept(a,rows,cols);

(MU-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

UQ. Write a program to calculate sum of list by


Accepts element of 3 × 3 matrix and store it in ith row and jth
column of origin matrix. passing array to a function.

} MU - May 13, 5 Marks.


}
printf("\n Original matrix:\n\t");
 Ans. :
for (i=0;i<3;i++) Program
cal(int arr1[])
th th
{ Copies the entered element at j row and i column of {
trans_matrix.
for (j=0;j<3;j++) int sum,i;
{ sum = 0;
printf("%d\t",orign_matrix[i][j]); Prints original for(i=0;i<5;i++)
} matrix. {
printf("\n\t"); sum = sum + arr1[i];
} }
printf("\n Transposed matrix:\n\t"); printf("\nSum of array elements : %d",sum);
for (i=0;i<3;i++) }
{
for (j=0;j<3;j++) Prints transpose of main()
{ original matrix. {
printf("%d\t",trans_matrix[i][j]); int arr[5], i;
} printf("\nEnter 5 els : ");
printf("\n\t"); for(i=0;i<5;i++)
} scanf("%d",&arr[i]);
}
cal(arr);
Output
}
Output

UQ. Write a program to validate whether accepted


string is palindrome or not.
MU - May 13, 5 Marks, Dec. 13,
May 14, Dec. 18, 10 Marks.

 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>

UQ. Write a program to find reverse of given string int main()


without using string library function.
{
MU - May 15, 5 Marks.
char first_str[20],second_str[20];
 Ans. : int count=0, i=0;
Program printf("\n Enter first string :\t");
int main() scanf("%s", first_str);
{
printf("\n Enter Second string:\t");
char s[1000], r[1000];
scanf("%s", second_str);
int begin, end, count = 0;
printf("\n Before copy:\t First String=%s and Second
String=%s", first_str,second_str);
printf("Input a string\n");
gets(s); Until the end of string the
while (first_str[i]!='\0') loop will continue.

// Calculating string length

(MU-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)

UQ. Write a menu driven program to perform {


arithmetic operations on two integers. The menu printf("\n Enter two numbers :" );
should be repeated until the user selects 'STOP' scanf("%d %d",&n1,&n2);
option. Program should have independent user }
defined function for each case. switch(choice)
MU - May 17, 10 Marks. {
case 1:
 Ans. : Program
add(n1,n2);
#include<stdio.h> break;
#include<conio.h> case 2:
int result; sub(n1,n2);
add(int n1,int n2) break;
{ case 3:
result = n1 + n2; mul(n1,n2);
printf("\n Addition is %d",result); break;
} case 4:
sub(int n1,int n2) div(n1,n2);
{ break;
result = n1 - n2; case 5:
printf("\n Subtraction is %d",result); break;
}
mul(int n1,int n2) default:
{ printf("\n Invalid choice");
result = n1 * n2; }
printf("\n Multiplication is %d",result); }
} }
div(int n1,int n2)
Output
{
if(n2!=0)
{
result = n1 / n2;
printf("\n Division is %d",result);
}
else
{
printf("\n Cannot divide by zero");
}
}
main()
{
int n1,n2,choice;
while(choice!=5)
{
printf("\n--------Menu---------");
printf("\n 1 : Addition");
printf("\n 2 : Subtraction");
printf("\n 3 : Multiplication");
printf("\n 4 : Division");
printf("\n 5 : STOP");
printf("\n Select your choice : ");
scanf("%d",&choice);
if(choice>= 1 && choice<=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-22)

 Assignment 7 : Recursion  Ans. :


UQ. Write a recursive program to calculate factorial Program
of accepted number. MU - May 13, 6 Marks. #include <stdio.h>
#include<conio.h>
 Ans. :
Program int Fibbo(int);
#include <stdio.h>
int fact(int); int main()
int main( ) {
{ int n, i = 0, c;
int n, f ; printf("\n Enter value of n : ");
printf ( "\nEnter any number " ) ; scanf("%d",&n);
scanf ( "%d", &n ) ; Loop will execute n
printf("\nFibonacci series\n"); times it will call
f = fact ( n ) ; for (c = 1 ; c <= n ; c++) Fibbo() each times and
prints return value of
printf ("Factorial value = %d", f ); Suspend execution of { Fibbo()
main() and transfers
control to definition printf(" %d ", Fibbo(i));
of fact() and passes i++;
return 1; value of n to num.
} }
int fact (int num)
{ getch();
int f ; }
if (num == 1)
{ int Fibbo(int n)
return (1) ;
} {
else if (n == 0)
return 0;
{ else if (n == 1)
f = num * fact (num - 1) ; Recursively
return 1;
calls itself
} else
return (f) ; Recursively calls itself return (Fibbo(n-1) + Fibbo(n-2) );
} }
Output Output

UQ. Write a program to display Fibonacci series using


recursion. MU - May 13, 6 Marks. UQ. Write a program to reverse a number using

OR Write a program using function to print first ‘n’ recursion. MU - May 16, 8 Marks.

numbers in Fibonacci series.

MU - Dec. 14, May 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) (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

Employee name, Department, Date of joining, records in ascending order of Price.

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

UQ. Define a structure consisting of following


elements.
(1) Student roll_no Program on Union
(2) Student name
#include <stdio.h>
(3) student percentage
#include <string.h>
Write a program to read records of 5 students
and display same. MU - Dec. 18, 10 Marks.
union student
 Ans. : {
Program char name[20];
char subject[20];
#include<stdio.h>
float percentage;
main()
};
{
int main()
struct student
{
{
union student record1;
int rno;
union student record2;
float per;
char name[20];
// assigning values to record1 union variable
}s[5];
strcpy(record1.name, "Raju");
int i;
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
for(i=0;i<5;i++)
{
printf("Union record1 values example\n");
printf("\n Enter name, rollno and percentage : ");
printf(" Name : %s \n", record1.name);
scanf("%s %d %f",&s[i].name, &s[i].rno,&s[i].per);
printf(" Subject : %s \n", record1.subject);
}
printf(" Percentage : %f \n\n", record1.percentage);
printf("\n Name \t Rno \t Percentage");
for(i=0;i<5;i++)
// assigning values to record2 union variable
printf("Union record2 values example\n");
{
strcpy(record2.name, "Mani");
printf("\n %s \t %d \t %.2f",s[i].name,s[i].rno,s[i].per);
printf(" Name : %s \n", record2.name);
}

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

which are swapped just now.


GQ. Write a program to find minimum of two
numbers using pointer and function.

 Assignment 9 : Pointers  Ans. : Program


#include<stdio.h>
UQ. Write program to swap to values by using call by
#include<conio.h>
reference concept. MU - Dec . 17, 4 Marks.
int* min(int *, int*);
 Ans. : int main()
Function call min()
#include<stdio.h> { accepts two
void swap(int *, int*); int m,num1=50,num2=60; parameters and
returns a pointer
int main() int *p;
back to calling
{ p = min(&num1,&num2); function
int num1=50,num2=60;
printf("\n value of num1 and num2 before swapping:"); printf("\n The minimum between num1 and num2 is:
printf("\n value of num1 :\t%d",num1); %d",*p);
printf("\n value of num1 :\t%d",num2); getch();
}
Call by reference:
swap(&num1,&num2); passes address of two int* min(int *a,int *b)
If value pointed by a is less than
numbers to swap() {
value pointed by b then b is
function if(*a > *b) returned back otherwise a is
printf("\n value of num1 and num2 after swapping:"); { return back to main()
printf("\n value of num1 :\t%d",num1); return b;
printf("\n value of num1 :\t%d",num2); }
return 1; else
} {
Address of num1 stored in a
void swap(int *a,int *b) return a;
and address of num2 stored in
{ 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) (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)

 Module I : Introduction & Fundamentals of


C Programming ......... M1-1 to M1-5

 Module II : Control Structures ......... M2-1 to M2-8

 Module III : Functions ......... M3-1 to M3-8

 Module IV : Arrays and Strings ......... M4-1 to M4-6

 Module V : Structure and Union ......... M5-1 to M5-9

 Module VI : Pointers ......... M6-1 to M6-8


MODULE I Introduction & Fundamentals
of C Programming
Multiple Choice Questions

Part A - Introduction Q. 1.8 In computer science, algorithm refers to a special method


useable by a computer for solution of a problem.
Q. 1.1 First step in process of problem solving is to ______ (a) True (b) False
(a) Design a solution (b) Understanding of problem (c) May be (d) Can't say Ans. : (a)
(c) Define a problem (d) Solving the problem
Q. 1.9 Actual instructions in flowcharting are represented in
Ans. : (c) __________
Q. 1.2 Which one of the following is not an algorithms (a) Circles (b) Boxes
characteristics? (c) Arrows (d) Lines Ans. : (b)
(a) Input (b) Output Explanation : The actual instructions are written in
(c) Infiniteness (d) Unambiguous Ans. : (c) boxes. Boxes are connected by using arrows to indicate
the exact flow of a flowchart and the order in which they
Q. 1.3 In computer science, algorithm refers to a pictorial are to be executed.
representation of a flowchart.
(a) True (b) False Ans. : (b) Q. 1.10 _______ is a procedure or step by step process for
solving a problem.
Explanation : The statement is false. The correct
statement would be: In computer science, flowchart (a) Algorithm (b) Flowchart
refers to a pictorial representation of an algorithm. (c) Pseudocode (d) All of these Ans. : (a)

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.5 To repeat a task number of times we use _______


(d) Pseudocode Ans. : (b)
(a) input statement (b) conditional statement Q. 1.12 Which of the following is incorrect?
(c) loop statement (d) output statement Algorithms can be represented : _______
Ans. : (c) (a) as pseudo codes (b) as syntax

Q. 1.6 The process of drawing a flowchart for an algorithm is


(c) as programs (d) as flowcharts Ans. : (b)
called __________ Q. 1.13 The following box denotes _______
(a) Performance (b) Evaluation (a) Decision (b) Initiation
(c) Algorithmic Representation (d) Flowcharting (c) Initialization (d) I/O Ans. : (a)
Ans. : (d) Explanation : A diamond shape box denotes the
Explanation : It is called as flowcharting. A flowchart is decision making statements. It jumps to a truth value or a
nothing but a pictorial representation of an algorithm. false value.

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");

Q. 1.19 When you write an algorithm the order of the main();


instructions is very important. }
(a) True (b) False Ans. : (a) (a) Wrong statement
(b) It will keep on printing Phoenix InfoTech
Q. 1.20 Any algorithm is a program.
(c) It will Print Phoenix InfoTech once
(a) True (b) False
(d) None of the these Ans. : (b)
(c) May be (d) Can't say Ans. : (b)
Explanation : In this program, the main function will
Q. 1.21 Which of the following is not an advantage of a call itself again and again. Therefore, it will continue to
flowchart? print Phoenix InfoTech.
(a) Better communication
Q. 1.28 Which of the following is not a valid variable name
(b) Efficient coding declaration?
(c) Systematic testing (a) int __a3; (b) int __3a;
(d) Improper documentation Ans. : (d) (c) int __A3; (d) None of the mentioned
Explanation : Flowcharts provide a proper Ans. : (d)
documentation. It also provides systematic debugging.
Q. 1.29 C is a which level language.?
Q. 1.22 ______ is a symbol used connects two symbols of
(a) Low Level (b) High Level
flowchart.
(c) Low + High (d) None Ans. : (b)
(a) Circle (b) Rectangle
Explanation : C is a high level language. Another
(c) Diamond (d) Arrow Ans. : (d) example is BASI(c)
Q. 1.23 The symbol denotes _______
Q. 1.30 C Language was developed in the year ____
(a) I/O (b) Flow
(a) 1970 (b) 1975
(c) Terminal (d) Decision Ans. : (c) (c) 1980 (d) 1985 Ans. : (a)
Explanation : The symbol denotes a terminal. It is used
for indication of start and stop nodes of 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) (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;

Q. 1.33 Which of the following is not a valid variable name {


declaration? int i = 4, j = 5;
(a) int _a3; (b) int a_3;
printf("%d %d", i, j);
(c) int 3_a; (d) int _3a Ans. : (c)
Explanation : Variable name cannot start with a digit. }

Q. 1.34 Which program outputs "Hello World.." .? printf("%d %d", i, j);


(a) main() }
{ (a) 4525 (b) 2525
(c) 4545 (d) None of the these Ans. : (a)
scanf("Hello World..");
Explanation : In this program, it will first print the inner
} value of the function and then print the outer value of the
(b) main() function.

{ Q. 1.38 All keywords in C are in ____________


printf("Hello World.."); (a) LowerCase letters (b) UpperCase letters
(c) CamelCase letters (d) None of the mentioned
}
Ans. : (a)
(c) main()
Q. 1.39 C is _______ type of programming language.
{
(a) Object Oriented (b) Procedural
print("Hello World.."); (c) Bit level language (d) Functional
} Ans. : (b)
(d) main() Explanation : C is a procedural language. It is written in
a number of steps using statements and functions. Logic
{ is clearly depicted in the program. Procedural language is
scan("Hello World.."); also called Imperative Language.

} Q. 1.40 C variable name can start with a ____


Ans. : (b) (a) Number (b) Plus Sign (+)
(c) Underscore (d) Asterisk (*) Ans. : (c)
Q. 1.35 Which one is not a reserve keyword in C Language?
(a) auto (b) final Q. 1.41 C language is primarily developed as ___
(c) case (d) register Ans. : (b) (a) System programming language
(b) General purpose language
(c) Data processing language
(d) None of the above. 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-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

(a) 4 Bytes (b) 8 Bytes extern int i; _____

(c) Depends on the system/compiler (a) Declaration (b) 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

Multiple Choice Questions


Q. 2.1
Q. 2.4 What will be the output of the following piece of code?
#include <stdio.h>
for(i = 0; i<10; i++);
int main()
printf("%d", i);
{
(a) 10 (b) 0123456789
int i = 1024;
(c) Syntax error (d) 0 Ans. : (a)
for (; i; i >>= 1)
printf("GeeksQuiz"); Q. 2.5 What will be the output of the following piece of code?
return 0; void main()
} {
How many times will Phoenix InfoTech be printed in the int num=10;
above program? if(num)
(a) 10 (b) 11 (c) Infinite printf("If Executed");
(d) The program will show compile-time error else
Ans. : (b) printf("Else Executed");
Explanation : In for loop, mentioning expression is }
optional. >>= is a composite operator. It shifts the binary (a) If Executed (b) Else Executed
representation of the value by 1 to the right and assigns
the resulting value to the same variable. The for loop is (c) Error (d) Blank Ans. : (a)
executed until value of variable i doesn’t drop to 0.
Q. 2.6 What will be the output of the following piece of code?
Q. 2.2 In the following loop construct, which one is executed void main()
only once always? {
for(exp1; exp2; exp3) int num=-3;
(a) exp1 (b) exp3 if(num>0)
(c) exp1 and exp3 (d) exp1, exp2 and exp3 printf("If Executed");
Ans. : (a) else
Explanation : Expression exp1 is executed only once printf("Else Executed");
since this is used for initialization
}
Q. 2.3 What is the output of this C code?
(a) If Executed (b) Else Executed
int main()
(c) Error (d) Blank Ans. : (b)
{
int a = 0, i = 0, b; Q. 2.7 Choose a right C Statement.
for (i = 0;i < 5; i++) (a) Loops or Repetition block executes a group of
{ statements repeatedly.
a++; (b) Loop is usually executed as long as a condition is
met.
continue;
(c) Loops usually take advantage of Loop Counter
}
(d) All the above. Ans. : (d)
}
(a) 2 (b) 3 (c) 4 (d) 5 Ans. : (d)
C Programming (MU-FE-Sem II) (Control Structures)….Page no. (M2-2)
Q. 2.12 What will be the output of the following code?
Q. 2.8 For loop in a C program, if the condition is missing
#include
(a) it is assumed to be present and taken to be false
void main()
(b) it is assumed to be present and taken to the true
{
(c) it result in a syntax error
int s=0;
(d) execution will be terminated abruptly
while(s++<10)
Ans. : (b)
{
Q. 2.9 What will be the output of the following piece of code? if(s<4 && s<9)
int main() continue;
{ printf("%dt", s);
int i = 0; }
switch (i) }
{ (a) 1 2 3 4 5 6 7 8 9 (b) 1 2 3 10
case '0': printf("Phoenix"); (c) 4 5 6 7 8 9 10 (d) 456789 Ans. : (c)
break;
Q. 2.13 What is the output?
case '1': printf("InfoTech");
void main()
break;
{
default: printf("Phoenix InfoTech");
} if(-100)
printf("Negative number");
}
else
(a) Phoenix (b) InfoTech
printf("Positive number");
(c) Phoenix InfoTech (d) Compile-time error
}
Ans. : (c)
(a) Positive number (b) Negative number
Explanation : At first look, the output of the program
seems to be Phoenix. But, the cases are labeled with (c) Error (d) Random Behavior
characters which gets converted to their ascii values Ans. : (b)
48(for 0) and 49(for 1). None of the cases is labeled with
Q. 2.14 Loops in C Language are implemented using _____
value 0. So, the control goes to the default block and
Phoenix InfoTech is printed. (a) While Block (b) For Block
(c) Do While Block (d) All the above Ans. : (d)
Q. 2.10 The continue statement cannot be used with _____
(a) for (b) while Q. 2.15 If c is a variable initialised to 1, how many times will the
following loop be executed?
(c) do while (d) switch Ans. : (d)
while ((c > 0) && (c < 60))
Explanation : continue is used to skip the statements and
cannot be used with switch {
loop body
Q. 2.11 What is the output of this C code?
c ++;
int main()
}
{
(a) 60 (b) 59 (c) 61 (d) None of these
int a = 0, i = 0, b;
Ans. : (b)
for (i = 0;i < 5; i++)
{ Q. 2.16 Predict the output of the below program : _____
a++; #include <stdio.h>
if (i == 3) #define EVEN 0
break; #define ODD 1
} int main()
} {
(a) 1 (b) 2 (c) 3 (d) 4 Ans. : (d) int i = 3;
switch (i & 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) (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

Multiple Choice Questions

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)

double func(int); Q. 3.45 What is the return-type of the function sqrt()


int func(float); (a) int (b) float
(a) A function with same name cannot have different (c) double
signatures (d) depends on the data type of the parameter
(b) A function with same name cannot have different Ans. : (c)
return types
(c) A function with same name cannot have different Q. 3.46 A function _____
number of parameters (a) May or may not need input data
(d) All of the mentioned Ans. : (c) (b) May or may not return a value
(c) Both (a) and (b)
Q. 3.40 If the function returns no value then it is called ____
(d) None of these Ans. : (c)
(a) Data type function (b) Calling function
(c) Main function (d) Void function
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) (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

Multiple Choice Questions

Q. 4.1 Array in C is_______


Q. 4.6 If S is an array of 80 characters, then the value assigned
(a) A group of elements of same data type. to S through the statement scanf("%s",S) with input
(b) Contains more than one element 12345 would be ______
(c) Whose elements are stored in memory in continuous (a) "12345"
or contiguous locations. (b) nothing since 12345 is an integer
(d) All the above. Ans. : (d) (c) S is an illegal name for string
Q. 4.2 How do you initialize an array in C? (d) %s cannot be used for reading in values of S
(a) int arr[3] = (1,2,3); (b) int arr(3) = {1,2,3}; Ans. : (a)
(c) int arr[3] = {1,2,3}; (d) int arr(3) = (1,2,3); Explanation : scanf("%s", S) only scans first parameter
Ans. : (c) of input stream .So Option A is correct.

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

Multiple Choice Questions

Part A - Introduction Q. 5.6 What is the size of a C structure.?


(a) C structure is always 128 bytes.
Q. 5.1 What is a structure in C language.? (b) Size of C structure is the total bytes of all elements
(a) A structure is a collection of elements that can be of of structure.
same data type. (c) Size of C structure is the size of largest element.
(b) A structure is a collection of elements that can be of (d) None of the above Ans. : (b)
different data type.
Explanation : Individually calculate the sizes of each
(c) Elements of a structure are called members. member of a structure and make a total to get Full size of
(d) All the above Ans. : (d) a structure.

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?

printf("%d %c", test.x,test.y); (a) struct temp{}s; main(){}

return 0; (b) struct temp{}; struct temp s; main(){}

} (c) struct temp s; struct temp{}; main(){}

(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

Multiple Choice Questions


Q. 6.1 What will be the output of the following C code?
Q. 6.5 What is the output of this C code?
#include <stdio.h>
int main()
void foo(int*);
{
int main()
char *p = NULL;
{
char *q = 0;
int i = 10;
if (p)
foo((&i)++);
printf(" p ");
}
else
void foo(int *p)
printf("nullp");
{
if (q)
printf("%d\n", *p);
printf("q\n");
}
else
(a) 10
printf(" nullq\n");
(b) Some garbage value
}
(c) Compile time error
(a) nullp nullq
(d) Segmentation fault/code crash Ans. : (c)
(b) Depends on the compiler
Q. 6.2 If a variable is a pointer to a structure, then which of the (c) x nullq where x can be p or nullp depending on the
following operator is used to access data members of the value of NULL
structure through the pointer variable? (d) p q Ans. : (a)
(a) . (b) & (c) * (d) -> Ans. : (d)
Q. 6.6 Consider the declaration : ______
Q. 6.3 Prior to using a pointer variable it should be _____ char x[]="WHATIZIT";
(a) Initialized (b) Declared char *y="WHATIZIT";
(c) Both (a) and (c) (d) None of the above The output of puts(x) an puts(y) will be
Ans. : (c) (a) Will be the same (b) Different
Q. 6.4 A pointer is _____ (c) Not related (d) Error Ans. : (a)
(a) A variable that stores address of an instruction Q. 6.7 What do the following declaration signify?
(b) A variable that stores address of other variable int (*pf)();
(c) A keyword used to create variables (a) pf is a pointer to function.
(d) None of these Ans. : (b) (b) pf is a function pointer.
Explanation : A pointer is a programming language (c) pf is a pointer to a function which return int
object that stores the memory address of another value
(d) pf is a function of pointer variable. Ans. : (c)
located in computer memory. A pointer references a
location in memory, and obtaining the value stored at that Q. 6.8 "&" is called as ___________ in pointer concept.
location is known as dereferencing the pointer. (a) Conditional Operator (b) Logical Operator
(c) Address Operator (d) None of these
Ans. : (c)
C Programming (MU-FE-Sem II) (Pointers)….Page no. (M6-2)
const int x=y;
Q. 6.9 Which is an indirection operator among the following?
printf("%d\n", x);
(a) * (b) & (c) # (d) % Ans. : (a)
return 0;
Q. 6.10 What is the output of this C code? }
int main() (a) Garbage Value (b) Error
{ (c) 128 (d) 0 Ans. : (c)
int i = 10;
Q. 6.14 What is the output of this C code?
void *p = &i;
int main()
printf("%d\n", (int)*p);
return 0; {
int i = 10;
}
void *p = &i;
(a) Compile time error
printf("%f\n", *(float*)p);
(b) Segmentation fault/runtime crash
return 0;
(c) 10
}
(d) Undefined behaviour Ans. : (a)
(a) Compile time error (b) Undefined behaviour
Q. 6.11 What do the following declaration signify? (c) 10 (d) 0.000000
char *arr[10]; Ans. : (d)
(a) arr is a array of 10 character pointers.
Q. 6.15 A pointer variable can be ______
(b) arr is a array of function pointer.
(a) Passed to a function
(c) arr is a array of characters.
(b) Changed within a function
(d) arr is a pointer to array of characters. Ans. : (a)
(c) Returned by a function
Q. 6.12 What will be the output of the following C code? (d) Can be assigned an integer value Ans. : (c)
#include <stdio.h>
Q. 6.16 What does the following declaration mean?
int main()
int (*ptr)[10];
{
(a) ptr is array of pointers to 10 integers
int i = 11;
(b) ptr is a pointer to an array of 10 integers
int *p = &i;
(c) ptr is an array of 10 integers
foo(&p);
printf("%d ", *p); (d) ptr is an pointer to array Ans. : (b)
} Q. 6.17 What will be the output of the program ?
void foo(int *const *p) #include<stdio.h>
{ int main()
int j = 10; {
*p = &j; int i=3, *j, k;
printf("%d ", **p); j = &i;
} printf("%d\n", i**j*i+*j);
(a) Compile time error return 0;
(b) 10 10 }
(c) Undefined behaviour (a) 30 (b) 27 (c) 9 (d) 3 Ans. : (a)
(d) 10 11 Ans. : (a)
Q. 6.18 What will be the output of the following C code?
Q. 6.13 Assume the output ______ #include <stdio.h>
#include<stdio.h> int main()
int main() {
{ int i = 10;
int y=128; int *p = &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) (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?

int main() (a) Representation of NULL pointer

{ (b) Representation of void pointer

int *p = f(); (c) Error

printf("%d\n", *p); (d) None of above Ans. : (a)


} Q. 6.23 What is the output of this C code?
int *f() int main()
{ {
int j = 10; int *ptr, a = 10;
return &j; ptr = &a;
} *ptr += 1;
(a) 10 printf("%d,%d/n", *ptr, a);
(b) Compile time error }
(c) Segmentation fault/runtime crash (a) 10,10 (b) 10,11
(d) Undefined behaviour Ans. : (a) (c) 11,10 (d) 11,11 Ans. : (d)
Q. 6.24 What is wild pointer?
Q. 6.20 Output of following program?
# include <stdio.h> (a) Pointer which is wild in nature

void fun(int *ptr) (b) Pointer which has no value.

{ (c) Pointer which is not initialized

*ptr = 30; (d) None Ans. : (c)


} Q. 6.25 Consider the following program fragment.

int main() static char wer[3][4] = {"bag", "let", "bud"};

{ char(*ptr)[4] = wer;

int y = 20; The putchar (* (wer [1] + 1)) ;

fun(&y); (a) prints e (b) prints a

printf("%d", y); (c) prints 1 (d) prints b Ans. : (a)


return 0; Q. 6.26 "*" is called as ___________.
} (a) Address Operator
(a) 20 (b) 30 (b) Value at Operator
(c) Compiler Error (d) Runtime Error (c) Scope Resolution Operator
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) (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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy