0% found this document useful (0 votes)
423 views

Ge6151 Computer Programming All Five Units

This document outlines the aims and objectives of a computer programming course syllabus. The key goals are: 1. Students will learn the basic organization of a digital computer and be exposed to number systems and logic. 2. Students will learn to think logically, write pseudocode, and draw flowcharts to solve problems. 3. Students will be introduced to C syntax and learn to program in C, including using arrays, strings, functions, pointers, structures, and unions.

Uploaded by

Monica Esther
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
423 views

Ge6151 Computer Programming All Five Units

This document outlines the aims and objectives of a computer programming course syllabus. The key goals are: 1. Students will learn the basic organization of a digital computer and be exposed to number systems and logic. 2. Students will learn to think logically, write pseudocode, and draw flowcharts to solve problems. 3. Students will be introduced to C syntax and learn to program in C, including using arrays, strings, functions, pointers, structures, and unions.

Uploaded by

Monica Esther
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 159

Aim and objective of the subject

The students should be made to:


 Learn the organization of a digital computer.
 Be exposed to the number systems.
 Learn to think logically and write pseudo code or draw flow charts for
problems.
 Be exposed to the syntax of C.
 Be familiar with programming in C.
 Learn to use arrays, strings, functions, pointers, structures and unions
in C.

1
Anna University, Chennai Syllabus
GE6151 COMPUTER PROGRAMMING LTPC
3003
UNIT I INTRODUCTION 8
Generation and Classification of Computers- Basic Organization of a
Computer –Number System – Binary – Decimal – Conversion – Problems.
Need for logical analysis and thinking – Algorithm – Pseudo code – Flow
Chart.
UNIT II C PROGRAMMING BASICS 10
Problem formulation – Problem Solving - Introduction to ‘ C’ programming –
fundamentals – structure of a ‘C’ program – compilation and linking processes
– Constants, Variables – Data Types – Expressions using operators in ‘C’ –
Managing Input and Output operations – Decision Making and Branching –
Looping statements – solving simple scientific and statistical problems.
UNIT III ARRAYS AND STRINGS 9
Arrays – Initialization – Declaration – One dimensional and Two dimensional
arrays. String- String operations – String Arrays. Simple programs- sorting-
searching – matrix operations.
UNIT IV FUNCTIONS AND POINTERS 9
Function – definition of function – Declaration of function – Pass by value –
Pass by reference – Recursion – Pointers - Definition – Initialization – Pointers
arithmetic – Pointers and arrays- Example Problems.
UNIT V STRUCTURES AND UNIONS 9
Introduction – need for structure data type – structure definition – Structure
declaration – Structure within a structure - Union - Programs using structures
and Unions – Storage classes, Pre-processor directives.
TOTAL: 45 PERIODS
TEXTBOOKS:
1. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming
in C”, Dorling Kindersley (India) Pvt. Ltd., Pearson Education in South
Asia, 2011.
2. Pradip Dey, Manas Ghosh, “Fundamentals of Computing and
Programming in C”, First Edition, Oxford University Press, 2009
3. Yashavant P. Kanetkar. “ Let Us C”, BPB Publications, 2011.
REFERENCES:
 Byron S Gottfried, “Programming with C”, Schaum’s Outlines, Second
Edition, Tata McGraw-Hill, 2006.
 Dromey R.G., “How to Solve it by Computer”, Pearson Education,
Fourth Reprint, 2007.
 Kernighan,B.W and Ritchie,D.M, “The C Programming language”,
Second Edition, Pearson Education, 2006.

2
Detailed lesson plan
Wee No of Cummlati
S. No Topics Book No
k No Hrs ve hours
UNIT – I NTRODUCTION
Introduction – Definition of Computer –
1 1 1 T1/ T2/R3
History & Characteristics of Computer
Computer Generations – First, Second,
2 1 2 T1/T2/R3
Third, Fourth and Fifth generation.
Classification of Computers – Micro,
3 1 3 T1/T2/R3
I Mini, Mainframe and Super Computers.

Basic Computer Organization –


4 Hardware – Input – CPU – ALU – CU – 1 4 T1/T2/R3
Registers – Output devices – Memory
Number system - Introduction - Radix - 1
5 5 T1/T2/R3
Types of Number system
Conversions - Binary – Octal –
6 Hexadecimal – Conversion to / from 1 6 T1/T2/R3
Decimal from/to other radix,
Conversion among Binary, Octal and
7 1 7 T1/T2/R3
Hexadecimal numbers.
II Need for logical analysis and thinking –
8 1 8 T1/R2
Algorithm
9 Pseudo code, Flow Chart 1 9 T1/T2
Examples of algorithms, flow charts &
10 1 10 T2
Pseudocode
UNIT II - C PROGRAMMING BASICS

Problem formulation – Problem


Solving - Introduction to ‘C’
11 1 11 T1/T2/R3
programming – Fundamentals-
Structure of a C Program
Compilation and linking processes – T1/T2/T3/
12 1 12
Constants, Variables, Data types R3
Operators and Expressions -
Properties, Types – Arithmetic,
13 III 1 13 T1/T2/R3
Increment and Decrement, Assignment
and comma operator- Programs.
Operators and Expressions -
14 Relational, logical, Conditional, Bit – 1 14 T1/T2/R3
Example Programs.
Managing Input and Output
T1/T2/T3/
15 operations – I/O functions, 1 15
R3
Formatted Functions
16 IV Managing Input and Output 1 16 T1/T2/T3/
operations – unformatted R3

3
Wee No of Cummlati
S. No Topics Book No
k No Hrs ve hours
Functions, Library functions.
Decision Making – Branching – if,
if-else, nested if else – go to - T1/T2/T3/
17 1 17
switch .. case – example R3
programs
Looping – while , for ,do while , T1/T2/T3/
18 1 18
break , continue - R3
Solving simple scientific and
statistical problems –
Temperature conversions, Finding
19 1 19 T2/R3
area of geometrical shapes,
Programs using control
statements
Programs using looping
20 1 20 T2/R3
statements
UNIT III - ARRAYS & STRINGS
Arrays – Initialization – Declaration- 1D T1/T2//T3
21 1 21
Array /R3
2D Array – Initialisation – definition –
T1/T2/T3/
22 Multidimensional Arrays – Matrix – 1 22
R3
Programs.
Strings – String declaration & T1/T2/T3/
23 V 1 23
Initialization, basic sting functions R3
String Library functions –
24 1 24 T1/T2/R3
strcpy(),strlen(),strcmp(),strcat()
String Library functions –
25 tolower(),toupper(),strlwr(),strupr(),strnc 1 25 T1/T2/R3
at()
26 Array of strings 1 26 T1/T2

27 Simple Programs : Sorting & Searching 1 27 T1


VI
Matrix Operation : Addition, Subtraction,
28 1 28 R3
Transpose of a matrix
Matrix Operation : Multiplication, Sum of
29 1 29 R3
diagonal elements
UNIT IV - FUNCTIONS AND POINTERS
Functions : User Defined Functions-
30 1 30 T1/T2/R3
Definitions and declaration
VII
31 Types of User Defined functions 1 31 T1/T2/R3

4
Wee No of Cummlati
S. No Topics Book No
k No Hrs ve hours

32 Call by reference - Call by value 1 32 T1/T2/R3

33 Recursion – Example programs 1 33 T1/T2/R3


Library functions – Fixed & variable
1 34 T1
34 argument functions
Pointers – Introduction – features –
35 1 35 T1/T2/R3
arithmetic operations with pointers
36 Null Pointers, Pointers with arrays 1 36 T1/T2/R3
VIII
37 Pointers with functions 1 37 T2/R3
Pointer to pointer and array, Pointers
38 1 38 T1/T2/R3
with strings and void pointers
UNIT V - STRUCTURES AND UNIONS
Structures - Definition – declaration –
39 VIII 1 39 T1/T2/R3
Nested Structure
Array of structures , Pointers &
40 1 40 T1/R3/R3
structures
T1/R1/R3
41 Structures and Functions 1 41
/R3
42 Typedef & Structures 1 42 T1
IX
Union :Difference between union &
43 Structure , declaration , accessing & 1 43 T2/R3
initialization
44 Practical Applications of union 1 44 T1

45 Enumerations & bitfields 1 45 T1


T1/T2/R1/
46 X Storage classes 1 46
R3
47 Pre-processor directives. 1 47 T1/T2/T3

Total Hours: 47

5
Unit – I
Introduction

Generation and Classification of Computers- Basic Organization of a


Computer –Number System – Binary – Decimal – Conversion –
Problems. Need for logical analysis and thinking – Algorithm – Pseudo
code – Flow Chart.

Part – A

1. What are mainframe computers? Give one example.

 Mainframe computers are multi user, multiprogramming and high


performance computers.
 They operate at a very high speed, have very high storage capacity and
handles the workloads of many users
 They are large and powerful systems used in centralized databases.
 Users access the mainframe computers via dumb terminal or intelligent
terminal or a PC
 Used in banks and companies.
 Example : CDC 6600, IBM ES 9000 series

2. What are super computers? Give some examples. April / May 15

Fastest and most expensive machines which perform trillions of


calculations per second.
 The speeds of super computers are measured in FLOPS
(Floating Point Operations Per Second).
 Super computers are built by interconnecting thousands of
processors that can work in parallel
 It performs highly intensive calculations.
 Super computers are used in climate research, molecular
research, nuclear research, military agencies, etc
 Example: IBM Roadrunner, IBM Blue gene and Intel ASCI red

6
3. Define pseudo code. Write two characteristics of pseudo code.
Jan 14, Nov / Dec 16, April / May 15
Pseudo code is a short, readable and formally styled English language
used for explaining an algorithm. It is a short hand way of describing a
computer program.

Characteristics of pseudo code:


 it shows the algorithm clearly
 it does not have any natural-language sentences or phrases
 it is independent from any particular programming language (i.e.
its syntax is language-neutral)
 its syntax is not totally free, but it is more flexible and open than
programming language syntax
 it is code, so it must be understandable, and self-documenting
with headers and comments and meaningful identifiers (labels and variable
names)
 it makes good use of spacing and alignment.

4. Classify the computers based on performance, size, cost and


capacity. May / June 16
Based on physical size, capacity, performance, cost and application
areas the computers are classified into
 micro computers,
 mini computers,
 super computers and
 mainframe computers

5. List some important hardware and software technologies of fifth


generation computers. Jan 14

 Hardware Technology: Uses SLSI (Super Large Scale


Integration) chips
 Software Technology:
o Supports parallel processing
o Simulates human way of thinking and reasoning and uses
Artificial Intelligence.
o It includes area like Natural Language Processing (NLP),
Speech Recognition, Voice Recognition, etc.

7
6. What are flow charts and list down their advantages?

A flowchart is a diagrammatic representation that illustrates the


sequence of operations to be performed to get the solution of a problem.
Flowcharts are generally drawn in the early stages of formulating computer
solutions. Flowcharts facilitate communication between programmers and
business people. The benefits of flowcharts are as follows:

a) Communication: Flowcharts are better way of communicating the


logic of a system to all concerned.
b) Effective analysis: With the help of flowchart, problem can be
analysed in more effective way.
c) Proper documentation: Program flowcharts serve as a good
program documentation, which is needed for various purposes.
d) Efficient Coding: The flowcharts act as a guide or blueprint during
the systems analysis and program development phase.
e) Proper Debugging: The flowchart helps in debugging process.
f) Efficient Program Maintenance: The maintenance of operating
program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part.

7. Define flow chart. Why is flow chart required? Nov / Dec 2014

A flowchart is a diagrammatic representation that illustrates the


sequence of operations to be performed to get the solution of a problem.
Flowcharts are generally drawn in the early stages of formulating computer
solutions.
Requirements of flow chart
 Flow charts are easy-to-understand diagrams that show how the
steps in a process fit together.
 Their simplicity makes them useful tools for communicating how
processes work, and for documenting how to do a particular job.

8. What is an algorithm? List its advantages. Nov/Dec 14, 15


Algorithm is an ordered sequence of finite, well defined, unambiguous
instruction for completing a task.
Advantages:
 They are easy to debug
 There is a clear set of instructions that can be followed, and
 They are independent of programming language.
8
9. Define computer.
Computer is an electronic machine which accepts data from the user,
performs operations on it and produces the result.
10. List out the characteristics of the computer.
a. Speed
b. Diligence
c. Accuracy
d. Storage Capacity
e. Versatility
11. Differentiate analog and digital computers

Analog Computers Digital Computers


These computers recognize data They recognize data by counting
as a continuous measurement of a discrete signal representing either
physical property (voltage, a high or low voltage state of
pressure, speed and temperature). electricity.
Analog computers are used mainly These computers are widely used
in scientific design and production in commercial and control
environments. systems.
An analog computer operates on In digital computers,
inputs of continuously varying mathematical expressions are
electrical Voltages. represented as binary digits (0
and 1) and all operations are
done using these digits at a very
high rate.

12. Convert the binary number 110 100 111 101 to octal.
May/June 2014
(110100111101)2 = (6475)8

13. Convert the binary number 10110111.1101 to decimal.


May / June 16

10110111.1101 2
= 1*27+0*26+1*25+1*24+0*23+1*22+1*21+1*20+1*2-1+1*2-2+0*2-3+1*2-4
=183.8125

9
Part – B

1. Evolution and Generations of Computer

 Write in detail about the evolution and the various generations of computer. January 14
 Discuss various generations of computers. April / May 15,14
 Explain in detail about the various generations of computers. June 14

Third Fifth
First Second
Generation Fourth Generation Generation
S.No Features Generation Generation
(1964-Early (early 70's to till date) (present and
(1940-56) (1956-63)
70's) beyond)
Microprocessor,
LSI - 1000's of
SLSI(Super
Hardware Vacuum Tubes Integrated transistors
1 Transistor Large Scale
Technology for circuitry Circuits VLSI - 100's of 100's
Integration)
of transistors , Linking
of computers: Internet
Human
Input - Input - Mouse and behaviour like
Input - Input -
Punched cards Handheld devices. thinking,
Input / Punched Keyboard
2 / Paper tape Output - speaking and
Output cards Output Output -
Output – Monitors/Printers/ reasoning. It
– Printouts Monitors
printouts Plotters uses expert
system

10
Third Fifth
First Second
Generation Fourth Generation Generation
S.No Features Generation Generation
(1964-Early (early 70's to till date) (present and
(1940-56) (1956-63)
70's) beyond)
Primary
memory –
Primary Memory –
Magnetic
Semiconductor
Core
memory with faster
technology
Magnetic RAM. Secondary
3 Memory Secondary    
Drums Memory : Hard Disk
memory –
( Smaller, Cheaper
Magnetic
and Bigger in
Disk &
Capacity)
Magnetic
Tapes
Computing Gig seconds,
Microsecond
4 Characteristi Milliseconds Nanoseconds Pico seconds parallel
s
cs processing
Very Large.
Physical
5 More space for Smaller Smaller Smaller Smaller
Appearnce
installation.
6 Software Machine Assembly Operating High level Language, based on
Technology Language. language, system GUI (Graphical User Artificial
Language Difficult to use High Level interfaces Interface) : allows Intelligence
and to program Programming keyboard and users to intearct with which
with 1's & 0's. : COBOL & monitor, High the computer includes

11
Third Fifth
First Second
Generation Fourth Generation Generation
S.No Features Generation Generation
(1964-Early (early 70's to till date) (present and
(1940-56) (1956-63)
70's) beyond)
FORTRAN level Natural
were also Language is language
developed. used for processing,
less difficult profgramming. speech
to program Easier to recognition,
and time program and vision
efficient time efficient recognition
used Commercial Purpose,
used for
Commercial commercially, Computers are used for
7 Application scientific
purpose and by mass availabe for home research
applications
audience users
Generate large
amount of heat Generate
Heat Generate les Negligible amount of
8 with thousands less amount  
generation heat heat
of vacuum of heat
tubes
Constant Less frequent
Maintenance, maintenance, Low
9 Maintenance High less maintenance , Minimum maintenance  
Maintenance maintenance Minimum cost
cost cost
10 Example ENIAC,EDVAC PDP-8, IBM IBM 370, PDP APPLE II , ALTAIR Robotics
12
Third Fifth
First Second
Generation Fourth Generation Generation
S.No Features Generation Generation
(1964-Early (early 70's to till date) (present and
(1940-56) (1956-63)
70's) beyond)
1401,CDC
& UNIVAC 11 8800,CRAY-I
1604

13
2. Basic computer organization

 Explain the basic computer organisation using a neat diagram.


Jan 14, May 16
Explain in detail with neat diagram about the digital computer
organization and each of its units. Nov / Dec 14, 15
Computer is an electronic device that accepts input, processes the
input data by performing mathematical and logical operations on it and gives
desired the output. The computer system consists of four parts. a) Hardware
b) Software c) Data and d) Users.
Hardware consists of mechanical parts that make up the computer as a
machine. The hardware consists of physical devices of computer. The
hardware devices are required for input(Keyboard),
output(monitor),storage(hard disk, floppy disk drive) and processing of
data(processor, motherboard).
Software is a set of instructions that tell the computer about the tasks to
be performed and how these tasks are to be performed. Program is a set of
instructions, written in a language understood by the computer, to perform a
specific task. A set of programs and documents are collectively called
software. Software instructs the computer about the task to be performed. The
hardware carries out these tasks.
Data are isolated values or raw facts, which by themselves have no
much significance. The data is provided as input to the computer, which is
processed to generate some meaningful information.
Users are people who write computer programs or interact with the
computer. They are also known as skinware, liveware, humanware and
peopleware. Example: programmers, system analyst.
Components of Computer Hardware: The computer system hardware
comprises of three main components.
 Input / Output (I/O) Unit consists of the input unit and output unit
 Central Processing Unit (CPU) calculations and processing on
the input data, to generate the output
 Memory Unit is used to store the data, the instructions and the
output information
Input / Output Unit:
 The user interacts with the computer via the I/O unit.
 The input accepts the data from the user and converts it into a
form that is understandable by the computer
 Similarly the output unit provides the output in a form that is
understandable by the user.
14
 Examples of input devices: keyboard, trackball and mouse
 Examples of output devices: monitor and printer
Memory Unit

CPU

Input Unit Registers Output Unit


re

CU ALU

Figure 1.1 – Computer organisatio

Central Processing Unit (CPU):


 It is often called as brain of the computer
 CPU controls, coordinates and supervises the operations of the
computer
 It is responsible for processing of the input data.
 CPU consists of
o Arithmetic Logic Unit (ALU): It performs all the arithmetic
and logic operations on the input data
o Control Unit (CU): It controls the overall operations of the
computer i.e. it checks the sequence of execution of instructions and controls
and coordinates the overall functionality of the units of computers.
o Registers: CPU also has a set of registers for temporary
storage of data, instructions, addresses and intermediate results of
calculation.
 CPU executes the stored program instructions, i.e. instructions
and data are stored in the same memory before execution.
 For processing CPU gets data and instructions from the memory.
It interprets the program instructions and performs the arithmetic and logic
operations required for the processing of data. Then it sends the result to
memory.
 CPU also acts as an administrator and is responsible for
supervising operations of other parts of the computer.
Memory Unit:
 Memory unit stores the data, instructions, intermediate results
and output temporarily, during the processing of data.
15
 This memory is also called as main memory or primary memory
of the computer.
o Primary memory: The input data that is to be processed is
brought to the main memory before processing. The instructions required for
processing and any intermediate results are also stored in the main memory.
The output is stored in the main memory before being transferred to the output
device.CPU can work with the information stored in the main memory. Eg :
ROM and RAM
o Secondary Memory: The data, the program and the output
are stored permanently in the storage unit of the computer. Eg: Magnetic
disks, Optical disks, magnetic tapes.

3a. Classification of the computer

 Explain in detail about the classification of the computer in detail.

The digital computers that are available nowadays vary in their sizes
and types. The computers are broadly classified into four categories based
on the size and type:
a. Micro computers,
b. Mini computers,
c. Super computers and
d. Mainframe computers

Fast Expensive Complex Large

Super computers

Mainframe computers

Mini Computers
Slow Cheap Simple Small

Micro Computer

Figure 1.2 Classification of computers


a. Micro computers:

16
 Microcomputers are small low cost and single user digital
computer.
 They consist of CPU, input unit, output unit, storage unit and the
software.
 Although microcomputers are stand alone machines, they can be
connected together to create a network of computers that can serve more
than one user.
 Examples : IBM PC and Apple Macintosh
 Microcomputers include Desktop, Notebook, Net book, Tablet
computer, Handheld computer and Smart phones
 Desktop Computer / Personal Computers (PC) is the most
common type of microcomputer. It is a stand-alone machine that can be
placed on the desk. It consists of three units externally – keyboard, monitor
and system unit containing the CPU, memory, Hard disk drive, etc. It is not
expensive and is suited to the needs of a single user at home, small business
units and organizations.
 Notebook computers or Laptops resemble a netbook. They are
portable and have the features of a desktop computer. The advantage of
laptop is that it is small in size, can be carried anywhere, has a battery backup
and hence all the functionality of the desktop. Laptops are costlier than
desktop machines.
 Netbook are smaller notebooks optimized for low weight and low
cost, and designed for accessing web based applications.
 Tablet Computer has the features of the notebook computer but
it can accept the input from a stylus or pen instead of the keyboard or mouse.
It is a new kind of PC.
 Handheld Computer or Personal Digital Assistant (PDA) is a
small computer that can be held on the top of the palm. It is small in size.
Instead of keyboard, PDA uses a pen or stylus for input. PDAs do not have a
disk drive. They have limited memory and are less powerful. PDA can be
connected to the Internet via a wireless connection.
 Smart Phones are cellular phones that function both as a phone
and as a small PC. They may use a stylus or a pen or may have a small
keyboard. They can be connected to the Internet wirelessly.
b. Mini computers:
 Minicomputers are digit computers, generally used in multi-user
systems.
 They have high processing speed and high storage capacity than
microcomputers.

17
 Minicomputers can support 4-200 users simultaneously.
 The users can access the minicomputer through their PCs or
terminal.
 They are used for real time applications in industries, research
centres, etc.
 Example PDP 11, IBM (8000 series)
c. Mainframe computers:
 Mainframe computers are multi user, multiprogramming and high
performance computers.
 They operate at a very high speed, have very high storage
capacity and handle the workloads of many users.
 They are large and powerful systems used in centralized
databases.
 Users access the mainframe computers via dumb terminal or
intelligent terminal or a PC.
 Used in banks and companies.
 Example : CDC 6600, IBM ES 9000 series
d. Super computers:
 Fastest and most expensive machines which perform trillions of
calculations per second.
 The speeds of super computers are measured in FLOPS
(Floating Point Operations per Second).
 Super computers are built by interconnecting thousands of
processors that can work in parallel.
 It performs highly intensive calculations.
 Super computers are used in climate research, molecular
research, nuclear research, military agencies, etc.
 Example: IBM Roadrunner, IBM Blue gene and Intel ASCI red.

3b. Characteristics of a computer

 Explain in detail about the characteristics of a computer.

 Speed : The computer can process data very fast at a rate of


millions of instructions per second
 Accuracy: Computer provides high degree of accuracy.
 Diligence: When used for long period of time, the computer does
not get tired or fatigue. It can perform long and complex calculations with the
same speed and accuracy from the start till the end.
18
 Storage Capability: Large volumes of data and information can
be stored in the computer and also retrieved whenever required. A limited
amount of data can be stored temporarily in the primary memory. Secondary
storage devices like CD and DVD can store large amount of data
permanently.
 Versatility: Computer is versatile in nature. It can perform
different types of task with the same ease.

3c. Need for logical analysis and thinking

 Discuss the need for logical analysis and thinking in detail.


Dec 14
 Logical analysis is the process of understanding something.
 Logics and reasoning are also known as concepts understanding
something logically
 It recognised as a structure of thinking and analysing the
appearance and development of something through which specific goals or
targets are achieved.
 Brain is powerful in logical thinking. This enables human being to
scientifically expose the essence of something in an abstract and logical way
with consciousness.
 Logic is an abstract thinking, higher form thinking. Its
characteristics are abstract concept, judgement and reasoning as basic forms
of thinking, such as analysis, synthesis, generalization and so no.
 The same logic applies to in computer programming.

4a. Flow chart

 Explain in detail about flow chart.

Flowcharts: It is the pictorial representation of the algorithm.


Flowchart Symbols
The process symbol represents a process, action, or function. It’s
the most widely-used symbol in flowcharting.

The document symbol represents the input or output of a


document. Examples of input are receiving a report, email, or order.
Examples of output are generating a presentation, memo, or letter.
19
The decision symbol indicates a question to be answered—usually
yes/no or true/false. The flowchart path may splinter into different branches
depending on the answer.

The connector symbol connects separate elements across one


page. It’s usually used within complex charts.

The off-page connector (also known as the off-page link) symbol


connects separate elements across multiple pages. It is frequently
used within complex charts. The page number is sometimes placed on the
shape for easy reference.

The data symbol (also called the input/output symbol) represents


data that is available for input or output. It may also represent resources used
or generated. The paper tape symbol also represents input/output, but is
outdated and no longer in common usage. Another symbol used to
represent data is the circle shape.
Flow lines: It is used to connect the symbols

The stored data symbol represents data housed on a storage


device.

The summing junction symbol sums the input of several


converging paths.

The terminator symbol represents the start points, end points, and potential
outcomes of a path.

The predefined process symbol indicates a complicated process


or operation that is well-known or defined elsewhere.

The internal storage symbol represents data stored in random-


access memory (RAM).

20
Guidelines for preparing flowcharts:

 It should be simple.
 Standard symbols should be used.
 The flow lines should not intersect each others.
 In case of complex flowcharts use the connectors symbols.
 Only one flow line should enter the process symbol and only one
flow line should come out from a process symbol.

 Only one flow line used with the terminal symbol.

 Only one flow line should enter the decision symbol and two or
three flow lines may leave from the decision symbol.

Benefits of Flowcharts: The benefits of flowcharts are as follows:


Communication: Flowcharts are better way of communicating the logic of a
system to all concerned.
Effective analysis: With the help of flowchart, problem can be analysed in
more effective way.
Proper documentation: Program flowcharts serve as a good program
documentation, which is needed for various purposes.
Efficient Coding: The flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
Proper Debugging: The flowchart helps in debugging process.
Efficient Program Maintenance: The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put
efforts more efficiently on that part
Limitations of flow chart
• It is difficult to use flowcharts for large program
• May run into multiple pages,
• difficult to understand
• Difficult to update with changing requirements
• High Cost of maintenance for large and complex problems.

4b. Flow chart to find biggest of two numbers

 Draw a flow chart to find the maximum of two numbers.

21
4c. Flow chart to find biggest of three numbers

 Draw a flow chart to find the maximum of three numbers.

Start

Read three numbers a, b, c


22
if a>b & a>c

Print a is greater if b>c

Print b is greater Print c is greater


Yes NO

Stop
Yes NO

23
4d. Flowchart to find factorial of a number

 Draw a flow chart to find factorial of a number. May / June 14

Start

READ N

i=1
fact = 1

fact = fact * i

Yes
i=i+1 Is i<=n

No

PRINT fact

Stop

24
4e. Flow chart to find sum of first 100 natural numbers

 Draw a flow chart to find sum of first 100 natural numbers. May /
June 14

Start

SUM = 0

N=1

N=N+1

SUM = SUM + N

Yes
IS N<=100

No
PRINT SUM

Stop

25
4f. Flow chart to multiply two matrices
 Draw a flow chart to multiply two matrices.

26
4g. Flow chart to generate Fibonacci series
 Draw the flow chart to generate Fibonacci series.

27
28
4h.Flow chart to check the given number is positive or negative

 Draw a flowchart to check the given number is zero, positive or


negative

29
4i. Flow chart to
solve quadratic equation

 Draw the flowchart to solve quadratic equation. May / June 16

30
31
5a. Pseudo code

 What is pseudo code? Explain its guideline and benefits.


Pseudo code is a short, readable and formally styled English language
used for explaining an algorithm. It is a short hand way of describing a
computer program.
Characteristics of pseudo code:
 it shows the algorithm clearly
 it does not have any natural-language sentences or phrases
 it is independent from any particular programming language (i.e.
its syntax is language-neutral)
 its syntax is not totally free, but it is more flexible and open than
programming language syntax
 it is code, so it must be understandable, and self-documenting
with headers and comments and meaningful identifiers (labels and variable
names)
 it makes good use of spacing and alignment
Advantages of Pseudo code
 Pseudo code uses English like statements. Therefore, it can be
written easily and quickly.
 In Pseudo code, each step is independent of other steps.
Therefore, if any modification is done in any step, it does not affect the codes
of other module i.e. the code has not to be rewritten if any change occurs in
any other step.
 The format of Pseudo code is similar to that of the programs.
Both Pseudo code and program consist of a set of sequential statements and
use defined set of keywords. Therefore, Pseudo code can be converted to a
full-fledged program using any programming language.
 Since, it is written in highly simple language and thus can be
understood by any naïve user also.
Pseudo code guidelines:
 Statements should be written in simple English and should be
programming language independent.
 Steps must be understandable and when the steps are followed
they should produce the solution.
 Pseudo code should be concise.
 Each instruction should be written in a separate line and each
statement in the pseudo code expresses just one action of the computer.
 Capitalize keywords like READ, PRINT, and so on.

32
 Each set of instructions is written from top to bottom, with only
one entry and one exit.
 It should allow easy transition from design to coding in
programming language.
Benefits of Pseudo code
 It is easier to develop a program from pseudo code than in flow
chart.
 It is easy to translate the pseudo code into a programming
language
Limitations of Pseudo code
 Pseudo code is textual representation of an algorithm. It does not
provide graphical representation. Therefore, sometimes, it becomes difficult to
understand the complex logic written in Pseudo code.
 When too many nested conditions are used in the Pseudo code,
the level of difficulty to understand the code increases.
 Since Pseudo code focus on detailed description, a lot of practice
and concentration is required.
 Pseudo code lacks the standards and follows very few rules. Due
to this, some programmers reject the code because they fail to see the logic
behind it.

5b. Pseudo code for swapping two numbers without using


temporary storage
 Write a pseudo code for swapping two numbers without using
temporary storage.

READ the values of a and b


PRINT “The values of a and b before swapping: “
PRINT a
PRINT b
COMPUTE a=a+b
COMPUTE b=a-b
COMPUTE a=a-b
PRINT “The values of a and b after swapping:”
PRINT a
PRINT b

33
6. Number System
 Perform the following:

a. 2A947H = (?)2 Nov / Dec 14

2A947H =0010 1010 1001 0100 01112


b. 4872= (?)8 Nov / Dec 14
8 4872
8 609 - 0
8 76 -1
8 9 -4
8 1 -1

4872 = 114108

c. 1011.11012= (?)10 Nov / Dec 15

1011.11012 = 1*23+0*22+1*21+1*20+1*2-1+1*2-2+0*2-3+1*2-4
= 11.812510
1011.11012= 11.812510

d. D8BCH= (?)2 Nov /


Dec 15

D8BCH= 1101 1000 1011 11002

e. 48710= (?)8 Nov / Dec 15

8 48710
8 6088 -6
8 761 -0
8 95 -1
8 11 -7
8 1 -3

48710= (137106)8

Unit – II

34
C PROGRAMMING BASICS

Problem formulation – Problem Solving - Introduction to ‘ C’


programming –fundamentals – structure of a ‘C’ program –
compilation and linking processes – Constants, Variables – Data
Types – Expressions using operators in ‘C’ – Managing Input and
Output operations – Decision Making and Branching – Looping
statements – solving simple scientific and statistical problems.
Part - A
1. What are the various types of C operators? Jan 2014
 Arithmetic operators
 Logical operators
 Relational operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Comma operators
 sizeof and address operators

2. Write a for loop to print numbers from 10 to 1. Jan 2014


for(i=10;i>=1;i--)
{
printf(“%d\t,”i);
}

3. What is a variable? Illustrate with an example.


Nov/Dec14, May/June 16
Variable is the named memory location whose value or whose data can be
changed during execution of the program.
Declaration of a variable: datatype variable name;
Example: int a;

4. Give an example of ternary operator. Nov / Dec 2014


Conditional or ternary operators in C: Conditional operators return
one value if condition is true and returns another value is condition is false.
This operator is also called as ternary operator.
Syntax     :        (Condition? true_value: false_value);
Example :        (A > 100  ?  0  :  1); // if A is greater than 100, 0 is
returned else 1 is returned. 

35
5. List the various input and output statements in C. April / May 15
 Input statement:
o scanf(), getchar(),gets(),getch()
 Output statement:
o printf(), putchar(),puts()

6. What is compilation process? Nov / Dec 15


The compiler accepts a pre-processed output file from the pre-
processor and produces a special file called an object file. This object
file contains machine code generated from the source program. Usually
a special file extension (obj) is given to an object file. The compiler also
removes all comments from the input file. A compiler searches all the
errors of a program and lists them. If the program is error free then it
converts the code of program into machine code and then the program
can be executed by separate commands.

7. Discuss the working of modulo operator. Nov / Dec 15


Modulo operator used to find the remainder. The operands of the
modulo operator must be integer.
Example: 9%2=1
8. List different data types available in C. June 2014
 Basic / Primitive Data Types :
o Character(char)
o Integer(int)
o Single – precision floating point(float)
o Double – precision floating point(double)
o No value available(void)
 Derived Data Types:
o Array
o Pointer
o Function
 User Defined Data Types:
o Structure
o Union
o Enumeration

36
9. What is the importance of keywords in C? April / May 15
Keyword is a reserved word that has a particular meaning in the
programming language. The meaning of a keyword is predefined.
Keyword cannot be used as an identifier name in C language.
Example : while, if, do ....
10. Write a C program to find factorial of a number using iteration.
June 14
#include<stdio.h>
#include<conio.h>
void main()
{
int a,fact,i;
clrscr();
printf("Enter a number: ");
scanf("%d",&a);
fact=1;
i=1;
while(i<=a)
{
fact = fact * i;
i++;
}
printf("Factorial of %d is %d",a,fact);
getch();
}
Output: Enter a number: 3
Factorial of 3 is 6
11. What do you mean by C tokens?
C tokens are the basic buildings blocks in C language which are
constructed together to write a C program. Each and every smallest
individual unit in a C program are known as C tokens. C tokens are of
six types. They are,
1. Keywords (eg: int, while),
2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)

37
12. Write a C program for the following expression.
a. A=5<=8&&6!=5
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
a =5<=8&&6!=5;
printf("%d",a);
getch();
}
Output:1
b. A=B++ + ++B where b=50
#include<stdio.h>
#include<conio.h>
void main()
{
int b=50, a;
a=b++ + ++b;
printf("A=%d",a);
getch();
}
Output: A=102
13. Write a C program to implement the expression ((m+n)/p-m)*m),
where m=4;n=6;p=8.
#include<stdio.h>
#include<conio.h>
void main()
{
int k,m=4,n=6,p=8;
clrscr();
k=((m+n)/p-m)*m);
printf("%d",k);
getch();
}
Error: statement missing

38
14. What will be the outputs for the following program when the value
of i is 5 and 10.
void main()
{
int i;
scanf(%d”,&i);
if(i=5)
printf(“five”);
}
i=5 five
i=10 five

15. Define implicit type conversion. April / May 2016

Type conversions can be implicit which is performed by the


compiler automatically, or it can be specified explicitly through the use
of the cast operator. It is considered good programming practice to
use the cast operator whenever type conversions are necessary.

Example: int a=52,c;


float b=5.2;
c=a/b;
value of c=10 [since c is an integer value the result of
52/5.2=10.0 is type converted into integer]

39
Part – B

1. a. Problem formulation and problem solving

 Explain in detail about problem formulation and problem solving.

Problem formulation:
 A computer program is basically a set logical instruction written in
a set computer programming language that tells the computer how it
accomplishes a task.
 The process of developing a program starts with identifying the
problem first. Once a problem is well understood and documented a series of
problem solving techniques like algorithm, flowcharts and pseudo codes are
carried out in arriving at the most efficient solution.
 Planning the computer program:
o Whenever a user wants to use a computer for solving a
problem, the user has to perform various inter related tasks in a systematic
manner.
o All the activities that have to be performed by a user in
order to solve a problem using a computer is grouped into three phases:
a) Identifying the purpose.
 Identifying the parameters and constraints.
 Collecting information
b) Developing the program
c) Executing the program
Problem solving:
 Problem solving is the process of solving a problem in a
computer system by following a sequence of steps. The major steps that need
to be followed are:
o Preparing hierarchy chart
o Developing algorithm
o Drawing flowchart
o Writing Pseudo code.

40
1. b. Constants

 What are constants? Explain in detail about various types of


constants in C. May 2015
Constants:
 The constants refer to fixed values that the program may not alter
during its execution. These fixed values are also called literals.
 Constants can be
a) Numerical constants:
 integer constant,
 real constant,
b) Character constant
 Single Character constant
 String constant
 The constants are treated just like regular variables except that
their values cannot be modified after their definition.
a) Numerical Constants:
Integer constants: An integer literal can be a decimal, octal, or
hexadecimal constant.
Example: 578, 2,256
Real constants: A real constant has an integer part, a decimal
point, a fractional part, and an exponent part. Real constants
can be represented either in decimal form or exponential form.
-2
Example: 5e , 5.39
b) Character constants:
Single character constant: Character literals are enclosed in single
quotes, e.g., 'x', ‘1’and can be stored in a simple variable of char type. A
character literal can be a plain character (e.g., 'x'), an escape
sequence (e.g., '\t')
String constants: String literals or constants are enclosed in
double quotes "". A string contains characters that are similar
to character literals: plain characters, escape sequences, and
universal characters.
Example: “Hai”, “123”, “H12A”

41
1. c. Compilation and execution process in C

 Explain in detail about compilation and execution process in C.


Pre-processing, Compiling and Linking
 There are three basic phases that are important when
programming in C and using a C compiler.
 The phases are called pre-processing, compiling, and linking.
 When programming in other languages, only two phases are
required: compiling and linking.  
 A C input file is first passed to a pre-processing program called
the pre-processor.
 The output of the pre-processor is passed to the true-C compiler. 
 The output of the C compiler is then fed into a linker program. 
 The linker finally produces an executable form of the program. 
 The following diagram demonstrates a C program one.c being
converted into an executable program.
one.c  -->  PRE-PROCESSOR ->   tmp.c(temporary)   -> 
COMPILER  ->  one.obj   -> LINKER ->  one.exe (final Executable)
Pre-processing Phase:
 A C pre-processor is a program that accepts C code with pre-
processing statements and produces a pure form of C code that contains no
pre-processing statements.
 A pre-processor basically reads line by line from the input and
replicates the line to the output. If the line is a pre-processing statement, then
it performs the pre-processing directives.
 All pre-processing statements in C begin with the # symbol and
are at the beginning of a line.
 The operations of taking the input file and generating the output
file, pre-processed file, is called pre-processing.
Input File(ie One.c)   --->  Pre-processor     -->  Output File (ie tmp.c )
 The output file is then fed as input into the true C compiler.  If
there are no pre-processing directives in the original C input file, then the
output file will look identical to the input file.
 Also called pre-processor directives, pre-processor statements
are special statements that tell the pre-processor to perform special set of
operations. The main two pre-processor statements are the #define and the
#include statements. Pre-processor statement must be on independent lines.
Compile Phase:
 This is the true C compiler.
42
 The C compiler accepts a pre-processed output file from the pre-
processor and produces a special file called an object file.
 This object file contains machine code generated from the source
program
 Usually a special file extension (obj) is given to an object file.
Pre-processor Output File   ---> True C-Compiler    --->   Object File
 The compiler also removes all comments from the input file.
 A compiler searches all the errors of a program and lists them. If
the program is error free then it converts the code of program into machine
code and then the program can be executed by separate commands.
 An interpreter checks the errors of a program statement by
statement.
Link Phase:
 The link phase is implemented by the linker.
 The linker is a process that accepts as input object files and
libraries to produce the final executable program. Libraries contain object
code.
 This object code in turn contains functions.
 In the link phase the object code from the compile phase is bound
to the missing function code such as printf(). The function printf() is located in
the standard input and output libraries. The final executable now contains all
the necessary code for execution.
Object File ----> Linker (Searches Libraries)    ------>  Exe File
Errors:
 It is very important to know the different phases as many errors
are directly related to them.
 The errors generated can be pre-processing errors, compiler
errors, linker errors, logical errors, and run-time errors.
 A common pre-processor error is not finding the include file in
the include statement. Either the filename is spelled wrong or the pre-
processor has the wrong directory to search for that file.
 Compiler errors are generated whenever either the syntax of the
C language is not met or undefined symbols are met in the code.
 Linker Errors are generated when linker finds missing symbol
references in the object code generated by the compiler.
 Logical Errors are errors in the design of the program.
 Run-Time Errors: The last class of errors are those programs
that execute and fail.  These are called run-time errors. 

43
44
2. Branching statements in C

 Write about the needs of and types of branching statements in C


language and discuss with examples. Jan 2014, Nov / Dec 15

Need for branching statements:


The C language programs follow a sequential form of execution
of statements. Many times it is required to alter the flow of sequence of
instructions. C language provides statements that can alter the flow of a
sequence of instructions. These statements are called as control
statements. To jump from one part of the program to another, these
statements help. The control transfer may be unconditional or
conditional.
Types of branching statements: Branching Statement are of following
categories:
a) Simple if statement
b) if...else statement
c) Nested if...else statement
d) else if ladder.
Simple if statement: If statement is a conditional branching statement.
In conditional branching statement a condition is evaluated, if it is
evaluate true a group of statement is executed. The simple format of an
if statement is as follows:

if (expression) 
        statement;

If the expression is evaluated and found to be true, the single statement


following the "if" is executed. If false, the following statement is skipped. 
Program:
#include<stdio.h>
void main()
{
int price;
printf(“Enter the book price of computer programming”);
scanf(“%d”,&price);
if(price<500)
printf(“Purchase book”);
getch();
}

45
Output:
Enter the book price of computer programming 360
Purchase book
if..........else statement: The if...... else statement is an extension of the
simple if statement. The general form is:
if (test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
statement-x
If the test expression is true, then the true-block statement(s), immediately
following the if statement are executed; otherwise the false-block statement(s)
are executed. In either case, either true-block or false-block will be executed,
not both.
Program:
#include<stdio.h>
void main()
{
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n%2==0)
printf("The given number is even");
else
printf("The given number is odd");
getch();
}
Output:
Enter a number: 5
The given number is odd
Nested if ...........else statement: When a series of decisions are involved, the
programmers may have to use more than one if.....else statement in nested
form as follows:
If the condition-1 is false statement-3 will be executed; otherwise it
continues to perform the second test. If the condition-2 is true, the
statement-1 will be evaluated; otherwise the statement-2 will be
evaluated and then the control is transferred to the statement-x.

46
if (test condition1)
{
if (test condition 2)
{statement-1;}
else
{statement-2;}
}
else
{ statement-3;}
Program: statement-x;
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
if(n>0)
{
if(n%2==0)
printf("The number is positive and even");
else
printf("The number is positive and odd");
}
else
printf("The number is negative");
getch();
}
Output: Enter a number: 6
The number is positive and even
The else if ladder: There is another way of putting ifs together when
multipath decisions are involved. A multipath decision is a chain of ifs in
which the statement associated with each else is an if . It takes the
following general form: This construct is known as the else if ladder. The
conditions are evaluated from the top (of the ladder), downwards. As
soon as a true condition is found, the statement associated with is
executed and the control is transferred to the statement x (skipping the
rest of the ladder).When all the n conditions become false, then the final
else containing the default statement will be executed.

if (condition 1) statement 1 ;
else if (condition 2) statement 2;
else if (condition 3) statement
47 3;
else if (condition n) statement n;
else default statement; statement x;
Program: Consider an example of grading the students in an academic
institution. The grading is done according to the following rules:
Average marks Grade
75-100 Honours 60- 74 First Division 50- 59 Second Division 0- 49 Fail
#include<stdio.h>
#include<conio.h>
void main()
{
int marks;
clrscr();
printf("Enter the mark");
scanf("%d",&marks);
if (marks >=75)
printf("grade = Honours");
else if (marks>=60&&marks<75)
printf("grade = First Division");
else if (marks>=50&&marks<60)
printf("grade = Second Division");
else
printf("grade = Fail");
getch();
}
Output: Enter the mark 61 grade = First Division
Switch statement / Multiway Branching statement: The switch-
case statement is a multi-way decision making statement. Unlike the multiple
decisions statement that can be created using if-else, the switch statement
evaluates the conditional expression and tests it against the numerous
constant values. During execution, the branch corresponding to the value that
the expression matches is taken. The value of the expressions in a switch-
case statement must have to be an ordinal type i.e. integer, char, short, long,
etc. Double and Float are not allowed.
The syntax of switch statement is as follows:
switch( expression )
{case constant-expression1:
statements1; break
case constant-expression2:
statements2; break;
case constant-expression3:
statements3; break;
default : statements4; break;}
48
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int choice,a,b;
clrscr();
printf("1 ADDITION\t2 SUBTRACTION\t3 MULTIPLICATION\t4
DIVISION\n");
printf("Enter your choice:");
scanf("%d",&choice);
printf("Enter the values for a and b:");
scanf("%d%d",&a,&b);
switch(choice)
{
case 1:
printf("%d + %d = %d",a,b,a+b); break;
case 2:
printf("%d - %d = %d",a,b,a-b); break;
case 3:
printf("%d * %d = %d",a,b,a*b); break;
case 4:
printf("%d / %d = %d",a,b,a/b); break;
default:
printf("Wrong choice"); break;
}
getch();
}
Output: 1 ADDITION 2 SUBTRACTION 3
MULTIPLICATION 4 DIVISION
Enter your choice: 1
Enter the values for a and b: 4 5 4+ 5 = 9

3. Looping statements in C

 Write about the need and types of looping statements in C and


discuss with examples. Jan 2014
OR

49
Differentiate entry and exit checked looping constructs with
example. May / June
2014
Need for looping statements: A computer is used for performing many
repetitive types of tasks The process of repeatedly performing tasks is known
as looping .The statements in the block may be executed any number of times
from zero to up to the Condition is true. The loop is that in which a task is
repeated until the condition is true or the loop will execute all the statements
until the given condition is not to be false.
Types of looping statements: Depending on the position of the control
statement in the loop, a control structure can be classified into two types;
 Entry Controlled: The types of loop where the test condition is
stated before the body of the loop, are known as the entry controlled loop. So
in the case of an entry controlled loop, the condition is tested before the
execution of the loop. If the test condition is true, then the loop gets the
execution, otherwise not.
 Exit Controlled: The types of loop where the test condition is
stated at the end of the body of the loop, are know as the exit controlled loops.
So, in the case of the exit controlled loops, the body of the loop gets execution
without testing the given condition for the first time. Then the condition is
tested. If it comes true, then the loop gets another execution and continues till
the result of the test condition is not false.
 In The loop generally there are three basic operations are
performed
i) Initialization
ii) Condition check
iii) Increment
Looping Constructs in C:
C provides a number of looping way.
a) for loop
b) while loop
c) do-while loop
a. for loop:
 It is an Entry Controlled Loop because it first initializes the loop
variable and then the condition is checked.
 If the condition is true then it will execute the statements within
the loop body and then after it increments or decrements the value of the loop
variable.

50
 In for loop all the basic operations like initialization, condition
checking and incrementing or decrementing all these are performed in only
one line.
 Syntax:

for( initialization; conditional expression; increment/decrement)


{
Single statement
or
Block of statements;
}

Program
#include <stdio.h>
void main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d\t ",i);
}
}
Output : 0 1 2 3 4 5 6 7 8 9
b. while loop:
 while loop is Known as Entry Controlled Loop because in the
while loop first the loop variable is initialized and then the condition is checked
 If the condition is true then it will execute the statements within
the loop body and then after it increments or decrements the value of the loop
variable.
 Otherwise the loop body will be skipped and the statement next to
loop block will be executed.

51
Syntax:
while ( conditional expression )
{
Single statement
or
Block of statements;
}

Program :
#include <stdio.h>
void main()
{
int i=0;
while(i<10)
{
printf("%d\t",i);
i++;
}
}
Output : 0 1 2 3 4 5 6 7 8 9
c. do ... while loop:
 This is also called as exit controlled loop.
 It is just like a while loop except that the test condition is checked
at the end of the loop rather than the start. This has the effect that the content
of the loop are always executed at least once.
Syntax:
do
{
Single statement
or
Block of statements;
}while(conditional expression);
Program :
#include <stdio.h>
void main()
{
int i=0;
do
{
printf("%d\t",i);
52
i++;
} while(i<10);
}
Output : 0 1 2 3 4 5 6 7 8 9

4.Input and output statements in C

 Explain briefly the formatted and unformatted I/O functions in C.


Describe the various input and output statements in C with
suitable examples. May / June 16

Input : In any programming language input means to feed some data
into program. This can be given in the form of file or from command line. C
programming language provides a set of built-in functions to read given input
and feed it to the program as per requirement.
Output : In any programming language output means to display some data on
screen, printer or in any file. C programming language provides a set of built-
in functions to output required data.
There are number of I/O functions in C based on the data types.
The I/O functions are classified into two types:
Formatted I/O functions. Formatted I/O function accepts or
present in a particular format.
 printf(): Used to print any combination of data.
Syntax:
printf(“control_string 1, - - , control_string n”,variable1, - - - , variable n);
Control String may be format specifier, escape sequence, string to
be displayed.
Format
Data type
specifier
%d Integer
%f Float
%c Character
%s string
 scanf(): reads all types of data values. It is used for runtime assignment
of variables.
Syntax:
scanf(“control_string 1, - - , control_string n”,&variable1, - - - ,variable n);
Program:
#include<stdio.h>
#include<conio.h>
53
void main()
{
int no;
char ch;
char s[20];

printf("Enter a character : ");


scanf("%c",&ch);
printf("Enter a No : ");
scanf("%d",&no);
printf("Enter a Word or String : ");
scanf("%s",&s);
printf("\n Character : %c",ch);
printf("\n No : %d",no);
printf("\n String : %s",s);
getch();
}
Output:

Unformatted I/O functions. This function cannot control the format of reading
and writing the data. There are two types of unformatted console Input/Output
functions:-
 Character I/O functions: These are the functions that can input/output
of one character at a time. These functions deal with the individual
character value. Some of the character I/O functions are:
o getchar():This is used for reading a character from the keyboard.
Syntax:  Character_variable  = getchar();
Ex.:- char ch; ch=getchar( ); 

54
This statement accepts a character and stores it to "ch". In this
function the typed character is echoed to the monitor and waits for carriage
return (Enter) to assign it to variable. 
o putchar(): It is used to display a character
Syntax: putchar(character_variable/'character')
Ex: putchar(ch);
o getch():It also accepts a single character. It doesn't display the
character at the time of typing. And also it doesn't require enter to
assign value to variable.  
Syntax: Character_variable  = getch()
o putch(): It is also used to display a single character on the
screen.
Syntax : putch(variable name);
o getche():It is same as getch( ) but only difference is it it echoes
the character at the time of typing on the monitor.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character:");
ch=getchar();
putchar(ch);
getch();
}
Output: Enter a character: a
a
 String I/O functions: These are the functions that are used to
input/output of whole string. Following functions are used to input and
output in program:
o gets():reads a whole line of input into a string until a newline or
EOF is encountered. It is critical to ensure that the string is large
enough to hold any expected input lines. When all input is
finished, NULL as defined in stdio.h is returned.
Syntax: gets(str var);
Ex: gets(s);
o puts(): writes a string to the output means it displays the
character on the screen, and ends it with a newline character.
55
Syntax: puts(string);
Ex : puts(hai);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char s[20];
clrscr();
puts("Enter a string");
gets(s);
puts("The string is");
puts(s);
getch();
}
Output: Enter a string:
Hai
The string is
Hai

5. Operators available in C

 What are the various operators available in C. Discuss each one of


them in detail. Nov / Dec 14,15
Explain the different types of operators available in C.
May/June 15,16
OPERATORS IN C
 The symbols which are used to perform logical and mathematical
operations in a C program are called C operators.
 These C operators join individual constants and variables to form
expressions.
 Consider the expression A + B * 5. where, +, * are operators, A, B
are variables, 5 is constant and A + B * 5 is an expression.
Simple and compound expression
 An expression that has only one operator is called simple
expression. Eg.a+2
 An expression that involves more than one operator is called as
compound expression. Eg.b=2+3*5

56
Classification of operators
1 Based on no of operands on which an operator operates
2. Based on role of the operator.

1. Based on no of operands on which an operator operates


a. unary operator : it operates on only one operand. Eg.-3
b. binary operator: it operates on two operands. Eg. 2+3
c. ternary operator : it operates on three operands.
2. Based on the role of the operator
Types of C operators:
C language offers many types of operators. They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
1. Arithmetic Operators
C Arithmetic operators are used to perform mathematical calculations like
addition, subtraction, multiplication, division and modulus in C programs.
S.no Arithmetic Operators Operation Example
1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
Example program for C arithmetic operators:
#include <stdio.h>
int main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
57
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);
}
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0

2. Assignment operators in C:
o In C programs, values for the variables are assigned using
assignment operators.
Operators Example  Explanation 
Simple assignment
= sum=10 10 is assigned to variable sum
operator
+= sum+=10 This_is_same_as_sum=sum+10…………
-= sum-=10 This is same as sum = sum-10
*= sum*=10 This is same as sum = sum*10
Compound
/+ sum/=10 This is same as sum = sum/10
assignment operators
%= sum%=10 This is same as sum = sum%10
&= sum&=10 This is same as sum = sum&10
^= sum^=10 This is same as sum = sum^10
Example program for C assignment operators:
# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total = Total+i
}
printf("Total = %d", Total);
}
Output:
Total = 45
3. Relational operators in C: Relational operators are used to find the
relation between two variables. i.e. to compare the values of two
variables in a C program.
58
S.no Operators Example  Description
1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
Example program for relational operators in C:
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal"); }
}
Output:
m and n are not equal
4. Logical operators in C:
These operators are used to perform logical operations on the given
expressions. There are 3 logical operators in C language.
S.no Operators Name Example Description
logical It returns true when both conditions
1 && (x>5)&&(y<5)
AND are true
logical It returns true when at-least one of
2 || (x>=10)||(y>=10)
OR the condition is true
It reverses the state of the operand
logical “((x>5) && (y<5))”
3 ! !((x>5)&&(y<5))
NOT If “((x>5) && (y<5))” is true, logical
NOT operator makes it false
Example program for logical operators in C:
#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
59
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \"But, status is inverted as
false\n");
}
}
Output:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false
5. Bit wise operators in C:
These operators are used to perform bit operations. Decimal values are
converted into binary values which are the sequence of bits and bit wise
operators work on these bits.
Bit wise operators in C language are & , |, ~, ^, << and >> .

60
Truth table for bit wise operation                                          
Bit wise operators
 X y  x|y x&y x^y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
  << Left Shift
>> Right Shift
 Consider x=40 and y=80. Binary form of these values is given below.
x = 00101000, y=  01010000
x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x =1111111111111111111111111111111111111111111111111111111111
010111= -41(dec)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)
Example program for bit wise operators in C:
#include <stdio.h>
int main()
{
int m=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}

61
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
6. Conditional or ternary operators in C: Conditional operators return
one value if condition is true and returns another value is condition is
false. This operator is also called as ternary operator.
Syntax     :        (Condition? true_value: false_value);
Example :        (A > 100  ?  0  :  1); // if A is greater than 100, 0 is returned else
1 is returned. 
Example program for conditional/ternary operators in C:
#include <stdio.h>
int main()
{ int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Output:
x value is 1
y value is 2
7. C – Increment/decrement Operators

 Increment operators are used to increase the value of the variable by


one and decrement operators are used to decrease the value of the
variable by one in C programs.
 Syntax:
Increment operator : ++var_name; (or) var_name++;
Decrement operator :     - - var_name; (or) var_name –  -;
Difference between pre/post increment & decrement operators in C:
S.no Operator type Operator Description
++i Value of i is incremented before assigning it to
1 Pre increment
variable i.
i++ Value of i is incremented after assigning it to
2 Post-increment
variable i.
– –i Value of i is decremented before assigning it
3 Pre decrement
to variable i.
62
i– – Value of i is decremented after assigning it to
4 Post_decrement
variable i.
 Example program for increment operators in C:
#include <stdio.h>
void main()
{
int c=2;
clrscr();
printf("%d\n",c++); //this statement displays 2 then, only c
incremented by 1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is
displayed.
getch();
}
Output:
2
4
 Example program for decrement operators in C:
#include <stdio.h>
void main()
{
int c=2;
clrscr();
printf("%d\n",c--); //this statement displays 2 then, only c
incremented by 1 to 3.
printf("%d",--c); //this statement increments 1 to c then, only c is
displayed.
getch();
}
Output:
2
0

63
8. Special Operators in C:
 S.no Operators Description
This is used to get the address of the
1 & variable.
Example : &a will give address of a.
This is used as pointer to a variable.
2 * Example : * a  where, * is pointer to
the variable a.
This gives the size of the variable.
3 Sizeof () Example : size of (char) will give us
1.
Example program for & and * operators in C:
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output:
50
Example program for sizeof() operator in C:
sizeof() operator is used to find the memory space allocated for each C data
types.
#include <stdio.h>
int main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));
return 0;
64
}
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

6. a. DATA TYPES IN C

Discuss the basic data types in C. April / May 2016

Data Types is one of the important attribute of an Identifier.


Data type determines the possible values that an identifier can have and the
valid operations that can be applied on it.
Data types in C language can be classified into the following categories.
1. Basic or Primitive Data types
2. Derived Data Types
3. User Defined Data types

1. BASIC DATA TYPE


The five basic types available in C are:
1. Character (char)
2. Integer (int)
3. Float
4. Double
5. No value available(void)
Character Types:
 A single character can be defined as character (char) type data.
 Characters are usually stored in 8 bits (one byte) of internal storage.

65
 The qualifier may be signed or unsigned.
Unsigned chars have values between 0 and 255, signed char have values
from -128 to +127.
Integer Types:
 Integers are whole numbers with a range of values supported by a
particular machine.
 Integers occupy two bytes of storage. A signed integer uses one bit for
sign and 15 bits for the magnitude of the number
 C has three classes of integer storage namely short int, int and long int.
Floating Point Types and Double:
 Floating point or real number are stored in 32 bits (4 Bytes) with 6 digits
of precision.
 Floating point numbers are defined in C by the keyword float.
 A double data type number uses 64 bits giving a precision of 14 digits.
These are known as double precision numbers.
void Types:
The void types has no values. This is usually used to specify the type of
functions. The type of a function is said to be void when it does not return any
value to the calling function. It contains nothing or a NULL value. This data
type is used to specify return values of function. If there is nothing to return
from a function, the return type can be specified as “void”.
Eg:
void main()
{
------------
------------
}
Following tables shows the Size and Range of Data Types on a 16-bit
Machine:
Type Size (bits/bytes) Range
Char 8/1 -128 to 127
Int 16 / 2 -32,768 to +32,767
float 32 / 4 3.4E - 38 to 3.4E + 38
double 64 / 8 1.7E-308 to 1.7E+308
DERIVED DATA TYPES
a. Arrays
b. Pointer
c. Function

66
a. Arrays: Arrays can be defined as the collection of similar type of data. It
can also be called as subscripted variables. Each value in the array can
be retrieved using the subscript.
Example: int mark[100];
here the variable mark is defined as an array and it can hold 100 values
of type integer. Each value can be accessed as Mark[0], Mark[1], …….
Mark[99]
b. Pointer: A pointer is a variable whose value is the address of another
variable, i.e., direct address of the memory location.
The general form of a pointer variable declaration is: type *var-name;
type is the pointer's base type; it must be a valid C data type and var-
name is the name of the pointer variable.
c. Function: A function is a group of statements that together perform a
task. Every C program has at least one function, which is main(),
A function declaration tells the compiler about a function's name, return
type, and parameters. A function definition provides the actual body of
the function.
The general form of a function definition in C programming language is
as follows:
return type function_name(parameter list)
{
Body of the function
}
USER DEFINED DATA TYPE
User defined data type are those which are derive from the basic data types.
Some of the user defined data types are
a. Structures
b. Unions
c. Enumeration
Structures
Structures are nothing but a collection of data items. Unlike in arrays, it can
hold set of data items of different data types under a single name. This data
type can be created using the keyword struct
Eg:
struct student
{
int rno;
char name[25];
float avg;};
struct student s1, s2;
67
student is an user defined data type. The structure variable s1 consist of 3
values namely rno, name and avg.
Union
Union is same as that of structure; here the main difference is in the allocation
of memory. In structure the memory is allocated for each and every member.
Here the maximum memory needed to store any of a variable is allocated and
the other members share the same. In union only one member will be active
at a time. The union keyword is used to create this data type.
Eg:
union student
{
int rno;
char name[25];
float avg;
};
union student s1, s2;
ENUMERATED DATA TYPE:
Enumerated data types are those in which a variable can contain only some
specific set of values. For example if a variable needs to hold only the moths,
it can have any one of the values from January to December. These types of
variables can be created as enumerated data types. This is done using the
key word “enum”.
Eg:
enum months = { “January”, “Feburary”, “March”, “April”, “May”, “June”, “July”,
“August”, “September”, “October”, “November”, “December” };
months m1, m2;
Here the variables m1 and m2 are of enumerated data types. It can
hold only the values from January to December as declared.

6. b. Structure of a C program

 Explain in detail about structure of a C program.


C language is very popular language among all the languages.
The general basic structure of C program is shown in the figure below.
The whole program is controlled within main ( ) along with left
brace denoted by “{” and right braces denoted by “}”.
If you need to declare local variables and executable program
structures are enclosed within “{” and “}” is called the body of the main
function.

68
The main ( ) function can be preceded by documentation,
preprocessor statements and global declarations. 

Documentations: The documentation section consist of a set of comment


lines giving the name of the program, the another name and other details,
which the programmer would like to use later.
Preprocessor Statements
The preprocessor statement begin with # symbol and are also called the
preprocessor directive. These statements instruct the compiler to include C
preprocessors such as header files and symbolic constants before compiling
the C program. Some of the 8preprocessor statements are listed below.

Global Declarations: The variables are declared before the main ( ) functions
as well as user defined functions are called global variables. These global
variables can be accessed by all the user defined functions including main ( )
function.
The main ( ) function: Each and Every C program should contain only one
main ( ). The C program execution starts with main ( ) function. No C program
is executed without the main function. The main ( ) function should be written
in small (lowercase) letters and it should not be terminated by semicolon.
69
Main ( ) executes user defined program statements, library functions and user
defined functions and all these statements should be enclosed within left and
right braces.
Braces: Every C program should have a pair of curly braces ({, }). The left
braces indicates the beginning of the main ( ) function and the right braces
indicates the end of the main ( ) function. These braces can also be used to
indicate the user-defined functions beginning and ending. These two braces
can also be used in compound statements.
Local Declarations: The variable declaration is a part of C program and all
the variables are used in main ( ) function should be declared in the local
declaration section is called local variables. Not only variables, we can also
declare arrays, functions, pointers etc. These variables can also be initialized
with basic data types. For examples:
Code:
main ( )
{
int sum = 0;
int x;
float y;
}
Here, the variable sum is declared as integer variable and it is
initialized to zero. Other variables declared as int and float and these
variables inside any function are called local variables.
Program statements: These statements are building blocks of a program.
They represent instructions to the computer to perform a specific task
(operations). An instruction may contain an input-output statements, arithmetic
statements, control statements, simple assignment statements and any other
statements and it also includes comments that are enclosed within /* and */ .
The comment statements are not compiled and executed and each
executable statement should be terminated with semicolon.
User defined functions: These are subprograms, generally, a subprogram is
a function and these functions are written by the user are called user ; defined
functions. These functions are performed by user specific tasks and this also
contains set of program statements. They may be written before or after a
main () function and called within main () function. This is an optional to the
programmer.
Now, let us write a small program to display some message shown below.
Code:
# include <stdio.h>
main()
70
{
printf ("welcome to the world of C/n");
}

7.a.C program to print Fibonacci series


 Write a C program to print Fibonacci series of a given number.
Jan 2014
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, first = 0, second = 1, next, c;
clrscr();
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0; c <n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
getch();
}
Output: Enter the number of terms
5
First 5 terms of Fibonacci series are:-
0
1
1
2
3

71
7b. C program to display a pyramid structure using numbers

 Write a C program that displays a pyramid structure using


numbers.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, c, a = 1;
clrscr();
printf("Enter the number of rows of to print\n");
scanf("%d", &n);
 for (i = 1; i <= n; i++)
{
for (c = 1; c <= i; c++)
{
printf("%d ",a);
a++;
}
printf("\n");
}
getch();
}
Output: Enter the number of rows of to print
3
1
2 3
4 5 6

72
7c. C programs to display vowels in the read character
 Write a C program that reads a character and displays only the
vowels using switch case structure.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char x1,x;
clrscr();
printf("\n Enter any character:");
scanf("%c",&x);
x1=toupper(x);
switch(x1)
{
case 'A': printf("\n%c is a vowel",x); break;
case 'E': printf("\n%c is a vowel",x); break;
case 'I': printf("\n%c is a vowel",x); break;
case 'O': printf("\n%c is a vowel",x); break;
case 'U': printf("\n%c is a vowel",x); break;
default: printf("\n%c is not a vowel");
}
getch();
}
Output:
Enter any character: a
a is a vowel

7d. C program to check whether a given number is prime or not

 Write a C program to check whether a given number is prime or


not. May / June 14
Program:
#include <stdio.h>
void main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
73
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
getch();
}
Output:
Enter a positive integer: 29
29 is a prime number.

7e. C program to find sum of the digits of an integer

 Write a C program to find sum of the digits of an integer.


May/June 2014
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,temp,i,sum=0;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
temp=n;
while(temp>0)
{
i=temp%10;
sum=sum+i;
temp=temp/10;
}
printf("The sum of digits of %d is %d",n,sum);
getch();
}
74
Output:
Enter a number: 123
The sum of digits of 123 is 6

7f. C program to print the prime numbers lesser than 10

 Write a C program to print the prime numbers lesser than 10.


Program:
#include <stdio.h>
#include<conio.h>
void main()
{
int n,j,i, flag=0;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
{
flag=1;
break;
}
flag=0;
}
if (flag==0)
printf("%d\t ",i);
getch();
}
}
Output:
Enter a positive integer: 10
2 3 5 7

7g. C program to reverse a number

75
 Write a C program to reverse a number.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,temp,d,rev=0;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
while(temp>0)
{
d=temp%10;
rev=rev*10+d;
temp=temp/10;
}
printf("The reverse of the number %d is %d",n,rev);
getch();
}

Output:

Enter a number: 123

The reverse of the number 123 is 321

7h. C program to check even or odd


 Write a C program to check whether the given number is even or
odd.
Program:
#include<stdio.h>
main()
{
int a;
printf("Enter a Number\n");
scanf("%d",&a);
if(a%2==0)
printf("The Given Number is Even");
else
76
printf("The Given Number is Odd");
}
OUTPUT:
Enter a Number
13
The Given Number is Odd

7i. C program to check given year is leap or not

 Write a C program to check whether the given year is leap or not.


Program:
#include<stdio.h>
main()
{
int year;
printf("Enter a year: ");
scanf("%d",&year);
if(year%4==0 || year%400==0)
printf("The given year is a leap year");
elseif(year%100==0)
printf("The given year is not a leap year");
else
printf("The given year is not a leap year");
}
OUTPUT:
Enter a year: 2012
The given year is a leap year

7j. C program to find greatest among three numbers

 Write a C program to find greatest among three numbers.


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,big;
clrscr();
printf("\nEnter three numbers:");
scanf("%d%d%d",&a,&b,&c);
77
if(a>b&&a>c)
printf("%d is the greatest number",a);
else if(b>c)
printf("%d is the greatest number",b);
else
printf("%d is the greatest number",c);
getch();
}
Output:
Enter three numbers: 5 6 20
20 is the greatest number

7k. C program to find greatest among two numbers

 Write a C program to find greatest among two numbers.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("\nEnter two numbers:");
scanf("%d%d%d",&a,&b);
if(a>b)
printf("%d is the greatest number",a);
else
printf("%d is the greatest number",b);
getch();
}
Output:
Enter numbers: 5 6
6 is the greatest number

7l. C program to swap two variables without using intermediate


variable

 Write a C program to swap two numbers without using


intermediate variable.
78
Program:
#include <stdio.h>
void main()
{
int a,b;
printf("enter number1: ie a");
scanf("%d",a);
printf("enter number2:ie b ");
scanf("%d",b);
printf(“value of a and b before swapping is a=%d,b=
%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf(“value of a and b after swapping is a=%d,b=%d"a,b);
}
Output:
Enter number1: 3
Enter number2: 6
Value of a and b before swapping is a=3, b=6
Value of a and b after swapping is a=6, b=3

7m. C program for Armstrong number checking

 Write a C program to check whether the given number in


Armstrong or not. (Armstrong number: 153, 13+53+33=153)
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,temp,i,sum=0;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
temp=n;
while(temp>0)
{
i=temp%10;
sum=sum+i*i*i;
79
temp=temp/10;
}
if(sum==n)
printf(“%d is an Armstrong number”,n);
else
printf(“%d is not an Armstrong number”,n);
getch();
}
Output:
Enter a number: 371
371 is an Armstrong number
Enter a number: 432
432 not an Armstrong number

7n. C program to check the given number is palindrome or not

 Write a C program to check whether the given number is


palindrome or not.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,temp,d,rev=0;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
temp=n;
while(temp>0)
{
d=temp%10;
rev=rev*10+d;
temp=temp/10;
}
if(n==rev)
{
printf("The number %d is a palindrome”,n);
}
else
{
80
Pritnf(“The number %d is not palindrome”,n);
}
getch();
}
Output:
Enter a number: 121
The number 121 is a palindrome

7o. C program to find roots of a quadratic equation

 Write a C program to find roots of a quadratic equation.


May/June 14,15
#include <stdio.h>
#include <math.h>

int main()
{
double a, b, c, determinant, root1,root2, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
determinant = b*b-4*a*c;
// condition for real and different roots
if (determinant > 0)
{
// sqrt() function returns square root
root1 = (-b+sqrt(determinant))/(2*a);
root2 = (-b-sqrt(determinant))/(2*a);
printf("root1 = %f and root2 = %f",root1 , root2);
}
//condition for real and equal roots
else if (determinant == 0)
{
root1 = root2 = -b/(2*a);
printf("root1 = root2 = %f;", root1);
}
// if roots are not real
else
{
81
realPart = -b/(2*a);
imaginaryPart = sqrt(-determinant)/(2*a);
printf("root1 = %f+%fi and root2 = %f-%fi", realPart,
imaginaryPart, realPart, imaginaryPart);
}

return 0;
}
Output:
Enter coefficients a, b and c: 2.3 4 5.6
Roots are: -0.87+1.30i and -0.87-1.30i

7p. C program to find sum on 1st n natural numbers

 Write a C program to find sum of first n natural numbers.


Write a C program for the following series: 1+2+3……….+n
May 16

#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, sum = 0;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=1; i <= n; i++)
{
sum += i; // sum = sum+i;
}
printf("Sum = %d",sum);
getch();
}
Output:
Enter a positive integer: 10
Sum = 55

82
UNIT III

ARRAYS AND STRINGS

Arrays – Initialization – Declaration – One dimensional and Two


dimensional arrays. String- String operations – String Arrays. Simple
programs- sorting- searching – matrix operations.
Part – A
1. Define array. Jan 2014
What is an array? Give an example. April 15

An array is a fixed size sequential collection of elements of the same type.


It is a linear and homogenous data structure. They are able to store more than
one value at a time.
Example: int a[5];

2. Define string with an example.


How a character string is declared? May/June 15

Strings: The group of characters, digit and symbols enclosed within


quotes is called as String (or) character Arrays. Strings are always terminated
with ‘\0’ (NULL) character. The compiler automatically adds ‘\0’ at the end of
the strings.
Example: char name[]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’\0’};
The characters of a string are stored in contiguous memory locations as
follows:
C O L L E G E \0
100 1001 1002 100 100 1005 100 1007
0 3 4 6

3. Write example code to declare two dimensional arrays. June 2014

A two dimensional array can be thought as a rectangular display of


elements with rows and columns. A two dimensional array is a collection of a
number of one dimensional arrays, which are placed one after another.
Declaration : datatype arrayname[rowsize][colsize];
Example : int a[3][3];
4. Name the library functions used for string handling.
Jan 14/June 14
 strlen() – used to calculate the length of a string
83
 strcat() – used to concatenate two strings
 strcpy() – used to copy a string from one string variable to another
 strrev() – used to reverse a string

5. Give an example for initialization of a string array. Nov / Dec 14

Example: char name[]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’\0’};


The characters of a string are stored in contiguous memory locations as
follows:
C O L L E G E \0
1000 1001 1002 1003 1004 1005 1006 1007

6. Declare a float array of size 5 and assign 5 values to it.


Nov / Dec 14

float a[5]={1.5,1.0,1.6,1.8,1.9};

7. Declare a character array of size 5 and assign vowels to it.


Dec 15

Char vowel[5]={‘a’,’e’,’i’,’o’,’u’};

8. Define sorting.

Arranging elements in a specific order, either in ascending or


descending order is known as sorting.

9. Define searching.

The process seeking a specified element in an array is called searching.

10. Why the array is needed?

Need for array: In C programming, one of the frequently


arising problems is to handle similar types of data. For example: If
the user wants to store marks of 100 students. This can be done
by creating 100 variables individually but, this process is rather
tedious and impracticable. This type of problem can be handled in
C programming using arrays.

84
Part – B

1. String

 Explain in detail about the strings.


In C programming, array of character are called strings. A string
is terminated by null character \0.
“c string tutorial”
Here, "c string tutorial" is a string. When, compiler encounters
strings, it appends null character at the end of string.
G \0
Declaration of strings: Strings are declared in C in similar manner as
arrays. Only difference is that, strings are of char type.
char s[5];

Initialization of strings:
char c[]="abcd"; OR char c[5]="abcd"; OR char
c[]={'a','b','c','d','\0'};OR
char c[5]={'a','b','c','d','\0'};

Program:
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Output:
Enter name: Dennis Ritchie
Your name is Dennis.

85
2. Array
 Write short notes on array.
Need for array: In C programming, one of the frequently arising
problems is to handle similar types of data. For example: If the
user wants to store marks of 100 students. This can be done by
creating 100 variables individually but, this process is rather
tedious and impracticable. This type of problem can be handled in
C programming using arrays.
Definition: An array is a sequence of data item of
homogeneous value (same type).
Types of array: Arrays are of two types:
 One-dimensional arrays
 Multidimensional arrays
Declaration of one dimensional array:
data_type
array_name[array_size];
For example:
int age[5];
Here, the name of array is age. The size of array is 5, i.e.,
there are 5 items (elements) of array  age. All elements in an
array are of the same type (int, in this case).
Array elements
Size of array defines the number of elements in an array.
Each element of array can be accessed and used by user
according to the need of program. For example:
int age[5];

Note that, the first element is numbered 0 and so on. Here,


the size of array age is 5 times the size of int because there are 5
elements. Suppose, the starting address of age[0] is 2120d and
the size of int be 4 bytes. Then, the next address (address of  a[1])
will be 2124d, address of a[2] will be 2128d and so on.
Initialization of one-dimensional array:
Arrays can be initialized at declaration time in this source
code as:
int age[5]={2,4,34,3,4};
It is not necessary to define the size of arrays during
initialization.
86
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by
calculating the number of elements of an array.

Program:
#include <stdio.h>
void main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
clrscr();
/* initialize elements of array n to 0 */
for ( i = 0; i < 5; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 5; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
getch();
}
Output:
Element[0]=100
Element[1]=101
Element[2]=102
Element[3]=103
Element[4]=104
3. String operations

 Explain in detail about various string operations. Dec 14


 Explain in detail about various string handling functions. May 15

i. strlen(): In C, strlen() function calculates the length of string. It is


defined under "string.h" header file. It takes only one argument, i.e,
string name.Function strlen() returns the value of type integer.
87
Syntax: temp_variable = strlen(string_name);

Program:
#include <stdio.h>
#include <string.h>
void main()
{
char c[20];
printf("Enter string: ");
gets(c);
printf("Length of string c=%d \n",strlen(c));
}
Output : Enter string: String
Length of string c=6
ii. strcpy():Function strcpy() copies the content of one string to the
content of another string. It is defined under "string.h" header file. It
takes two arguments.
Syntax: strcpy(destination,source);
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10],s1[10];
clrscr();
puts("Enter a string");
gets(s1);
strcpy(s,s1);
puts("The string after copy");
puts(s);
getch();
}
Output:
88
Enter a string:
Hai
The string after copy
Hai
Here, source and destination are both the name of the string.
This statement, copies the content of string source to the
content of string destination.
iii. strcat():In C programming, strcat() concatenates(joins) two
strings.It takes two arguments, i.e, two strings and resultant string is
stored in the first string specified in the argument.
Syntax: strcat(destination,source);
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10],s1[20];
clrscr();
puts("Enter the first string:");
gets(s);
puts("Enter the second string:");
gets(s1);
strcat(s,s1);
puts(“The concatenated string is:”);
puts(s);
getch();
}
Output:
Enter the first string: come
Enter the second string: in
The concatenated string is:
comein
iv. strcmp():In C, strcmp() compares two string and returns value 0, if
the two strings are equal. It is defined under "string.h" header file.
Syntax: temp_varaible=strcmp(string1,string2);
Program:
#include <stdio.h>
#include <string.h>
void main()
89
{
char a[100], b[100];
clrscr();
printf("Enter the first string:");
gets(a);
printf("Enter the second string:");
gets(b);
if( strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
getch();
}
Output:
Enter the first string:hai
Enter the second string: Hai
Entered strings are not equal.
v. strrev(): This function reverses a given string in C language.
Syntax: strrev(str)
Program:
#include <stdio.h>
#include <string.h>
 void main()
{
char arr[100];
printf("Enter a string to reverse\n");
gets(arr);
strrev(arr);
printf("Reverse of entered string is %s",arr);
}
Output:
Enter a string: welcome
Reverse of entered sting is emoclew
vi. strlwr() function converts all the uppercase characters in that string
to lowercase characters. The resultant from strlwr() is stored in the same
string.
Syntax: strlwr(string_name);
Program:
#include <stdio.h>
#include <string.h>
90
void main()
{
char str1[]="LOWer Case";
puts(strlwr(str1)); //converts to lowercase and displays it.
}
Output: lower case
vii. strupr()function converts all the lowercase characters in that string
to uppercase characters. The resultant from strupr() is stored in the
same string.
Syntax: strlwr(string_name);
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[]="UPPEer case";
puts(strupr(str1)); //converts to upper case and displays it.
}
Output: UPPER CASE
4. a Sum of two matrices

 Write a C program to find sum of two matrices. Jan 14, May 15


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[12][12],b[12][12],n,m,p,q,i,j,c[12][12];
clrscr();
printf("Enter the no of rows and columns of matrix a:");
scanf("%d %d",&n,&m);
printf("Enter the no of rows and columns of matrix b:");
scanf("%d %d",&p,&q);
if((n==p)&&(m==q))
{
printf("Matrix Addition can be performed:\n");
printf("Enter Matrix A:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
91
{
scanf("%d",&a[i][j]);
}
}
printf("Enter Matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<n;i++)
for(j=0;j<m;j++)
c[i][j]=a[i][j]+b[i][j];
printf("Matrix A:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("Matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("The resultant matrix is : \n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",c[i][j]);
}
92
printf("\n");
}

}
else
printf("Matrix Addition is not possible");
getch();
}
Output:
Enter matrix A: 2 1 2
321
233
Enter matrix B: 2 1 0
230
112
Resultant Matrix is:
422
551
345
4b.C program to perform subtraction of two matrices
 Write a C program to subtract two matrices and display the
resultant matrix. May / June 15

#include<stdio.h>
#include<conio.h>
void main()
{
int a[12][12],b[12][12],n,m,p,q,i,j,c[12][12];
clrscr();
printf("Enter the no of rows and columns of matrix a:");
scanf("%d %d",&n,&m);
printf("Enter the no of rows and columns of matrix b:");
scanf("%d %d",&p,&q);
if((n==p)&&(m==q))
{
printf("Matrix subtraction can be performed:\n");
printf("Enter Matrix A:\n");
for(i=0;i<n;i++)
{
93
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter Matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<n;i++)
for(j=0;j<m;j++)
c[i][j]=a[i][j]-b[i][j];
printf("Matrix A:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("Matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("The resultant matrix is : \n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",c[i][j]);
94
}
printf("\n");
}
}
else
printf("Matrix subtraction is not possible");
getch();
}

95
5. C program to multiply two matrices

 Write a C program to multiply two matrices. Dec 15, May 16


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[12][12],b[12][12],n,m,p,q,i,j,k,c[12][12];
clrscr();
printf("Enter the no of rows and columns of matrix a:");
scanf("%d %d",&n,&m);
printf("Enter the no of rows and columns of matrix b:");
scanf("%d %d",&p,&q);
if(m==p)
{
printf("Matrix Multiplication can be performed:\n");
printf("Enter Matrix A:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter Matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
c[i][j]=0;
for(k=0;k<m;k++)
{
96
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Matrix A:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("Matrix B:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("The resultant matrix is : \n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}

}
else
printf("Matrix Multiplication is not possible");
getch();
}

97
Output:Enter the no of rows and columns of matrix a:
2 2
Enter the no of rows and columns of matrix b:
2 2
Matrix Multiplication can be performed:
Enter Matrix A:
2 1
2 3
Enter Matrix B:
1 3
2 1
Matrix A:
2 1
2 3
Matrix B:
1 3
2 1
The resultant matrix is :
4 7
8 9

6a.C program to find sum of diagonal elements

 Write a C program to find sum of diagonal elements.


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],i,j,sum=0,m,n;
clrscr();
printf("\nEnter the row and column of matrix: ");
scanf("%d %d",&m,&n);
printf("\nEnter the elements of matrix: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nThe matrix is\n");
for(i=0;i<m;i++)
{
98
printf("\n");
for(j=0;j<m;j++)
{
printf("%d\t",a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
sum=sum+a[i][j];
}
}
printf("\n\nSum of the diagonal elements of a matrix is: %d",sum);
getch();
}
Output: Enter the row and column of matrix: 3 3
Enter the elements of matrix: 2
3 5 6 7 9 2 6 7
The matrix is
2       3       5
6       7       9
2       6       7
Sum of the diagonal elements of a matrix is: 16

6b. C program to transpose of a matrix

 Write a C program to transpose of a matrix.


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
clrscr();
printf("Enter the number of rows and columns of matrix ");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix \n");
for( c = 0 ; c < m ; c++ )
99
{
for( d = 0 ; d < n ; d++ )
{
scanf("%d",&matrix[c][d]);
}
}
for( c = 0 ; c < m ; c++ )
{
for( d = 0 ; d < n ; d++ )
{
transpose[d][c] = matrix[c][d];
}
}
printf("Transpose of entered matrix :-\n");
for( c = 0 ; c < n ; c++ )
{
for( d = 0 ; d < m ; d++ )
{
printf("%d\t",transpose[c][d]);
} printf("\n");
} getch();
}
Output: Enter the number of rows and columns of matrix 2 3
Enter the elements of matrix
1 2 3 4 5 6
Transpose of entered matrix :-
1 4
2 5
3 6

7a. C Program to sort an array of elements in ascending order

 Write a C program to sort an array of numbers. Nov / Dec 14


Write a C program to arrange the numbers in ascending order.
May/June 14
Program:
#include <stdio.h>
#include<conio.h>
void main()
{
100
int i, j, a, n, number[30];
clrscr();
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below
\n");
for (i = 0; i < n; ++i)
printf("%d\t", number[i]);
getch();
}
Output: Enter the value of N 6
Enter the numbers
1 9 8 0 2 10
The numbers arranged in ascending order are given below
0 1 2 8 9 10

7b. C program to perform searching of a number


 Write a C program to search a given number in an array of
elements. April / May 15
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int j,n,a[15],flag=0,s;
101
clrscr();
printf(“Enter the array size:”);
scanf(“%d”,&n);
for(j=0;j<n;j++)
scanf(“%”,&a[j]);
printf(“Enter the element to be searched”);
scanf(“%d”,&s);
for(j=0;j<n;j++)
{
if(a[i]==s)
{
printf(“ The element %d is present at %d position in
the list \n”,s,j+1);
flag=1;
break;
}
}
if(flag==0)
printf(“\n The element is %d is not present in the list \ n”,s);
getch();
}
Output :
Enter array size 5
8 4 7 2 9
Enter element to be search 7
The element 7 is present in the list

7c. C Program to sort an array of elements in descending order

 Write a C program to arrange the given 10 numbers in descending


order. May/June 16
Program:
#include <stdio.h>
#include<conio.h>
void main()
{
int i, j, a, n, number[30];
clrscr();
printf("Enter the value of N \n");
scanf("%d", &n);
102
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in descending order are given below
\n");
for (i = 0; i < n; ++i)
printf("%d\t", number[i]);
getch();
}
Output: Enter the value of N 10
Enter the numbers
1 9 8 0 2 10 22 36 19 12
The numbers arranged in ascending order are given below
36 22 19 12 10 9 8 2 1 0

7d. C program to check whether the given string is palindrome or


not

 Write a C program to check whether the given string is palindrome


or not. May / June 16
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[10],s1[10];
clrscr();
103
puts("Enter a string");
gets(s);
strcpy(s1,s);
strrev(s);
if(strcmp(s,s1)==0)
puts("Sring is a palindrome");
else
puts("String is not a palindrome");
getch();
}
Output:
Enter a string:
Madam
String is a palindrome

7e. C program to reverse a string

 Write a C program to reverse a string . January 2014


Program:
#include<stdio.h>
#include<string.h>
void Reverse(char str[]);
void main()
{
char str[100];
clrscr();
printf("Enter a string to reverse: ");
gets(str);
Reverse(str);
printf("Reversed string: ");
puts(str);
getch();
}
void Reverse(char str[])
{
int i,j;
char temp[100];
for(i=strlen(str)-1,j=0; i+1!=0; --i,++j)
{
temp[j]=str[i];
104
}
temp[j]='\0';
strcpy(str,temp);
}
Output:
Enter a string to reverse: program
Reversed string: margorp

7f. C program to find minimum and maximum element in a matrix

 Write a C program to find minimum and maximum element in a


matrix.

PROGRAM:
#include<stdio.h>
main()
{
int a[10][10],i,j,m,n,big,small;
printf("enter the values of m,n");
scanf("%d%d",&m,&n);
printf("enter the elemnts of matrix a");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
big=a[0][0];
small=a[0][0];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(a[i][j]>big)
big=a[i][j];
if(a[i][j]<small)
small=a[i][j];
printf("biggest element =%d",big);
printf("smallest element =%d",small);
}
OUTPUT:
enter the values of m,n
3,3
enter the elements of matrix a
123
105
345
567
biggest element 7
smallest element 1

7e. C program to count the number of vowels in a string


 Write a C program to count numbers vowels in your name.
May/June 16
Write a C program to count number of vowels in a string.

#include<stdio.h>
#include<conio.h>
void main()
{
char ch[10];
int i,count=0;
clrscr();
printf("Enter the string\n");
gets(ch);
for(i=0;ch[i]!='\0';i++)
{
if(ch[i]=='a' || ch[i]=='e' || ch[i]=='i' || ch[i]=='o' || ch[i]=='u')
{
count++;
}}
printf(“No of vowels - %d”,count);
getch();
}
Output:
Enter the string: Francis Xavier
No of vowels – 5

106
Unit – IV
Functions & Pointers

Function – definition of function – Declaration of function – Pass by


value – Pass by reference – Recursion – Pointers - Definition –
Initialization – Pointers arithmetic – Pointers and arrays- Example
Problems.

Part – A

1. What is an argument? Differentiate the formal and actual


arguments.
Compare actual parameters and formal parameters. April /May 15
Arguments provide the data communication between the calling function
and called function. There are two types of arguments. They are formal and
actual argument.

Actual Arguments Formal Arguments


Parameters transferred from the Parameters used in the called
calling program to the called program to stand for the values that
program are passed from the called program
Eg: main() Eg: main()
{ {
………….. …………..
Fun(a,b); Fun(a,b);
………….. …………..
} }
Fun(a1,b1) Fun(a1,b1)
{ {
………… …………
………… …………
} }
a, b actual arguments a1, b1 formal arguments

2. How a variable is declared to be a pointer?


Dereference operator(*) and Pointer variables: Pointers variables are
the special types of variables that holds memory address rather than
data, that is, a variable that holds address value is called a pointer
variable or simply a pointer.
Declaration of Pointer: Dereference operator(*) are used to
identify an operator as a pointer.
107
data_type *
pointer_variable_name;
Example: int *p;
3. What is the need for functions? Jan 2014
Specify the advantages of functions. June 2016

 Modularity and Clarity: Functions helps to decompose the large


program into small segments which makes programmer easy to
understand, maintain and debug.
 Reusability: If repeated code occurs in a program. Function can
be used to include those codes and execute when needed by
calling that function.
 Portability: programs can be written that are system
independent.
 Programmer working on large project can divide the workload by
making different functions.
4. What is the use of return statement?
A function may or may not return a value. A return statement returns
a value to the calling function and assigns to the variable in the left side
of the calling function. If a function does not return a value, the return
type in the function definition and declaration is specified as void.
Syntax: return ; OR return (expr/value);
5. What is a function? Nov / Dec 14,15
A function is a self contained program segment that carries out some
specific, well defined task. A function takes some data from main () and
returns a value.
6. Define recursion. June 2014
Recursion is the process of calling the same function itself again
and again until some condition is satisfied. This process is used for
repetitive computation in which each action is satisfied in term of a
previous result. The function which is called recursively is called
recursive function.
7. What is NULL pointer?
It is always a good practice to assign a NULL value to a pointer variable
in case you do not have exact address to be assigned. This is done at
the time of variable declaration. A pointer that is assigned NULL is
called a null pointer.
int *ptr = NULL;
8. What is void pointer?

108
An object of type void cannot be created, but it is possible to create a
pointer to void. Such a pointer is known as “void pointer” and has a type
void *. A void pointer is a generic pointer and can point to any type of
object.

9. Differentiate call by value and call by reference.


Differentiate pass by value and pass by reference. June 2014

Call by value Call by reference


While passing parameters using call While passing parameters using call
by value, photo copy of original by reference, the actual address of
parameter is created and passed to the parameter is passed to the
the called function. called function.
Any update made inside method will Any update made inside method will
not affect the original value of affect the original value of variable
variable in calling function. in calling function.
As their scope is limited to only
function so they cannot alter the
values inside main function.

10. What is the purpose of main()?

All C language programs must have a main() function. It's the


core of every program. It's required. The main() function doesn't really
have to do anything other than be present inside your C source code.
Eventually, it contains instructions that tell the computer to carry out
whatever task your program is designed to do. When the operating
system runs a program in C, it passes control of the computer over to
the main() function of that program. 

11. Define pointer. What are the uses of pointers? Jan 2014
Pointer is a variable that holds the address of another variable.
Uses of pointers:
 Pointers can be used to pass information back and forth between the
function and its reference points.
 It provides a way to return multiple data functions from a function via
function arguments.
 It reduces the length and complexity of a program
 It increases the execution speed.
 It enables to access the variables that is defined outside the function.
109
12. How is pointer arithmetic done? May / June 16
A pointer in c is an address, which is a numeric value. Therefore, arithmetic
operations can be performed on a pointer just as on a numeric value. There
are four arithmetic operators that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, that ptr is an integer pointer which points to
the address 1000. Assuming 32-bit integers, the following arithmetic
operation can be performed on the pointer –
ptr++
After the above operation, the ptr will point to the location 1004 because each
time ptr is incremented, it will point to the next integer location which is 4
bytes next to the current location. This operation will move the pointer to the
next memory location without impacting the actual value at the memory
location. If ptr points to a character whose address is 1000, then the above
operation will point to the location 1001 because the next character will be
available at 1001.

13. What are the operators exclusively used with pointers?


What is address operator and indirection operator?
Nov / Dec14, 15
A pointer is a variable which contains the address in memory of
another variable. There can be a pointer to any variable type.
 Address operator (&): The unary operator & gives the ``address of a
variable''.
 Indirection operator(*): The indirection or dereference
operator * gives the ``contents of an object pointed to by a pointer''.
14. Distinguish between library functions and user defined function.

Library function User defined function

Need not written by the user. It is It has to be written or developed


standard and predefined in the by the user at the time of writing
library program
It requires the corresponding
It is not predefined and hence not
header files to be included in the
available in the header file.
program

Example : printf(), scanf() Example : sum(), swap()

110
15. What is the output of the following program? May / June 15
main()
{
int a=8,b=4,c=1,*p1=&a,*p2=&b;
c= *p1**p2-*p1/*p2+9;
printf(“%d”,c);
}
Output : 39

111
Part – B

1. Functions with and without arguments

 Explain the functions with and without arguments with examples.


Jan 2014
The user defined functions can be broadly classified into four types as
below:
a. Function without arguments and without return type
In this prototype no data transfer takes place between the calling
function and called function i.e. the called program does not
receive any data from the calling program and does not send
back any value to the calling program. The main function does
not have control over the way they receive the input data

main() No i/p fun()


{ {
...... ......
fun(); ......
...... ......
) No o/p }
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void add();
clrscr();
add();
getch();
}
void add()
{
int a,b,c;
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
c=a+b;
printf("The addition of %d and %d is %d", a,b,c);
}

112
Output:
Enter the values of a and b 2 3
The addition of 2 and 3 is 5
b. Function with argument and without return type: In this
prototype data is transferred from calling function to called
function i.e. the called program receives some data from the
calling program and does not send back any value to the calling
program. Such functions are partly dependent on the calling
function.

main() i/p fun(x,y)


{ {
...... ......
fun(a,b); ......
...... ......
) No o/p }
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void add(int,int);
int a,b;
clrscr();
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
add(a,b);
getch();
}
void add(int a1,int b1)
{
int c;
c=a1+b1;
printf("The addition of %d and %d is %d", a1,b1,c);
}
Output:
Enter the values of a and b 2 3
The addition of 2 and 3 is 5
c. Function with argument and with return type: In this prototype
data is transferred from calling function and called function i.e. the

113
called program receives some data from the calling program and
send back a value to the calling program.

main() i/p fun(x,y)


{ {
...... ......
fun(a,b); ......
...... return;
) o/p }

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int add(int,int);
int a,b,c;
clrscr();
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The addition of %d and %d is %d",a,b,c);
getch();
}
int add(int a1,int b1)
{
return(a1+b1);
}
Output:
Enter the values of a and b 2 3
The addition of 2 and 3 is 5
d. Function without argument and with return type: In this
prototype the calling program cannot pass any argument to the
called program but the called program may send some return
value to the calling program.

main() No i/p fun()


{ {
...... ......
fun(); ......
...... return;
) o/p
114 }
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int add();
int c;
clrscr();
c=add();
printf("The sum of is %d",c);
getch();
}
int add()
{
int a,b;
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
return(a+b);
}
Output:
Enter the values of a and b 2 3
The sum is 5

2. Function prototype

 Explain in detail about function declaration. Jan 2014


OR
Explain in detail about function prototype.

A function is a self contained program segment that carries out some


specific, well defined task. A function takes some data from main () and
returns a value.
There are two types of function. They are
 Library function: Library functions are the in-built function in C
programming system.
For example: printf()
 User defined function: C allows programmer to define their own
function according to their requirement. These types of
functions are known as user-defined functions.
115
For example: sum(). 
Elements of user defined function: In order to write an efficient
user defined function, the programmer must be familiar the
following three elements:
a. Function Declaration: Like the normal variable the function must
be declared before it is defined and called or invoked.
Syntax :
return_type function_name(arg1, arg2,..........)
Example : int add(int x, int y); OR int add(int,int);
b. Function Definition: It is the process of specifying and
establishing the user defined function by specifying all its
elements and characteristics.
Syntax:
return_type function_name(arg1,arg2............)
{
Local variable declaration
___________
Body of the function
___________
return(expr);
}
Example:
int add(int a,int b)
{
int c;
c=a+b;
return(c);
}
c. Function Call: The function can be simply called by specifying
the name of the function, return value and parameters if present.
Syntax:
function_name();
OR
function_name(arg1,arg2..............)
OR
return_value=function_name(arg1,arg2..............);
Example:
add();
OR
add(x,y);
116
OR
z=add(x,y);
Every C program begins from main() and program starts executing the
codes inside main() function. When the control of program reaches
to function_name() inside main()function. The control of the program
jumps to void function_name() and executes the codes inside it. When
all the codes inside that user-defined function are executed, control of
the program jumps to the statement just after function_name() from
where it is called as given below:

#include<stdio.h>
void main()
{
..........
void function_name();
...........
function_name();
............Step 1
}
void function_name()
{
.............Step 2
.............
}

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int c,a,b;
int add(int,int);
clrscr();
printf("Enter the values of a and b to perform addition:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The sum is %d",c);
getch();
}
int add(int a1, int b1)
117
{
return(a1+b1);
}
Output:
Enter the values of a and b to perform addition: 2 3
The sum is 5

3. Call by value and call by reference

 Explain about call by value and call by reference. Jan 14, Nov 14
Explain about pass by value and pass by reference. May 16
OR
Explain in detail about parameter passing methods in C

Call by value: If data is passed by value, the data is copied from


the variable used in for example main() to a variable used by the
function. So if the data passed (that is stored in the function variable) is
modified inside the function, the value is only changed in the variable
used inside the function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1=50,num2=70;
void swap(int,int);
clrscr();
printf("Before Swapping\n");
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
printf("\nAfter Swapping\n");
swap(num1,num2);
getch();
}
void swap(int number1,int number2)
{
int temp;
temp = number1;
number1 = number2;
number2 = temp;
118
printf("\nNumber 1 : %d",number1);
printf("\nNumber 2 : %d",number2);
}
Output:
Before Swapping
Number 1: 50
Number 2: 70
After Swapping
Number 1: 70
Number 2: 50
Call by Reference: If data is passed by reference, a pointer to
the data is copied instead of the actual variable as is done in a call by
value. Because a pointer is copied, if the value at that pointers address
is changed in the function, the value is also changed in main(). 
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1=50,num2=70;
void swap(int *,int *);
clrscr();
printf("Before Swapping\n");
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
swap(&num1,&num2);
printf("\nAfter Swapping\n");
printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
getch();
}
void swap(int *num1,int *num2)
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
Output:
Before Swapping
119
Number 1: 50
Number 2: 70
After Swapping
Number 1: 70
Number 2: 50

4. Pointers

 Write short notes on pointers.


Pointer is a variable which holds address of another variable.
Declaration of Pointer: Dereference operator(*) are used to
identify an operator as a pointer.
Syntax: data_type * pointer_variable_name;
Example: int *p;
Initialization of pointers: A pointer variable can be initialized by
assigning it the address of another variable.
Syntax: data_type *pointer_variable_name;
pointer_variable_name=&var;
Example: int i=10;
int *j;
int j=&i;
Variable Value Address of variable
I 10 1001
J 1001 1005

Accessing variable through pointer: Once the pointer is declared and


assigned to the address of another variable, the variable can be
accessed through its pointers. This can be done by using indirection
operator or dereferencing operator (*).
Syntax: *ptr_var; OR *(addr of a var);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3,*j;
j=&i;
clrscr();
printf("&i=%d\n",&i);
printf("Address of i is %d\n",j);
120
printf("j=%d\n",j);
printf("i=%d\n",i);
printf("&j=%d\n",&j);
printf("*(&j)=%d\n",*(&j));
printf("*j=%d\n",*j);
getch();
}
Output:
&i=-12
Address of i is -12
j=-12
i=3
&j=-14
*(&j)=-12
*j=3

5. Recursion

 What is recursion? Explain the recursive function with suitable


example. Dec 14
What is recursion? Give an example. Jan 14
Write a C program to find factorial of a number using function.
May 15
Definition: Recursion is the process calling the same function itself
again and again until some condition is satisfied. This process is used
for repetitive computation in which each condition is satisfied in terms of
a previous result. The function which is called recursively is called
recursive function.In order to write a recursive program the user must
satisfy the following:
 Problem must be analysed and written in recursive form
 Problem must have the stopping condition

121
Syntax: fun()
{
fun();
}
Program:
To calculate factorial of a number
#include<stdio.h>
#include<conio.h>
main()
{
int fact(int);
int n;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
printf("The factorial of %d is %d",n,fact(n));
getch();
}
int fact(int n1)
{
int f;
if(n1==0||n1==1)
return(1);
else
f=n1*fact(n1-1);
return(f);
}
Output:
Enter a number: 5
The factorial of 5 is 120

6a.C program to sum of digits using recursive function

 Write a C program to sum of digits using recursive function.


May 15

#include<stdio.h>
int main(){
  int num,x;
  clrscr();
  printf("\nEnter a number: ");
122
  scanf("%d",&num);
  x=findsum(num);
  printf("Sum of the digits of %d is: %d",num,x);
  return 0;
}
int r,s;
int findsum(int n){
if(n){
         r=n%10;
         s=s+r;
         findsum(n/10);
     }
     else
       return s;
}
Output:
Enter a number : 123
Sum of the digits of 123 is 6

6b. C program to find the power of a number


 Write a iterative and recursive function to find power of a number.
Nov / Dec 14
Iterative program to find power of a number
Program
#include <stdio.h>
void main()
{
int base, exponent;
long long result = 1;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter an exponent: 4");
scanf("%d", &exponent);
while (exponent != 0)
{
result *= base;
--exponent;
}
printf("Answer = %lld", result);
getch();
}
Output
123
Enter a base number: 3
Enter an exponent: 4
Answer = 81
Program to find power of a number using recursion
#include <stdio.h>
#include <conio.h>
void main()
{
int base, exponent, counter, result = 1;
printf("Enter base and exponent \n");
scanf("%d %d", &base, &exponent);
result = getPower(base, exponent);
printf("%d^%d = %d", base, exponent, result);
getch();
}
int getPower(int base, int exponent)
{
if(exponent == 0)
{
return 1;
}
else
return base * getPower(base, exponent - 1);
}
Output :
Enter base and exponent: 2 3
2^3=8

6c. C program using pointers to reverse an array

 Write a C program using pointers to read in an array of integers


and print its elements in reverse order. May 15

#include<stdio.h>
#include<conio.h>
#define MAX 30
void main() {
int size, i, arr[MAX];
int *ptr;
clrscr();
ptr = &arr[0];

printf("\nEnter the size of array : ");


124
scanf("%d", &size);
printf("\nEnter %d integers into array: ", size);
for (i = 0; i < size; i++) {
scanf("%d", ptr);
ptr++;
}
ptr = &arr[size - 1];
printf("\nElements of array in reverse order are :");
for (i = size - 1; i >= 0; i--) {
printf("\nElement%d is %d : ", i, *ptr);
ptr--;
}
getch();
}
Output:
Enter the size of array : 5
Enter 5 integers into array : 11 22 33 44 55
Elements of array in reverse order are :
Element 4 is : 55
Element 4 is : 44
Element 4 is : 33
Element 4 is : 22
Element 4 is : 11

7.a C program to count number of words in a string using pointers

 Write a C program to count number of words in a string using


pointers. May / June 16
/*C program to count vowels and consonants in a string using pointer.*/
#include <stdio.h>
int main()
{
    char str[100];
    char *ptr;
    int  cntV,cntC;
     printf("Enter a string: ");
    gets(str);
     
    //assign address of str to ptr
    ptr=str;
     cntV=cntC=0;
125
    while(*ptr!='\0')
    {
        if(*ptr=='A' ||*ptr=='E' ||*ptr=='I' ||*ptr=='O' ||*ptr=='U' ||*ptr=='a' ||
*ptr=='e' ||*ptr=='i' ||*ptr=='o' ||*ptr=='u')
            cntV++;
        else
            cntC++;
        //increase the pointer, to point next character
        ptr++;
    }
    printf("Total number of VOWELS: %d, CONSONANT:
%d\n",cntV,cntC);       
    return 0;
}

Enter a string: This is a test string


Total number of VOWELS: 5, CONSONANT: 16

7b. C program to generate Fibonacci series

 Write a C program to generate the Fibonacci series


Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i = 0, c;
int Fibonacci(int);
clrscr();
printf("Enter the number of terms in fibonacci series:");
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\t", Fibonacci(i));
i++;
}
getch();
}

126
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Output:
Enter the number of terms in fibonacci series:5
Fibonacci series
0 1 1 2 3

7c. C program to find smallest and largest number in array using


functions

 Write a C program to find smallest and largest number from


the given 10 numbers using functions. May / June 16
Write a C program to find smallest and largest numbers in an
array of n elements.

Program:
#include <stdio.h>
#include<conio.h>
void max_min(int number[],int n);
void main()
{
int i, j, a, n, number[30];
clrscr();
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
max_min(number,n);
getch();
}
void max_min(int number[],int n)

127
{
int a,i,j;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\t", number[i]);
printf("\nThe minimum element in the array is %d",number[0]);
printf("\nThe maximum element in the array is %d",number[n-1]);
}
Output:

128
Unit – V
Structures & Unions

Introduction – need for structure data type – structure definition –


Structure declaration – Structure within a structure - Union - Programs
using structures and Unions – Storage classes, Pre-processor
directives.

Part – A

1. Write any two pre-processor directives in C. Jan 2014


#define – used to define symbolic constants
#include – includes header files to the program
2. Differentiate structure and union. Jan 2014

Structure Union
When a variable is associated with a
When a variable is associated with a
structure, the compiler allocates the
union, the compiler allocates
memory for each member. The size
the memory by considering the size
of structure is greater than or equal
of the largest memory. So, size of
to the sum of sizes of its members.
union is equal to the size of largest
The smaller members may end with
member.
unused slack bytes.
Each member within a structure is
Memory allocated is shared by
assigned unique storage area of
individual members of union.
location.
Individual member can be Only one member can be accessed
accessed at a time at a time.
Syntax: Syntax:
struct structure_name union structure_name
{ {
Structure member1; union member1;
Structure member 2; union member 2;
------------------------ ------------------------
} }

129
3. What is the purpose of Unions in C? June 2014
What are advantages of union over structure?
State the importance of union. April / May 16
 All the members use the same memory space to store the values,
hence storage space is reduced.
 It can handle only one member at a time even all the members use the
same memory space.
 Unions are particularly useful in situations where there is a need to use
only one of its member elements at any given point of time.

4. What is the use of pre-processor directives? June 2014, May 15


The pre-processor directives are the directives, which give instruction to
the compiler to pre-process the information before actual compilation
starts.

5. Consider the declaration


struct
{
char name;
int num;
} student;
Illustrate the application of size of operator to this structure.
#include<stdio.h>
#include<conio.h>
struct student
{
char name;
int num;
}s;
void main()
{
printf("size of stu is %d",sizeof(s));
getch();
}
Size of structure student is : 3 (char occupies 1 byte and integer
occupies 2 bytes)

6. What do you mean by structures? April / May 15,16


130
Structure is a group of logically related data items of different data types
under a single name.
struct student
{
char name;
int regno;
}s;

7. What is typedef?
The typedef keyword allows the programmer to create a new data type
name for an existing data type. The typedef does not occupy storage; it
simply defines a new type.
Syntax:
typedef <existing data type> <new data type...>;
Example:
typedef int id_no;
id_no regno;

8. What is enumerated data type?


An enumeration is a user-defined data type consists of integral
constants and each integral constant is giving a name.
Keyword enum is used to define enumerated data type.
Syntax:
enum type_name{ value1, value2,...,valueN };
Example:
enum
day{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sun
day};

9. Define static storage class. Nov / Dec 14

The static storage class: The value of static variable persists until the
end of the program. A variable can be declared static using
keyword: static.
Syntax: static datatype var1,var2,..........;
Example: static int a;
Program:
#include<stdio.h>
#include<conio.h>
void main()

131
{ void f1();
clrscr();
f1();
printf("\tFirst Call\n");
f1();
printf("\tSecond Call\n");
getch();
}
void f1()
{ static int k=0;
int j=10;
printf("Value of K is %d and J is %d",k,j);
k=k+10;
}
Output:
Value of K is 0 and J is 10 First Call
Value of K is 10 and J is 10 Second Call

10. What is the use of #define pre-processor? Nov/Dec 14,15


This is used to define symbolic constants in the source program. The
identifier or string or integer defined is replaced by macro substitution.
Syntax: #define identifier string/integer
Example #define PI 3.14
The pre-processor replaces the every occurrence of an identifier by the
specified string or integer in source program.
11. Write a note on register storage class. Nov / Dec 15

The register storage class: Register variables are similar to


automatic variable and exist inside that particular function only. If
the compiler encounters register variable, it tries to store variable
in microprocessor's register rather than memory. Value stored in
register can be accessed much faster than that of in memory. In
case of larger program, variables that are used in loops and
function parameters are declared as register variables. Since,
there are limited number of register in processor and if it couldn't
store the variable in register, it will automatically store it in
memory.
Syntax: register datatype var1,var2,...........;
Example: register int a,b;

132
12. Justify the need for structured data type. Nov / Dec 14

 A structure in C is a collection of items of different types. You can think


of a structure as a "record" is in Pascal or a class in Java without
methods.
 Structures, or structs, are very useful in creating data structures larger
and more complex than the ones we have discussed so far.
 Simply various built-in data types can be grouped into a structure.
 Object conepts was derived from Structure concept. Few object
oriented goals using C structure can be achieved but it is very complex.

133
Part – B

1.Structures in C

 What is a structure? Create a structure with data members of


various types and declare two structure variables. Write a program
to read data into these and print the same.
Nov / Dec 14,15, May / June16
Structure is the collection of variables of different types under a single
name for better handling.
Structure Definition in C
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};

Example:
struct student
{
char name[50];
int regno;
int m1;
int m2;
};
This declaration above creates the derived data type struct student.
Structure variable declaration
Syntax: struct structure_name structure_variable;
When a structure is defined, it creates a user-defined type but, no
storage is allocated. For the above structure of student, variable can be
declared as:
struct student
{
char name[50];
int regno;
134
int m1;
int m2;
};
Inside main function:
struct student s1, s2, s[20];
Another way of creating sturcture variable is:
struct student
{
char name[50];
int regno;
int m1;
int m2;
}s1 ,s2 ,s[20];
In both cases, 2 variables s1, s2 and array s having 20 elements of type
struct student are created.
Accessing members of a structure
There are two types of operators used for accessing members of a
structure.
1. Member operator(.)
2. Structure pointer operator(->)
Syntax: Any member of a structure can be accessed as:
structure_variable_name.member_name;
Example: s.regno;
Program:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int regno;
int m1,m2,m3,tot,per;
}s[10];
void main()
{
int i,n;
clrscr();
printf("Enter the number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
135
printf("Enter the regno, name, marks for three subjects");
scanf("%d%s%d%d
%d",&s[i].regno,s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);
}
printf("Reg No\tName\tMark1\tMark2\tMark3\tTotal\tPercentage\n");
for(i=0;i<n;i++)
{
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].per=s[i].tot/3;
}
for(i=0;i<n;i++)
{
printf("%d\t%s\t%d\t%d\t%d\t%d\t
%d",s[i].regno,s[i].name,s[i].m1,s[i].m2,s[i].m3,s[i].tot,s[i].per);
printf("\n");
}
getch();
}
Output:
Enter the number of students: 3
Enter the regno, name, marks for three subjects: 1 xxx 56 56 50
Enter the regno, name, marks for three subjects: 2 eee 50 50 50
Enter the regno, name, marks for three subjects: 3 yyy 80 80 81
Reg No Name Mark1
Mark2
Mark3
Total Percentage
1 xxx 56 56 50
162 54
2 eee 50 50 50
150 50
3 yyy 80 80 81
241 80

136
2. Union

 Explain in detail about union.


Write short notes on unions. Nov / Dec 2014
What is union? Discuss with an example. April / May 15
Union is derived data type and it is similar to structure. When
a variable is associated with a union, the compiler allocates the memory
by considering the size of the largest memory. So, size of union is
equal to the size of largest member. Memory allocated is shared by
individual members of union. Only one member can be accessed at a
time.
Keyword union is used for creating a union.
Syntax of union
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
Example:
union student
{
char name[50];
int regno;
int m1;
int m2;
};
This declaration above creates the derived data type union student.
Union variable declaration
Syntax: union union_name union_variable;
When a union is defined, it creates a user-defined type but, no
storage is allocated. For the above union of student, variable can be
declared as:
union student
{
char name[50];
int regno;
int m1;
137
int m2;
};
Inside main function:
union student s1, s2, s[20];
Another way of creating union variable is:
union student
{
char name[50];
int regno;
int m1;
int m2;
}s1 ,s2 ,s[20];
In both cases, 2 variables s1, s2 and array s having 20 elements
of type union student are created.
Accessing members of a union
There are two types of operators used for accessing members of a
union.
1. Member operator(.)
2. Union pointer operator(->)
Syntax: Any member of a union can be accessed as:
union_variable_name.member_name;
Example: s.regno;
Program:
#include<stdio.h>
#include<conio.h>
union stud
{
int rno,total;
char name[20];
};
void main()
{
union stud s[5];
int i,n;
clrscr();
printf("How many students?");
scanf("%d",&n);
printf("\n Enter the Roll Number:");
for(i=0;i<n;i++)
scanf("%d",&s[i].rno);
138
for(i=0;i<n;i++)
printf("\n %d",s[i].rno);
printf("\n Enter the name of the student:");
for(i=0;i<n;i++)
scanf("%s",s[i].name);
for(i=0;i<n;i++)
printf("\n %s",s[i].name);
printf("Enter the total marks:");
for(i=0;i<n;i++)
scanf("%d",&s[i].total);
for(i=0;i<n;i++)
printf("\n %d",s[i].total);
getch();
}

OUTPUT:-
How many students? 3
Enter the Roll Number: 201 202 203
201
202
203
Enter the name of the student: Anu Banu Angel
Anu
Banu
Angel
Enter the total marks: 100 99 100
100
99
100

3. Storage classes

 What is storage class? List and explain with example. Jan 2014
Explain the concept of storage classes with suitable example.
May / June 14,15,16
A storage class defines the scope (visibility) and life-time of variables
and/or functions within a C program. These specifiers precede the type
that they modify. There are the following storage classes, which can be
used in a C program.
a. auto
139
b. register
c. static
d. extern
a. The auto storage class: Variables declared inside the
function body are automatic by default. These variables are
also known as local variables as they are local to the
function and don’t have meaning outside that function. Since,
variable inside a function is automatic by default, keyword
auto are rarely used.
Syntax: auto datatype var1,var2,........;
Example: auto int a,b; OR int a,b;
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
auto int c=3;
clrscr();
printf("C=%d\n",c);
{
c=4;
printf("C=%d\n",c);
}
printf("C=%d",c);
getch();
}
Output:
C=3
C=4
C=4
b. The static storage class: The value of static variable persists
until the end of the program. A variable can be declared
static using keyword: static.
Syntax: static datatype var1,var2,..........;
Example: static int a;
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
140
void f1();
clrscr();
f1();
printf("\tFirst Call\n");
f1();
printf("\tSecond Call\n");
getch();
}
void f1()
{
static int k=0;
int j=10;
printf("Value of K is %d and J is %d",k,j);
k=k+10;
}
Output:
Value of K is 0 and J is 10 First Call
Value of K is 10 and J is 10 Second Call
c. The extern storage class: External variable can be accessed
by any function. They are also known as global variables.
Variables declared outside every function are external
variables.
Syntax: extern datatype var1,var2,..........;
Example: extern int a;
Program:
#include<stdio.h>
#include<conio.h>
extern int d=150;
void main()
{
void calla();
void callb();
clrscr();
calla();
callb();
printf("In main() D=%d\n",d);
getch();
}
void calla()
{
141
int d=124;
printf("In calla() D=%d\n",d);
}
void callb()
{
printf("In callb() D=%d\n",d);
}
Output:
In calla() D=124
In callb() D=150
In main() D=150
d. The register storage class: Register variables are similar to
automatic variable and exist inside that particular function
only. If the compiler encounters register variable, it tries to
store variable in microprocessor's register rather than
memory. Value stored in register can be accessed much
faster than that of in memory. In case of larger program,
variables that are used in loops and function parameters are
declared as register variables. Since, there are limited
number of register in processor and if it couldn't store the
variable in register, it will automatically store it in memory.
Syntax: register datatype var1,var2,...........;
Example: register int a,b;
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
register int i;
clrscr();
for(i=0;i<=2;i++)
printf("i=%d\n",i);
getch();
}
Output:
i=0 i=1 i=2

4. Pre-processor directives

 Explain in detail bout pre-processor directives. May / June 16


142
 Pre-processing is the first step in the C program compilation stage.
These are placed before the main() function in the source program.
 The compiler examines the pre-processor for any pre-processor
directives. If there is any pre-processor directives the appropriate
actions are taken and then the source program is moved for
compilation.
 The pre-processor directive begins with #.
 The pre-processor operates under the following pre-processor
directives:
a. File inclusion
b. Macro substitution
c. Conditional inclusion
a. File inclusion: This is used to include an external file which
contains functions or some other macro definitions to our source
program, so it is not necessary to rewrite that functions and
macros in our source program.
Syntax: #include “filename”
OR
#include<filename>
-“filename” is the name of the file that can be included in the
program. It searches the specified file in the current working
directory and then in standard directories. After that entire content
of the files are included in the source program.
Example: #include “loop.c”
Header file inclusion: When the file is included in angle
brackets(<>) the included file searched only in standard
directories.
#include<stdio.h>
b. Macro substitutions: This is used to define symbolic constants
in the source program. The identifier or string or integer defined is
replaced by macro substitution.
Syntax: #define identifier string/integer
The pre-processor replaces the every occurrence of an identifier
by the specified string or integer in source program.
Example 1
#define PI 3.14 // substitutes PI=3.14 for every
occurrences of PI
Example 2
#define A 10-5
#define B 20-10
143
Consider C=(A)+(B)
then C=(10-5)+(20-10)=15
Example 3
#define exp if(10>5)
#define true printf(“Greater”);
#define false else printf(“Smaller”);
Then expr true false
Gives if(10>5) printf(“Greater”) else printf(“Smaller”);
Argumented Macros: It is used to define more complex and
useful form of replacements in the source program.
Syntax: #define identifier(v1,v2---)
string/integer
Example:
#define square(n) n*n
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,s;
clrscr();
s=square(a);
printf(“Square of %d is %d”,a,s);
getch();
}
Output: Square of 5 is 25
Nested macros: Macros can be defined within another macros
Example:
#define A 5
#define B A+2
#undef: Used to undefine a macro
Syntax: #undef macro_name
Example: #define FILE_SIZE 42
#undef FILE_SIZE
This tells the CPP to undefine existing FILE_SIZE and define it as
42.
c. Conditional Directives: It is used to control pre-processor with
conditional statements.
i. #if: Tests if the compile time condition is true.
#if<const_expr>
<stmt_seq1>
144
#endif
ii. #if and #else:
#if<constant_expr>
<stmt_seq1>
#else
<stmt_seq2>
#endif
iii. #if...#elif...#else:
#if<constant_expr>
<stmt_seq1>
#elif<constant_expr>
<stmt_seq2>
.......
#endif
iv. #ifdef and #ifndef:
#ifdef: Returns true if this macro is defined
#ifndef: Returns true if this macro is not defined
Example:
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
This tells the CPP to define MESSAGE only if MESSAGE
isn't already defined.

Predefined Macros in C language


Predefined Value
macro
__DATE__ String containing the current date
__FILE__ String containing the file name
__LINE__ Integer representing the current line number
__STDC__ If follows ANSI standard C, then value is a nonzero
integer
__TIME__ String containing the current date.
C Program to find the current time
#include <stdio.h>
int main(){

145
printf("Current time: %s",__TIME__); //calculate the current
time
}
Output
Current time: 19:54:39

5. Nested structures
 Write short notes on nested structure
Explain about structure within structure
Define a structure to store date, which including day, month and
year. Jan 2014
Structures within structures: A structure can be defined with
another structure.Structures can be nested within other structures in C
programming.
struct person;
{
int pid;
char name[20];
struct dob
{
int date;
int month;
int year;
};};
struct person
{ struct dob d; }p1,p2;
To access date of dob : p1.d.date;

6. Employee information using structures


 Write a C program to store employee information using and search
a particular employee using employee number. May / June 14
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno,epay;
char ename[20],j[12];
};
void main()
{
struct emp e[3];
int i;
146
clrscr();
for(i=0;i<3;i++)
{
printf("Enter the employee number:");
scanf("%d",&e[i].eno);
printf(" Enter the employee name:");
scanf("%s",e[i].ename);
printf("Enter the pay:");
scanf("%d",&e[i].epay);
printf("Enter the Joining :");
scanf("%s",e[i].j);
}
printf("Sl.No Eno Ename Joining date Epay Gpay");
for(i=0;i<3;i++)
{
printf("\n%d%d%s%s%d
%d",i+1,e[i].eno,e[i].ename,e[i].j,e[i].epay,(e[i].epay+(e[i].epay*50/100)));
}
getch();
}
OUTPUT:-
Enter the employee number:101
Enter the employee name: Preethi
Enter the employee pay:15000
Enter the Joining :21.11.2011
Enter the employee number:102
Enter the employee name:Sujitha
Enter the employee pay:14000
Enter the Joining :3.12.2011
Enter the employee number:103
Enter the employee name:Ayisha
Enter the employee pay:16000
Enter the Joining :5.10.2011
Sl.No Employee number Employee name Joining Employee pay Grosspay
1 101 Preethi 21.11.2011 15000 2500
2 102 Sujitha 03.12.2011 14000 100 3
103 Ayisha 05.10.2011 16000 4000

7. Book details using structures

 Define a structure called book with book name, author name


and price. Write a C program to read the details of book name,
author name and price of 200 books and display the total cost
of books and the book details whose price is above Rs.500.
May 2015
147
#include <stdio.h>
#include<conio.h>
struct Bookinfo
{
char bname[20]; char bauthor[20]; int price;
}book[200];
void main()
{
int i,n,total; clrscr();
printf("Enter the number of books:");
scanf("%d",n);
for(i=0;i<n;i++)
{
printf("\nEnter the Name of the book : ");
scanf("%s",book[i].bname);
printf("\nEnter the Name of the author : ");
scanf("%s",book[i].bauthor);
printf("\nEnter the Price of Book : ");
scanf("%d",book[i].price);
}
printf("\n--------- Book Details ------------ ");
for(i=0;i<n;i++)
{
printf("\nName of the book : %s",book[i].bname);
printf("\nNumber of the author : %s",book[i].bauthor);
printf("\nPrice of Book : %d",book[i].price);
}
for(i=0;i<n;i++)
total=total+book[i].price;
printf("The total cost of book in library is:%d",total);
for(i=0;i<n;i++)
{ if(book[i].price>500)
{
printf("\nName of the book : %s",book[i].bname);
printf("\nNumber of the author : %s",book[i].bauthor);
printf("\nPrice of Book : %d",book[i].price);
}} getch();}

148
Practical and industrial connectivity of the subject

 Problem solving techniques plays a vital role during the project


development phase.
 Logical thinking and problem solving is the key for success in the
industry. The problem solving techniques prescribed in this subject
enable the students to have a basis for that.

149
University Questions

B.E/B.TECH. DEGREE EXAMINATION, JANUUARY 2014


FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)
1. List out the important hardware and software technologies of fifth
generation computers. [Page No 7 ]
2. Write two characteristics of pseudo code. [Page No 7 ]
3. What are various types of operators? [Page No 33 ]
4. Write a for loop statement to print numbers from 10 to 1.[Page No 35]
5. Define array. [Page No 82]
6. Name any two library functions used for string handling. [Page No 82]
7. What is the need for function? [Page No 107]
8. What is the uses of pointers? [Page No 108]
9. Write any two preprocessor directives in C. [Page No 128]
10. Differentiate between structure and union. [Page No 128]
PART – B (5*16=80 MARKS)
11. a. Write in detail about the evolution and various generations of
computers. [Page No 10] (16)
OR
b. Explain the basic computer organization using a neat diagram.
[Page No 14] (16)
12. a. Write about the needs and types of looping statements in C language
and discuss with examples. [Page No 48] (16)
OR
b. Write about the needs and types of branching statements in C
language and discuss with examples. [Page No 42] (16)
13. a.i. Write a C program to reverse a string. [Page No 103] (8)
ii. Write a C program to print Fibonacci series of a given number.
[Page No 69] (8)
OR
b. Write a C program to find sum of two matrices. [Page No 90] (16)
14. a. Explain the following with suitable examples:
i. Function declaration. [Page No 114] (8)
150
ii. Call by reference and call by value. [Page No 117] (8)
OR
b. i. Explain the function with and without arguments with example for
each. [Page No 111] (10)
ii. What is recursion? Give an example. [Page No 120] (6)
15. a. i. What is storage class? List and explain with example.
[Page No 138] (8)
ii. Define and declare a structure to store date, which includes day,
month and year. [Page No 145] (8)
OR
b. Write a C program to create a mark sheet for students using
structure. [Page No 133] (16)

B.E/B.TECH. DEGREE EXAMINATION, NOVEMBER / DECEMBER 2014

FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)
1. Define flowchart. Why is flowchart required? [Page No 8]
2. What is an algorithm? [Page No 8]
3. What is a variable? Illustrate with an example. [Page No 33]
4. Give an example of ternary operator. [Page No 33]
5. Declare a float array of size 5 and assign 5 values to it. [Page No 83]
6. Give an example for initialization of string array. [Page No 83]
7. What is a function? [Page No 107]
8. What is an address operator and indirection operator? [Page No 109]
9. Define static storage class. [Page No 131]
10. What is the use of #define preprocessor directive? [Page No 131]
PART – B (5*16=80 MARKS)
11. a. i. Explain in detail with neat diagram about the digital computer
organization and each of its units. [Page No 14] (10)
ii. What is pseudo code? Write a pseudo code for swapping two
numbers without using temporary storage. [Page No 30 & 31] (6)
OR
b. i. Perform the following: [Page No 32] (12)
151
1. (100101)2 – (11111001)2
2. (1011101)2*(1011)2
3. (2A947)H=(?)2
4. (4872)=(?)
ii. Discuss the need for Logical Analysis with an example in brief.
[Page No 19] (4)
12. a.What are the various operators available in C? Discuss each one of
them with suitable illustration. [Page No 54] (16)
b. Explain in detail about looping structures available in C with
illustrative programs. [Page No 48] (16)
13. a. i. Write a C programs for sorting array of numbers. [Page No 99] (8)
ii. Explain the various string operations. Write a C program to find out
the length of the string without using string functions.
[Page No 86] (8)
OR
b. i. Write a C program to multiply two matrices. [Page No 95] (8)
ii. Write a C program to search an element in a given array.
[Page No 100] (8)
14. a. What is a function in C? Discuss about call by value and call by
reference with illustration. [Page No 117] (16)
OR
b. What is recursion? Explain a recursive function with suitable
example. Write a iterative and recursive function to find power of a number.
[Page No 120] (16)
15. a.i. What is a structure? Create a structure with data members of
various types and declare two structure variables. Write a C program to
read data into these and print the same. [Page No 133] (10)
ii. Justify the need for the structured data type. [Page No 132] (6)
b. Write short notes on : (4*4=16)
i. Unions [Page No 136]
ii. Register storage class [Page No 131]
iii. #include statement [Page No 142]
iv. #ifndef…..#endif [Page No 144]

B.E/B.TECH. DEGREE EXAMINATION, MAY / JUNE 2014


FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)

152
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART-A(10*2=20 Marks)
1. Convert Binary Number 110 100 111 101 to Octal. [Page No 9]
2. Draw Flow chart to find biggest of two number. [Page No 22]
3. List different data Types in C. [Page No 34]
4. Write a C Program to find a factorial of a given Number using iteration.
[Page No 35]
5. Write a Example code to declare two dimensional Array.[Page No 82]
6. List any four String handling function. [Page No 82]
7. Define Recursion. [Page No 107]
8. What is the difference between pass by value and Pass by reference?
[Page No 108]
9. What is the purpose of Union in C? [Page No 129]
10. What is the use of Pre-Processor Directives? [Page No 129]
PART-B (5*16=80 Marks)
11. (a) (i) Discuss about Generation of digital computer.
[Page No 10] (10)
(ii) Draw flow chart to find factorial of a number.
[Page No 24] (6)
OR
(b)(i) Explain the basic organization of a computer.
[Page No 14] (10)
(ii)Draw a flow chart to find sum first 100 natural numbers.
[Page No 25] (6)
12. (a) (i) Write a program to check whether a given number is prime or not.
[Page No 71] (8)
(ii) Write a C program to find sum of digits of an integer.
[Page No 72] (8)
OR
(b) (i) Write a C program to find roots of a quadratic equation.
[Page No 79]
(8)
(ii) Differentiate entry and exit checked conditional constructs with an
example. [Page No 48] (8)
13. (a) (i)Explain the concept of pass by reference with suitable example.
[Page No 117] (8)
(ii) Write a C program to find factorial of a number using recursion.
[Page No 117] (8)
153
OR
(b) (i) Write a C program to swap the content of two variables using
Pointers. [Page No 118] (8)
(ii) Explain the use of pointers in arrays with suitable example. (8)
14. (a) Write a C Program to arrange the numbers in ascending order.
[Page No 99] (16)
OR
(b) Write a C Program to subtract two matrices and display the resultant
matrix. [Page No 92] (16)
15. (a) Explain the concept of storage class with suitable example.
[Page No 138] (16)
OR
(b) Write a C Program to store the employee information using structure
and search a Particular employee using Employee Number.
[Page No 145] (16)
B.E/B.TECH. DEGREE EXAMINATION, NOVEMVER / DECEMBER 2015

FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)
1. What is a pseudocode? [Page No 7]
2. What is an algorithm? [Page No 8]
3. What is compilation process? [Page No 34]
4. Discuss the working of modulo operator. [Page No 34]
5. Declare a character array of size 5 and assign vowels to it.
[Page No 83]
6. Give some examples of string functions. [Page No 82]
7. What is function definition? [Page No 107]
8. What is an address operator and indirection operator? [Page No 109]
9. Write a note on register storage class. [Page No 131]
10. What is the usage of #define pre-processor? [Page No 131]

PART – B (5*16=80 MARKS)


11. a. Explain in detail with neat diagram about the digital computer
organization and each of its unit. [Page No 14] (16)

154
OR
b. Perform the following: [Page No 32] (4*4=16)
i. (1011.11011)2=(?)10
ii. (10111)2*(1011)2=(?)
iii. (D8BC)H=(?)2
iv. (4871)10=(?)8
12. a. What are the various operators in C? Discuss each one of them with
suitable examples. [Page No 54] (16)

OR
b. Explain in detail about various decision making structures available in
C with illustrative examples. [Page No 42] (16)
13. a. Write a C program to find the largest element and smallest element in
a matrix. [Page No 104] (16)

OR
b. Write a C program to multiply two matrices. [Page No 95] (16)
14. a. Discuss about call by value and call by reference with illustrations.
[Page No 117] (16)

OR
b. What is recursion? Explain a recursive function with suitable
example. Write a recursive function to find the factorial of a number.
[Page No 120] (16)
15. a. What is a structure? Create a structure with data members of various
types and declare two variables. Write a program to read data in to
these and print the same. [Page No 133] (16)
b. Write short notes on: (4*4=16)
i. Union [Page No 136]
ii. Static storage class [Page No 131]
iii. #include statement [Page No 142]
iv. #ifndef……#endif [Page No 144]

155
B.E/B.TECH. DEGREE EXAMINATION, MAY / JUNE 2015
FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)
1. What is super computer? Give an example. [Page No 6]
2. Define pseudo code. [Page No 7]
3. What is the importance of keywords in C ? [Page No 35]
4. List the various input and output statement in C. [Page No 34]
5. What is an array? Give an example. [Page No 82]
6. How is a character string declared? [Page No 82]
7. Compare actual parameters and formal parameters. [Page No 105]
8. What is the output of the following program? [Page No 110]
main()
{
int a=8,b=4,c,*p1=&a,*p2=&b;
c=*p1**p2-*p1/*p2+9;
printf(“%d”,c);
}
9. What do you mean by structures? [Page No 130]
10. Give the use of preprocessor. [Page No 129]

PART B(5*16=80 MARKS)


11. (a) (i) Describe various generations of computers. [Page No 10] (10)

(ii) Convert the decimal number 681.75 into binary, octal and
hexadecimal equivalent. [Page No 32](6)
Or
(b) (i) Explain the basic organization of a computer with neat diagram.
[Page No 14] (10)
(ii) Draw a flowchart to check whether the given number is zero, positive or
negative. [Page No 28] (6)
12. (a) (i) Explain the different types of operators available in C.
[Page No 54] (8)

(ii)What are constants? Explain the various types of constants in C.


[Page No 39] (8)

156
Or
(b) (i) Describe the various looping statements used in C with suitabl
examples. [Page No 48] (8)
(ii) Write a C program to solve the quadratic equation.
[Page No 79] (8)
13. (a) (i) Write a C program to add two matrices. [Page No 90] (10)

(ii) Write a C program to search a given number in an array of elements.


[Page No 100] (6)
Or
(b) (i) Write a C program to arrange the given 10 numbers in ascending
order. [Page No 90] (10)
(ii)Explain the various string handling functions. [Page No 86] (6)
14. (a) (i) Write a C program to find the factorial of a given number using
function. [Page No121] (8)

(ii)Write a C program to exchange the value of two variables using


pass by reference. [Page No 118] (8)
Or
(b)(i) Write a C program to find sum of digits using recursive function.
[Page No 121] (8)
(ii) Write a C program using pointers to read in an array of integers
and print its elements in reverse order. [Page No 123] (8)
15. (a)(i) Define a structure called book with book name, author name and
price, Write a C program to read the details of book name, author name
and price of 200 books in a library and display the total cost of the books
and the book details whose price is above Rs.500. [Page No 148] (16)

Or
(b)(i) Explain the various storage classes in C. [Page No 138] (10)
(ii)What is union? Discuss with an example. [Page No 136] (6)
B.E/B.TECH. DEGREE EXAMINATION, MAY / JUNE 2016
FIRST SEMESTER
CIVIL ENGINEEERING
GE6151 – COMPUTER PROGRAMMING
(COMMON TO ALL BRANCHES)
(REGULATION 2013)
TIME : 3 HOURS MAXIMUM MARKS: 100
Answer ALL questions
PART – A (10*2=20 MARKS)

157
1. Classify the computers based on performance, size, cost and capacity.
[Page No 7]
2. Convert the binary number 10110111.1101 into decimal number.
[Page No 9]
3. What are variables? Give examples. [Page No 33]
4. Define implicit type conversion. [Page No 37]
5. What is an array? [Page No 82]
6. Define string. Give examples. [Page No 82]
7. Specify the advantages of functions. [Page No 107]
8. How is pointer arithmetic done? [Page No 107]
9. What do you mean by structures? [Page No 130]
10. State the importance of union. [Page No 129]
PART – B (5*16=80 MARKS)
11. a.(i) Describe the basic organization with neat diagram.
[Page No 14] (10)
(ii) Draw the flow chart to solve the quadratic equation.
[Page No 29] (6)
OR
b.(i)Explain the various generations of computers.[Page No 10] (8)
(ii) What is pseudo code? Explain its guideline and its benefits.
[Page No 30] (8)
12. a. (i) Explain the different types of operators available in C.
[Page No 54] (10)
(ii) Discuss the basic data types in C. [Page No 63] (6)
OR
b. (i) Describe the various input and output statements in C with suitable
examples. [Page No 51] (10)
(ii) Write a C program for the following series:
1+2+3+4+....................+n [Page No 80] (6)
13. a.(i) Write a C program to count the number of vowels in your name.
[Page No 105] (6)
(ii) Write a C program to multiply two matrices. [Page No 95] (10)
OR
b.(i) Write a C program to check wether the given string is palindrome or
not. [Page No 102] (6)
(ii) Write a C program to arrange the given 10 numbers in descending
order. [Page No 101] (10)
14. a. (i) Write a C program to find the smallest and largest number from the
given 10 numbers using functions. [Page No 126] (10)
(ii) Explain the pass by reference with an example.[Page No 117] (6)
158
OR
b. (i) Write a C program to find the factrorial of a given number using
recursion. [Page No 121] (8)
(ii) Write a C program to count the number of words in a string using
pointers [Page No 124] (8)
15. a. Define a structure called student would contain name, register
number and marks for five subjects and percentage. Write a program to
read the details of name, rgister number and marks for five subjects for 25
students, calculate the percentage and display the name, register number,
marks of 25 subjects, percentage of all the students and also the name of
the students who got highest percentage among the 25 students.
[Page No 133] (16)
OR
b. (i) Explain the various storage classes in C. [Page No 138] (8)
(ii) Describe about the pre-processors with suitable example.
[Page No 142] (8)

159

You might also like