Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (1 vote)
134 views

TS Programming in C Final 23-01-2022 With Preface

This document provides an overview of Programming in C, including objectives, topics, and structure. The textbook covers Programming Methodology and Introduction to C Language, Constants, Variables, Data Types, Input Output functions, Decision making and looping statements, Arrays and Strings, User defined functions, and Structures, Unions and File Management. Key concepts covered include algorithms, flowcharts, the C language structure, compilers, data types, operators, control structures, arrays, strings, functions, structures, unions, and file I/O. The textbook aims to help diploma students learn C programming based on the C-21 syllabus prescribed by the Telangana state board of technical education.

Uploaded by

enjoypandugoimmu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
134 views

TS Programming in C Final 23-01-2022 With Preface

This document provides an overview of Programming in C, including objectives, topics, and structure. The textbook covers Programming Methodology and Introduction to C Language, Constants, Variables, Data Types, Input Output functions, Decision making and looping statements, Arrays and Strings, User defined functions, and Structures, Unions and File Management. Key concepts covered include algorithms, flowcharts, the C language structure, compilers, data types, operators, control structures, arrays, strings, functions, structures, unions, and file I/O. The textbook aims to help diploma students learn C programming based on the C-21 syllabus prescribed by the Telangana state board of technical education.

Uploaded by

enjoypandugoimmu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 192

CS - 205

As Per C-21

Programming in C
Common to All Branches - 1st Year II Semester Diploma Students

Dr. A. YASWANTH KUMAR

Price Rs. 180

Maanya’s M.G.B Publications


Hyderabad. Cell: 9290 429 549, Tirupati. Cell: 9000 3050 79
Programming in C

First Edition: Jan – 2022

© All Rights Reserved

Printing of books passes through many stages–writing, composing, proof


reading, printing etc. We try our level best to make the book error-free. If any
mistake has inadvertently crept in, we regret it and would be deeply indebted to
those who point it out. We do not take any legal responsibility.
No part of this book may be reproduced, stored in any retrieval system or
transmitted in any form by any means - electronic, mechanical photocopying,
recording or otherwise without the prior written, permission of the author and
publishers.

For Copies Please Contact

Maanya’s M.G.B Publications


Cell: 9290 429 549 & 9000 3050 79
Also Available at All Leading Book Shops
Preface
This Textbook of Programming in C has been carefully designed for First
Year Second Semester TS Diploma students.
The object of this book is to provide a suitable Textbook for Diploma students. A
modern approach has been adopted in presentation of this text.
This book meets the desires of all students. Some of the salient features of this
book are:
1. This book is written strictly as per the C-21 syllabus prescribed by SBTE Telangana
State.
2. The material has been presented in a very simple and logical manner so as to lead
the students from simple to complex in Programming in C.
3. The language used in this book is so simple.
4. The book will be very much useful not only to the students but also to the subject
teachers.
5. The book is organized into SIX chapters.
6. In order to bridge the gap between theory and practical, each concept is explained at
length in an easy-to-understand manner supported with numerous examples and
programs.
7. All the Programs given in this are complied and run on Turbo C Compliers.
8. A set of 3 Model question Papers As Per C-21 are also included at the end of 6th
chapter.
Dr. A. Yaswanth Kumar (Author)
Table of Contents

Chapter Name ……. Page. No


1. Programming Methodology and Introduction to C ……. 1.1 to 1.30
Language
2. Constants, variables, data types, input output ……. 2.1 to 2.15
functions
3. Decision making, looping statements and pre- ……. 3.1 to 3.14
processor directives
4. Arrays and Strings ……. 4.1 to 4.21
5. User defined functions ……. 5.1 to 5.17
6. Structures, unions and file management ……. 6.1 to 6.27
PROGRAMMING in C
Course Title Programming in C Course Code CS-205

Semester II Course Group Core

Teaching Scheme
4:1:0 Credits 3
in Periods (L:T:P)

Total Contact
Methodology Lecture +Tutorial 75
Periods

CIE 60 Marks SEE 40 Marks

Specific Learning Outcomes

1.0 Programming Methodology and Introduction to C Language


1.1. State different steps involved in problem solving
1.2. Define algorithm and know its characteristics
1.3. State the steps involved in algorithm development
1.4. Develop algorithms for simple problems.
1.5. Define flowchart and know symbols used in drawing flowcharts
1.6. Draw flowchart for simple problems.
1.7. Differentiate algorithm and flowchart
1.8. Define program and differentiate between program and algorithm
1.9. Define High level language and low level language
1.10. Define Compiler, Assembler, Linker and Loader
1.11. Define source code, assembly code, object code, machine code.
1.12. state the importance of C language
1.13. Explain the structure of C program
1.14. List and Explain different stages in converting the C program source code to
executable code.
1.15. Explain the steps involved in executing the C program
2.0 Constants, Variables , Data Types in C and Operators and Expressions and
Input , Output functions in C
2.1 Describe character set, C Tokens-Keywords, Variables, Identifiers, Constants and
Variables.
2.2 Define Data type. Classify data types and explain with examples
2.3 Explain declaration of a variable and assigning values to variables
2.4 Define operator.
2.5 Classify and Explain operators with examples
2.6 Describe precedence and associativity of operators
2.7 Define expression
2.8 Describe evaluation of Arithmetic, Relational and logical expressions
2.9 Illustrate type conversion techniques.
2.10 Define and List Pre-processor directives
2.11 Discuss #include and #define Pre-processor directives.
2.12 Define Header file and discuss stdio.h, conio.h, math.h, string.h Header files.
2.13 Illustrate getchar(),putchar(),scanf(),printf() with programs.

3.0 Decision making , Looping statements


3.1 Discuss decision making in programming
3.2 Explain decision making statements- if , if-else, nested if, else-if ladder - with
syntax and programs
3.3 Discuss break and continue statements.
3.4 Explain decision making statement- switch statement - with syntax and programs
3.5 Define looping and list loop statements
3.6 Explain the loop statements – while, do- while, for statement- with syntax and
programs
3.7 Define nesting of loops and implement it
3.8 Compare different loop statements
3.9 Know about Infinite loop and steps to avoid it
4.0 Arrays and Strings
4.1 Define Array. Describe declaration and initialization of One Dimensional Array
with syntax and program
4.2 Explain about ‘accessing array out of bounds’ problem
4.3 Explain reading elements of an array, accessing the elements and display them
with program
4.4 Explain sorting elements in an array in ascending order
4.5 Explain finding the average of elements in an array and finding the largest
element in an array
4.6 Explain declaration and initialization of two Dimensional Arrays
4.7 Illustrate the concept of two dimensional arrays with sample programs on matrix
addition, subtraction, matrix multiplication and transpose of a matrix
4.8 Define String and know about declaration and initialization of a String variable.
4.9 Know about reading & writing of strings with programs
4.10 Explain about various String handling functions with sample programs.

5.0 User defined functions and Applications


5.1 Define function, state the need for user defined functions, advantages of functions
5.2 Know the elements of function and return values.
5.3 Define and discuss function prototype, function call, and function definition with
syntax and program.
5.4 Discuss the scope, visibility and lifetime of variables in functions
5.5 Differentiate Local and Global variables
5.6 Illustrate functions with no arguments and no return values with programs
5.7 Illustrate functions with no arguments and with return values with programs
5.8 Illustrate functions with arguments and with no return values with programs
5.9 Illustrate functions with arguments and with return values with programs
5.10 Illustrate passing arrays to functions with programs
5.11 Define recursion and Illustrate recursion with programs
6.0. Structures and Unions and File Management

a) Structures and Unions


6.0 Define structure
6.1 Illustrate creating a structure tag and declaring structure variables,
6.2 Explain accessing structure members and structure assignment
6.3 Know size of a structure.
6.4 Discuss nested structure concept.
6.5 Illustrate array of structures, structures containing arrays, arrays of structures
containing arrays.
6.6 Illustrate structure as function arguments and returning of structure variables as
function values.
6.7 Define Union and illustrate usage of a union.
6.8 Know the differences between Structure and Union
b) Files management
6.9 Define file
6.10 Know how to declare file pointer to a file
6.11 Illustrate the concept of file opening in various modes
6.12 Illustrate the concept of closing of a file
6.13 Illustrate the concept of Input / Output operations on a file
6.14 Illustrate the concept of random access to files
1 Programming Methodology
and Introduction to C Language

OBJECTIVES
 1.0. Programming Methodology and Introduction to C Language
 1.1. State different steps involved in problem solving
 1.2. Define algorithm and know its characteristics
 1.3. State the steps involved in algorithm development
 1.4. Develop algorithms for simple problems.
 1.5. Define flowchart and know symbols used in drawing flowcharts
 1.6. Draw flowchart for simple problems.
 1.7. Differentiate algorithm and flowchart
 1.8. Define program and differentiate between program and algorithm
 1.9. Define High level language and low level language
 1.10. Define Compiler, Assembler, Linker and Loader
 1.11. Define source code, assembly code, object code, machine code.
 1.12. state the importance of C language
 1.13. Explain the structure of C program
 1.14. List and Explain different stages in converting the C program source
code to executable code.
 1.15. Explain the steps involved in executing the C program
Programming Methodology and Introduction to C Language 1-2

1.1. State different steps involved in problem solving


 Problem solving by the computer involves the following steps.
1. Problem definition
2. Analysis
3. Algorithm
4. Flowchart
5. Pseudo code
6. Coding
7. Running the program
8. Debugging
9. Testing
10. Documentation
 Please note that an algorithm, flowchart and pseudocode are the steps involved in
the design phase of a problem.
1. Problem Definition
o This is the first step in computer problem solving.
o The problem solver should understand the problem thoroughly in terms of the
requirements.
o That is, what are the input and output operations to be performed?
o The programmer should extract from the problem statement, a set of well-
defined and precise tasks that can be carried out.
o If the problem is not properly interpreted then we cannot obtain the desired
results.
2. Analysis
o The given problem must be analyzed before it is solved. This determines the
data items, their types and relationship.
o We should specify the operations (Arithmetic and logical) to be performed on
them and check the suitability in terms of memory execution time.
3. Algorithm
o Refer Section: 1.2.1
4. Flow chart
o Refer Section: 1.5.1

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-3

5. Pseudocode
o A pseudocode is neither an algorithm nor a program.
o It is an abstract form of a program. It consists of English like statements, which
perform the specific operations.
o It is defined for an algorithm.
o It does not use anigraphical representation.
o In a pseudocode, the program is represented in terms of words and phrases,
but the syntax of a program is not strictly followed.
o Advantages
 Easy to read
 Easy to understand
 Easy to modify
 The program can be developed easily from a pseudo code rather than a
flowchart.
Example 1: Write a pseudocode to perform the basic arithmetic operations.
Solution:
Read n1, n2
Sum = n1 + n2
Diff = n1 - n2
Mult = n1 * n2
Quot = n1/n2
Print sum, diff, mult, quot
End
6. Coding
o The complete structure of a problem to be solved by a computer is called a
program.
o The computer does not process an algorithm or a flowchart, but executes the
program.
o A program is a set of instructions to solve a particular problem by the
computer and the actual process of writing a program is called coding.
o Programs are written using programming languages and are fed to the
computer.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-4

7. Running the program


o The program can be run (executed) in the central processing unit (CPU). This
phase of problem solving by a computer involves three steps.
 Understand the instructions
 Store data and instructions
 Perform computations
o The user prepares his/her program and makes it ready for execution. All the
instruction stored in the RAM, must be fetched one by one by the ALU to
perform corresponding operations.
o This is called the fetch/execute cycle. The processed data is stored again in the
RAM. Finally, they are transferred to the output devices.
8. Debugging
o The process of detecting and correcting errors (mistakes) in the program is
known as debugging.
o There is a program called debugger that takes object program as input and
executes it and helps in eliminating the mistakes that occur in the source
program.
o The term debug was coined after detecting a real bug in MARK-I, an electro-
mechanical computer, in 1945, by Admiral Gracehopper.
o She removed the bug from the machine and wrote it in a record book The
MARK-I was debugged today.
o Generally, programmers commit three types of errors. They are,
 Syntax errors
 Logical errors
 Run-time errors
9. Testing
o The process of executing the program to test the correctness of the output
(result) of the problem is called testing.
o Executing with different sets of data tests the program. Logical errors are the
outcome of this process. .
10. Documentation
o While writing programs, it is a good programming practice to make a brief
explanatory note on the program or program segments.
o This explanatory note is called a comment.
o It explains how the program works and how to interact with it.
o Thus, it helps other programmers to understand the program.
Maanya’s M.G.B Publications Programming in C
Programming Methodology and Introduction to C Language 1-5

1.2. Define algorithm and know its characteristics


1.2.1. Algorithm
 This is a problem solving technique. It can be defined as a step-by-step procedure to
solve a particular problem.
 It consists of English like statements. Each statement must be precise and well-
defined to perform a specific operation.
 When these statements are carried out for a given set of conditions, they will
produce the required results.
 The word Algorithm is named after the famous ninth century Arabic author and
mathematician, Abu Jafar Mohammed Ibn Musa AI Khowarizmi.
 The last two terms of the name took different pronunciations over the period such
as Alkhowarism, Algorism and finally it became Algorithm.
1.2.2. Characteristics of Algorithm
 Each and every algorithm is characterized by the following five important
characteristics.
1. Input : It may accept zero or more inputs.
2. Output : It should produce at least one output (result).
3. Definiteness : Each instruction must be clear, well-defined and precise.
There should not be any ambiguity.
4. Finiteness : It should be a sequence of finite instructions. That is, it
should end after a fixed time. It should not enter a
infinite loop.
5. Effectiveness : This means that operations must be simple and carried
out in a finite time at one or more levels of complexity.
It should be effective whenever traced manually for
the results.

 Computer programming languages are required to check the definiteness and


effectiveness of each instruction of the algorithm.

1.3. State the steps involved in algorithm development


 The development of an algorithm (a plan) is a key step in solving a problem. Once
we have an algorithm, we can translate it into a computer program in some
programming language.
 Our algorithm development process consists of the following steps.
Maanya’s M.G.B Publications Programming in C
Programming Methodology and Introduction to C Language 1-6
Example 1: Real life example algorithm to write a ‘C’ program
Step 1: Start
Step 2: Analyze the problem
Step 3: Gather what are the inputs required and outputs needed
Step 4: Write program in C editor
Step 5: Compile the program
Step 6: If errors then
Step 6.1: Go to editor, correct the errors and repeat from step 5
Step 6.2: Else
Step 6.3: Supply input
Step 6.4: endif
Step 7: Verify outputs
Step 8: Stop

1.4. Develop algorithms for simple problems.


Example 1: Algorithm to find the number is negative or positive. Assume
that the number is ‘n’.
Step 1: Start
Step 2: Read n
Step 3: If n > 0 then
Step 3.1: Print number is negative
Step 3.2: Else print number is positive
Step 3.3: endif
Step 4: Stop
Example 2: Algorithm to find biggest in two number Assume that the two
numbers are ‘a’ and ‘b’.
Step 1: Start
Step 2: Read a, b
Step 3: If a > b then
Step 3.1: Print „a‟ is big
Step 3.2: Else
Step 3.3: Print „b‟ is big
Step 4: endif
Step 5: Stop
Maanya’s M.G.B Publications Programming in C
Programming Methodology and Introduction to C Language 1-7
Example 3: Write a program to find the largest of three numbers
Step 1: Start
Step 2: READ a, b, c
Step 3: IF (a > b) and (a > c) Then
Step 3.1: Print „A is Big‟
ELSE
Step 4: IF 9b > c) Then
Step 4.1: Print „B is Big‟
ELSE
Step 4.2: Print „C is Big‟
Step 5: Stop
Example 4: Write a program to find area of the triangle.
Step 1: Start
Step 2: Read the value of a, b, c
Step 3: To calculate three sides of the triangle using formula
s  (a + b + c)/2
Step 4: To find area of a triangle apply formula.
area  sqrt(s *(s - a) *(s - b) *(s - c))
Step 5: Print the area
Step 6: Stop
Example 5: Write a program to find the factorial of the given number
Step 1: Start
Step 2: Read the value of n
Step 3: Set initial values of Fact, i
Step 4: Is I < = n else Goto step 6
Step 4.1: Fact¬Fact *i
Step 4.2: i  i +1
Step 5: Goto step 4
Step 6: Print Fact
Step 7: Stop

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-8
Example 6: Write an algorithm to find the roots of the quadratic equation.
Step 1: Start
Step 2: Enter the value of a ,b, c.
Step 3: Find the value of 'D' of using the formula
D=b*b–4*a*c
Step 4: If D is greater than or equal to zero then find the two roots are
root 1  (- b + sqrt(d)) / (2 * a)
root 2 (- b – sqrt (d)) / (2 * a)
Step 5: Print the two roots, root l, root 2.
Step 6: If D is not greater than or equal to zero, then print the roots are imaginary.
Step 7: Stop
Example 7: Algorithm to compute the area of circle.
Algorithm: Area of a circle
Step 1: Start
Step 2: Read radius
Step 3: [Compute the area] Area =3.142 x radius x radius
Step 4: [Print the area] Print 'Area of a circle:', Area
Step 5: [End of algorithm]
Step 6: Stop.
Example 8: Algorithm to perform the basic arithmetic operations such as
addition, subtraction, multiplication and division.
Algorithm: Arithmetic operation
Step 1: Start
Step 2: [Read the value of A and B]
Read A, B
Step 3: [Compute the sum, difference, product and quotient]
sum = A+ B
diff = A- B
prod = A x B
quot = A + B
Step 4: [Print the contents of sum, diff, prod, quot]
Print 'Sum of A and B =', sum
Print 'Difference of A and B =', diff
Print 'Product of A and B =', prod
Maanya’s M.G.B Publications Programming in C
Programming Methodology and Introduction to C Language 1-9
Print 'Quotient after dividing A by B =', quot
Step 5 : [End of algorithm]
Step 6: Stop
Example 9: Algorithm to calculate the simple interest and compound
interest for the amount deposited (P) for some years (T) for the rate of
interest (R).
Algorithm: Simple Interest
Step 1: [Re
Step 2: [Read the value of P, R, T]
Read P, R, T
Step 3: [Compute the simple interest]
SI = (P x R x T) /100
Step 4: [Compute the compound interest]
CI = P x [1 + (R/100W - P
Step 5: [Print the simple interest and compound interest]
Print 'Simple interest =', SI
Print 'Compound Interest =', CI
Step 6: [End of algorithm]
Step 7: Stop

1.5. Define flowchart and know symbols used in drawing


flowcharts
1.5.1. Flowchart
 This is a chart showing a flow of logic involved in solving a problem. This is
defined for an algorithm.
 The flowchart can be defined as a diagramatic representation of an algorithm. It is
referred to as the blue print of an algorithm.
 It is also defined as a visual or graphical representation of an algorithm.
 The flowchart is an easy way to understand and analyze the problem. It is a useful
aid for programmers and system analysts. It is machine independent. Itcan be used
for any type of problems.
 Flowcharts are classified into two types. They are,
o Program flowcharts
o System flowcharts.
 Flowcharts make use of geometrical figures, to specify a particular operation.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-10

1.5.2. Symbols used in drawing flowcharts


 Following table shows different geometrical figures used in a program flowchart
with their functions. While drawing a flowchart, operations must be written inside
the geometric figures.
Geometrical Name Function
figure
Oval Start and stop

Parallelogram Input and Output

Rectangle Processing

Rhombus Decision Making

Arrows Connections

Circle Continuation

The symbols used in the flowchart are described below.


1. Oval /Rounded rectangle: Show the starting and ending point of the process.
2. Parallelogram: Represents the Inputs given to the process or an Output generated
by the process.
3. Rectangle: Illustrates a processing step.
4. Rhombus/Diamond: Renders the decision point generally in the form of Yes/No
or True/False.
5. Arrows/Flow lines: These are the left to right or top (to bottom lines connecting
symbols. These lines shows the flow of control through the program. These
flowlines indicates the exact sequence in which the statements or instructions to be
executed. However to avoid ambiguity, flowlines are usually drawn with an arrow
head.
6. Circle/Connectors: A connector symbol is represented by a circle and a letter or
digit is placed in the circle to specify the link. Whenever a complex flowchart is to
be drawn with the number of direction of flow lines is confusing or it can long as
over the more than one page, in such a situation, the connector symbols are used to
connect the flowchart.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-11

1.6. Draw flowchart for simple problems.


Example 1: Draw a flowchart to find largest of three numbers.

Example 2: Draw a flowchart to find the area of a triangle when its three
sides are given.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-12
Example 3: Draw a flowchart to compute the factorial of a given number.

Example 4: Draw a flowchart to find the roots of the quadratic equation.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-13

1.7. Differentiate algorithm and flowchart


S. No Algorithm Flow chart

1 An algorithm is the series of steps It is nothing but a manner of


that must be executed to solve a representing an algorithm. It is also
problem. known as the flow diagram
A flowchart is the pictorial illustration
of the algorithm.

2 Hard to understand Easily interpreted

3 Uses text Uses symbols

4 No rules are employed Predefined rules are implemented.

5 Debugging is easier Debugging is difficult

6 It is difficult to write algorithm as It is easy to make flowchart.


compared to flowchart.

Example:

Example Flowchart Step by step Algorithm

Begin the flowchart.

Initialize value for memory variables a and b.

Multiply a and b and store the result in


variable c.

Print the value of variable c.

End the flowchart.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-14

Example Flowchart Step by step Algorithm


Begin the flowchart.
Read two variables and store the value in
variable m and n.
Check whether the value of m is greater
than value of n.
If m is greater than n then print m is
greater. Otherwise print n is greater
End of the flowchart.

1.8. Define program and differentiate between program


and algorithm
 Program: A program is a set of instruction written to carry out a particular task, so
that computer can follow them.
 The terms computer program, software program, applications program, system
software, or just programs that are used to refer either an executable program or the
collection of source code from which an executable program is created.
 A computer program is a set of instructions or statements to carry out particular
task by the computers CPU.
 Using set of instructions or statements the users can develop a program or software
which is called programming.
 The program tells the computer what the system will do. Specifically the term
software describes an operating system or application.
 A computer takes instructions, in the form of computer programs, and carries out
the requested task.
 The human beings cannot interact directly with the computer using natural
languages such as English, Tamil, etc., because computers knows and understand
only programming languages.
 The example of the programming languages are BASIC, COBOL, FORTRAN,
PASCAL, C,C++, JAVA etc.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-15

1.8.1. Differences between program and algorithm


S. No. Algorithm Program
1. Algorithm is finite Program need not to be finite
2. Algorithm is written using natural Programs are written using a specific
language or algorithmic language. programming language.
3. An algorithm is a description of A program is an implementation of
how to solve a problem. an algorithm in a particular language
to run on a computer.
4. Algorithms are free from Programs must follow some syntax
grammatic rules. rules
5. It helps to simplify and understand A method of developing an
the problem algorithm.

1.9. Define High level language and low level language


 Basically, computer languages are classified into low level and high level
programming languages.
 Here, the terms low level do not mean the real world low level or high level.
 The low level languages are those which are easily understood by machines.
 For example, machine language is a low level language.
 On the other hand, the high level languages are those which are nearer to the
natural languages like English.
 The figure shows the classification of computer programming languages.

1. Low Level Languages


 These are easily understood by computers. They are machine dependent languages.
That is, these languages are specific to computers.
 The machine language and assembly language are specific to computers.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-16
 The machine language and assembly language are examples of low level languages
and they are discussed in the following sections.
 Programs written in these languages are not transferable from one computer to
another.
a) Machine Languages
o As the name itself implies, programming is done at machine level. The
vocabulary of computer consists of only two words, zero and one. That is, the
digits of a binary number system.
o A 0 indicates low voltage level and 1 indicates high voltage level, since the
computer is operating in only two levels of voltage such as high and low.
o The machine level language is considered as a first generation language. This
is because, programming was started with this language.
o Any sequence of 0'sand 1's forms an instruction in this language.
b) Assembly Language
o To overcome the drawbacks of the machine level language, computer
engineers developed a new programming language which uses symbolic
instructions.
o This symbolic instruction oriented programming language is known as
assembly language or assembly level language.
o This is called as the second generation programming language
o Symbolic words used in this language are referred to as mnemonics.
o Examples:
ADD for Addition
SUB for Subtraction
MUL for Multiplication
STA for Store at
Accumulator
HALT for Halt
JMP for Jump
INR for Increment and so
on.
o The writing of program in assembly language is much easier as compared to
the writing of a program in machine language.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-17
2. High Level Languages
 The machine language and assembly language are highly machine dependent. It
will be ·very difficult for the programmer to switch over from one machine
language to another and from one assembly language to other.
 Programming languages that are more concerned with the problem specification
and not oriented towards the details of a computer are called High Level
Languages (HLLs).
 High level languages are English like. The elements of these languages are
alphabets, digits, punctuations and other special symbols. The instructions are
composed from these elements.
 Hence, each and every instruction is easier to read and understand. Instructions are
machine independent.
 That is, program written for one computer can be run on another computer with
very little or no modifications. Hence, the programmer feels comfortable. These are
standardized as compared to the other two programming languages.
1.9.1. Differences between machine level and assembly level
programming
S.No. Machine Language Assembly Language High-Level Language
1 Language consists of Language consists of Language consists of
binary codes which mnemonics which English-like statements
specify the operation. specify the operation. which specify more-than
one operation.
2 Processor dependent Processor dependent and Independent of
and hence requires hence requires processor.
knowledge of internal knowledge of internal
details of processor to details of processor to
write a program. write a program.
3 Programs require less Programs require less Programs require more
memory. memory. memory.
4 Programs have less Programs have less Programs have more
execution time. execution time. execution time.
5 Program development Program development is Program development is
is difficult. similar than machine easy.
language.
6 It is not user friendly. It is less user friendly. It is user friendly.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-18

1.10. Define Compiler, Assembler, Linker and Loader


 Assembler: It is a software that converts assembly language program codes to
machine language codes.
 Compiler: It is a software that converts the programs written in high level language
to machine language.
 Interpreter: It is similar to a compiler but it converts the instructions one by one.
 Compiler and Assembler plays an important role in the execution of a program.
Some compilers directly generate the executable code instead of assembly code.
 The compiler takes the preprocessed source code and translates it into the assembly
code.
 The assembler takes the assembly code from the compiler and translates it to the
relocatable machine code.
 The below fig illustrates the translation of high level and assembly languages into
machine language.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-19
1.10.1. Assembler
 The process of converting assembly language instructions to machine readable form
is carried out by a program called assembler.
 The translation process is show in the figure.

 The assembly language program (ALP) that is given as input to the assembler is
called source program and the output of the assembler is called object program.
 There are different assembler programs available in the software market.
 Example: TASM (Turbo Assembler), MASM (Macro Assembler).
1.10.2. Compiler
 The process of translating high level language program into machine language
requires an intermediatory program called the translator.
 The compiler and interpreter are two translator programs that are used to translate
the high level language programs into machine language.
 Here, also the program written in high level language is called source program.
 The corresponding program after translation (either by compiler or interpreter) is
called object program.
 The high level language program to machine level conversion is shown in figure.

1.10.3. Differences between the compiler and an interpreter


S. No Complier Interpreter
1. It takes entire high level language It takes one statement of a high level
program as input and translates it Language program as input and
into machine language. translates it into machine language
and executes it.
2. All errors that occur in the Errors that occur only in the
program are listed and displayed. statement being taken for translation
are displayed
3. Debugging is faster. Debugging is slower.
4. Requires more memory Requires less memory.
5. Costlier. Cheaper.
Maanya’s M.G.B Publications Programming in C
Programming Methodology and Introduction to C Language 1-20

1.10.4. Linker and Loader

a) Linker vs Loader

Linker is the software that links the object The loader is the system software that
code with additional files such as header loads the executable file generated by the
files and creates an executable file with linker to the main memory.
.exe extension.

b) Role of Linker and Loader

Source code Written in any HLL

Compiler Convert LLL into 0 and 1

Assembler Assembler generates the object code of a source program

Object code Code produced by a compiler or assembler executable machine


code

Linker Helps to link a object modules of program into a single object file.
It is executable file as output for loader.

Executable file Input for Loader

Loader Load the executable file/module to the main memory for


execution.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-21

1.11. Define source code, assembly code, object


code, machine code.
1.11.1. Source code and Object Code

 Source code: A program written in a high-level language is called source code.


Source code is also called a source program. The computer cannot understand the
statements written in a high-level language. Source code cannot be executed by the
computer directly. It is converted into object code then executed.
 Object code: A program written in machine language is called an object code.
Object code is also called an object program. The computer can understand object
code directly.
S. No. Source Code Object Code

1. Source code is written in high level Object code is written in machine


or assembly language. language through compilers.

2. Source code is easy to understand. Object code is difficult to understand.

3. Source code is easy to modify Object code is difficult to modify

4. Source code contains fewer Object code contains more statements


statements than object code. than source code.

5. Source code is human Object code is not human


understandable. understandable.
Maanya’s M.G.B Publications Programming in C
Programming Methodology and Introduction to C Language 1-22

6. Source code is not directly Object code is machine


understandable by machine. understandable and executable.
7. It is written in high level language It is written in machine language
like C, C++, Java, Python etc or through compiler or assembler or
assembly language. other translator.
8. It contains less number of It contains more number of
statements than object code. statements than source code.

1.11.2. Machine code and Assembly Language


S. No. Machine code Assembly Language
1. Consists of binaries, which are zeros Follows syntax similar to the
and ones English language.
2. Only understood by the CPU Understood by the programmer.
3. Depends on the platform or the Consists of a set of standard
operating system instructions.
4. Can be directly executed by the CPU Used by applications such as real-
to perform the defined tasks in the time systems and microcontroller-
computer program based embedded systems

* Programming Language *

Fig. Programming Language


 When a particular problem is to be solved, it is necessary to design statements or
instructions for the computer to carry out.
 The art of writing instructions for a computer to solve the specific task is known as
programming.
 The output of programming is a well-defined set of instructions. This is called a
program.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-23
 Software is a program or a collection of programs. Software cannot be sensed or
touched. It makes the computer hardware to work. Software can be developed by
using programming languages.
 A Programming language is the medium of communication between the man and
the machine.

1.12. State the importance of C language


 To write a computer program, we need a programming language.
 Based on the applications different programming languages such as FORTRAN,
COBOL, PASCAL, PROLOG, LISP,B, C, C++, JAVA etc., were developed.
 Every programming language has a specific goal.
 For example FORTRAN was developed for scientific calculations, COBOL for
business data processing, PASCAL for general applications and PROLOG and LISP
for artificial intelligence applications.
 There was need for a programming language which would be used to develop both
application programs and the system programs. C is a new programming language,
is developed to fulfill this requirement.
Additional Information
* History of ‘C’ *
 C is a high level language. It is both a general purpose and a specific purpose
programming language. C is the most popular and common programming
language for every application developer.
 C was developed by Dennis Ritchie in the year 1972 at AT& T Bell Laboratories;
USA. C is derived from two early programming languages such as BCPL (Basic
Combined Programming Language) and B language.
 The BCPL was developed by Martin Richards and B was developed by Ken
Thompson.
 In 1972, Dennis Ritchie developed a new version of B and named it as C. He
selected the name C for his new language because C comes after B in the
alphabetical order which indicates of BCPL (i.e., C) for naming his language.
 Initially, there was a plan to develop the UNIX operating system using C language,
but C language itself is implemented on the UNIX operating system.
 Although, C is strongly associated with the UNIX operating system, it also runs
under various operating systems including MS-DOS, Windows 95/98/2000/XP,
LINUX etc.
 For years the book “The C Programming Language, 1st edition” was the standard
on the language C.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-24
 In 1983 a committee was formed by the American National Standards Institute
(ANSI) to develop a modern definition for the programming language C.
 In 1988, they delivered the final standard definition ANSI C. (The standard was
based on the book from K&RC 1st edition).
* Features of ‘C’ *
 C language has number of characteristics or features. Due to this C-language
becomes a popular programming language. The important characteristics of C are
given below:
1. C is a general purpose and simple programming language.
2. C is a structure based programming language.
3. Helps in the development of system software.
4. It has more operators than other languages
5. It has more data types.
6. It has very less number of reserved words (32 keywords).
7. C programs are highly portable.
8. C programs are efficient and have fast execution speed.
9. No rigid format. Any number of statements can be typed in a single line.
*Note: Portable means any C program can be run on different machines with little or
no modification.
 The C programming language timeline is shown in the table below.

Language Year Founder

ALGOL 1960 International group

BCPL 1967 Martin Richards

B 1970 Ken Thompson

C 1972 Dennis Ritchie

K&RC 1978 Kernighan and Ritchie

ANSI C 1989 ANSI committee

ANSI/ISO C 1990 ISO committee

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-25

* Applications of ‘C’ *
 Because of its portability and efficiency, C is used to develop the system as well as
application software. Some of the system and application softwares are listed
below.
a) System Software
1. Operating system
2. Interpreters
3. Compliers
4. Assemblers
5. Editors
6. Loaders
7. Linkers
b) Application Software
1. Graphics Packages
2. Spread Sheets
3. Office Automation Tools
4. Word Processors
5. Scientific and Engineering Application
6. Data Base Management System (DBMS)

1.13. Explain the structure of C program


1. Documentation Section
 The documentation section is used to write the details about the program like,
name of the program, author, when it is coded and what are the features of it, etc.
 The documentation section begins with /* symbol and ends with */ symbol.
 The documentation section is only for the user or programmer understandable
purpose, the documentation part is not compiled and executed by the compiler.
2. Link Section
 The link section provides instructions to the compiler to link functions from the
system library. The syntax used to include files is as shown below.
Include<header file name>
*Note: The statements begin with # symbol are called the preprocessor directives.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-26
3. Definition Section
 The definition section defines all symbolic constants.
 The general syntax is,
#define NULL 0, for defining symbolic constant, NULL = 0.
#define PI 3.14 for defining symbolic constant PI = 3.14.

Part-I
Documentation section
Link (preprocessor)section
Definition section
Global Declaration section

OR Part-II
main() Function section
{
Declaration part;
Executable part;
}
Part-III
User defined functions

4. Global Declarations
 There are some variables that are used in more than one function. Such variables
are called global variables whose existence is known throughout the program. This
declaration should be made before main() function.
 Examples:
1. inta,b,c;
2. float x,y,z;
3. char name[20];

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-27
5. The main() function
 As the name itself indicates this is the main function of every C program. Execution
of a C program starts with main(). No C program executes without the main()
function
 This section contains two parts: declaration part and executable part.
 The declaration is a part of the C program where all the variables, arrays, functions
etc used in the C program are declared and may be initialized with their basic data
types.
 The executable part is a set of statements to perform a given task, there should be at
least one statement in the executable part.
6. Braces
 Every C program uses a pair of curly braces({ , }). The left braces indicates the
beginning of the main() function. On the other hand, the right brace indicates the
end of the main() function.
7. User-Defined Functions
 These are subprograms.
 These are written by the user, hence the name user-defined functions.
Additional Information
* Compiling and Executing a C program *
 A C program typed from the keyboard cannot be directly used as it is not in the
machine language of the computer.
 A readable C program is known as the source program. It normally has a .C
extension. The source program is converted to machine language using C
compilers.
 Compiling a C program means translating it into machine language. The C
program to be compiled must be typed in using an editor. An editor is a program
which allows the programmer to write the program and edit it.
 C compilers are available with and without editors. The environment where you
find the compiler, editor, debugging tools, linking facilities, tracing and testing
tools is called the Integrated Development Environment (IDE).
 Examples: Turbo C (TC), Borland C/C++, Microsoft C/C++ and ANSI C.

1.14. List and Explain different stages in converting the


C program source code to executable code.
 Programs written in high level language must be translated into machine language
for execution.
 Creating and executing C program requires at least four steps as follows:

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-28

1. C program (source code) is sent to preprocessor first. The preprocessor is


responsible to convert preprocessor directives into their respective values. The
preprocessor generates an expanded source code.
2. Expanded source code is sent to compiler which compiles the code and converts
it into assembly code.
3. The assembly code is sent to assembler which assembles the code and converts it
into object code. Now a simple.obj file is generated.
4. The object code is sent to linker which links it to the library such as header files.
Then it is converted into executable code. A simple.exe file is generated.
5. The executable code is sent to loader which loads it into memory and then it is
executed. After execution, output is sent to console.

1.15. Explain the steps involved in executing the C


program
 There are basically five steps in the successful execution of a program.
1. Creating a program file (source file)
2. Saving the program ( with .c as extension)
3. Compilation
4. Linking system library functions
5. Running (executing .exe file) the program
 The fig. illustrates how an executable program is created from the source code.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-29

 The steps involved in the procedure are:


Step 1: The source code is entered using a text editor in a file with a .C extension.
(Press F2 to save). It consists of preprocessor directives and functions.
Step 2: The preprocessor expands the #define directive and adds the #include
files.
Step 3: Press Alt + F9 to compile the program. The compiler produces an
intermediate object code with a.obj extension from the extended source code.
Step 4: If there are errors, correct the errors and recompile the program. If there
are no errors, then press Ctrl + F9 to execute/run the program.
Step 5: Press Alt + F5 to open User Screen and check the result. The linker adds
the relevant library routines and produces an executable version with a.exe
extension.

Maanya’s M.G.B Publications Programming in C


Programming Methodology and Introduction to C Language 1-30

Maanya’s M.G.B Publications Programming in C


2 Constants, Variables, Data Types In C
and Operators and Expressions and Input,
Output functions in C

OBJECTIVES
 2.1 Describe character set, C Tokens-Keywords, Variables, Identifiers,
Constants and Variables.
 2.2 Define Data type. Classify data types and explain with examples
 2.3 Explain declaration of a variable and assigning values to variables
 2.4 Define operator.
 2.5 Classify and Explain operators with examples
 2.6 Describe precedence and associativity of operators
 2.7 Define expression
 2.8 Describe evaluation of Arithmetic, Relational and logical expressions
 2.9 Illustrate type conversion techniques.
 2.10 Define and List Pre-processor directives
 2.11 Discuss #include and #define Pre-processor directives.
 2.12 Define Header file and discuss stdio.h, conio.h, math.h, string.h
Header files.
 2.13 Illustrate getchar(),putchar(),scanf(),printf() with programs.
Constants, variables, data types, input output functions 2-2

2.1. Describe character set, C Tokens-Keywords,


Variables, Identifiers, Constants
2.1.1 Character set
 A character denotes any alphabet, digit or special symbol used to represent
information.

1) Source character set


 These are used to construct the statements in the source program. These are of four
types.
o Alphabets Upper case: A, B, C, …..,Z
Lowercase: a, b, c,…….,z
o Decimal Digits 0 to 9
o White spaces Blank space, Horizontal tab, vertical
tab, New line, Form feed etc.
o Special Characters:
+ Plus , Comma < Lesser than
- Minus . Full stop > Greater than
* Asterisk ; Semicolon = Equal to
/ Slash : Colon ( Open parenthesis
\ Back slash „ Apostrophe ) Close parenthesis
% Percent “ Double quote [ Open bracket

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-3

| Vertical Bar & Ampersand ] Close bracket


~ Tilde # Hash { Open set bracket
? Question mark $ Dollar } Close set bracket
!Exclamation mark ^ Caret _ Underscore

2) Execution Character set


 These are employed at the time of execution.
 This set of characters are also called as non graphic characters because, these
characters are invisible and cannot be printed or displayed directly.
 These characters will have effect only when the program is being executed.
 Execution characters set are always represented by a backslash (\) followed by a
character.
 These are also called as „escape‟ sequences.
Character Escape Sequence Result
Bell (Alert) \a Beep Sound
Back space \b Moves Previous position
Horizontal tab \t Moves next horizontal tab
Vertical tab \v Moves next vertical tab
Newline \n Move next line
Form feed \f Move initial position of next page
Carriage return \r Moves beginning of the line
Null \0 Null
*Note: C is a case sensitive language therefore, upper case and lower case letters are
different.
2.1.2. C Tokens
 The basic and smallest elements in a C program are called C tokens.
 There are several types of C tokens. These are,
1. Keywords
2. Identifiers
3. Constants or literals
4. Separators
5. Operators
6. Data Types

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-4
2.1.3. Keywords
 In „C‟ language every word is classified into either a keyword or an identifier
 C language has some reserved words which cannot be used as variables or
identifiers.
 These reserved words are known as keywords.
 All keywords have fixed meanings and these meanings cannot be changed.
 Keywords serve as basic building blocks for program statements.
 There are 32 keywords in C, which have standard, predefined meanings in C.
 The standard keywords are listed below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2.1.4. Variables
 The quantity that changes during the execution of a program is called a variable.
 A variable is a data name that may be used to store a data value.
 A variable name can be chosen by the programmer in meaningful way so as to the
reflect its function or nature in the program.
 Rules for Forming Variable Names
1. Variable names may consist of letters, digits and the underscore (_).
2. The first character of a variable name must be an alphabet or an underscore (_).
3. A variable name should not be of length more than 8 characters.
4. Both uppercase and lowercase variables are significant in C.
5. White space is not allowed.
6. Keywords should not be used as variables.
7. No commas ( , ) are allowed in a variable name.
8. Special characters are not allowed, except underscore ( _ ).
9. Writing the variable names in lowercase is a good programming practice.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-5

2.1.5 Identifiers
 Identifiers (user-defined names) are names that are given to variables, functions
and arrays.
 Rules for identifiers
1. The first character must be a letter/alphabet or underscore (_).
2. It can contain characters a-z, A-Z, 0-9 or underscore (_).
3. Keywords cannot be used as identifiers.
4. No space and special symbols are allowed between the identifier.
Identifier Why it’s in valid

2krishna First character must be a letter

Net salary Contains a space

„a‟ Illegal characters

2.1.6 Constants
 Constant is a value that does not change during the execution of the program.
 C supports three types of constants. These are:
1. Numeric constants
o Integer constants
o Real (or) Floating point constants
2. Character constants
3. String constants

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-6

(i) Numeric Constants


 There are two types of numeric constants.
 Integer constant
 Real or floating point constant
a) Integer constant
 A sequence of numeric digits without the decimal point is called an integer
constant.
 An inter constant is a signed or unsigned whole number.
 There are three types of integer constants
o The valid decimal (base/radix = 10) integer constant are:
1024 -128 +127 65536
o A number preceded by „0‟ is known as octal integer constant. The valid octal
(base/radix = 8) integer constants are:
0123 0456 016 04096
o A number preceded by „0x‟ or 0X‟ is known as hexadecimal integer constant.
The valid hexadecimal (base/radix = 16) integer constants are:
0x100 0X234 0X64 0x2017
 Rule for defining on Integer constant:
1. It must have at least one digit.
2. Decimal point is not allowed.
3. It can be either positive or negative.
4. It is negative, the sign must be preceded, for positive the sign is not necessary.
5. No commas or blank spaces are allowed.
6. The allowable range for integer constants is -32,768 to +32,767.
(b) Real (or) Floating point constants
 A sequence of numeric digits with either a decimal point or an exponent or both is
called a floating point constant
 Floating point constant is a real number. It can contain minus sign and decimal
point.
 Valid floating point constants are:
32.68 256.12 10e-3 -0.00246
(ii) Character constants
 A character constant is any printable or non printable single character enclosed
within single quotes.
 Valid character constants are:
„M‟ „@‟ „$‟ „=‟ „ ‟
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-7

(iii) String Constant


 Any string of characters consists of letters, digits and symbols enclosed in double
quotes are called string constant.
 Valid string constants are:
“MY NAME IS” “MAANYA” “0765-EC-001”

2.2 Define Data type. Classify data types and explain


with examples

 The kind of data that variables may hold in a programming language is called the
data type.
 The data types can be broadly classified into the following types.
o Built in or primary data types
o User defined data types
o Derived data types
o Empty data type
 These data types are further classified as shown in above fig.
 „C‟ supports the following 4 classes of data types.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-8

Data Types Keyword Size(bytes)


Character char 1
Integer int 2
Signed long integer long 4
Single-precision float 4
Floating point numbers
Double-precision floating double 8
point numbers
Explanation:
o char refers to character. It can hold one letter/symbol.
o int refers to integer. It can hold a signed or unsigned whole number with in
the specified range.
o float refers floating point or real number. It can hold a floating point number
like 7.8690 with six decimal digits in decimal or exponential form. A float
number using 6 decimal digits is called single precision numbers.
o double also refers to floating point or real number. It can hold a real number
in double precision. A double precision number uses 12 decimal digits like
3.123456789123.
Examples:
1. int Type:
 Syntax: int variables_name;
 Example: int a,b,c,g = 10;
2. long int type:
 Syntax: long int variables_name;
 Example: long int a,b,c;
3. char type:
 Syntax: char variable_name;
 Example: char m,n,s[50];
 Where m, n are character variables and s[50] is a string of character data
type.
4. float type data:
 Syntax: float variable_name;
 Example: float b,g,c;

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-9
5. double data type:
 Syntax: double variable_name;
 Example: double p,s;

Additional information
Data Type Bytes Range Format
Specifiers
char 1  2 7 to 2 7  1 %c

unsigned char 1 0 to 2 8  1 %c

signed short int or short int or short 2  2 15 to 2 15  1 %d

signed int or int 2  2 15 to 2 15  1 %d

signed long int or long int or long 4  2 31 to 2 31  1 %d

unsigned long int or unsigned long 4 0 to 2 32  1 %u

float 4 3.3e 38 to 3.4e 38 %f


double 8 1.7e-308 to 1.7e+308 %lf
long double 10 3.4e-4932 to 1.1e+4932 %lf

2.3 Explain declaration of a variable and assigning


values to variables
a) Declaring a Variable
 A variable can be used to store a value of any data type.
 Every variable used in the program must be declared.
 At the time of declaring a variable you have to specify the data type.
 The syntax for declaring a variable is as follows,

Where, v1, v2,…..vn are the names of variables.


 Example: flot p, t, r;
 Variables can also be defined in multiple lines instead of on the same line.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-10

 Examples:
int code;
char sex;
float price;
char name[10];
 Here the variables, code is type of integer, sex is type of character, price is type
of float and name[10] is defined an array of character.
*Note:
1. When the variables are declared in single line, then the variables must be
separated by commas.
2. A declaration statement must end with a semicolon (;).
b) Initializing variables (or Assigning values to variables)
 Variables initializaiton means assigning a value to the variable.
 Initializaiton of variable can be done using the assignment operator (=).
 Variables should be declared in the C program before to use.
 The syntax for declaring a initializing variables is as follows,

Description i, f, c are the type of int,


float, char data types
Example 1 i = 29;
f = 29.77;
c = q;
Example 2 int i = 29;
float f = 29.77;
char c = „l‟;
int l = a = k = 29;
*Note: The last example shows that the varibles i, a, k are initialized with the
content of 29 itself for all variables.
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-11

2.4 Define operator.


 An operator is a symbol that specifies the type of operators to be carried out.
 These are used to perform basic arithmetic and logical operations, comparison,
manipulations of bits and so on.
 The value that can be operated by these operators are called operands.
 The operators are classified into unary. Binary and ternary depending on whether
they operate on one, two or three operands respectively.
 Example: a+b, Where „+‟ is operator and „a‟, „b‟ are the Operands

2.5 Classify and Explain operators with examples


 The table also shows the classification of C operators.

S. No. Operator Symbols


1 Arithmetic +,-,*,/,%
2 Relational
a. Comparison <,<=,>,>=
b. Equality ==,!=
3 Logical &&,¦¦,!
4 Assignment
a. Simple =
b. Shorthand +=,*=,-
=,/=,%=
5 Increment/Decrement
a. Prefix ++m,--m
b. Postfix m++,m--
6 Conditional
a. Single ternary ?:
b. Nested ternary (?(?:):)
7 Bitwise &,¦,<<,>>,~,^
8 Special +,-, , sizeof(),
., ->

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-12

2.5.1. List the five Arithmetic Operators


 Arithmetic operators are used to perform arithmetic operations.
 „C‟ allow us to carryout basic arithmetic operations like addition, subtraction,
multiplication, and division.
 The following table shows the Arithmetic Operators and their meaning.
Operator Meaning Examples
+ Addition 2+9=11
- Subtraction 9-2=7
* Multiplication 2*9=18
/ Division 9/3=3
% Modulo division 9%2=1
*Note:
1. All the above operators are called „Binary‟ operators as they act upon two operands
at a time.
2. The modlo division gives the remainder of an integer division.
3. The arithmetic operators +,-,*, and / may be used with int or double data
type operands.
4. On the other hand, the remainder operator % also known as modulus operator can
be used with integer operands to find the remainder of the division.

Here the remainder value only is assigned to variable „c‟


5. The operator „%‟ cannot be used with real operands. The following table shows
how the divison operator operates on various data types.
Operation Result Examples
int/int int 2/5=0
real/int real 5.0/2=2.5
int/real real 5/2.0=2.5
real/real real 5.0/2.0=2.5
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-13
In the first example the integer division truncates the fractional part.
Example 1: Program illustrate the usage of arithmetic operators
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
i = 10;
j = 20;
k = i + j;
printf(“Value of k is %d\n”, k);
getch();
}
Output:
Value of k is 30
Explanation: This program prints the value of arithmetic expression k=i+j, where the
variables „I‟ and „j‟ are predefined variables.
2.5.2. List and explain relation operators
 Relational operatos are used to compare two or more operands. Operands may be
variables, constants or expression.
 For example we may compare the age of two persons, or the price of two items and
so on. These comparisons can be done with the help of relational operators.
 An expression containing 4 relational operator is termed as a relational expression
 The value of relational expression is either one or zero. It is one if the specified
relation is true and zero if the relation is false.
 C supports six relational operatos
 These operation and their meanings are shown in Table
Operator Meaning Example Return
Value
 Less than 9  10 1
 Greater than 9  10 0
 Less than or equal to 9  9 1
 Greater than or equal 10  9 1
to
 Equal to 5  9 0
! Not equal to 5! 9 1
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-14
*Note:
 All relational operators need two operands.
 Relational operators are used in decision making process. They are generally used
in conditional and control statements
2.5.3. Explain logical operators
 Logical operators are used to combine the results of two or more conditions
 C language has the following three logical operators.
Logical Operator Meaning
! NOT
&& Logical AND
|| Logical OR
 The NOT operator is a unary operator operating on a single operand; while the
other two operators are binary operators that operate on two operands.
 The logical operators && and | are used when we want to test more than one
condition and make decisions

Additional information
 The logical AND operator is used to perform ANDing operation on two logical
operands. It performs the multiplication operation. The result of a logical ANDing
is true, when both the operands are true. Otherwise the answer is false. The
following table show logical operators.
Operand 1 Operand 2 Operand 1&& Operand 2
False False False
False True False
True False False
True True True
 The logical OR operator is used to perform logical addition operation. The result
of a logical addition is false only when both the operands are false; otherwise the
answer is always true. The following truth table illustrates this.
Operand 1 Operand 2 Operand 1¦¦Operand 2
False False False
False True True
True False True
True True True

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-15
 The logical NOT is used to obtain the logical complement or inverse of the given
operand. The result of a logical NOT is true when the operand is false and vice
versa. The truth table following illustrates the same.
Operand !Operand
False True
True False

Examples of Logical Operators

Declarations: int i  3 , j  7
double f  5.5 , g  4.5
char ch ' T'
Expression Interpretation Value
i  5 & &ch ' T' True 1

 j  8 || ch ' L' True 1

f  g  10.0|| i  2 True 1

f  6 || i * j  15 False 0

!f  5.0 False 0

2.5.4. Explain writing the assignment statement.


 Assignment operator (=) assigns the value or an expression or value of expression
on the right side of it to the variable on the left of it.
 A statement is an instruction to the computer to perform a specific operation.
 Assignment stateemtn is an assignment expression followed by asemicolon.
 If a semi-colon is placed at the end of an assignment expression, the result is an
assignment statement.
 For example x  15 is an assignment expression, whereas x  15; is an assignment
statement.
 The general form the assigment statement is,

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-16
Assignment expression Assigment statement
x=10 x=10;
x=a+b x=a+b;
x=y*y x=y*y;
2.5.4.1. Types of assignment statements
 C language supports different types of assignment statements. They are:
a) General assignment statement
b) Declaration assignment statement
c) Multiple assignment statement
d) Increment / decrement statement
a) General Assignment Statement:
 According to this statement an expression/value can be assigned to a variable
using the following syntax.

 Examples:
 a  10  20* 3 ;
 a  70 ;
b) Declaration Assignment Statement:
 The initialization of variables is possible at the time of declaration itself.
 In this case, the declaration must consist of a data type followed by a variable name,
an equal sign and a number appropriate to the data type and finally a “semicolon
(;)”.

 Examples:
 int x  1 ;
 float sum  0.0 ;
 char ch ' Y' ;
c) Multiple Assignment Statement:
 According to this statement, more than one variable can be assigned a single value
or an expression using the following syntax:

 Example: a  b  c  10;

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-17

d) Increment/Decrement statement
 With assignment we can use either increment/decrement operator.
 Example 1: a    b
Let us take the value of b  5
Then the above statement increments the value of b by one, then value is assigned
to a.
Hence, a  6 , b  6
 Example 2: a  b  
Let us take the value of b  5
First a takes the value of b; then value of b is incremented it by one.
Hence, a  5 , b  6
2.5.5. Explain the increment and decrement operators
 In certain cases the value of a variable to be incremented or decremented by one.
 C uses two very useful operators not generally found in other languages. These are
increment (++) and decrement (--) operators.
 The „++‟ adds one to the variable and „--‟ substracts one from the variable.
Operator Meaning
++a Prefix increment
--a Prefix decrement
a++ Postfix increment
a-- Postfix decrement
*Note:
1. ++a is equivalent to a  a  1; or a   1;
2. --a is equivalent to a  a  1; or a   1;
Explanation:
i) Increment Operator
 This operator is used to increment (or increase) the value of an integer quantity by
one. This is represented by „++‟ (double plus) symbol. This symbol can be placed
either before or after an integer variable.
 These are further subdivided into two categories:
1. Prefix increment
2. Postfix increment
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-18

a) Prefix Increment b) Postfix Increment


 Increment and use(assign).  Use and increment.
 In the prefix increment operator, first  In the postfix increment operator, first
of all values will be incremented and of all value will be assigned to the
then incremented value will be variable and then it will be
assigned to a variable. incremented.
 Example:  Example:
a    b; a  b  ;
This is equivalent to two assignment This is equivalent to two assignment
statements statements
b  b  1; and a  b; a  b and b  b  1;

ii) Decrement Operator


 This operator is used to reduce the value of an integer quantity by one. This is
represented by „- -„ (double minus) symbol. This symbol can be placed either before
or after an integer variable.
 These are further subdivided into two categories:
3. Prefix decrement
4. Postfix decrement
1. Prefix Decrement 2. Postfix Decrement
 In this prefix decrement operator, first of  In the postfix decrement operator,
all value will be decrement and then first of all value will be assigned
decrement value be assigned to the and then it will be decremented.
variable.
 Example:  Example:
a    b; a  b  ;
This is equivalent to two assignment This is equivalent to two
statements assignment statements
b  b  1; and a  b; a  b; and b  b  1;
*Note: Increment/decrement operators work with integers or character type variables.
2.5.6. Explain conditional operator
 The conditional operator is also called ternary operator.
 The conditional operator contains a condition followed by two statements or
values. If the condition is true then the first expression is executed otherwise the
second.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-19
 It is called ternary operator because the conditional operator (?) and the (:) takes
three arguments.
 Syntax: condition? expression 1: expression2;
 Here the two expressions are separated by a colon (;). If the condition is true then
the expression1 gets executed otherwise expression2.
2.5.7. Explain bitwise operators
 Bitwise AND, OR, XOR are binary operators and produce a result depending on the
comparison of corresponding bits in each of the operands.
 For an 8-bit computer, the equivalent binary value of a=4 = 0000 0100 and the
equivalent binary value of b=3 = 0000 0011.
1. Bitwise AND operator
 The result of a bitwise ANDing is 1 when both the bits are 1. Otherwise, it is a 0.
 Example: The result of bitwise ANDing of a and b
a = 0000 0100
b = 0000 0011
………………
a&b = 0000 0000
2. Bitwise OR operator
 The result of a bitwise ORing is 1 if one of the bits is 1 and the other is 0. Otherwise
it is 0.
 Example: The result of bitwise ORing of a and b
a = 0000 0100
b = 0000 0011
………………
a/b = 0000 0111
3. Bitwise XOR operator
 The result bitwise XORing is 1, if the bits are different (1 and 0). Otherwise, it is a 0
(when both are 0s and both are 1s).
 Example: The result of bitwise XORing of a and b
a = 0000 0100
b = 0000 0011
………………
a^b = 0000 0111

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-20

4. Bitwise 1’s complement operator


 The bitwise complement operator is an unary operator that reverses the state of
each bit within an integer or character.
 It is used to obtain the one‟s complement of a binary sequence. This means that
each zero gets changed to one and each one gets changed to zero during bitwise
complement operation.
5. Left shift and right shift operators
 The left shift operator shifts the bits towards left and the right shift operator shifts
the bits towards right. Consider the following example
 The left shift and right shift operators change the contents of an input number. The
general form of bitwise shifting is:

Where,
variable  An int or char data element
shift operator  Left shift or right shift operator
nob  Number of bits to be shifted
 Examples: The left shift and right shift operations are illustrated pictorially below.
 Consider the binary number 10000100. It is equivalent to 132 in decimal.
a) Bitwise Right shifting b) Bitwise Right shifting
Before shifting one bit right Before shifting one bit right
1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0

After one bit shifted to right After one bit shifted to right
0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0

2.5.8. Explain special operators


 Along with these operators, the C language supports some of the special operators
given below.
Operators Meaning
, comma operators
sizeof size of operators
& and * pointer operators
. and -- Member selection operators
 The pointer and member selection operators are discussed in the pointers concept.
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-21

a) Comma operator (,) :


 Usually the comma operator is used to separate the statement elements such as
variables, constants or expression etc, and this operator is used to link the related
expressions together, such expressions can be evaluated from left to right and the
value of right most expressions is the value of combined expression.
 Example: val = (a=3, b=9, c=77, a+c);
Where, First assigns the value 3 to a
Then assigns the value 9 to b
Then assigns the value 77 to c
Finally assigns 80 to the val
b) The sizeof() operator:
 The sizeof() operator is used to calculate the size of an operand. This means how
many bytes in memory.
 The operand may be a variable, a constant or a data type.
 The size of operator is normally used to determine the lengths of arrays and
structures when their sizes are not known to the programmer. It also used to
allocate memory dynamically during program execution.
 Examples
a = sizeof{int);
b = sizeof{3.5)
c) Pointer operators :
 & : This symbol specifies the address of the variable.
 * : This symbol specifies the value of the variable.
d) member selection operators:
 . and -- : These symbols used to access the elements from a structure.

2.6 Describe precedence and associativity of operators


 C Programming supports wide range of operators. Therefore, there must be some
rules for evaluating complex expressions.
 So to evaluate complex expressions, C has adopted two important rules namely;
1. Operator Precedence and
2. Operator Associatively
 Precedence is used to determine the order in which different operators in a complex
expression are evaluated.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-22
 “C” expression may have different types of operators present in the expression. In
that case operators will get executed in the following order.
o Unary operator
o Arithmetic, multiply, division and modulus
o Arithmetic, add and subtract
o Relational operators
o Equality operators
o Logical AND
o Logical OR
o Conditional operator
o Assignment operator
o Comma operator
 The higher the precedence of an operator, the earlier the expression
containing that operator is evaluated.
 Associativity indicates the order in which the terms in the expression are evaluated.
That is, either from left to right (L to R) or Right to Left (R to L). Table shows the
arithmetic operations, operators and their precedence and associativity (order of
evaluation).
S. No. Operations Operator Precedence Associativity
1 Addition + 2 L to R
2 Subtraction - 2 L to R
3 Multiplication * 1 L to R
4 Division / 1 L to R
5 Modulus % 1 L to R
 Here, the lowest number indicates the highest priority and the highest number
indicates the lowest priority. The priority indicates which term is to be evaluated.
Precedence Operator Operation Associativity
level
1 () Function call Left to Right
[] Array subscript Left to Right
- Dot Left to Right
-> Arrow Left to Right

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-23

2 ! Logical NOT Right to Left


~ One‟s complement Right to Left
- Unary minus Right to Left
(negation)
++ Increment Right to Left
-- Decrement Right to Left
& Address of Right to Left
* Indirection- Right to Left
(data_type) Cast operator Right to Left
size of Size of Right to Left
3 * Muliplication Left to Right
/ Division Left to Right
% Modulus Left to Right
4 + Addition Left to Right
- Subtraction Left to Right
5 << Left shift Left to Right
>> Right shift Left to Right
6 < Less than Left to Right
<= Less than or equal to Left to Right
> Greater than Left to Right
>= Greater than or equal Left to Right
to
7 == Equal to Left to Right
!= Not equal to Left to Right
8 & Bitwise AND Left to Right
9 ^ Bitwise XOR Left to Right
10 | Bitwise OR Left to Right
11 && Logical AND Left to Right
12 || Logical OR Left to Right
13 ?; Conditional Right to Left
14 = += -= *= /= %= Simple and compound Right to Left
>>= <<= &= ^= |= Assignment
15 , Comma Left to Right

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-24
Explanation:
 Arithmetic expressions are evaluated from left to right. Expressions involving
high priority operators are evaluated first. The precedence of each arithmetic
operator is given in table. Consider the following simple arithmetic operations.
a+b
 It is very simple expression involving only one operator (addition operation).
Here the value of a is added to the value of b. x*y/z
 There are two operators (* and /) having the same priority. In this case, the
expression is scanned from left to right. And, the expression x*y is evaluated
first. Then this result is divided by the value of z.
1. a+b*c/d-e
2. 2.0*a+0.05*b-1.0
 There are four separators. The steps involved in evaluating expression3 are
given in table.
S .No. Terms Reasons
1 b*c *having highest priority than + and -
2 (b*c)/d /is having highest priority than + and – and appear
after *
3 a+(b*c)/d Both + and- having same priority before –sign

4 (a+(b*c)/d)-e In L to R scan - appears at the end

2.7 Define expression


 An expression is a combination of constants, variables and operators arranged as
per the syntax of the language.
 The examples of algebraic expressions and C expressions are shown in table.
Algebric expressions C expressions
a  bc a  b*c
ax 2  bx  c a *x*x  b*x  c

 4ac  4 * a * c /2 * a 
 
 2a 
 2x 2  2 * x * x  / b  c
   c
 b 

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-25

2.8 Describe evaluation of Arithmetic, Relational and


logical expressions
 While evaluating an expression C compiler follows hierarchy rules.
1. The expression is scanned from left to right.
2. While evaluating an expression the operator with highest precedence will be
evaluated first, then the second highest precedence operator and the operator
with least precedence will be evaluated last.
3. * / % have high priority level.
4. + - have lower priority level than above.
5. If parenthesis is encountered then the expression within the parenthesis is
evaluated first.
Example 1:
sum  x  y / 3  z * 3  1
Where, x  3, y  9, z  77
sum  3  9 / 3  77 * 3  1
Solution:
This expression sum  3  9 / 3  77 * 3  1 is revalued in two phases, as follows:
First phase:
Step 1: sum  3  3  77 * 3  1 (/ operation)
Step 2: sum  3  3  231 1 (* operation)
Second Phase:
Step 3: sum  0  231  1 (- operation)
Step 4: sum  231  1 (+ operation)
Step 5: sum  230 (- operation)
This can be illustrated in fig.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-26
Example 2: Z  5 * 4/2  5/5  8  2
Solution:
Z  20/2  5/5  8  2 (* operation)
Z  10  5/5  8  2 (/ operation)
Z  10  1  8  2 (/ operation)
Z  11  8  2 (+ operation)
Z  19  2 (+ operation)
Z  17 (- operation)
2.7.1. Evaluate a logical expression.
Example 1:
 Consider the following logical expression, a && b||c && !b
 Suppose a, b and c are three variables having the values 2, 4, and 3 respectively.
Then the above logical expression is evaluated as
Step 1: Substituting the values, 2 && 4 || 3 && !4
Step 2: Evaluating the NOT operator, 2 && 4 || 3 && 0
Step 3: Now evaluating the AND operator,
(2 && 4) || (3 && 0)
1 || 0
Step 4: Finally evaluating the OR operator,
1 || 0
1
Example 2:
a  b&&c  d
Let us assume, a  10, b  12, c  12 , d  13
10  12&&12  13
false&&false
False

2.9 Illustrate type conversion techniques.


 Conversion of a value of one data type to another is called type conversion.
 There are two types of type conversions
1. Implicit
2. Explicit

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-27
1. Implicit Type conversion
 The implicit type conversion is referred as coercion.
 It is an automatic type conversion.
 If the operands are of different types, the „lower‟ type is automatically converted to
the „higher‟ type before the operation proceeds. The result is of the higher type.
 Example: 3  2.0; the expression evaluates to type double and gives output 5.0,
since 2.0 has higher data type.
2. Explicit Type conversion
 The explicit type conversion is also known as type casting.
 Casting can be used to round off a given value.
 Example: int  22/10; output for this statement is 2.
 The operator used to force the conversion of a value to another type is called the
cast operator.
 The general form of a cast is:

 Where data_type is one of the standard C data types. The expression may be a
constant, variale or an expression.
 Example:
double d = 6.5;
double b = 6.5;
int result = (int)(a) + (int)(b);
 Result would be equal to 12 instead of 13.
 Some other examples of casts and their actions are shown in Table.

Example Action

x  int 7.5 7.5 is converted to integer by truncation.


a  int 21.3 / int 4.5 Evaluated as 21/4 and the result would be 5.
b  double sum / n Division is done in floating point mode.
y  int a  b  The result of a + b is converted to integer.
z  int a  b a is converted to integer and then added to b.
x  cosdouble x  Converts x to double before using it.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-28
*Note: The following rules have to be followed while converting the expression from
one type to another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.

2.10 Define and List Pre-processor directives


2.10.1. Introduction
 The portability and efficiency of a program increases with the language flexibility.
 Flexibility is the ability of the programming language to incorporate appropriate
modifications automatically.
 C provides such a facility called the C Preprocessor.
 This helps the C programmer to make his/her programs easy to read, easy to
modify, portable and efficient.
2.10.2. C Preprocessor
 This is a macro processor program that processes the source program before it is
compiled.
 It is a collection of special statements called preprocessor statements or
preprocessor directives.
 These directives are executed before the C program passes through the compiler.
 Figure shows the stages involved in compiling a C program.

2.10.3. Preprocessor directives


 These are statements which begin with the #symbo1 placed in the first column.
 They are placed before the function main().
 There will be no semicolon at the end of such statements.
 There are three types of preprocessor directives. They are,
1. Macro substitution directives
2. File inclusion directives
3. Conditional compilation directives
4. Miscellaneous directives

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-29
 The preprocessor can be thought as a smart editor. Like a smart editor, it inserts,
includes, excludes, and replaces text based on commands supplied by the
programmer. These commands are known as Pre-processor Commands or Pre-
processor directives.
 The following points about the preprocessor commands are very important and
must be noted carefully.
1. All the pre-processor commands start with a pound sign (#).
2. Pre-processor directives are placed in the source program before the main line.
3. They do not require a semicolon (;) at the end.
 The preprocessor directives are broadly divided into two categories:
1. Unconditional Preprocessor directives
2. Conditional Preprocessor directives
 The Unconditional Pre-processor directives in C are listed in table.
S. No. Directive Description
1. #include Inserts a external file from the system library or a user
defined directory
2. #define Substitutes a preprocessor macro
3. #undef Undefines a preprocessor macro
4. #error Prints the error message detected by the preprocessor
5. #pragma Causes the compiler to perform implementation-defined
actions
6. #line Sets the line number and the filename for a program
7. # Null command
 The conditional Pre-processor directives in C are listed in table.
S. No. Directive Description
1. #if Tests if a compile time condition is true
2. #ifdef Returns true if this macro is defined
3. #ifndef Returns true if this macro is not defined
4. #elif #else an #if in one statement
5. #else The alternative for #if
6. #endif Ends preprocessor conditional

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-30
*Note: Some directives are used to compile a part of the program based on certain
conditions. It means that if a specific condition is fulfilled, then the program will be
executed otherwise not. These preprocessor directives are known as Conditional
Preprocessor Directives. The conditional Preprocessor directives in C are listed below:

2.11 Discuss #include and #define Pre-processor


directives.
2.11.1. #include
 The #include directive causes the pre-processor to fetch the contents of another file
into the source code. It will add the content at the point where the #include
directive is found.
 The #include directive is typically used to include the C header files for the C
functions that are held outside of the current source file.
 A header file is a file which contains the extension ".h". This extension has C macro
definitions and C function declarations to be shared between several source files.
Header files are of two types:
 Files that the programmer writes
 Files that come with the compiler.
 We request to use a header file in our program by including it with the C
preprocessing directive #include, like as we have seen the stdio.h header file, which
comes along with the compiler
 Syntax: The syntax for the #include directive is:
#include <header file>
 The #include <headerfile> tells the compiler to look for the directory where system
header files are held.
(Or)
#include "header file."
 The #include "header file" tells the compiler to look in the current directory from
where the program is running.
 *Note: If a header file is included within the symbol <>, the pre-processor will
search a predetermined directory path to locate the header file. If the header file is
enclosed in quotation mark " ", the pre-processor will look for the header file in the
same directory as the source file.
2.11.2. #define
 The #define pre-processor directive is used to define pre-processor variable,
constant or macro. Macro operates much like functions. The #define can use any
basic data type. This pre-processor directive can be used to replace a word with a
number globally. It acts as if an editor did a global search-and-replace edit of the
file.
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-31
 We can use the #define directive for the debugging purpose. We can have print
statements that will be only active while debugging.
 Syntax: The syntax for using #define in the C language is:
#define constant_name value
(Or)
#define constant_name (expression)
 Constant_name: The name of the constant.
 Value: The value of the constant.
 Expression: It is an expression whose value is assigned to the constant.
The expression must be enclosed in parentheses if it contains any operators.

2.12 Define Header file and discuss stdio.h, conio.h,


math.h, string.h Header files.
 The collection of some library functions over a single file is called as header file. The
extension name of an header file is „h‟.
 Files that are placed at the header portion (before main()) of a C program are called
the header files. Normally, the standard header files are having.h as extension
which designates a header file. However, the user-defined header files may have
different extensions.
 The header files are used to provide the necessary information in support of the
various library functions. Each header file contains declaration for certain related
library function. For example, stdio.h is a header file containing declarations for
input/output functions. Similarly, math.h header file contains declaration for
certain mathematical functions. Some of the important and commonly used header
files are given below:
Header file Declaration for
Stdio.h Input/ Output functions
math.h Mathematical functions
string.h String manipulation functions
malloc.h Memory allocation/deallocation functions
stdlib.h Some standard library functions
ctype.h Character manipulation functions
time.h Time computing functions
graphics.h Graphical functions
dos.h Functions linking DOS routines.
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-32
 The header files are entered into the source program via a# include statement. The
#include statement is a preprocessor statement and must be written at the
beginning of the program.
 The stdio.h header file can be included in your source program by writing the
following statement.
#include<stdio.h>
 Observe that the header files stdio.h is enclosed within angle brackets (<, >).
Alternatively, we can also write the header file within double quotes as
#include”stdio.h”
 If we write the header file is enclosed within angle brackets, it means that the
compiler will search for the header file in the default include directory. (Note that
the include directory is one in which the compiler‟s installation program will place
the header files). If the required header file is not found in the current directory
during the compilation process, then the compiler searches for it in the include
directory. On the other hand, if we write the header file name within double quotes,
the compiler will search for that header file in the current directory only. If the file
is not found, it will flag an error message.
2.12.1. Types of Header Files
 There are two types of Header files in C-
1. System defined: Means which is predefined header files.
2. User defined: Means which is defined by the User.
Header Files Functions Defined
stdio.h Printf(), scanf(), getchar(), putchar(), gets(), puts(), fopen(),
fclose()
conio.h Clrscr(), getch()
Ctype.h Toupper(), tolower()
Math.h Pow(), sqrt(), cos(), log()
Stdlib.h exit()

2.12.2. stdio.h, conio.h, math.h, string.h


// Header Files in C
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-33
 #include<stdio.h>: The full form of stdio is - Standard Input Output. So we can
understand this header file is used for Input / Output functions (printf() and
scanf()).
 #include<conio.h>: conio stands for Console Input Ouput. Usually this header file
is used for MS-DOS compilers.
 #include<string.h>: This header file is used for performing string related
functionalities , like strcpy(),strcmp() etc.
 #include<math.h>: It is used for perform mathematical operations,like
pow(),sqrt().(Discussed in below)

Additional information

*INPUT OUTPUT STATEMENTS*


 We know that input, process, output are the three essential features of computer
program. The program takes some input data, processes it and gives the output.
 We have two methods for providing data to the program.
o Assigning the data to the variables in a program
o By using the Input/Output funcitons
 In „C‟ language, two types of Input/Output statemetns are available, and all input
and ouput operations are carried out thorugh function calls. Several functions are
available for input/output operations in „C‟. These functions are collectively known
as the standard I/O library.
o Unformatted Input/Output statements
o Formatted Input/Output statemets

 Formatted Input/Output refers to input and output, that has been arranged in a
particular format.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-34

Additional information

 getchar( )  Reads a character from the keyboard.


 putchar( ) Prints a character to the screen.
 gets( )  Accepts a string of characters entered at the keyboard and places them
in the string variable mentioned with it.
 puts( )  Writes a string on the screen and advances the cursor to the newline.
i.e. it ends with a new line character.

a) List three functions used for reading strings


 A string or a group of strings can be read from the input device {keyboard or a data
file} using the following functions.
1. scanf() with the %s format specification.
2. gets() function.
3. getchar() function.

b) List three functions used for writing strings.


 A string or a group of strings can be written to the monitor using the following
output functions.
1. printf() with the %s format specification.
2. putchar() function
3. puts() function

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-35

2.13 Illustrate getchar(),putchar(),scanf(),printf() with


programs.
2.13.1. Explain printf ()and scanf () functions
 In many of the computer languages the input/output operations are done through
statements.
 But in “C” language all input/output operations are performed through function
calls such as printf and scanf etc. These functions are collectively known as the
standard I/O library.
1. Input Function: scanf( )
 C provides a function called scanf( ) to read the values for the variables in a C
program from the keyboard. „
 The scanf() function is used to read information from the standard input device
(keyboard).
 It is included in the header file <stdio.h>.
 The general form of scanf( ) is given below.

 This function should have at least two parameters.


o First parameter is control string which is conversion specification character. It
should be within double quotes.
o The conversion specification character may be one or more, it depends on the
number of variables.
o Conversion specifications are used to provide the type and size of the data.
Each conversion specification must begin with a percent sign (%).
o For example if we want to use integer data then %d to be used as conversion
specifier. If we want to use float data then %f is to be used as conversion
specifier.
o The other parameters are variable names. In the scanf( ) atleast one variable
name should be present. Each variable name must be preceded by an
ampersand (&). This gives the starting address of the variable name in
memory.
Examples:
1. scanf(“%d”,&a); Here we are accepting a value into variable „a‟ of type int.
2. scanf(“%f”, &x); Here we are accepting a value into a variable‟x‟ of type float.
*Note: Comments are not allowed in scanf( ).
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-36

2. Output Function:
 C provides the printf( ) function to display the data on the standard output
device(monitor). The printf( ) function is included in the header file
<stdio.h>.
 The general form of printf( ) function is

 Control string consists of three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b.
Examples: Some examples of printf() statement are given below:
1. printf(“programming is an art”);
2. printf(“%d”,number);
3. printf(“%f %f”,p,q);
4. printf(“sum of three numbers=%d”,sum);
5. printf(“%s,is input string\n”,string);
6. printf(“\n X=%d Y=%f\n”,x,y);
Explanation:
o The first statement displays a sequence of characters enclosed within the
double quotes.
o The second statement displays the value of the number. (Note that there is no.
and symbol before the number as in the scanf()statement).
o The third statement displays content of the variables p and q.
o The fourth statement prints the message and in front of that it prints the
content of the sum.
o The fifth statement outputs the value of x and y respectively in front of X= and
Y=. The inclusion of newline character in the printf()statement transfer the
control to the next line.
o The %d, %f and %s are character groups as in scanf()statement.
o Refer to the table and read the meaning of each character group by replacing
the term read by print. In the following section printf()statement is
discussed for outputting integer, character and other types of data.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-37
*Note:
 printf() is similar to the input function scanf(), except that it display data
rather than input
 No & (ampersand) is used while outputting data.
2.13.2. Explain getchar ()and putchar () functions
 In C, we have functions for performing input and output operations of single
character at a time, known as character I/O functions.
 The character I/O functions in standard C library are
1. getchar()
2. putchar()
 The getchar()is used for character input and putchar() is used for character
output.
 The character I/O functions are found in the C library conio.h.
 Therefore, whenever you use the character I/O functions in your C program, the
preprocessor statement# include <conio.h> should be included in the
program.
1. getchar()
 This function reads a character just entered from standard input unit that is
keyboard, during the execution of the program.
 The syntax for calling getchar() function is

Here var_name is a char type variable.


 The following program shows the usage of getchar() function
2. putchar()
 putchar() function is a file handling function in C programming language which
is used to write a character on standard output screen.
 The syntax for calling putchar() function is

Here, character is a char type variable or a direct character.


*Note: The following example shows the usage of getchar() function.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-38

……………….………..Simple C Programs…………….…………
Program 1: C program to find the area of triangle having base ‘b’ and
height ‘h’.
1./*to find the area of a triangle*/
2.#include<stdio.h>
3.void main()
4.{
5. float area,base,height;
6. printf(“Enter base,height\n”);
7. scanf(“%f %f”,&base,&height);
8. area=0.5*base*height;
9. printf(“Area= %f “,area);
10. }
Output:
Enter base,height
15.0,10.0
Area =75.000000
Explanation:
The program lines have been indicated for explanation purposes only and they do
not from part of the program.
Line 1: Comment line to explain the purpose of the program.
Line 2: Header file inclusion.
Line 3: The main function starts with the keyword void which indicates the main
fuction does not return a value.
Line 4: {
Line 5: Declaration of floating variables area, base, height.
Line 6: printf is used to print the message “Enter base, height”, so as to interact
with the user.
Line 7: scanf is used to accept values for base, height from user.
Line 8: To compute area.
Line 9: To display the result
Line 10: }
*Note: The braces (Line number 4 and 10) are used to indicate the beginning and end
of the faction main ().

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-39
Program 2: C program to calculate simple interest
#include <stdio.h>
void main( )
{
float p,t,r,si;
printf (“Enter principal p \n”);
scanf (“%f”,&p);
printf (“Enter number of years t\n”);
scanf (“%f”,&t);
printf (“Enter rate of interest r \n”);
scanf(“%f”,&r);
si=(p*t*r)/100;
printf(“Simple Interest=%f”,si);
}
Output:
Enter principal p
1000
Enter number of years t
5
Enter rate of interest r
15
Simple Interest =750.000000
Explanation: Here the principal, number of years and rate of interest are fed though
the three scanf( ) calls. The interest is calculated as per the formula. Finally interest is
displayed though the printf( ).
Program 3: C program to convert a given Fahrenheit temperature to
Centigrade scale.
#include <stdio.h>
void main( )
{
float f,c;
printf (“Enter temperature in Fahrenheit \n”);
scanf (“%f”,&f);
c=5.0/9.0*(f-32);
printf(“The temperature in Centigrade= %f”,c);
}
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-40
Output:
Enter temperature in Fahrenheit
100
The temperature in Centigrade=37.78
Explanation: In the above program Fahrenheit temperature is received from the user
though the scanf(). The Centigrade temperature is calculated by using the standard
formula. Finally Centigrade temperature isdisplayed though the printf().
Program 4: C program to print sum and average of 6 subjects*/
#include<stdio.h>
void main( )
{
int m1,m2,m3,m4,m5,m6,total;
float avg;
printf(“Enter 6 subject marks\n”);
scanf(“%d%d%d%d5d%d%”,&m1,m2,m3,m4,m5,m6);
total = m1+m2+m3+m4+m5+m6;
avg= total/6;
printf(“sum of 6 subjects=%d\n”,total);
printf(“Average of 6 subjects=%f”,avg);
}
Output:
Enter 6 subjects marks
92 90 85 99 89 94
Sum of 6 subjects=549
Average of 6 subjects=91.500000
Program 5: C program to calculate slope and midpoint of a line
#include<stdio.h>
void main()
{ float x1, x2, y1, y2, slope;
printf(“Enter the First Point x1, y1\n”);
scanf(“%f%f”,&x1, &y1);
printf(“Enter the Second Point x2, y2\n”);
scanf(“%f%f”,&x2, &y2);
slope=(y2-y1)/(x2-x1);
printf(“Slope of line=%f\n”, slope);
}
Maanya’s M.G.B Publications Programming in C
Constants, variables, data types, input output functions 2-41
Output:
Enter the First Point x1, y1
10 20
Enter the sceond Point x2, y2
30 40
Slope of line=1.000000
Explanation :
Let x1, y1 and x2, y2 are the coordinates of the extremites of the line
y2  y1
The slope of this line is, slope 
x 2  x1
For this program x1, y1, x2, y2 are the inputs, slope is output.
Program 6: C program to determine the area of a given three side
#include<stdio.h>
#include<math.h>
void main()
{
float a, b, c, s, area;
printf(“Enter three sides of a triangle\n”);
scanf(“%f%f%f”,&a, &b, &c);
s=(a+b+c)/2.0;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf(“Area of triangle=%f”, area);
}
Output:
Enter three sides of a triangle
10 10 10
Area of triangle=43.301270
Explanation :
o The program given above determine the Area of Triangle using the following
formula:
abc
Area  ss  a s  bs  c Where s 
2
o The variable a, b, c, s and area are declared as float type. The program reads the
three sides of triangles a, b, c and calculates s and area of the triangle and then
prints the area of the triangle.

Maanya’s M.G.B Publications Programming in C


Constants, variables, data types, input output functions 2-42
Program 7: C program to calculate the real roots of a quadratic equation
#include <stdio.h>
#include <math.h>
void main( )
{
float a,b,c,d,n,root1,root2;
printf(“Enter a,b,c\n”);
scanf(“%f%f%f”,&a,&b,&c);
d=sqrt(b*b-4*a*c);
n=2*a;
root1=(-b+d)/n;
root2=(-b-d)/n;
printf(“X=%f y=%f”,root1,root2);
}
Output:
Enter a, b, c
1 -5 6
X=3.000000 y=2.000000

Maanya’s M.G.B Publications Programming in C


3
Decision making, looping statements
And Pre-processor directives

OBJECTIVES
 3.1 Discuss decision making in programming.
 3.2 Explain decision making statements- if , if-else, nested if, else-if l
adder - with syntax and programs
 3.3 Discuss break and continue statements.
 3.4 Explain decision making statement- switch statement - with syntax
and programs
 3.5 Define looping and list loop statements
 3.6 Explain the loop statements – while, do- while, for statement- with
syntax and programs
 3.7 Define nesting of loops and implement it
 3.8 Compare different loop statements
 3.9 Know about Infinite loop and steps to avoid it
Decision making, Looping statements and Pre-Processor directives 3-2

3.1 Discuss decision making in programming


 The statements placed inside a program are executed in the order in which they are
placed; this type of execution is called sequential execution. But in most of the
programs, it is necessary to:
o Select a set of statements from several alternatives.
o Skip certain statements depending on some conditions in the program and
continue the execution from some other point.
o Repeat a set of statements for a known number of times or until a specified
condition is fulfilled.
 Under such situations, we make use of conditional statements.
 Conditional statements are also known as control statements or control structures.
 The conditional statements are essential:
o To alter the flow of a program
o Test the logical conditions
o Control the flow of execution as per the selection

3.2 Explain decision making statements- if , if-else,


nested if, else-if ladder - with syntax and programs
 The conditional statements are popularly known as decision-making statements.
Since these statements control the flow of execution, they are also known as control
statements.
 C language supports the following decision-making statements as listed below:
o Simple if statement
o The if...else statements
o Nested of if...else statements
o The else if ladder
o The switch statement
o The go to statement.
Statement Description
if statement The if statement is called a single selection structure because it
selects or ignores a single action.
if….else The if-else statement is called a double selection structure
statement because it selects between two different actions.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-3

nested if The nested if statement is a multiple branching statement. In


statement which n conditions are checked. It is useful when a series of
decisions are involved.

switch The switch statement is called a multiple selection structure


statement because it selects among many different actions.

3.2.1. if statement

Fig. Simple if Statement


 Simple if statement is used to execute or skip one statement or group of statements
based on a particular condition.
 The general form of if statement is,

 When if statement is executed, the computer first evaluates the value of the test
condition.
 If the value is true, statement block and next statement are executed sequentially.
 If the value is false, statement block is skipped and execution starts from next
statement.
 The fig. was the operation of if statement using flowchart.
*Note: The „statement-block‟ may be a single statement or a group of statements.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-4
Program 1 : C program to demonstrate simple if statement
#include<stdio.h>
#include<conio.h>
main( )
{
int mark;
printf(“\n enter the mark”);
scanf(“%d”, &mark);
if(mark>=90)
{
printf(“\n Excellent”);
}
getch( );
}
Explanation:
 This program tests the mark of the student. If the mark is greater than or equal to 90
then the message “Excellent” will be displayed.
3.2.2. if-else Statement
 if-else statement is used to execute a group of statements if the test condition is
true or the other group of statements are executed if the test condition is false.
 The general form of if-else statement is,

 When this statement is executed, the computer evaluates the value of the test
condition.
 If the value is true, statement block1 is executed and the control is transferred
to next statement.
 If the value is false, statement block2 is executed and the control is transferred
to next statement.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-5
 The fig. shows the operation of if-else statement using flowchart.

Fig. if-else Statement


Program 2 : C program to demonstrate if-else statement
#include<stdio.h>
main( )
{
int mark;
printf(“\n enter the mark”);
scanf(“%d”, &mark);
if(mark>=40)
printf(“\n Pass”);
else
printf(“\n Fail”);
getch( );
}

Explanation:
 This program tests the mark of the student. If it is greater than or equal to 40 it
prints pass. If it is less than 40 it prints fail.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-6

3.2.3. if-else-if Statement (Nested if…..else statement)


 When a series of if…else statements are occurred in a program, we can write an
entire if…else statement in another if….else statement called nesting, and the
statement is called nested if.
 If either the if-block or else-block or both contains another if statement or
if…else statement, then the construct is known as nested conditional statement or
simply nesting of if statements.
 nested if statements are used when a series of decisions are involved.

Fig. nested if statement


 The general form of if-else-if statement is,
 If the condition-1 is false, the statement block-3 will be executed; otherwise
it continues to perform the second test.
 If the condition-2 is true, the statementblock-1 will be evaluated; otherwise
the statement block-2 will be evaluated and then the control is transferred to
the next statement.
 The fig. shows the operation of nested if statement using flowchart.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-7

Program 3 : C program to demonstrate nested if statement


#include<stdio.h>
void main( )
{
int n1, n2;
printf(“Enter two numbers: \n”);
scanf(“%d %d”, &n1, &n2);
if(n1>=n2)
if(n1>n2)
printf(“%d is greater than %d”, n1, n2);
else
printf(“%d is equal to %d”, n1, n2);
else
printf(“%d is less than %d”, n1, n2);
}
Output (Run 1):
Enter two numbers: 11 12
11 is less than 12
Output (Run 2):
Enter two numbers: 45 40
45 is greater than 40
Output (Run 3):
Enter two numbers: 15 15
15 is equal to 15
Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-8

3.2.4. The else if ladder

 When we take multipath decisions at that moment we use the else if ladder
statement.
 It is like a chain of if statements, in which the statement associated with each else is
known as a if.
 Syntax:
if (condition-l)
statement-l;
else if (condition-2)
statement-2;
else if (condition-31
statement-3;
else if (condition-n)
statement-n;
else
default statement;
Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-9
 Working Process
o In the else.. if ladder the conditions are evaluated from top to downwards.
o When the controller of the program found a true condition, the statement
associated with the condition will be executed and the controller skips other
conditions and transfer to the statement-x.
o When all conditions becomes false at that moment the final else (i.e., default
else) statement will be executed i.e., default statement.
o The working process of else.. .if ladder is represented on the Fig. shown above

3.3 Discuss break and continue statements.


3.3.1. Break Statement
 The break statement is used to terminate the loop
 When the break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the
loop.
 Syntax: break;
 Break statement can be used in while, do…while, for loop or in switch statement.
 The use of break statement in terminating loop with break statement is shown in
fig.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-10

3.3.2. Continue Statement

 When the statement continues is encountered inside any „C‟ loop control
automatically passes to the beginning of the loop.
 The continue statement tells the compiler. “SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”. The format of
the continue statement is simply Continue;
 The continue statement can be used in for, while, do ..while loops. It cannot be used
in switch statement
 The use of the continue statement in loops is illustrated in fig.
 In while and do loops, continue causes the control to go directly to the test-
condition and then to continue the iteration process. In the case of for loop, the
increment section of the loop is executed before the test-condition is evaluated.
3.3.3. Differentiate break and continue statements
S. No Break Continue
1. Control exit from the loop Control will be within the loop only.
2. Can be used in while, do-while, for Used in for, while, do-while
and switch statement
3. Use of break statement causes to Use of continue statement is to skip
escape from a loop, or skip the the execution of some statements in
remainder of switch statement the loop, and performs next iteration
of the loop
Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-11

4. Syntax: break; Syntax: continue;


5. More useful than continue Less useful than break statement.
statement.

3.4 Explain decision making statement- switch


statement - with syntax and programs
 The switch statement is used to pickup or executes a particular group of statements
from several available group of statements. It allows us to make a decision from the
number of choices.
 It is a multi way decision statement, it tests the value of given variable or
expression against a list of case values and when a match is found, a block of
statements associated with that case is executed.
 The general form of the switch statement is,

 The below fig. in next page shows the operation of switch statement using
flowchart.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-12

Fig. Switch statement


Program 4 : C program to demonstrate switch statement
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf(“Enter a Number:”);
scanf(“%d”, &n);
switch(i%2)
{
case 0:
Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-13
printf(“The number %d is even \n”, i);
break;
case 1:
printf(“The number %d is even \n”, i);
break;
} /*Switch case*/
getch();
} /*main*/
Output:
Enter a number: 7
The number 7 is odd
Explanation:
 This program is used to find out whether the given number is even or odd and it
checks for the n number.
 If the number is divided by 2 then it is even if the number is not divided by 2 then it
is odd number.
Program 5: C program to check whether input alphabet is a vowel or not
using switch
#include <stdio.h>

int main()
{
char ch;

printf("Input a character : ");


scanf("%c", &ch);

switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-14
case 'O':
case 'u':
case 'U':
printf("%c is a vowel.\n", ch);
break;
default:
printf("%c is not a vowel.\n", ch);
}

return 0;
}
Output 1:
Input a character: A
A is a vowel.
Output 2:
Input a character: x
x is not a vowel.
Program 6: C program to perform arithmetic operations using switch
statement
Option Operation
1 Addition
2 Subtraction
3 Multiplication
4 Division
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b ,c, option;
clrscr( );
printf(“\n Enter the values of a and b:”);
scanf(“%d %d”, &a, &b);
printf(“\n Enter your option:”);
scanf(“%d”, &option);

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-15
switch(option)
{
case 1:
c=a+b;
break;
case 2:
c=a-b;
break;
case 3:
c=a*b;
break;
case 4:
c=a/b;
break;
}
printf(“\n The resultant value is %d”, c);
getch( );
}
Output:
Enter the value of a and b: 10 5
Enter your option: 1
The resultant value is 15
Explanation:
 In the program switch statement consists of four options. The options is entered
according to user‟s choice.
 The four options are addition, subtraction, multiplication and division. Each option
contains several operation.
 Thus statements is executed according to selected choice.
 In the program the character variable op reads the character entered by the user‟s.
According to the entered character the switch statement is executed and prints the
output.
Program 7: C program which accepts student percentage of marks and
displays the appropriate grade.
#include<stdio.h>
#include<conio.h>
main( )

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-16
{
int percent, i;
clrscr( );
printf(“Enter Percentage of Marks : “);
scanf(“%d”, &percent);
i=percent/10;
switch(i)
{
case 10:case 9:case 8:
printf(“Grade is Excellent”);
break;
case 7:
printf(“Grade is Distinction”);
break;
case 6:
printf(“Grade is First Class”);
break;
case 5:
printf(“Grade is Second Class”);
break;
case 4:
printf(“Grade is Pass”);
break;
default:
printf(“Grade is Fail”);
}
}
Output:
Enter Percentage of Marks: 85
Grade is Excellent

3.5 Define looping and list loop statements


 A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
 In C language there are three types of loop control statements. They are:
o The while loop
o The do-while loop
o The for loop
 These are also called as repetitive or iterative control statements.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-17

3.6 Explain the loop statements – while, do- while, for


statement- with syntax and programs
3.6.1. While Loop
 The simplest of all the looping structures in C is the while statement.
 It is used to execute a set of statement repeatedly as long as the specified condition
is true.
 The syntax of while loop is,

Where,
while  is a keyword
test condition  logical expression that results in either true or false
body of the loop  may be a simple or compound statement
 The while loop is an entry controlled loop statement, means the condition is
evaluated first and it is true, then the body of the loop is executed.
 After executing the body of the loop, the condition is once again evaluated and if it
is true, the body is executed once again, the process of repeated execution of the
body of the loop until the condition finally becomes false and the control is
transferred out of the loop.
 The fig. shows the operation of while loop using flowchart.

Fig. while loop


Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-18
*Note: The while loop is a pre-test loop.
Program 8: C program to demonstrate do while loop
#include<stdio.h>
#include<conio.h>
main( )
{
int i;
clrscr( );
i 1;
while(i<5)
{
printf(“\n Welcome to MGB Publications”);
i++;
}
getch( );
}
Explanation:
 These program statements are used to display the message Welcome to MGB
Publications. Initially the condition i  5 is tested. If it is false the program ends
without executing the body of the loop. If it is true the body of the loop will be
executed repeatedly (four times).
3.6.2. do-while Loop
 The do…while loop is a post-test loop,
 Because, the test for repeating is made at the end of each loop.
 The syntax of do-while is,

 When this statement is executed the body of the loop is executed first.
 Then the test condition is evaluated.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-19
 If the value is false, the control is transferred to the next statement. If the value is
true the body of the loop is executed repeatedly until the test condition becomes
false.
 When the test condition becomes false the control is transferred to the next
statement.
 The fig. shows the operation of do while loop using flowchart.

Fig.
Program 9: C Program for addition of numbers using do…..while loop
#include<stdio.h>
main()
{
int i=1, sum=0;
do
{
sum = sum + i;
i++;
}
while(i<=10);
printf(“Sum of the numbers upto 10 is…%d”, sum);
}

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-20
Output:
Sum of the numbers upto 10 is …55
Explanation:
 In above program the value of i is initialized as 1 and value of sum si initialized as
0. In this program the do…while loop is executed the body and calculated the sum
value and increment the i and by 1 until the condition satisfies i<=10. Then points
sum value as output.
3.6.3. for Loop
 The for loop is another entry-controlled loop that provides a more concise loop
control structure.
 The general form of the for loop is,

 for loop has three parts


1. Initialize counter is used to initialize counter variable.
2. Test condition is used to test the condition.
3. Increment/decrement counter is used to increment or decrement counter
variable.
 The fig. shows the operation of for loop using flowchart.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-21
Program 10: C Program for addition of numbers using for loop
#include<stdio.h>
main()
{
int i, sum=0;
for(i=1; i<=10; i++)
{
sum = sum + i;
}
printf(“The addition of numbers upto 10 is %d”, sum);
}
Output:
The addition of numbers upto 10 is 55
Explanation:
 In the program the variables i and sum are declared as a integer type variable.
 The body of the for loop is executed at 10 times, each time the sum is calculated as
sum = sum + i. Finally the prints the value of sum as output.
3.6.4. Differences between while-loop, do-while and for-loops.
S. No while do-while for
1 Condition is tested at Condition is tested at the Conditional expression is
the beginning of the end of the loop tested at the beginning
loop
2 Minimum iterations is 0 Minimum iterations is 1 Minimum iterations is 0
3 Control variable will be Control variable will be Can initialized and
initialized outside the initialized outside the altered within the loop
loop loop
4 Not so flexible when Not so flexible when Very flexible structure
compared with for loop compared with for loop

3.7 Define nesting of loops and implement it


 Like if statement for loop also nested.
 The loop within loop is called nested loop.
 In nested for loops one or more for statements are included in the body of the
loop.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-22
 The syntax of nested for statement is,

 Here are two for statements. The first one is called the outer loop and the second
as the inner loop.
Program 11: C Program to demonstrate nesting of for loops
#include<stdio.h>
main()
{
int i, j;
for(i=1; i<=3; i++)
{
printf(“\n”);
for(j=1; j<=3; j++)
printf(“%d\t”, j);
}
}
Output:
1 2 3
1 2 3
1 2 3
Explanation:
 Here for each value of „i' the inner loop is executed completely, with in the inner
loop „j‟ taking from 1 to 3.
 The inner loop terminates when the value of „j‟ is greater than 3. Where „\n‟ causes
the control to the next line for each entry of the „i' loop and prints the output.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-23
* SIMPLE PROGRAMS BASED ON NESTED LOOPS *
Program 12: C program to print the figure using nested for loop.
*
**
***
****
*****
#include<stdio.h>
#include<conio.h>
void main( )
{
int i, j;
clrscr( );
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
{
printf(“* ”);
}
printf(“\n”);
}
getch( );
}
Explanation:
 In the above program the first for loop is used for rows and the second for loop is
used for column.
 The first printf statement within the inner for loop is used for print the “*”. The
second printf statement within the outer for loop is used for creates separate lines
(new line).
Program 13: C program to print the figure using nested for loop.
1
12
123
1234
12345

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-24
#include<stdio.h>
#include<conio.h>
void main( )
{
int i, j;
clrscr( );
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
{
printf(“%d ”, j);
}
printf(“\n”);
}
getch( );
}
Explanation:
 In the above program the two for loops are used for displaying as per the format
shown in the output. Variable i and j are used according to the requirement.
 On the time of execution the inner loop the value of „j‟ is printed and gives the
above figure.
 The second printf statement within the outer for loop is used for creates separate
lines (new line).
Program 14: C program to print the figure using nested for loop.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
#include<stdio.h>
#include<conio.h>
void main( )
{
int i, j, p=1;
clrscr( );
for(i=1; i<=5; i++)
Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-25
{
for(j=1; j<=i; j++)
{
printf(“%d ”, p++);
}
printf(“\n”);
}
getch( );
}
Explanation:
 Here in the above example the execution process is same as the previous one but
only difference is the value of p is printed in the inner loop and simultaneously
incremented by one.
Program 15: C program to print the figure using nested for loop.
*
***
*****
*******
*********
#include<stdio.h>
#include<conio.h>
void main( )
{
int i, j, c, p=1;
clrscr( );
for(i=1; i<=5; i++)
{
for(j=1; j<=5; j++)
printf(“ “);
for(c=1; c<=i; c++)
printf(“*”);
for(c=c-2; c>=1; c++)
printf(“*”);
printf(“\n”);
} getch( );
}
Maanya’s M.G.B Publications Programming in C
Decision making, Looping statements and Pre-Processor directives 3-26

3.8 Compare different loop statements


S. no while do-while for

1 Condition is tested at Condition is tested at the Conditional expression is


the beginning of the end of the loop tested at the beginning
loop

2 Minimum iterations is Minimum iterations is 1 Minimum iterations is 0


0

3 Control variable will Control variable will be Can initialized and


be initialized outside initialized outside the altered within the loop
the loop loop

4 Not so flexible when Not so flexible when Very flexible structure


compared with for compared with for loop
loop

3.9 Know about Infinite loop and steps to avoid it


 Looping is a powerful programming technique through which a group of
statements are executed repeatedly, until certain specified condition is satisfied.
 Looping is also called a repetitive or an iterative control mechanism.
 A loop in a program essentially consists of two parts, one is called the body of the
loop and the other is known as the control statement.
 The control statement performs a logical test whose result is either a true or false.
 If the result of this logical test is true, then the statements contained in the body of
the loop are executed. Otherwise, the loop is terminated.
 The control statement can be placed either before or after the body of the loop.
 If the control statement is placed before the body of the loop, it is called the entry-
controlled loop.
 If the control statement is written after the body of the loop, it is called the exit
controlled loop.
 C supports both types of loop statements.

Maanya’s M.G.B Publications Programming in C


Decision making, Looping statements and Pre-Processor directives 3-27
 There must be a proper logical test condition in the control statement, so that the
statements are executed repeatedly and the loop terminates gracefully.
 If the logical test condition is carelessly designed, then there may be a possibility of
formation of an infinite loop which keeps executing the statements over and over
again.
 Therefore, for an efficient-looping mechanism, the following steps are included.
1. Initialization: To set the initial values for the loop counter. The loop counter may
be an increment counter or a decrement counter.
2. Decision: An appropriate test condition to determine whether the loop be
executed or not.
3. Updation: Incrementing or decrementing the counter value.

Maanya’s M.G.B Publications Programming in C


4
ArrAys And strings

OBJECTIVES
 4.1 Define Array. Describe declaration and initialization of One
Dimensional Array with syntax and program
 4.2 Explain about ‘accessing array out of bounds’ problem
 4.3 Explain reading elements of an array, accessing the elements and
display them with program
 4.4 Explain sorting elements in an array in ascending order
 4.5 Explain finding the average of elements in an array and finding the
largest element in an array
 4.6 Explain declaration and initialization of two Dimensional Arrays
 4.7 Illustrate the concept of two dimensional arrays with sample
programs on matrix addition, subtraction, matrix multiplication and
transpose of a matrix
 4.8 Define String and know about declaration and initialization of a String
variable.
 4.9 Know about reading & writing of strings with programs
 4.10 Explain about various String handling functions with sample
programs.
Arrays and Strings 4-2

4.0. Introduction
 So far, you have seen different types of variables which hold only one value.
 There are many applications which require to process a group of data items that are
of same type such as int, float, char or double.
 For example, we can define an array of a list of marks obtained in an examination
by a group of students.
 In such a situation, it is necessary to have a unique variable which holds a group of
elements.
 Such a construct of programming language which stores and organises a set of data
items is called a data structure.
 There are different types of data structure such as array, stack, queue, linked lists,
structures, tree and file etc.
 In this chapter the data structure array is discussed with the following objective.
1. Definition
2. Classification of arrays
3. Declaration of an array
4. One-dimensional array
5. Two-dimensional array

4.1 Define Array. Describe declaration and initialization


of One Dimensional Array with syntax and program
4.1.1. Define Array
 An array can be defined as an ordered list of homogeneous data elements.
 These elements may be of type int, float, char or double.
 All these elements are stored in consecutive memory locations (on RAM).
 An array is described by a single name or an identifier.
 And each individual data item in the array is referenced by a subscript (or index)
enclosed in a pair of square brackets.
 This subscript indicates the position of an individual data item in an array.
 And, the subscript must be an unsigned positive integer.
 Because of these subscripts, sometimes an array is called as a subscripted variable.
 For example, in an array named even, the individual data items are as shown
below.

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-3

Where,
1, 2, 3, 4 and 5 are subscripts
even [1] :  indicates the first element in an array even.
even [2] :  indicates the second element in an array.
even [3] :  indicates the third element in an array.
even [4] :  indicates the fourth element in an array.
even [5] :  indicates the fifth element in an array.
In general, even [i] indicates the i th element of an even array.
4.1.2. Classification of Arrays
 Generally, arrays are classified into one-dimensional array and multi-dimensional
arrays.
 Further, the multi-dimensional arrays are classified into two-dimensional, three-
dimensional and so on n-dimensional arrays.
 The dimensionality is determined by the number of subscripts in an array.
 If there is one subscript, then it is called one-dimensional.
 If there are two subscripts then it is two dimensional and so on.
4.1.3. Declaration of One dimensional arrays
 Arrays must be declared before it is used like other variables.
 The general form is,

Where
data_type  int, float, char etc
drray_name valid C variable name
size  number of contiguous location in the memory to be
reserved
 Fig. shows three different array declarations: one for integers, one for floating-point
numbers and one for characters.

fig.(a) Integer array

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-4

fig . (b) Float array

fig .(c) Character array


4.1.4. One dimensional Array initialisation
 After an array is declared, its elements must be initialized. Otherwise, they will
contain “garbage”.
 The array can be initialized in the following two ways:
1. At compile time (static initialization)
2. At run time (dynamic initialization)
1. Compile time initialization
 We can assign initial values to the array just like assign values to variables when
they are declared.
 The general form is,

Where
data type type of data found in the array such as int, float, char etc
array-name valid C variable name
size number of contiguous locations in the memory to be
reserved
list of values initial values to be given to the array. This should be
separated by commas.
 Example 1: int age[3]={10, 20, 30}:
 This declares age as an integer array having three locations and assign initial
values as given below.
age[0] age[1] age[2]
10 20 30

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-5
 Example 2: int age[5]={10, 20, 30}:
 If the size of the array is greater than the number of values in the list, then the
unused locations are filled with zeros given below.
age[0] age[1] age[2] age[3] age[4]
10 20 30 0 0
*Note: The size may be omitted. In such cases the compiler allocates enough space for
all initialised elements.
 Example 3:float average[ ]={78, 89, 90, 56,45, 58}:
 This declares average as a real and the size of the array is automatically allocated
by counting the number of values. Here computer counts the value as six and
assigns the size as 6.
 Example 4:char a[10] = “mgbmaanya”;
 This declares name as a character array having characters and assign initial values
as

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
m g b m a a n y a \0

 Even though the character string has 9 characters, we have defined the array with
10 elements. This is to store \0 (null character) as the string terminator.
2. Run Time Initialization:
 An array can be explicitly initiated at run time. This approach is usually applied for
initializing large arrays.
 Example 5: while{i<=10}
{
if{i<5}
sum[i]=0;
else
sum[i]=sum[i]+i;
}
Explanation:
 The while loop checks the condition i<=10.
 If condition is true then if statement checks condition i<5, if condition is true
then sum[i] the assigned to zero else sum[i] assigned as sum[i]+i.

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-6
Program 1: C program to illustrate the initialization of five integers to the
corresponding elements of a one dimensional array
#include<stdio.h>
#include<conio.h>
void main()
{
int marks[5]={35,62,89,48,94};
int i;
printf("Elements of array are\n");
for(i=0;i<5;i++)
printf("marks[%d]=%d\n",i,marks[i]);
getch();
}
Output:
RUN 1:
Elements of array are
marks [0]=35
marks [1]=62
marks [2]=89
marks [3]=48
marks [4]=94

4.2 Explain about ‘accessing array out of bounds’


problem
 Some of the rules that govern the subscripts are given below.
o Each subscript must be a positive integer constant, or an expression.
o Subscript of subscript is not allowed.
o C does not perform bounds checking.
o Therefore, the maximum subscript appearing in a program for a subscripted
variable should not exceed the declared one.
o In C, the subscript value ranges from 0 to one less than the maximum size.
o If the size of an array is 10. Then, the first subscript is 0, the second' subscript
is1, and so on.
o The last subscript is 9.
o In general, the i th element has subscript (i - 1).

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-7
o For example, consider an array list having 5 elements. Then, the subscripts that
denote the position of an individual item is as shown below.

4.3 Explain reading elements of an array, accessing the


elements and display them with program
 For example, if we want to represent a set of five numbers, say (19, 10, 8, 17, 9), by
an array variable mark then we may declare the variable mark as follows:
int mark[5];
 ‘mark’ is the name of the array with 5 subscripts of integer data types and the
computer reserves five storage locations as shown below.

 The values to the array elements can be assigned as follows:

 This would cause the array value to store the values as shown below.

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-8

 In the above example we will be accessing array like this


mark[2] = Second Element of Array=8
mark[4] = Fourth Element of Array=9
Programs Using Arrays
Program 2: C program to find Largest Element in Array
#include<stdio.h>
int main()
{
int a[30], i, num, largest;
printf("\nEnter no of elements :");
scanf("%d", &num);
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
largest = a[0];
for (i = 0; i < num; i++)
{
if (a[i] > largest)
{
largest = a[i];
}
}
printf("\nLargest Element : %d", largest);
return (0);
}
Output:
Enter no of elements: 5
11 55 33 77 22
Largest Element: 77
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-9
Program 3: Find Smallest Element in Array in C Programming
#include<stdio.h>
int main()
{
int a[30], i, num, smallest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//consider first element as smallest
smallest = a[0];
for (i = 0; i < num; i++)
{
if (a[i] < smallest)
{
smallest = a[i];
}
}
// print out the Result
printf("\nSmallest Element : %d", smallest);
return (0);
}
Output:
Enter no of elements: 5
11 44 22 55 99
Smallest Element: 11
Program 4: C Program to Display First N terms of Fibonacci series using
array
#include<stdio.h>
int main()
{
int i, limit; // Array declaration.
printf("Enter the count of number in series:-");
scanf("%d", &limit);
int fib[limit]; fib[0] = 0; // as series starts from 0.

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-10
fib[1] = 1;
for(i=2; i<=limit; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(i=0; i<=limit; i++)
{
printf("\t %d", fib[i]);
}
return 0;
}
Output:
For limit = 6, 0 1 1 2 3 5
*Note:
 The Fibonacci sequence is a series where the next term is the sum of pervious two
terms. The first two terms of the Fibonacci sequence is 0 followed by 1.
 The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21.
Program 5: Reverse array by swapping (without using additional memory)
#include <stdio.h>
int main()
{
int array[100], n, c, t, end;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
end = n - 1;

for (c = 0; c < n; c++)


{
scanf("%d", &array[c]);
}
for (c = 0; c < n/2; c++)
{
t = array[c];
array[c] = array[end];
array[end] = t;
end--;
}
printf("Reversed array is:\n");

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-11
for (c = 0; c < n; c++) {
printf("%d\n", array[c]);
}
return 0;
}
Output:
Enter the number of elements in array
5
Enter the array elements
4
8
45
4568
1231
Reverse array is
1231
4568
45
8
4
*Note:
For example if a is an array of integer with three elements such that
a0  1
a1  2
a2  3
Then on reversing the array will be
a 0  3
a 1  2
a 0  1
Program 6: C program to sort the array in an ascending order
#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-12
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\n", number[i]);
}
Output:
Enter the value of N
6
Enter the numbers
3
78
90
456
780
200
The number arranged in ascending order are given b
3
78
90
200
456
780
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-13

4.4 Explain sorting elements in an array in ascending


order
Program 7: C program to sort the array in an ascending order
#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
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\n", number[i]);
}
Output:
Enter the value of N
6
Enter the numbers
3
78

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-14
90
456
780
200
The number arranged in ascending order are given b
3
78
90
200
456
780

4.5 Explain finding the average of elements in an array


and finding the largest element in an array
Program 8: C program to find average of Elements in Array
#include<stdio.h>
main()
{
int i,j,sum=0,num;
float avg;
printf("Enter number\n");
scanf("%d",&num);
int array[num];
printf("Enter %d numbers\n",num);
for(i=0;i<num;i++)
{
scanf("%d",&array[i]);
sum+=array[i];
}
avg=(float)sum/num;
printf("Average of %d numbers is %f\n",num,avg);
}
Output:
Enter number
5
Enter 5 numbers

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-15
89
90
98
99
97
Average of 5 numbers is 94.599998
Program 9: C program to find Largest Element in Array
#include<stdio.h>
int main()
{
int a[30], i, num, largest;
printf("\nEnter no of elements :");
scanf("%d", &num);
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
largest = a[0];
for (i = 0; i < num; i++)
{
if (a[i] > largest)
{
largest = a[i];
}
}
printf("\nLargest Element : %d", largest);
return (0);
}
Output:
Enter no of elements: 5
11 55 33 77 22
Largest Element: 77

4.6 Explain declaration and initialization of two


Dimensional Arrays
4.6.1. Declaration of Two dimensional arrays
 Like one dimensional arrays two dimensional arrays must be declared before it is
used like other variables. The general form is

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-16
Where
data type  int, float, char etc
array-name valid C variable name
row size  maximum number of rows in the table
column sizemaximum number of columns in the table

 Example: int mark[11][6];


 This declares mark as a two dimensional integer array having 11 rows and 6
columns. The following table shows the structure of the memory.
 The first subscript or index denotes the row number and the second denotes the
column number mark[0][0] .......mark[10][6] are called address of locations.
4.6.2. Two dimensional array initialization
 Like one dimensional array, the two-dimensional array can be initialized in two
ways i.e., static initialization (compile time initialization) and dynamic initialization
(run time initialization).
 In the static initialization the 2-D array may be initialized by following their
declaration with a list of initial values enclosed in braces. For example,
int a[2][3] = 1, 1, 1, 2, 2, 2;
 The above statement initializes the every element of the first row to 1s and of the
second row to 2s. The initialization can be done row by row. The above example
can be written as follows.
int a[2][3] = {{1, 1, 1},{ 2, 2, 2}};
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-17
 Also we can initialize the 2-D array in the form of matrix as follows
int a[2][3] = {
1, 1, 1},
{ 2, 2, 2}
};
 In the above example the comma is most needed after each brace that close of a
row, except in the case of last row. So in the above statement we can notice a
comma is placed after {1, 1, 1}.
Program 10: C program to illustrate the initialization of elements of a two
dimensional array
#include<stdio.h>
#include<conio.h>
void main()
{
int marks[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int i,j;
printf("Elements of array are\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf("marks[%d][%d]=%d\n",i,j,marks[i][j]);
getch();
}
Output:
RUN 1:
Elements of array are
marks [0] [0] =1
marks [0] [1] =2
marks [0] [2] =3
marks [1] [0] =4
marks [1] [1] =5
marks [1] [2] =6
marks [2] [0] =7
marks [2] [1] =8
marks [2] [2] =9

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-18

4.7 Illustrate the concept of two dimensional arrays with


sample programs on matrix addition, subtraction, matrix
multiplication and transpose of a matrix
Program 11: C Program to find the Sum of two matrices.
#include<stdio.h>
void main()
{
int a[2][2], b[2][2], c[2][2], i, j;
printf(“Enter the value of First 2 x 2 matrix: ”);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &a[i][j]);
}
printf(“Enter the value of second 2 x 2 matrix: ”);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &b[i][j]);
}
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &b[i][j]);
}
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &b[i][j]);
}
}

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-19
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
c[i][j]=a[i][j]*b[i][j];
printf(“Sum of Two matrix:%d\n”, c[i][j]);
}
}
getch();
}
}
}
}

Output:
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
1 2
3 4
Enter the elements of second matrix
5 6
2 1
Sum of entered matrices:-
6 8
5 5
Program 12: C Program to multiply two matrices.
#include<stdio.h>
#include<conio.h>
void main()
{
int mat1[3][3], mat2[3][3], mat3[3][3], sum=0, i, j, k;
printf("Enter first matrix element (3*3) : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-20
{
scanf("%d",&mat1[i][j]);
}
}
printf("Enter second matrix element {3*3} : ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d",&mat2[i][j]);
}
}
printf("Multiplying two matrices...\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
sum=0;
for(k=0; k<3; k++)
{
sum = sum + mat1[i][k] * mat2[k][j];
}
mat3[i][j] = sum;
}
}
printf("\nMultiplication of two Matrices : \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%d ", mat3[i][j]);
}
printf("\n");
}
getch();
}

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-21
Output:
Enter first matrix element (3*3):1
2
3
1
2
3
1
2
3
Enter second matrix element (3*3):1
2
3
1
2
3
1
2
3
Multiplying two matrices…..
Multiplication of two matrices:
6 12 18
6 12 18
6 12 18
*Note: How to multiply 2 matrices?
1 2 
 2 4   1 2   1  1  2  2  1  4  5
   2 4
3 5  

1 2 
2 4  1 2  1 2  2  4  2  8  10
   2 4
3 5   

1 2 
2 4  1 2  2  1  4  2  2  8  10
   2 4
3 5   

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-22
1 2 5 6 7 
A    B   
3 4  0 9 10 
Multiplication of two matrixes:
 1* 5  2 * 8 1* 6  2 * 9 1* 7  2 *10 
A * B   
 3 * 5  4 * 8 3 * 6  4 * 9 3 * 7  4 *10 
 21 24 27 
A * B   
 47 54 61 
Program 13: C program to display the transpose of given 3 X 3 matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],i,j;
printf("\nEnter the elements of matrix:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nThe Transpose of matrix is:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=a[j][i];
printf("\t%d\t",b[i][j]);
}
printf("\n");
}
getch();
}

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-23
Output:
Enter the elements of matrix:
1 2 3 4 5 6 7 8 9
The Transpose of matrix is:
1 4 7
2 5 8
3 6 9
*Note: This C Program finds the transpose of a given matrix. The transpose of a given
matrix is formed by interchanging the rows and columns of a matrix.

For example if a matrix is


1 2
3 4
5 6
Then transpose of above matrix will be
1 3 5
2 4 6
When we transpose a matrix then the order of matrix changes, but for a square matrix
order remains same.

4.8 Define String and know about declaration and


initialization of a String variable.
4.8.1. String Definition
 A String is a one-dimensional array of character. For example, "Computer", is a
string of 8 character. This is stored in the RAM as shown.

 Where, ch  is an array of characters.

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-24

 The very first character occupies 0 th subscript, second character, the 1tst subscript
and so on the last character the ( n  1)th subscript; in an n-character array.

 However an n-character array contains(n + 1) array elements.


 Because, each one-dimensional character array (string) ends with a null
character(\0).
 C provides string handling functions which are defined in the header file
<string . h>.
 Operations on the individual characters of a string or a group of strings can be
performed.
 Comparing, copying, concatenating etc. are some of the operations that can be
carried out on strings.

4.8.2. Declaration and initializing string variables


 Like a numeric array, character arrays must be declared before they appear in a
program.
 There is no change in the syntax except change in the date type (char), and
initialization to each element of a character array is made by assigning character
constants (a character enclosed within a single quotes) rather than a number placed
within a pair of curly brackets.
For example,
char name[l0] = {'S', 'u', 'm', 'a', '\0'};
Here, name is the string of 10 characters and initialized its first four elements
respectively by S,u, m, a; and the fifth element is assigned a null character with
which the string ends.
 Consider another example, where characters are not initialized individually.
chardays[10] = {"Monday"};
 Here, each character of string Monday is stored in an individual element of an array
days, but it automatically adds null character to the end of the string.
 A string or a group of strings can be written to the monitor using the following
output functions.
1. printf() with the %s format specification.
2. putchar() function
3. puts() function

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-25

4.9 Know about reading & writing of strings with


programs
 A string can be read in or written out using the input/output statements.
a) Reading Strings
 The following input functions can be used to read a string.
scanf() with the %s format specification.
gets() function
getchar() function
b) Writing Strings
 A string or a group of strings can be written to the monitor using the following
output functions.
Printf() with %S as format specification
puts() function
putchar()function
c) Unformatted input statements
 These statements are primarily concerned with reading the character type data
from the keyboard.
 The getchar( ) and gets( ) functions are used for this purpose. Since, they are
included in the stdio.h (header file), the C program that uses these functions
should exclusively have the following preprocessor statement.
#include<stdio.h>
1) getchar() Functions
 This function reads a single character from the standard input device. There is no
parameter within the parentheses. Its syntax is as follows.

Where,
ch_var is a character type variable to which an accepted character is assigned.
 Example:
main()
{
char 1etter;
letter = gethcer();
:
}

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-26
2) gets()_ Function
 This function reads in everything you enter from the keyboard until the ENTER key
or RETURN is pressed.
 Here, everything means a string which is a sequence of all printable ASCII
characters.
 The RETURN key that was pressed at last would not be stored in the character
string.
 It overcomes the limitation of the scanf() statement with %S option. The syntax
of gets() is

 Where, string is a sequence of characters and is of type char.


 Example:
main()
{
char name [ 25 ];
printf ("enter you name\n");
gets(name);
:
}
d) Unformatted output statements
 These statements are mainly concerned with displaying or printing the character
type data on the monitor.
 The putchar() and puts() functions are used for this purpose.
 The #inc1ude<stdio. h> statement is required if these are used in the C
program.
1) Putchar() – Function
 This function prints a single character on the screen. The character to be displayed
is of type char. It syntax is as follows:

 Where, ch-var  character variable which is enclosed within the parentheses.


 Example
main()
{
char ch;
putchar(ch);
}
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-27
 The following program illustrates both reading and printing of a single character.
include<stdio.h>
main()
{
char letter;
letter=getchar();
putchar(letter);
}
2) Puts () Functions
 This function prints a string of characters on the screen.
 The newline character that signalled the end of string will not be displayed.
 The syntax of puts() is as follows.

 Where,
string  a sequence of characters.
 Example
#include<stdio.h>
Main()
{
char messg[20];
puts(messg);
}

 The following program illustrates both reading and printing of a string.


#include<stdio.h>
Main()
{
char message[20];
printf("Enter the message to motivate students\n");
gets(message);
puts(message);
}

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-28
Program 14: C program to accept a character from the user using the
getchar() and print it back on the screen using printf()
#include<stdio.h>
#include<conio.h>
void main()
{
char x;
printf(“\n Enter a character:”);
x=getchar();
printf(“\n The character you entered is %c”, x);
}
Output:
Enter a character: M
The character you entered is: M
Program 15: C Program to demonstrate the usage of putchar() function
#include <stdio.h>
int main ()
{
char ch;
for(ch = 'A' ; ch <= 'Z' ; ch++)
{
putchar(ch);
}
return(0);
}
Let us compile and run the above program that will produce the following result:
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ

4.10 Explain about various String handling functions


with sample programs.
 The C library supports a large number of string handling functions that can be used
to carry out many of the string manipulations.
 The following are most commonly used string-handling functions.
strcat() Used to combine two stirngs.
strchr() Determines first occurrence of a given character in a string.
strncmp() Used to compare first ‘n’ character of two strings.
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-29
strcpy() Used to copy one string to another.
strlen() Used to find length of the string.
 These functions are defined in the header file string.h.
 Therefore, whenever you use the string handing functions in your C program, the
preprocessor statement # include < string. h > should be included in the
program.
1. strcat() function
Purpose This function is used for joining two strings.
Note: In other words this function is used to concatenate two strings. That is,
it appends one string at the end of the specified string.
Syntax

Example

strcat(“PROGRAM”,“MING”);
It will append string “MING” to the end of the string “PROGRAM”. The
resultant string is “PROGRAMMING”.
Program char st1[30]=” C programming”;
char st2[20]=”tutorial”;
char *st3;
st3=strcat(st1, st2);
printf(“%s\n”, st3);
Output: C programming tutorial

2. strchr() function
Purpose This function searches for a specified character in a given string. It returns
NULL if the desired character is not found in the string.

Syntax

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-30

Example strchr(“MGB”,’G ’);


Since G is present in MGB. The search for the character G is successful.
3. strcmp() function
Purpose This is a function which compares two string to find out whether they are
same or different. The two strings are compared until the end of the string is
reached. If the two strings are identical strcmp() returns a value zero. If
they are not equal, it returns the numeric difference between the first non-
matching characters.
Syntax

string1 and string2 may be string variables or string constants.


Example The function returns a value zero if the two strings are the same, a negative
value if string1 is less than string2 and a positive value if the string1 is
greater than string2.
strcmp(“be”, “betech” );will return the value of-15 which is the
numeric difference between ASCII “e” and ASCII “t”.

4. strncmp() function
Purpose This compares the first n characters of two input strings.
Syntax

Example strncmp(“devi”,”dev”,3);
This compares the first 3 characters in strings “devi” and “dev” respectively.
It returns one of the 3 values {-1, 0, 1} .
5. strcpy() functions
Purpose This function is used to copy the contents of one string to another and it
almost works like string assignment operator
Syntax

string1 = destination string


string2 = source string
Example char str1[10]={“PADMA”};
char str2[10]={“SRI”};
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-31
strcpy(str1,str2);
printf(“%s\n”,str2);
Output: SRI
This copies the string “SRI” to the “PADMA”. Here the current content of
“PADMA” is lost.
*Note: If you want to copy only part of the string2 to the string1 you need to use the
strncpy(char *string1, char *string2, int num_chars).
6. strlen( ) function
Purpose This returns the number of character in the string (i.e. string length).
Here, the string length does not include the ‘\0’ (NULL) character.
Syntax

Where,
string = One – dimensional array of characters.
Example 1: strlen(“programming”);
The length of the string programming is 11 as there are 11 characters in
it.
2: strlen(“India is great”);
Here, the string length is 14. It includes two white spaces apart from all
other alphabets.
Program 16: C program to copy the content of one string to another by
using strcpy()
#include<stdio.h>
#include<string.h>
void main()
{
char ori[20], dup[20];
printf(“Enter Your Name:”);
gets(ori);
strcpy(dup.ori);
printf(“Original String: %s”, ori);
printf(“\n Duplicate String: %s”, dup);
}

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-32
Output:
Enter Your Name: SACHIN
Original String: SACHIN
Duplicate String: SACHIN
Explanation:
 In the above example, we have declared two arrays namely ori[20] and dup[20].
The function strcpy( ) copies characters of ori[ ] to dup[ ]. The characters are
copied one by one from source string (ori [20]) to destinating string (dup
[20]).
Program 17: C program to count the number of characters in a given
string
#include<stdio.h>
#include<string.h>
void main()
{
char text[20];
int len;
printf(“Type Text Below.\n”);
gets(text);
len=strlen(text);
printf(“Length of String=%d”, len);
}
Output:
Type Text Below
Hello
Length of string = 5
Explanation:
In the above program, strlen() function is called. Through the text array base address
will be sent and this function returns the length of the string. It counts the string length
without the NULL character.
Program 18: C program to read and write line of text using gets() and
puts()
#include <stdio.h>
int main()
{
char name[30];
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-33
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Your Name is: ");
puts(name); //Function to display string.
return 0;
}
Output:
Enter name: Maanyas MGB Publications
Your Name is: Maanyas MGB Publications
Program 19: C Program to find the length of string without using a library
function
#include<stdio.h>
int main()
{
char str[100];
int length;
printf("\nEnter the String : ");
gets(str);
length = 0; // Initial Length
while (str[length] != '\0')
length++;
printf("\nLength of the String is : %d", length);
return(0);
}
Output:
Enter the String : MGB
Length of the String is : 3
Explanation:
Consider input string – “mumbai”
While loop iteration Length Str[length]
Before While Loop 0 m
After iteration 1 1 u
After iteration 2 2 m
After iteration 3 3 b
Maanya’s M.G.B Publications Programming in C
Arrays and Strings 4-34

After iteration 4 4 a
After iteration 5 5 i
After iteration 7 6 Loop Terminated
Program 20: C program to compare two strings using strcmp()
#include<stdio.h>
#include<string.h>
int main()
{
char a[100], b[100];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
if{ strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}
Output:
Enter first string: MGB Maanya.com
Enter second string: MGB Maanya.com
Both strings are equal
Program 21: C program is used to copy the string by using the library
function strcpy()
#include<stdio.h>
#include<string.h>
int main()
{
char str1[100];
char str2[100];
printf("\nEnter the String 1 : ");
gets(str1);
strcpy(str2, str1);
printf("\nCopied String : %s", str2);
return (0);
}

Maanya’s M.G.B Publications Programming in C


Arrays and Strings 4-35
Output:
Enter the String 1 : c4learn
Copied String : c4learn
Program 22: C program for palindrome
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf("Enter the string to check if it is a palindrome\n");
gets(a);
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("Entered string is a palindrome.\n");
else
printf("Entered string is not a palindrome.\n");
return 0;
}
Output:
Enter the string to check if it is a palindrome
wow
Entered string is a palindrome
Explanation:
1. A word, phrase, or sequence that reads the same backwards as forwards
2. Some palindrome strings examples are "dad", "radar", "madam" etc.
3. To check if a string is a palindrome or not, a string needs to be compared with the
reverse of itself.
4. Consider a palindrome string: radar,

5. To compare it with the reverse of itself, the following logic is used:


0th character in the char array, string1 is same as 4th character in the same string.
o 1st character is same as 3rd character.
o 2nd character is same as 2nd character.
Maanya’s M.G.B Publications Programming in C
5
User defined fUnctions

OBJECTIVES
 5.1 Define function, state the need for user defined functions, advantages
of functions
 5.2 Know the elements of function and return values.
 5.3 Define and discuss function prototype, function call, and function
definition with syntax and program.
 5.4 Discuss the scope, visibility and lifetime of variables in functions
 5.5 Differentiate Local and Global variables
 5.6 Illustrate functions with no arguments and no return values with
programs
 5.7 Illustrate functions with no arguments and with return values with
programs
 5.8 Illustrate functions with arguments and with no return values with
programs
 5.9 Illustrate functions with arguments and with return values with
programs
 5.10 Illustrate passing arrays to functions with programs
 5.11 Define recursion and Illustrate recursion with programs
User defined funtions 5-2

5.1. Define function, state the need for user defined


functions, advantages of functions
 A function is a set of instructions to carry out a particular task.
 The programs written in C language are highly dependent on functions. The C
program is nothing but a combination of one or more functions. Every C program
starts with user defined function main ().
 Generally, the function is classified into standard functions and user-defined
functions. The standard functions are also called library functions or built-in
functions.

 Main is an example of user-defined function. Printf and scanf belong to the


category of library functions.
 The main distinction between these two categories is that library functions are not
required to be written by user where as a user-defined function has to be developed
by the user at the time of writing a program.

5.1.1. Advantages of user-defined functions


 The length of the source program can be reduced by dividing it into the smaller
functions.
 By using functions it is very easy to locate and debug an error.
 The user-defined functions can be used in many other source programs whenever
necessary.
 Functions avoid coding of repeated programming of the similar instructions.
 Functions enable a programmer to build a customized library of repeatedly used
routines.

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-3

5.2 Know the elements of function and return values.


 Any C program contains at least one function that is main() function.
 If a problem can be divided into small modules, then each module can be
represented as a function.
 A function is a group of statements in a program that performs a specific task when
called. (or)
 A function is a self contained block of code or instructions that performs a specific
task.
5.2.1. Elements of function
 A function definition, also known as function implementation shall include the
following elements:
1. Function name
2. Function type (data-type of function)
3. List of parameters/ arguments
4. Local variable declarations
5. Function statements
6. A return statement
 The six elements is grouped into parts such as function header and function body.
 The function header contains the first 3 elements and body contains the last 3
elements.
 The general form of a function definition can be as follows:

Example:
int sum (int a, int b, int c)
{
printf(“sum = %d” , a+b+c);
return ;
}
Maanya’s M.G.B Publications Programming in C
User defined funtions 5-4
5.2.2. Use of return statement
 A function may or may not send back any value to the calling function. If it does, it
is done through the return statement.
 The return statement serves the following two purposes:
1. Transferring control from the function back to the calling program.
2. It returns the values to the calling function.
 The return statement can take one of the following forms.

or

 The first form of return statement does not returns any value to the calling
function.
 The second form of return with an expression returns the value of the expression.
 Example 1:
mul(x,y)
int x,y;
{
int p;
= x*y;
return(p);
}
Returns the value of p which is the product of the values of x and y. The last two
statements can be combined into one statement as follows:
return (x*y);
 Example 2:
float add(float x, float y)
{
return(x+y);
}
Returns the value of the addition of x and y.

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-5

5.3 Define and discuss function prototype, function call,


and function definition with syntax and program.
5.3.1. Function call technique
 A function can be called by simply using the function name followed by a list of
actual parameters (or arguments), enclosed in parentheses.
 Example:
main ( )
{
int P ;
p = mul(10,5) ; /*function call*/
printf(“%d\n”,p);
}

int mul(int x, int y)


{
int p;
/*local variables*/
p = x*y;
/*x=0, y=5*/
return(p);
}
 When the compiler encounters a function call, the control is transferred to the
function mul(x,y).
 This function is then executed line by line as described and a value is returned
when a return statement is encountered. This value is assigned to p.
*Note: A function that does not return any value may not be used in expressions; but
can be called to perform certain tasks specified in the function.
5.3.2. Function Prototype
 All function in C program, must be declared, before they are invoked. A function
declaration (also known as function proto type) consists of four parts.
o Function type (return type)
o Function name
o Parameter list
o Terminating semicolon
 It is same as function header and the only difference is the function is ended with a
semicolon.

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-6
 Syntax:

 Example:
int sum(int a, int b); // prototype
 The prototype indicates the name of the function, what type of the value returned
the function and what the parameter lists are.
 When we place the declaration above all the function(in the global declaration
section),the prototype is referred to as a global prototype. Such declarations are
available for all the functions in the program.
 When we place it in a function definition (in the local declaration section), the
prototype is called a local prototype. Such declarations are primarily used by the
functions containing them.
Program 1: C function that performs the sum of two predefined numbers.
#include<stdio.h>
float total()
{
float x,y;
x=20.0;
y=10.0;
return(x+y);
}
void main()
{
float sum;
float total();
sum=total();
printf(“sum=%f\n”,sum);
}
Output:
sum = 30.000000
Program 2: C program to find the product of two numbers.
#include<stdio.h>
int product(int a,int b)
{
int res;
res=a*b;

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-7
return res;
}
void main()
{
int a,b;
printf (“Enter two numbers to find its product:”);
scanf(“%d %d”,&a,&b);
printf(“The product is %d:”,product(a,b));
}
Output:
Enter two numbers to find its Product: 9 10
The Product is: 90
Program 3: C program to find the maximum number of a given three
numbers.
#include<stdio.h>
int maximum(int , int, int);
void main()
{
int a,b,c;
printf(“Enter three Numbers :\n”);
printf(“%d %d %d”,&a,&b,&c);
printf(“Maximum is %d \n”,maximum(a , b, c));
}
int maximum ( int x, int y, int z)
{
int max=x;
if(y>max)
max=y;
if(z>max)
max=z;
return (max);
}
Output:
Enter three Numbers:
25 68 41
Maximum is 68
Maanya’s M.G.B Publications Programming in C
User defined funtions 5-8

Additional information
 Variables in C differ in behavior from other languages.
 To fully define a variable, one needs to mention not only its ‘type’ but also its
storage class.
 A variable’s storage class tells us:
1. Where the variable would be stored.
2. What the initial value of the variable will be.
3. What the scope of the variable is.
4. What life of the variable is i.e. how long would the variable exist.
 Basically the area or block of the C program from where the variable can be
accessed is known as the scope of the variable.

5.4 Discuss the scope, visibility and lifetime of variables


in functions
 Variables in C differ in behavior from other languages.
 To fully define a variable, one needs to mention not only its ‘type’ but also its
storage class.
 A variable’s storage class tells us:
1. Where the variable would be stored.
2. What the initial value of the variable will be.
3. What the scope of the variable is.
4. What life of the variable is i.e. how long would the variable exist.
 Basically the area or block of the C program from where the variable can be
accessed is known as the scope of the variable
5.4.1. Storage classes supported by C
 There are four storage classes of C:
1. Automatic storage class (automatic variables)
2. Register storage class (register variables)
3. Static storage class (static variables)
4. External storage class (external variable)
 The following table illustrates the different features of storage classes.
Feature Static Auto Extern Register

Storage Memory Memory Memory CPU register

Default Zero Garbage Value Zero Garbage Value


value

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-9

Scope Local Local Global Local

Life Value of the Till control As long as Till the control


variables persist remains within execution does remains within
between different the block in not end the block in
function which variable is which variable is
Call defined defined

5.5 Differentiate Local and Global variables


S .No. Local Variables External Variables

1. These are also known as automatic These are also known as Global
variables. variables.

2. Scope is within the function which Scope is entire program.


defined it.

3. Defined within the function. Defined outside the main function.

4. Same variables can be used in different External Variable has constant value
functions. The values differ from throughout the program.
function to function.

5. Local variables exist while the block of An external variable exists as long as
code in which they are declared is program is executing.
executing. That is a Local variable is
created upon entry into its block and
destroyed upon exit.

 The variables in general may be classified as


o Local and
o Global variables.
 Variables whose existence is known only to the main program or functions or
within a block are called local variables or automatic variables.
 Local variables are declared within the main program or a function.
 The, variables whose existence is known to both the main() function as well as
other functions are called global variables or external variables.
 The global variables are declared outside the main() and the other functions.

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-10

Additional information

* ARRAYS TO FUNCTIONS *
 To process array in a large program, we have to be able to pass them to functions.
We can do this in two ways: Pass individual elements or pass the entire array.
 In some situations we may want to pass individual elements of the array, and in
other situations we may want to pass the entire array to a function.

*DIFFERENTIATE CALL BY VALUE AND CALL BY REFERENCE


MECHANISMS OF PARAMETER PASSING TECHNIQUES *
 Function can be called by using parameters. Parameters can generally passed to a
function in the following two ways. They are
1. Call by value
2. Call by reference
1) Call by value
 According to the mechanism the value of each of the actual arguments are copied
into the corresponding formal arguments.
 Any changes done to the formal parameters have no effect on the actual
parameters, because the actual parameters and formal parameters have separate
memory locations.
2) Call by reference
 According to this mechanism the address of the actual parameters are passed while
calling a function.
 The formal parameters are Pointer variables and they point to the same memory
locations of the corresponding actual parameters.
 Hence any changes that are done to the formal parameters effect the values of the
actual parameters.

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-11

3) Call by value vs Call by reference


S.No Call by value Call by reference
1. This is the usual method to call a In this method , the adress of the variable
function in which only the value of is passed as an argument.
the variable is passed as an
argument
2. Any change in the value of the Any change in the value of the argument
argument passed is local to the passed is accepted in the calling
function and is not accepted in the program.
calling program.
3. Memory location is occupied by Memory location is occupied by formal
formal and actual parameters are and actual parameters are same and
different. there is a saving of memory location
4 Since a new location is created, this Since the existing memory location is
method is slow used through its adress, this method is
fast
5 There is no possibility of wrong data There is a possibility of wrong data
manipulation since the arguments manipulation since the addresses are
are directly used in an expression used in an expression and the
programming is bit diffirent.
Program 4: C program swap two number using call by value concept.
#include<stdio.h>
void swap(int, int);
void main( )
{
int a, b ;
prinrtf (“enter value for variable ‘a’ and ‘b’ \n”);
scanf(“%d%d”, &a,&b);
printf(“before swapping the value of a = %d and b = %d\n”,
a,b);
swap(a,b) ;
}
void swap (int x, int y)
{
x=x*y;
y=x/y;
Maanya’s M.G.B Publications Programming in C
User defined funtions 5-12
x=x/y;
printf (“After swapping the value of a =%d and b =%d”, x,y
);
}
Output:
Enter value for variable ‘a’ and ‘b’
10
20
Before swapping the value of a =10 and b=20
After swapping the value of a =20 and b = 10.
Explanation: In the above program we are passing the values of actual arguments
‘a’ and ‘b’ to the function swap( ). The formal argument ‘x’ and ‘y’ receives these values
and interchange occurs.
Program 5: C program to illustrate the call-by –reference method to
interchange two integer variables
#include<stdio.h>
int inter_change(int *n1,int *n2);
/*function prototyping */
void main()
{
int num1,num2;
printf(“Enter Two Numbers\n”);
scanf(“%d %d”, &num1 , &num2);
printf (“num1=%d and num2=%d (before function call)\n”, num1
, num2);
inter_change (&num1 , &num2);
printf(“num1=%d and num2=%d (after Function is called) \n”,
num1, num2);
}
/* function to interchange the value of two variables using pointers*/
int inter_change (int *n1, int *n2)
{
int temp;
temp= *n1;
*n1 = *n2;
*n2 = temp;
}
Maanya’s M.G.B Publications Programming in C
User defined funtions 5-13
Output:
Enter Two Numbers
14
23
Num1=14 and num=23 (Before Function call)
Num1=23 and num2=14 (After Function call)
*Note:
Rules to be followed to invoke the functions:
1. The number of actual parameters in the function call must be equal to the number
of formal parameters in the function header.
2. Each actual argument must be of the same data type as its corresponding formal
argument.

Additional information
 It is a variable that communicate between calling function to called function. There
are two types:
1. Actual argument
2. Formal argument
 Actual argument: The arguments which are defined in calling function are known
as actual argument.
 Formal argument: The arguments which are defined in called function are known
as formal argument.
 The actual and formal argument should match in number, type, and order.
 The values of actual arguments are assigned to the formal arguments on a one to
one basis, starting with the first argument as shown in fig .

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-14

Types of User Defined Functions:


1. Function with no argument, no return value.
2. Function with no argument with return value.
3. Function with argument no return value.
4. Function with argument with return value.

5.6 Illustrate functions with no arguments and no return


values with programs
 In this type of function the calling function does not passed the arguments when it
calls the called function, also the called function does not sent back value to the
calling function.
 In other words we can say that neither the arguments are passed through the
calling function nor the data is sent back from the called function.
 There is no data transfer between calling and called function.
 Here each function is independent. They read data values and calculate the result
and display it in the same block.
 The working principle of this type of function is given below:
Calling Function Operational Analysis Called Function
main()  No arguments are passed to the calling sum()
{ function. {
…………………  No output or data’s are sent back from the …………………
sum(); called function. …………………
………………… …………………
} }
Program 6: Write a program to illustrate the concept, no argument, no
return value.
#include<stdio.h>
void call_fun(); //function prototype
void main ( )
{
call_fun(); //calling function
printf(“\n Now I am in main”);
}
void call_fun( ) //called function
{
printf(“\n Now I am in called function “);
}
Maanya’s M.G.B Publications Programming in C
User defined funtions 5-15
Output:
Now I am in called function
Now I am in main
Explanation:
 We know every C program starts execution from main function. When the compiler
encounter the calling function call_fun() at that moment the controller of the
program directly jump to the called function i.e., is written in outside of the main
function.
 The body of the called executed and gives the output, "Now I am in caned function"
after printing this message the controller of the program came back to the calling
function (no value is returned by the called function) and the next line of the calling
function executed and gives the message "Now I am in main".
Program 7: C program illustrates the function with no arguments and no
return value.
#include<stdio.h>
Void main( )
{
read_value();
}
read_value( )/*no return value*/
{
char name[10];
printf("Enter your name:\n");
scanf("%s", name);
printf("Your name is %s", name);
}
Output:
Enter your name : Maanya
Your name is Maanya

5.7 Illustrate functions with no arguments and with


return values with programs
 In this type of function the no arguments are passed through the calling function to
the called function but the called function returns value.
 The variables required for the called function that are declared and initialized at the
same called function module.

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-16
 The called function is independent.
 Here both called and calling function are partially communicated with each other.
 The analysis picture of this function is given below:
Calling Function Operational Analysis Called Function
void main()  No arguments are passed by the calling sum()
{ function. {
int x;  But values are sent back from called int p=4, q=7, s=p + q
x = sum(); function to the calling function. return(s);
…………. }
}
 Here the output always printed at the calling function side.
 The return statement is required for returning value from called side to calling side.
 The data-type of the returning value and the function return type must be same.
Program 8: C program illustrates the function with no arguments and
with return value.
#include<stdio.h>
float total();
main( )
{
float sum;
float total( );
sum = total ( );
printf("Sum = %f\n", sum);
}
float total( )
{
float x, y;
x = 20.0;
y = 10.0;
float z = x+y;
return z
}
Output:
Sum = 30.000000

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-17

5.8 Illustrate functions with arguments and with no


return values with programs
 In this type of function the arguments are passed through calling function to the
called function. But the called function does not return value.
 Such types of functions are partly dependent on the calling function.
 The pictorial analysis is given below:
Calling Function Operational Analysis Called Function
void main()  Arguments are passed through the void sum(int x, int y)
{ calling function to the called function. {
int a, b;  No values are sent back from the called int add;
sum (a, b); function. add = x + y;
} printf (“%d” add);
}
 In the above analysis by the calling function sum 0; the actual argument 'a' and 'b'
are passed to the called function.
 In the called function side 'x' and 'y' are the formal argument (the actual argument
and the formal argument data type must be same but the name may be same or
may not be).
 The called function receives the values and operated them and the output is printed
in the same module. So before of the header of the called function void is written.
Program 9: C program illustrates the function with arguments and with
no return values with programs
#include<stdio.h>
void Maximum(int,int);
void main( )
{
int x, y;
printf(" Enter the value of x and y\n");
scanf("%d %d", &x, &y);
Maximum(x, y);
}
/* function to compute the maximum*/
void Maximum(int x, int y)
int p, q;

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-18
{
if(p > q)
printf("Maximum is p ");
else
printf("Maximum is q ");
}
Output:
Enter the values of x and y
14
10
Maximum is p

5.9 Illustrate functions with arguments and with return


values with programs
 In this type of function the calling function passed the arguments to the called
function and called function sent back value to the calling function.
 Both two functions are dependent with each other.
 The pictorial analysis is given below:
Calling Function Operational Analysis Called Function
void main()  Arguments are passed through the calling Sum(int a, int b)
{ function to the called function. {
int a=5, b=6, y;  Values are sent back int add;
y=sum (a, b); add = a+b;
printf(“%d”, y); return(add);
} }
Program 10: Write a program to input a 3 digit number and reverse it
using function.
#include<stdio.h>
int reverse(int) ; //prototype
void main()
{
int x, numl,y;
printf("Enter the value for x:");
scanf (" %d" ,&x) ;
y=reverse(x); //calling function
Maanya’s M.G.B Publications Programming in C
User defined funtions 5-19
printf ("Reverse number=%d", y);
}
int reverse(int num) //called function
{
int rem, rev=0;
while (num>0)
{
rem= num %10 ;
rev= rev*10 +rem;
num=num/10 ;
}
return rev;
}
Output:
Enter the value for x: 452
Reverse number = 254.

5.10 Illustrate passing arrays to functions with


programs
5.10.1. Passing the entire array
 The array name refers to the first byte of the array in memory.
 The address of rest of the elements in the array can be calculated using the array
name and the index value of the element.
 Therefore, when we need to pass an entire array to a function, we can simply pass
the name of the array.
 Here, array name itself appears without brackets or subscripts as an actual
argument in the function call.
 This passes the address of the array to the function and it is assigned to the
corresponding formal argument when the function is called.
 Example : Find the average of elements in the array.

Program 11: The C program demonstrates passing of entire array using


passing by reference
#include<stdio.h>
double average(int[]); /*function declaration*/
void main()

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-20
{
double av;
int arr[5]={3,6, 24, 18, 53};
av=average(arr);
printf(“The average is %2.2f”, av);
}
double average(int x[])
{
int i, sum=0;
for(i=0; i<5; i++)
{
sum=sum+x[i];
}
return(sum/5.0);
}

Output:
The average is 20.80
Comment:
 The address of array, arr is passed as an actual parameter. The function accesses the
same array with different name x.

5.11 Define recursion and Illustrate recursion with


programs
 Recursive functions are special functions which calls itself repeatedly until some
specified condition has been satisfied.
 These functions are used for repetitive computations in which each action is stated
in terms of a previous result. Many iterative problems can be written in this form.
 In order to solve a problem recursively, two conditions must be satisfied.
 First, the problem must be written in a recursive form and second, the problem
statement must include a stopping condition.

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-21
 Suppose, for example, we wish to calculate the factorial of a positive integer
quantity. We would normally express this problem as n!= 1  2  3  ......  n , where n is
the specified positive integer.
 However, we can also express this problem in another way, by writing
n! n  (n  1)!.
 This is a recursive statement of the problem, in which the desired action is
expressed in terms of a previous result.
 Also, we know that 1!=1 by definition. This last expression provides a stopping
condition for the recursion.
 Example:

5!=(5)(4!)
But 4! Is equal to 4(3!), so 5! Is equal to
(5)(4)(3!)
But 3! Is equal to 3(2!), so
5!=(5)(4)(3)(2!)
But 2!= 2(1!)=(2)(1), so
5!=(5)(4)(3)(2)(1)=120
 The above entire process to evaluate 5! Is shown in fig. .
 Figure shows how the succession of recursive calls proceeds until 1! Is evaluated to
be 1, which terminates the recursion.
 Figure shows the values returned from each recursive call to its caller until the final
value is calculated and returned.

Maanya’s M.G.B Publications Programming in C


User defined funtions 5-22
Program 13: The C program will find out the factorial of a given positive
number.

#include <stdio.h>
long int fact(int n);
void main( )
{ int n;
printf(“\nEnter n value:”);
scanf(“%d”,&n);
printf(“\n%d Factorial=%1d”,n,fact(n));
}
long int fact(int n)
{ if (n==1)
return 1;
else
return (n*fact(n-1));
}
Input-Output:
Enter N value:5
Factorial=120
For better visualization of recursion in this example:
Fact(5)
 5  fact(4)
 5  4  fact(3)
 5  4  3  fact(2)
 5  4  3  2  fact(1)
 5  4  3  2 1
 5  4  3  2`
 5  24
 120

Maanya’s M.G.B Publications Programming in C


6 StructureS, unionS and File
ManageMent

OBJECTIVES
Structures and Unions
 6.1 Define structure
 6.2 Illustrate creating a structure tag and declaring structure variables,
 6.3 Explain accessing structure members and structure assignment
 6.4 Know size of a structure.
 6.5 Discuss nested structure concept.
 6.6 Illustrate array of structures, structures containing arrays, arrays of
structures containing arrays.
 6.7 Illustrate structure as function arguments and returning of structure
variables as function values.
 6.8 Define Union and illustrate usage of a union.
 6.9 Know the differences between Structure and Union
Files management
 6.10 Define file
 6.11 Know how to declare file pointer to a file
 6.12 Illustrate the concept of file opening in various modes
 6.13 Illustrate the concept of closing of a file
 6.14 Illustrate the concept of Input / Output operations on a file
 6.15 Illustrate the concept of random access to files
Structures, unions and file management 6-2

6.0. Introduction
 We known a variable can stores a single value of a data type. Array can store more
than one value of same type.
 But our objective is to store more than one value to a variable of different type. So,
C provides a special feature to handle this things i.e., structure.
 An array is employed to store and process a group of homogeneous elements. For
example, marks of students, names of employees, etc. but, most of the real-world
applications need a group of heterogeneous elements.
 For example, in processing student information, it is necessary to process the
information like his roll number., name, branch and percentage is of type float. In
processing such information, the knowledge of the structure is required.
 Structure is a collection of one or more variables of different data types, grouped
together a single name. In other words we can say structure is a heterogeneous data
type.

6.1 Define structure


 ‘C’ provides a constructed data type known as structure which packs the data items
of different types.
 Definition: A structure is a collection of logically related variables of different data
types under a single name.
 Structure is a user defined derived data type.
 A structure contains one or more data items of different data type in which the
individual elements can differ in type. A simple structure may contain the integer
elements, float elements and character elements etc. the individual structure
elements are called members.
 In C, all the data items can be grouped together in one structure using the keyword
“struct”.
 Examples of structures are:
o Customer : name, city, phone
o Book : author, title, price, year
o Date : day, month, year
o Time : seconds, minutes, hours
o Address : house-number, street, city
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-3

6.2 Illustrate creating a structure tag and declaring


structure variables,
6.2.1. Creating structure
 A structure definition creates a format that may be used to declare structure
variables.
 The general format of a structure definition is as follows:

 Let us use an example to illustrate the process of structure definition and the
creation of structure variables. Consider a book database consisting of book name,
author, number of pages, and price. We can define a structure to hold this
information as follows:
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
 The keyword struct declares a structure to hold the details of four fields, namely
title, author, pages, and price. These fields are called structure elements
or members. Each member may belong to a different type of data, book_bank is
the name of the structure and is called the structure tag. The tag name may be used
subsequently to declare variables that have the tag’s structure.
 *Note: The structure is musty ended with a semicolon (;).
6.2.3. Declaration of structure variables
After declaration of the structure format, we can declare variable of the type. The
structure variable may be defined in the following ways.
a) In the structure Declaration
 The structure variables can be specified after the closing brace and before
semicolon.
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-4
struct book_bank
{
char title[20];
char author[15];
int pages ;
float prices;
}b1;
 Here, in the above example ‘b1’ is the variable of structure book_bank. We can
also declare more than one variable, list of variable names separated by commas.
 Example:
struct book_bank
{
char title[20];
char author[15];
int pages;
float prices;
}b1, b2, b3;
 Here b1, b2 and b3 are three variable of structure book_bank.
b) Using the structure Tag
 The variable of a structure may also be declared separately by using the structure
Tag.
Example:
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank b1,b2,b3;
 Here b1, b2 and b3 are three structure variables declared by the help of structure
tag i.e., struct book_bank.
*Note: Remember that the members of a structure themselves are not variables, They
do not occupy any memory until they are associated with the structure variables.

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-5

6.3 Explain accessing structure members and structure


assignment
6.3.1. Accessing structure members
 For accessing any member of the structure, we use dot (.) operator.
 Which is also known as member operator or period operator?
 To access a particular member, the dot operator must be placed between the name
of the structure variable and the name of the structure member.
 The syntax of accessing structure member is,

Where,
Structurevariable : Name of the structure variable
member : Name of a member within the structure
 The student’s roll_no of the structure “student” can be accessed by writing,
std1.roll.
 Similarly the student’s name of the structure “student” can be accessed by
writing, std1.name.
6.2.2. Structure Assignment
 The one structure information can be assigned to another structure of the same type
using single assignment statement. We do not require to assign the value of each
member separatly.
 The syntax for structure assignment is,

where, var1 and var2 are the the structure variables of same structure.
 The concept of structure assignment is clearly illustrated in the fig.

Fig.
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-6
 Example: Consider the following statement.
library book1, book2;
book1=book2;
 Here, the value contained in book2 will be assigned in book1.
 Internal assignments related to the above statement will be performed accordingly.
The following program initializes the variable book1 with some values. This
variable is also assigned to another variable book2.
Program 2: C program to demonstrate initialization and assignment
of a structure.
#include<stdio.h>
#include<conio.h>
main()
{
struct library
{
char name[30];
int price;
int pages;
};
struct library book1={“Harrypotter”, 560, 1015};
struct library book2;
book2=book1;
printf(“\n Name”, book2.name);
printf(“\n Price”, book2. price);
printf(“\n Pages”, book2.pages);
getch();
}
Output:
Name: Harrypotter
Price: 200
Pages: 1015

6.4 Know size of a structure.


 We normally use structures, and arrays to create variables of large sizes. The actual
size of these variables in terms of bytes may change from machine to machine.
 The total number of bytes that a structure will occupy in the memory is called its
size. The size of a structure (or any variable) can be calculated using ‘sizeof’
operator.

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-7
 It is a unary operator.
 Size of a structure can be determined using any one of the following two
expressions.

(or)

 The ‘sizeof’ operator returns the size in bytes of its operand or structure
variable. Its returned value is determined at compile time.
 The usage of ‘sizeof’ operator on structures is illustrated in the program-2.
Program 1: Write a C program to find the memory occupied by the
structure variable.
#include<stdio.h>
#include<conio.h>
void main()
{
struct mphone
{
char name[15];
char model[10];
float price;
}p;
printf(“\nThe size of structure variable is %d”,sizeof(p));
getch();
}
Output:
The size of structure variable is 29

6.5 Discuss nested structure concept.


6.5.1. Concept
 A structure within another structure is called a nested structure.
 Definition : when a structure is placed within another structure, as its member, then
the resultant structure is called nested structure.
 This means one structure is defined within another structure.

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-8
 For example, we can have a structure called ‘reminder’ that stores that date
and time. The date is in turn a structure that stores the month, day and year. The
time is also a structure that stores the hour, minute and second. This structure
design is shown in the fig.

Fig.
6.3.2. Declaring Nested structures
The declaration of nested structures may take one of the two forms mentioned
below.
Method 1:
 In this method, a structure may completely be defined within the other structure.
 We show the declaration of the structure ‘REMINDER’ and a variable that uses in
the following example.
struct REMINDER
{
struct DATE
{
int month;
int day;
int year;
}date;

struct TIME
{
int hour;
int min;
int sec;
}time;
}reminder;
 This method of declaring nested structures is not recommended because it is very
difficult to follow the structure if large number of sub-structures are involved.
 This shortcoming of this method can be overcome in the next method.
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-9
Method 2:
 In this method, all the sub-structures are declared separately and then grouped
together in the high-level structure.
 The ‘REMINDER’ structure declared in this method is shown in the following C
code snippet.
//structure decalrations
struct DATE
{
int month;
int day;
int year;
}
struct TIME
{
int hour;
int min;
int sec;
}
struct REMINDER
{
struct DATE date;
struct TIME time;
}
//variable declaration
struct REMINDER reminder;

6.6 Illustrate array of structures, structures containing


arrays, arrays of structures containing arrays.
Concept 1:
 Whenever the same structure is to be applied to a group of people, items, etc., in
such situation, an array of structures will be defined. In array of structures each
element is the structure in itself.
 For example, if the final internal assessment is to be made for a class of 30 students,
then the teacher may make use of an array of 30 structures, and each student
structure may be defined as,

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-10
Struct stud_rec
{
int rollno;
char name[30];
int ml;
int m2;
int m3;
float averg;
} stud_rec[30];
 Thus, an array of structures, would be visualized as

Concept 2:
 Array is a collection of similar data types. In the same way we can also define array
of structure. In such type of array every element is of structure type. Array of
structure can be defined as follows:
struct book
{
char name [30];
int page;
float price;
}b[5];
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-11
 In the above example the variable b[5] is an array of five elements. In other words
five variables are created of structure book type. i.e., book[O], book[l], book[2],
book[3], book[4]. Here, each variable has three members i.e., name, page, and price.

6.7 Illustrate structure as function arguments and


returning of structure variables as function values.
Program 1: Write a C program to find the memory occupied by the
structure variable.
#include<stdio.h>
#include <stdio.h>
// creating a student structure template
struct student {
char firstname[64];
char lastname[64];
char id[64];
int score;
};
// function declaration
struct student getDetail(void);
void displayDetail(struct student std);
int main(void) {
// creating a student structure array variable
struct student stdArr[3];
// other variables
int i;
// taking user input
for (i = 0; i < 3; i++) {
printf("Enter detail of student #%d\n", (i+1));
stdArr[i] = getDetail();
}
// output
for (i = 0; i < 3; i++) {
printf("\nStudent #%d Detail:\n", (i+1));
displayDetail(stdArr[i]);
}

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-12
return 0;
}
struct student getDetail(void) {
// temp structure variable
struct student std;

printf("Enter First Name: ");


scanf("%s", std.firstname);

printf("Enter Last Name: ");


scanf("%s", std.lastname);

printf("Enter ID: ");


scanf("%s", std.id);

printf("Enter Score: ");


scanf("%d", &std.score);

return std;
}

void displayDetail(struct student std) {


printf("Firstname: %s\n", std.firstname);
printf("Lastname: %s\n", std.lastname);
printf("ID: %s\n", std.id);
printf("Score: %d\n", std.score);
}
Output:
Enter detail of student #1
Enter First Name: Bruce
Enter Last Name: Wayne
Enter ID: dc-01
Enter Score: 8
Enter detail of student #2
Enter First Name: Peter
Enter Last Name: Parker
Enter ID: mc-01
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-13
Enter Score: 9
Enter detail of student #3
Enter First Name: Tony
Enter Last Name: Stark
Enter ID: mc-02
Enter Score: 7

Student #1 Detail:
Firstname: Bruce
Lastname: Wayne
ID: dc-01
Score: 8

Student #2 Detail:
Firstname: Peter
Lastname: Parker
ID: mc-01
Score: 9

Student #3 Detail:
Firstname: Tony
Lastname: Stark
ID: mc-02
Score: 7

6.8 Define Union and illustrate usage of a union.


 It is a heterogeneous user defined data type. In other words it is an user defined
data type that consists of dissimilar type of data, store in same memory location.
 In C, a union is a single memory location that is shared by two or more variables.
The variables that share the memory may be of different types. However, only one
variable may be in use at any one time.
 Like structures, a union can be declared using the keyword union as follows :
 Syntax:

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-14
 Example 1:
union result
{
int marks ;
float avg ;
char grade ;
};
 In the above example the union contains 3 members, each written a different data
type. However, we can use only one of the item at a time. This is due to the fact that
only one location is allocated for a union variable. Irrespective of its size. This is
represented in the in the fig.

 Example 2:
union item
{
int m;
float x;
char c ;
}code;
declares a variable code of type union item. The union contains three members,
each with a different data type.
 To access a union member, we can use the same syntax that we use for structure
members. That is,
code.m
code.x
code.c
 Are all valid member variables. During accessing, we should make sure that we are
accessing the member whose value is currently stored. For example, the statements
such as
code.m = 379;
code.x = 7859.36;
printf(“%d”,code.m);
would produce erroneous output(which is machine dependent).

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-15

6.9 Know the differences between Structure and Union


S. No Structure Union
A structure is a collection of number of A union is also a collection of
data type may or may not be of the same variables of different data types
type grouped together which may be basic data type or
1.
variable of another union.
2. Every member has its own memory All the members use the same
space. memory space to store the values.

3. Keyword union is used. Keyword union is used.

All members can be accessed at a time. Only one member of a union and
4. thus one data type can be accessed
at any one time.
5. The memory size of the structure The memory size of the union
variable is the sum of the size of its variable is the largest size of its
members. members.
6. Occupies more memory when compare Occupies less memory when
to union. compared with structure.
7. It may be initialized with all its Only its first members may be
members. initialized.
8. Structure definition Union definition
struct stu union stu
{ {
char name [7]; char name [7];
int age; int age;
}x; }x;
9. Storage in case of Structures: Storage in case of Structures:

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-16

Additional information
 The preprocessor can be thought as a smart editor. Like a smart editor, it inserts,
includes, excludes, and replaces text based on commands supplied by the
programmer. These commands are known as Pre-processor Commands or Pre-
processor directives.
 The following points about the preprocessor commands are very important and
must be noted carefully.
o All the pre-processor commands start with a pound sign (#).
o Pre-processor directives are placed in the source program before the main line.
o They do not require a semicolon (;) at the end.
 The preprocessor directives are broadly divided into two categories:
o Unconditional Preprocessor directives
o Conditional Preprocessor directives

6.10 Define file


 In our real life generally involves tremendous amount of data to be read, written
and memorize.
 This is difficult for human being to memorize these things. So, human being needs
some file or note for storing this data.
 Similarly, applications generally involves tremendous amount of data to be read
and written to an auxiliary memory. Hence, save this information in disc C
provides a concept file.
 Definition: A file is a complex data type that is stored externally to the main
memory, usually on disk. In other words we can say, it is a storage area of memory,
where the data are stored in an organized form.
Additional information
* STEPS FOR FILE OPERATION *
 C supports a number of functions that have the ability to perform basic file
operations, which include.
 Naming a file
 Opening a file
 Reading data from file
 Writing data to a file
 Closing a file.
 Mainly we trace about two point's i.e.,
 Opening of file
 Closing file
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-17

6.11 Know how to declare file pointer to a file


6.12 Illustrate the concept of file opening in various
modes
 Opening a file. A file must be opened before I/O operations can be performed.
 Definition: The process of establishing a connection between the program and file
is called opening the file.
 A structure FILE is defined in the header file <stdio.h>.
 File is opened by the function fopen().
 Syntax:
FILE *fp;
fp=fopen("file_name" , mode};
 For example,
FILE *fptr; /* 1*/
fptr=fopen("resu1ts.dat","w") ; /* 2 */
 Line 1 declares the pointer fptr which refers to a structure of type FILE. Line 2
actually opens the file and makes the logical connection between the filenames and
the file pointer.
 The file pointer is used by the program to refer to the file. The name of the file is
used by the operating system.
 Hence, the program name is made by the file open statement.
 To break this connection and put the file away one uses a file close statement.
6.11.1. Modes of Accessing
 There are different modes in which a file can be opened:
a) Text Modes
1. w (write): This mode open a new file for writing. If the file doesn't exists then a
new file is created. If the file is already exists the data will be overwritten
without any conformation.
Syntax:
fp=fopen("p.txt", "w");
Here "p.txt" is the file name and "w" is the mode
2. r (read): This mode reading data from an existing file. If the file is opened
successfully then the file pointer points to the first character of the file.
If the file doesn't exit then the compiler NULL to the file pointer.

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-18
Syntax:
fp= fopen("p.txt" , "r");
Here fp is a file pointer, p.txt is a text file.
3. a(append): This mode opens a preexisting file for adding new data at the end of
the file, if the file opened successfully then the file pointer points to last character
of the file. If the file doesn't exist then a new file is created.
Syntax:
fp=fopen(np.txt", "an);
Here "p.txt" is the file name and "a" is the mode.
4. w+ (write + read): This mode opens a file for both write and read. Writing new
contains, reading them and modify.
Syntax:
fp=fopen(Up.txt", "w+');
Here "p.txt" is the file name and "W +" is the mode
5. r+(read + write): This mode is used for both read and write.
Syntax:
fp=fopen("p.txt", "r+');
Here "p.txt" is the file name and "r+" is the mode
6. a+ (append +read): In this mode file can be read and record can be added at the
end of the file.
Syntax:
fp=fopen("p.txt", "a+");
Here "p.txt" is the file name and "a +" is the mode

b) Binary Modes
1. wb (write) : This mode opens a binary file in write mode.
Syntax:
fp=fopen("p.dat", "wb");
Here p.dat file is opend in binary mode for writing
2. rb (write) : This mode opens a binary file in read mode.
Syntax:
fp=fopen("p.dat","wb");
Here p.dat file is opened in binary mode for reading.

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-19
3. ab (write) : This mode opens a binary file in append mode, data can be added in
the end of the file.
Syntax:
fp=fopen("p.dat","ab");
Here p.dat file is opened in binary mode for appending.
4. w + b (read + write) : This mode creates a new file for read and write mode.
Syntax:
fp=fopen("p.dat","w+b");
Here p.dat file is created for reading and writing in binary mode.
5. r + b (read + write): This mode opens a pre-existing file in read and write mode.
Syntax:
fp=fopen("p.dat","w+b");
Here p.dat file is created for reading and writing in binary mode.
6. a + b (read + write) : This mode opens a file in append mode.
Syntax:
fp=fopen("p.dat","w+b");
Here p.dat file is opened in append mode, data can be added in the end of the
file.

6.13 Illustrate the concept of closing of a file


 Closing a file: The file that is opened by the fopen( ) function should be closed
after the work is over. To close a file use following functions.
o fclose()
o fclose all();
1. fclose()
It is closed a specified file.
Syntax:
fclose (FILE *);
Example
FILE *fp;
fp=fopen("cvrce.txt" , "w");
fclose(fp);
It returns 0 when the file close successfully, if it return EOF then error in file
closing.
2. fclose all();
It close all files that previously opened.
Syntax:
fclose all ( );

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-20

6.14 Illustrate the concept of Input / Output


operations on a file
 There are many functions used for file input and output purpose.
 File I/O function is mainly of five types. These are given below.
1. Character I/O fgetc(), fputc(), fgetc(), getc(), putc()
2. String I/O fgets (), fputs ()
3. Integer I/O getw (), putw ()
4. Formatted I/O fscanf (), fprintf ()
5. Structure read and write fread(), fwrite()

1. Character I/O
 fgetc()
It is used to read a single character from a given file. And increment the file
pointer position.
Syntax:
fgetc (FILE * fp) ;
 getc()
It is used to read a single character from the file.
Syntax:
getc (FILE *fp);
 fputc()
It is used to write a single character in a file at current position and then
increment the file pointer position.
Syntax:
fputc( char c, FILE *fp);
2. String I/O
 fputs()
It is used to write a line of text in a file. It doesn't write null character in a file.
Syntax:
fputs(constant char *str,FILE *fp);
 fgets()
It is used to read character from a file and these characters are stored in the
string [pointed to by str. It read at most n-l and appends '\0' character in replace
or '\n'. It returns NULL when reached in EOF.

Maanya’s M.G.B Publications Programming in C


Structures, unions and file management 6-21

3. Integer I/O
 putw()
It is used to write an integer data in a file.
Syntax:
int putw(int , FILE *fp);
 getw()
It is used to read an integer data from file.
Syntax:
int getw (FILE * fp) ;
4. Formatted I/O
 fprintf()
It is same as printf() but it writes formatted data into the file. In other words we
can say, this function is used for writing characters, strings, integer's floats etc., to
the file. It contains one more parameter that is the file pointer, which points the
opened file.
 fscanf()
This function reads character, strings, integers, float etc., from the file pointed
by file pointer.
5. Structure read and writes
 fwrite()
This function is used for writing a structure variable in a file.
Syntax:
fwtite(const void *ptr , sizeof(data),no-of-data, FILE *fp);
ptr is a pointer which points to the block of memory that contains the
information to be written to the file.
sizeof(data): Denotes the length of each item in bytes.
no-of-data: Denotes the number of items to be written to the file.
*fp: Denotes the file where the data are written.
 fread()
It is used to read an entire block from a given file.
Syntax:
fread(void *ptr, sizeof(data) , no-of-data, FILE *fp);
sizeof(data): Denotes the length of data (byte )in read.
*fp: Denotes the file where the data is read.
Maanya’s M.G.B Publications Programming in C
Structures, unions and file management 6-22

6.15 Illustrate the concept of random access to files


 In such case the data can be accessed and processed randomly.
 To access a particular record random access file takes less time, than sequential file.
 To handle the random access file use the following functions.
1. fseek()
2. ftell()
3. rewind()
 fseek()
It is used to move the file pointer in a particular position.
Syntax:
fseek(FILE *fp , long size, mode};
We can pass three arguments through the function.
1. File pointer
2. Positive long integer number to reposition the file pointer towards the backward
or forward direction.
3. Current position of file pointer (mode) .
Mode
SEEK_SET 0 Beginning of file
SEEK_CUR 1 Current position
SEEK_END 2 End of the file
Example:
fseek(fp,lO , SEEK_SET);
It skipped 10 byte forward from beginning of the file.
fseek(fp,-lO, SEEK_END);
It skipped 10 bytes forward from end of the file.
fseek(fp,5,SEEK-CUR);
It skipped 5 bytes forward from the current position of the file.
 ftell()
It returns the current position of file pointer.
Syntax:
long ftell(FILE *fp);
 rewind()
It is used to move the file pointer position to the beginning of the file.
Syntax:
void rewind(FILE *fp);
It is same as fseek(fp, 0, SEEK_SET).

Maanya’s M.G.B Publications Programming in C


Model Question Papers 0-i

BOARD DIPLOMA MID-SEMESTER - I EXAMINATION


CS - 205
Programming in C
MODEL QUESTION PAPER
TIME: 1 HOUR MAX. MARKS: 20
PART-A
Note: Answer ALL questions. Each answer carries TWO mark 4 x 1= 4M
1. List any two differences between algorithm and flowchart.
2. Define Low level language
3. List various types of constants.
4. Define an expression.
PART – B
Note: Answer any two questions. Each question carries three marks
2x3=6M
5. a) Write any three differences between algorithm and flowchart
(OR)
b) Write any three differences between high level language and low level language
6. a) How to declare variable in C? Give examples.
(OR)
b) Evaluate an expression (2+5)*(10-4)%10.
PART – C
Note: Answer two questions. Each question carries ten marks
2 x 5 = 10 M
7. a) Draw a flowchart to find factorial of given number N.
(OR)
b) Draw a flowchart to find biggest of three numbers.
8. a) Explain different data types in C with examples.
(OR)
b) Explain operators in C with examples.

Maanya's M.G.B Publications Programming in C


0-ii Model Question Papers

BOARD DIPLOMA MID-SEMESTER - I EXAMINATION


CS - 205
Programming in C
MODEL QUESTION PAPER
TIME: 1 HOUR MAX. MARKS: 20
PART-A
Note: Answer ALL questions. Each answer carries TWO mark 4 x 1= 4M
1. Give the syntax of if statement in C.
2. Give the syntax of while statement in C.
3. Define an array.
4. Give the syntax for declaring and initializing of one dimensional array.

PART – B
Note: Answer any two questions. Each question carries three marks
2x3=6M
5. a) Write any three differences between break and continue statements.
(OR)
b) Write any three differences between while and do-while statements.
6. a) Write a C program to find largest number in array.
(OR)
b) Explain any three String handling functions.
PART – C
Note: Answer two questions. Each question carries ten marks
2 x 5 = 10 M
7. a) Explain do-while statement with syntax and sample program
(OR)
b) Explain switch statement with syntax and sample program .
8. a) Write a C program to find the multiplication of two matrices.
(OR)
b) Write a C program to find the addition of two matrices.

Maanya's M.G.B Publications Programming in C


Model Question Papers 0-iii
BOARD DIPLOMA END-SEMESTER EXAMINATION (C – 21)
CS - 205
Programming in C
MODEL QUESTION PAPER
TIME: 2 HOUR MAX. MARKS: 40
PART-A
Instructions: Answer the following questions.
Each question carries ONE mark. 8 x 1= 8M
1. List any two differences between algorithm and flowchart..
2. Give the syntax of if statement in C.
3. List any two advantages of functions.
4. Give the syntax for declaring and initializing of one dimensional array.
5. Define function.
6. Define recursion.
7. What is a structure?
8. What is a file?
PART – B
Instructions: Answer the following questions.
Each question carries THREE marks. 4 x 3 = 12 M
9. a) Write any three differences between algorithm and flowchart.
(OR)
b) Write a C program to find factorial of a number using recursion.
10. a) Write any three differences between break and continue statements.
(OR)
b) Write any three differences between structure and union statements.
11. a) Explain elements of function in C.
(OR)
b) Write any three differences between local variable and global variable
statements.
12. a) Explain various modes to open a file.
(OR)
b) Explain how to access structure members.

Maanya's M.G.B Publications Programming in C


0-iv Model Question Papers
PART – C

Instructions: Answer the following questions.


Each question carries FIVE marks. 4 x 5 = 20 M
13. a) Draw a flowchart to find biggest of three numbers.
(OR)
b) Write a C program to illustrate functions without arguments and without return
values.
14. a) Write a C program to find the multiplication of two matrices.
(OR)
b) Explain random handling functions.
15. a) Write a C program to illustrate functions with arguments and without return
values.
(OR)
b) Write a C program to illustrate functions with arguments and with return values.
16. a) Write a C program to implement nested structures.
(OR)
b) Write a C program to implement array of structures.

Maanya's M.G.B Publications Programming in C

You might also like