Download as pdf or txt
Download as pdf or txt
You are on page 1of 372

Lesson 1:

Programming Fundamentals

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1 Introduction to Translators

3.1.1 Compiler

3.1.2 Interpreter

3.1.3 Comparison of Compiler and Interpreter

3.1.4 Assemblers

3.2 Concept of Problem Solving

3.2.1 Problem Identification / Analysis

3.2.2 Program Designing

Flow Charting, Decision Table, Decision Trees, Pseudo codes,

Algorithm Development

3.2.3 Program Coding

3.2.4 Program Compilation and Execution

3.2.5 Debugging and Testing

3.2.6 Implementation and Documentation

3.3 Types of Errors in programming

4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

2
1. Introduction

There are a number of ways of developing a program. One method is a graphical

technique called flowcharting. Another method is the definition of the problem in

pseudocode. Pseudocode is a formal language which resembles natural English but

which is sufficiently constrained and formalised to allow a precise statement of the

program's structure. The coding stage is the translation of the program from flowcharts

or pseudocode to the programming language of choice. The testing stage is always

necessary. What you are looking for are errors (bugs) in your program and you will

nearly always find some. The most common way to test for errors (often called

debugging or looking for and removing bugs) is to pass the program through a

translator program. The translator program expects the program to follow very rigid

syntactic rules. If this is not so the translator will send you an error message (ie. it will

tell you, by displaying a message on the screen, that you have made a syntax error).

For many languages, the translator examines the entire program at one time and

translates the program into a code that the machine can understand (machine code).

Such a translator program is called a compiler.

This lesson discusses about various programming language translators. This lesson also

discusses about the concept of problem solving and the various stages of program

development. Further, various types of errors in programming is also discussed in

detail.

2. Objectives

3
After working through this lesson you should be able to:

1. Understand the Compiler, Assembler and Interpreter.

2. Understand the Concept of problem solving

3. Understand the Debugging and documentation.

4. Understand what is error and types of errors.

3. Presentation of Contents

3.1 INTRODUCTION TO TRANSLATORS

Machine code i.e. 0’s and 1’s is the only language that a computer understands. People

however, have difficulty understanding machine code. To make program development

easier scientists developed more sophisticated programming languages such as assembly

language and High level languages. With the use of these languages, developers could

think about their programs in human terms rather than the computer terms. But for these

languages we need, translators that converts the humanlike instructions into strings of

numbers i.e. 0’1 and 1’s (machine code) that computers can understand. The most

commonly used translators are compiler, interpreter and assembler.

3.1.1 COMPILER

Compiler is simply a translator. The Compiler takes source language and translates it into

an equivalent target language program, generally in assembly language.

Source Compiler Target


program P language
program for P
4
Properties of a good compiler

1. It should generate a correct code.

2. No code or memory limitations should bother about the compiler.

3. The Compilers should be reliable, efficient and fast.

4. It should be user-friendly in error reporting. (Beginner programmers are often forget

to put ‘;’ at the end of the line, but error messages they get do not help them to find an

error.)

Disadvantages of Compilers

1. The compilers are comparatively difficult to write.

2. The compiler only translates a program in one programming language into an

equivalent program in another language.

3. It is very difficult to handle dynamic scoping in compilers.

4. It is very difficult to test the program since the compiler execution file gives

the final result.

5. It is very difficult and complicate to provide debugging facilities.

6. Translating process in compilers is slower than interpreters.

7. The compilers do not produce symbolic dumps hence required debugging

tools for trace of the program.

5
Advantages of Compilers

1. The Compiled code provided by the compiler generally runs faster.

2. Compilers have more access to machine as compared to interpreters.

3. It saves time since the code is compiled few number of times and executed many

times.

3.1.2 INTERPRETER

An interpreter processes a source program written in a high-level language line by line

and also executes it. The main difference between compiler and interpreter is that

interpreters execute the source program directly and produces the program output, instead

of translating it into machine code.

An interpreter performs lexical and syntactic analysis functions just like compiler and

then translates the source program into an internal form. The internal form may also be a

sequence of quadruples. After translating the source program into an internal form,

the interpreter executes the operations specified by the program.

Formally, an Interpreter is a program that takes program P written in some language and

input x to P. It translates P and runs it on x and than gives a resultant output of P on input

x. Interpreter is a translator plus virtual machine engine. The interpreter runs program “as

is” without any preprocessing or optimization.

Program P

Interpreter Output of P on x
6
Input x to P

Most programming languages can be either compiled or interpreted. However, some

languages are particularly well suited to the use of interpreter. Compilers usually generate

calls to library routines to perform function such as I/O and complex conversion

operations. In such cases, an interpreter might be performed because of its speed of

translation. Most of the execution time for the standard program would be consumed by

the standard library routines. These routines would be the same, regardless of whether a

compiler or an interpreter is used.

Advantages of Interpreters:

1. The Interpreters are very useful during program development process as program

testing can be done effectively.

2. The interpreters do not pay a penalty for unreachable statements.

3. They provide more help on run time errors.

4. They are simpler to write.

5. It is very easy to provide debugging facilities in interpreters.

Disadvantages of Interpreters:

1. The interpreted programs run comparatively very slow.

2. The object program is not an optimized one and hence takes more memory and

more time to run.

7
3.1.3 COMPARISON OF COMPILER AND INTERPRETER

The major differnces between copiler and interpreter are as follows.

Interpreters Compilers

1) The process of translating a source The process of translating a source

program into some internal form is program into some internal form is

simpler and faster slower than interpreter.

2) Execution of the translated program Executing machine code is much faster.

is much slower.

3) Debugging facilities can be easily Provisions of debugging facilities are

provided. difficult and complicated.

4) During execution the interpreter The compiler does not produce

produce symbolic dumps of data values, symbolic dumps of date value.

trace of program execution related to the Debugging tools are required for trace

source statement. the program.

5) Program testing can be done It is difficult to test as the compiler

effectively using interpreter as the execution file gives the final result.

operation on different data can be

traced.

6) Easy to handle dynamic scoping Difficult to handle dynamic scooping

3.1.4. ASSEMBLER

8
An assembler is a translator that translates an Assembly language program into machine

language program. In other words, an assembler translates the symbolic codes of

programs of an assembly language into machine language instructions. The assembler

programs translate the low-level language to the machine code. The translation job is

performed either manually or with a program called assembler. In hand assembly, the

programmer uses the set of instructions supplied by the manufacturer. In this case, the

hexadecimal code for the mnemonic instruction is searched from the code sheet. This

procedure is tedious and time-consuming. Alternate solution to this is the use of

assemblers. The program called assembler provides the codes of the mnemonics. This

process is fast and facilitates the user in developing the program speedily. There are two

types of assemblers, One Pass Assembler and Two Pass Assembler.

A One-pass Assembler performs all its functions by reading the source file once.

A Two-Pass Assemble reads the source file twice.

3.2 CONCEPT OF PROBLEM SOLVING

Any given problem can be solved by using the steps mentioned below. These steps are

called Program development life cycle. It is a systematic approach to solve any problem.

It breaks the jobs of solving a problem into manageable sub jobs in such a manner that

each sub job is successfully completed before moving to the next step. These sub jobs are

known as steps of programming life cycle. These steps are:

 Problem Definition/Identification

 Program Designing

9
 Flow Charting , Decision Table, Decision Trees, Pseudo codes, Algorithm

Development

 Program coding

 Program Compilation

 Debugging and Program Testing

 Implementation and Documentation

3.2.1 PROBLEM DEFINITION/IDENTIFICATION

It is first step to solve any problem. Before doing any thing one must have a proper

understanding of the problem that what is the Problem? One must know what is the

output requirement of the particular problem and what type of input data will be required.

There should be very clear about input data, output formats, reports, execution time

requirement, user interfaces etc. Normally, this entire analysis and facts collection is done

by System Analysts and once the problem is properly understood, they provide the result

of their work in the form of problem definition or program specification to the

programmer so that the same may clear to the programmer also.

10
Fig. 1. Problem Identification and Analysis

For Small projects the programmer itself can do the job of analysts (Problem

Identification and analysis) during this phase System analysts do feasibility tests include

economic feasibility, social and behavioral feasibility, system feasibility including

hardware and software feasibility etc. besides above stated jobs. For information

gathering or facts collection, analysts uses following tools: interviewing, questionnaire,

onsite observation and review of manuals, reports etc. Once the problem parts are

exposed it is properly defined or identified.

11
3.2.2 PROGRAM DESIGNING:

Once the problem is clearly understood its solution procedure is designed and all

alternatives are consulted. All types of input data, output formats and codes are designed

in this phase along with the groups of programmers or sub programmers to complete the

work. The complex or big problem is divided into smaller parts called modules.

Structured approaches like Top-down Approach, Bottom-Up Approach etc. are used for

it. Individual modules can be developed parallely or some times after completion of

previous modules. Team coordination and distribution of modules is also done in this

phase. Modules are easy to manage and if several modules are developed parallely it

takes less time to complete a project. Also error detection is easy in modules.

The main routine is identified and plans for modules are decided in this step. Language

best suited for project development is decided. Designing phase includes modular brake

ups input design, output design, code design and a conceptual plan for program

development.

12
Fig. 2. Program Design

(a) FLOW CHARTING, DECISION TABLE, DECISION TREES, PSEUDO CODES,

ALGORITHM DEVELOPMENT

1. Flowchart: The Symbolic or pictorial-representation of step-wise written instructions,

which are used to develop a program, is known as flowchart. It is nothing but a

diagrammatic representation of the various steps involved in designing a system. Some of

the symbols which are used in flowchart are shown in Fig 3.

13
Fig. 3. Common Symbols of Flow Chart

A flowchart consists of a set of ‘Flowchart symbols’ connected by arrows. Each symbol

contains information about what must be done at that point & the arrow shows the ‘flow

of execution’ of the algorithm, i.e., they show the order in which the instructions must be

executed. The purpose of using Flowcharts is to graphically present the logical flow of

data in the system and defining major phases of processing along with the various media

to be used.

Flowcharts are of three types:

a) System flowchart

b) Run flowchart

c) Program flowchart

14
(a) System Flowcharts: System flowchart describes the data flow for a data processing

system. It provides a logical diagram of how the system operates. It represents the flow of

documents and the operations performed in data processing system. It also reflects the

relationship between inputs, processing and outputs. Following are the features of system

flowcharts:

 The sources from which data is generated and device used for this purpose

 various processing steps involved

 The intermediate and final output prepared and the devices used for their storage.

Fig. 1.4 is a sample system flowchart for the following algorithm:

1. Prompt the user for any number.

2. Store the number in variable ‘num’.

3. If num % 2 = = 0

4. print ‘number is even’.

5. Otherwise ‘print number is odd’.

6. Stop

15
Fig. 4. System Flowchart

(b) Run Flowchart: Run flowchart is used to represent the logical relationship of

computer routines along with inputs, master files transaction files, and outputs. Fig. 1.5

illustrates a run flowchart.

16
Fig. 5. Run Flowchart

(c) Program Flowcharts: A program flowchart represents, in detail, the various steps to

be performed within the system for transforming the input into output. The various steps

are logical/arithmetic operation, algorithms, etc. It serves as the basis for discussion and

communication between the system analyst and the programmer. Program flowcharts are

quite helpful to programmers in organizing their programming efforts. These flowcharts

constitute important components of documentation for an application. These are

discussed in more detail in Lesson 2.

17
2. Decision Tables and Decision Trees: Decision tables and trees were developed long

before the widespread use of computers. They not only isolate many conditions and

possible actions but they help ensure that nothing has been overlooked.

(a) Decision Tables: The decision table is a chart with four sections listing all the

logical conditions and actions. In addition, the top section allows space for title,

date, author, system, and comment. These are discussed in more detail in Lesson

2.

(b) Decision Trees: The decision tree defines the conditions as a sequence of left to right

tests. A decision tree helps to show the paths that are possible in a design following an

action or decision by the user. These are discussed in more detail in Lesson 2.

3. Pseudo Codes: Pseudo code is a kind of structured English for describing algorithms.

It allows the designer to focus on the logic of the algorithm without being distracted by

details of language syntax. At the same time, the pseudo code needs to be complete. It

describes the entire logic of the algorithm so that implementation becomes a rote

mechanical task of translating line by line into source code.

In general the vocabulary used in the pseudo code should be the vocabulary of the

problem domain, not of the implementation domain. The pseudo code is a narrative for

someone who knows the requirements (problem domain) and is trying to learn how the

solution is organized.

4. Algorithms: An Algorithm is a step by step solution for any problem. It is a sequence

of statements designed in such a manner that on execution the desired output is achieved.

18
It may be written in simple English like language. If it gives correct result then it is

converted into a computer program using a computer programming language. Normally

During preparation of any program, firstly algorithm is prepared for it. Then algorithm is

represented in form of flow chart, which is the graphical representation of steps of

algorithm. Then flowchart is expressed in some programming language to make a

computer program.

Algorithms written in simple English is called ‘Pseudo code’ and written in computer

programming language is called ‘Program’. Thus every program is an Algorithm but

reverse is not true. An algorithm is very important for any program. If it contains an error

or mistake, one has to recheck the algorithm and restart all process.

These are discussed in more detail in Lesson 2.

3.2.3. PROGRAM CODING

Normally the Programming Language for coding the program for any project is decided

in advance. When the algorithm is prepared and tested then it requires implementing

using programming language, it is called program coding.

An algorithm is converted into step by step procedure called program by any

programming language. One must follow the Syntax and grammar of that particular

language while coding the program.

The names of program, subprogram and variables are chosen such that they are clear and

understandable. It is good practice to use comments in coding so that it must be clear

what steps performed what. Use meaningful variable names and meaningful program

name. Use easy logic for particular problem so that it is clear to all.

19
The process of translating an algorithm into a computer program by using computer

language is known as program coding. Once the program is coded it is handed over to

next step for making an executable code.

3.2.4. PROGRAM COMPILATION AND EXECUTION

Compiling the program: After creating the program, it is compiled by compiler (Alt+F9

in C Language) if there is any type of syntax error then compiler shows the listing of

error with line number and if there is no error then it is compiled successfully means

source code converted into object code(machine code). In UNIX, program compiled by

giving following command:

cc abc.c

Linking and execution of Program: after compilation linking is done by linker (Ctrl+F9 in

C Language) and executable code is generated and executed.

3.2.5. DEBUGGING AND TESTING

Program Debugging: Once the program is ready they must be checked for any type of

errors. Normally a program can have following errors: Syntax Errors, Logical Errors and

Execution Errors.

Isolation of errors and removal of errors is known as debugging. You must know that an

error in computer program is known as bugs and the process of detecting and correcting

these errors is called debugging. It is a time consuming step. Syntax errors are easily

located by compiler but logical and execution errors do not. Thus debugging is performed

in this step.

20
Program Testing: After converted algorithm in to programming code. This

programming code called as source code. Source code converted into object code

(Machine code) by compilation process when there is no syntax error in the source code.

If there is any syntax error in the source code then source code does not convert in to

object code. When successfully compiled then source code converted into object code but

still there may be some logical errors which towards to undesired or wrong output. These

errors may cause due to wrong logic used in source code. That is why the program is

tested before implementation.

For testing a program some sample input data are taken and their output is calculated

manually. The same data are given as input to the program. The output is compared to the

manual output. If the result is OK, there are no logical errors in the program. But if output

is deviate or incorrect, it means there are some logical errors in the program. To locate

these errors in the program one has to go back to Algorithm and flowchart and try to

locate the problem. Correct them, recode the program, recompile it and test it again. The

same steps are repeated until output during resting of program becomes correct.

3.2.6 IMPLEMENTATION AND DOCUMENTATION

This phase includes Installation of Software, Maintenance and documentation.

This is final and last phase of program development life cycle. Software installation

means to install or load the program at user’s site and train the user to use the software.

Provide proper training to the user of software for data entry and getting the output

reports. Some times user may encounter some errors that were not caught during program

testing and debugging. These errors are removed and the software is kept under watch

until a green signal is given by the user.


21
After installation the software is evaluated regularly to confirm its utility with time. It

needs maintenance i.e. there may be some errors discovered by user during day to day

use which need removal and also some times there may be slight changes in user

requirement which can be made time to time. Backups of data files must be taken timely.

In Brief, it may need modification, removal of errors from time to time, reinstallation of

some or full software or data files in case of corruption and some time is may lead to a

decision to abandon the current system and develop a new one.

Documentation means collecting, organizing, storing and maintaining a complete

historical record of developed software. It includes comments in program, structure

charts, pseudo codes, Decision tables, algorithms, flowcharts, program names and their

description, system specifications, program listings, test data files and their fields with

complete details of each program, loading and unloading methods, data entry procedure,

security, special checks etc. Documentation includes three types of manuals:

 System manual

 Operational manual

 Program manual (With in program comments servers as documentation)

3.3 TYPES OF ERRORS IN PROGRAMMING

There are four basic types of program errors. Your objective is to write programs that are

totally free of program errors. Program errors are also referred to as program bugs. Every

programmer, no matter how experienced, writes programs that contain errors. A skilled

programmer, however, can detect, isolate, and correct program errors more quickly than a

22
less skilled programmer. Also, experienced programmers do make fewer programming

errors simply because of their experience. In the beginning you will start off with the “

flat - forehead ” type of programming error. Those are the kind of errors that, when you

do find them, you slam the heel of your hand into your forehead while mumbling, “How

could I make such a silly mistake?” . View each program error as a challenge and learn

from the experience. While there will be fewer errors as you gain experience, those errors

you do make tend to become more sophisticated and harder to isolate and fix.

The four types of program errors are as follows:

1. Syntax Errors: The first type of error is a syntax error. The syntax errors are caused

when you do not obey the syntax rules of a language. A common syntax rule you might

make in the beginning is forgetting to terminate each program statement with a

semicolon.

2. Logic Errors: Logic errors are those errors that remain after all the semantic and

syntax errors have been removed. Usually, logic errors evident, when the result the

program produces does not match the result your test data suggest it should produce.

Logic errors occur when you implement the algorithm for solving the problem

incorrectly.

The key to fixing logic errors is to be able to reproduce the error consistently. A

repeatable logic error is much easier to track down and fix than an error that appears to be

occurring randomly.

23
3. Semantic Errors: A semantic error occurs when you obey the syntax rules of the

language but are using the statement out of context. For example, a sentence in English is

expected to have a noun and a verb. Consider the sentence “ The dog meowed. ” This

sentence does obey the rules of having a noun and a verb, but the context of the sentence

is out of whack. Dogs do not meow, therefore the context of the statement is incorrect.

The error message, the name ‘i’ does not exist in the current context refers to a type of

semantic error. There may be a variable named i defined somewhere in the program, but

it is not currently in scope. That is, you are trying to use i when it is out of scope.

4. Runtime Errors: If the computer detects and reports an error message during the

execution of the program, we refer to this as a runtime error. In this case, the computer

will stop executing the program, and report the type of error along with its approximate

location. However, the system might misinterpret the problem in many cases and lead

you in the wrong direction.

4. Summary

The Compiler takes source language and translates it into an equivalent target language

program.

An interpreter processes a source program written in a high-level language line by line

and also executes it.

The main difference between compiler and interpreter is that interpreters execute the

source program directly and produces the program output, instead of translating it into

machine code.

24
Any given problem can be solved by using Program development life cycle. It is a

systematic approach to solve any problem.

Problem definition is the first step to solve any problem. Before doing anything one must

have a proper understanding of the problem that what is the Problem.

Once the problem is clearly understood its solution procedure is designed and all

alternatives are consulted. All types of input data, output formats and codes are designed

in this phase along with the groups of programmers or sub programmers to complete the

work.

Isolation of errors and removal of errors is known as debugging. You must know that an

error in computer program is known as bugs and the process of detecting and correcting

these errors is called debugging.

Documentation means collecting, organizing, storing and maintaining a complete

historical record of developed software. It includes comments in program, structure

charts, pseudo codes, Decision tables, algorithms, flowcharts, program names and their

description, system specifications, program listings, test data files and their fields with

complete details of each program, loading and unloading methods, data entry procedure,

security, special checks etc. Documentation includes three types of manuals: System

manual, Operational manual, Program manual etc.

There are four basic types of program errors. These are Syntax Errors, Logic Errors

Semantic Errors, Runtime Errors.

5. Suggested Reading/Reference Material

1. Sinha, P.K. & Sinha, Priti, “Computer Fundamentals”, BPB

25
2. Dromey, R.G., “How to Solve it By Computer”, PHI

3. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

4. Norton, Peter, “Introduction to Computers”, McGraw-Hill

5. Leon, Alexis & Leon, Mathews, “Introduction to Computers”, Leon Tech World

6. Rajaraman, V., “Fundamentals of Computers”, PHI

6. Self Assessment Questions

1. What purpose serves by compiler? Explain.

2. What is the difference between compiler and interpreter?

3. What is Assembler? Explain in detail.

4. What is Problem? How we can solve a problem efficiently?

5. What are the steps involved in program development? Explain.

6. Explain the Program Compilation and Execution in detail.

7. What is testing? Is testing required in Program Development? Justify your

answer.

8. What are the different types of program errors? Explain.

9. Distinguish between syntax errors and logic errors.

26
Lesson 2

Flowcharts, Algorithms and Structured Programming

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1. Flowchart

3.2. Decision Tables And Decision Trees

3.3 Pseudo Codes

3.4 Algorithms

3.5. Structured Programming Concepts

3.6. Programming Methodologies

4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

2
1. Introduction

In the previous lesson you learn about programming fundamentals and the various

stages of program development. In this lesson, the various techniques namely

flowcharts, decision tables and algorithms used to solve problems are discussed in

detail. Further, the structured programming concepts are also discussed with their

advantages and disadvantages. Then two commonly used programming

methodologies i.e. top down and bottom up methodologies are also discussed.

2. Objectives

After working through this lesson you should be able to:


1. Understand the Flowcharts and their construction.
2. Understand the decision tables and their construction.
3. Understand the algorithms and how to write algorithms.
4. Understand the concepts of structured programming.
5. Understand the various programming methodologies.

3. Presentation of Contents

3.1. FLOWCHARTS

The Symbolic or pictorial-representation of step-wise written instructions, which are used

to develop a program, is known as flowchart. It is nothing but a diagrammatic

representation of the various steps involved in designing a system. Some of the symbols

which are used in flowchart are shown in Fig. 1

3
Fig. 1: Common Symbols of Flow Chart

A flowchart consists of a set of ‘Flowchart symbols’ connected by arrows. Each symbol

contains information about what must be done at that point & the arrow shows the ‘flow

of execution’ of the algorithm, i.e., they show the order in which the instructions must be

executed. The purpose of using Flowcharts is to graphically present the logical flow of

data in the system and defining major phases of processing along with the various media

to be used.

Flowcharts are of three types:

1. System flowchart

2. Run flowchart

4
3. Program flowchart

The first two types of flowcharts are discussed in lesson 1. In this lesson you will learn

about Program Flowcharts in more detail.

A program flowchart represents, in detail, the various steps to be performed within the

system for transforming the input into output. The various steps are logical/arithmetic

operation, algorithms, etc. It serves as the basis for discussion and communication

between the system analyst and the programmer. Program flowcharts are quite helpful to

programmers in organizing their programming efforts. These flowcharts constitute

important components of documentation for an application. Fig. 2 represents a program

flowchart for finding the sum of first five natural numbers (i.e., 1, 2, 3, 4, and 5).

Fig. 2. Program Flowchart

5
Guidelines for Flow Charts

The following are some guidelines that should be followed while drawing flowcharts:

1) In drawing a proper flowchart, all necessary requirements should be listed out in

logical order.

2) The flowchart should be clear, neat and easy to follow. There should not be any

room for ambiguity in understanding the flowchart.

3) The usual direction of the flow of a procedure or system is from left to right or top

to bottom.

4) Only one flow line should come out from a process symbol.

or

5) Only one flow line should enter a decision symbol, but two or three flow lines,

one for each possible answer, should leave the decision symbol.

6) Only one flow line is used in conjunction with terminal symbol.

7) If the flowchart becomes complex, it is better to use connector symbols to reduce

the number of flow lines. Avoid the intersection of flow lines if you want to make

it more effective and better way of communication.


6
8) Ensure that the flowchart has a logical start and finish.

9) It is useful to test the validity of the flowchart by passing through it with a simple

test data.

Advantages of Using Flowcharts

The benefits of flowcharts are as follows:

1) Communication: Flowcharts are better way of communicating the logic of a

system to all concerned.

2) Effective analysis: With the help of flowchart, problem can be analyzed in more

effective way.

3) Proper documentation: Program flowcharts serve as a good program

documentation, which is needed for various purposes.

4) Efficient Coding: The flowcharts act as a guide or blueprint during the systems

analysis and program development phase.

5) Proper Debugging: The flowchart helps in debugging process.

6) Efficient Program Maintenance: The maintenance of operating program

becomes easy with the help of flowchart. It helps the programmer to put efforts

more efficiently on that part

Limitations of Using Flowcharts

Some of the limitations of using flowcharts are as follows

1) Complex logic: Sometimes, the program logic is quite complicated. In that case,

flowchart becomes complex and clumsy.

2) Alterations and Modifications: If alterations are required the flowchart may

7
require re-drawing completely.

3) Reproduction: As the flowchart symbols cannot be typed, reproduction of

flowchart becomes a problem. The essentials of what is done can easily be lost in

the technical details of how it is done.

Example 1: A flowchart to find the sum of first 50 natural numbers is shown in Fig. 3.

Fig. 3. Sum of first 50 natural numbers

Example 2: A flowchart to accept the price of an item and calculate its VAT at 15% is

shown in Fig. 4.

8
Fig. 4. To calculate VAT

Example 3: A flowchart that accepts money in US dollars and converts it to its

equivalent local currency is shown in Fig. 5.

Fig. 5. Conversion of US dollar to local currency

9
Example 4: A flowchart that accepts the length and width of a rectangle and calculates

its area is shown in Fig. 5.

Fig. 6. Calculate the area of a rectangle.

Example 5: A flowchart to find the largest of three numbers A,B and C is shown in Fig.

7.

Fig. 7: Flowchart for finding out the largest of three numbers

10
Example 6: A flowchart for computing factorial N (N!), Where N! = 1 ´ 2 ´ 3 ´ …… N is

shown in Fig. 8.

Fig. 8: Flowchart for computing factorial N (N!)

3.2. DECISION TABLES AND DECISION TREES

Decision tables and trees were developed long before the widespread use of computers.

They not only isolate many conditions and possible actions but they help ensure that

nothing has been overlooked.

(a) Decision Tables: The decision table is a chart with four sections listing all the logical

conditions and actions. In addition, the top section allows space for title, date, author,

system, and comment as shown in the Fig. 9.

11
Fig. 9. Decision Table

Following are the four sections of a decision table

The Condition Stub contains a list of all the necessary tests in a decision table. In the

lower left-hand corner of the decision table we find the Action Stub where one may

write all the processes desired in a given module. Thus Action Stub contains a list of all

the processes involved in a decision table.

The upper right corner provides the space for the Condition Entry – all possible

permutations of 'yes' and 'no' responses related to the condition stub. The 'yes' and 'no'

possibilities are arranged as a vertical column called rules. Rules are numbered 1,2,3 and

so on. We can determine the rules in a decision table by the formula:

Number of rules = 2^N = 2N where N represents the number of condition and ^ means

exponentiate. Thus a decision table with four conditions has 16 = (24 =2 x 2x 2 x 2 = 16)

rules. One with six conditions has 64 rules and eight conditions yield 256 rules.

The Condition entry contains a list of all yes/no permutations in a decision table. The

lower right corner holds the action entry. X’s or dots/dash indicates whether an action

12
should occur as a consequence of the yes/no entries under condition entry. X’s indicate

an action should occur as a consequence of the yes/no entries under condition entry,

while dots indicate no action.

Thus Action entry indicates via dot or X whether something should happen in a decision

table or not.

Example 7: Consider the following example of book order given below:

If order is from book store

And if order is for 6 copies

Then discount is 25%

Else (if order is for less then 6 copies)

No discount is allowed

else (if order is from libraries) If order is for 50 copies or more

Then discount is 15%

Else if order is for 20 to 49 copies

Then discount is 10%

Else if order is for 6 to 19 copies

Then discount is 5%

Else (order is for less then 6 copies)

No discount is allowed

A decision table for the above process is illustrated in Fig. 10.

13
Fig. 10. Decision Table

(b) Decision Tree: The decision tree defines the conditions as a sequence of left to right

tests. A decision tree helps to show the paths that are possible in a design following an

action or decision by the user. Fig. 11 illustrates the concept of decision tree.

Fig. 11. Decision Tree

14
Decision tree turns a decision table into a diagram. This tool is read from left to right,

decision results in a fork, and all branches end with an outcome. Fig. 12 illustrates the

decision tree for the book order decision table we saw in Example 7.

Fig. 12. Decision tree for the book order

3.3 PSEUDO CODES

Pseudo code is a kind of structured English for describing algorithms. It allows the designer

to focus on the logic of the algorithm without being distracted by details of language syntax.

At the same time, the pseudo code needs to be complete. It describes the entire logic of the

algorithm so that implementation becomes a rote mechanical task of translating line by line

into source code.

In general the vocabulary used in the pseudo code should be the vocabulary of the problem

domain, not of the implementation domain. The pseudo code is a narrative for someone who

knows the requirements (problem domain) and is trying to learn how the solution is

organized.

15
Example 8: A pseudocode that prompts the user to enter a value and display its square

and cube values.

Step 1: start

Step 2: read num

Step 3: square  num * num

Step 4: cube  num * num* num

Step5: write square, cube

Step 6: stop

Example 9: A pseudocode that will accept the length and width and calculate and print

the area of the rectangle. (area = length * width)

Step 1: start

Step 2: read length, width

Step 3: area  length * width

Step 4: write area

Step 5: stop

Example 10: A pseudocode that will accept 25 integers and displays the number of

positive and negative numbers.

Step 1: start

Step 2: poscount 0, negcount 0

Step 3: for i  1 to 25

16
Step 3: read num

Step 4: if num>0 then

poscount = poscount +1

else

negcount = negcount +1

endif

Step 5: endfor

Step 6: write poscount,negcount

3.4 ALGORITHMS

An Algorithm is a step by step solution for any problem. It is a sequence of statements

designed in such a manner that on execution the desired output is achieved. It may be

written in simple English like language. If it gives correct result then it is converted into a

computer program using a computer programming language. Normally During

preparation of any program, firstly algorithm is prepared for it. Then algorithm is

represented in form of flow chart, which is the graphical representation of steps of

algorithm. Then flowchart is expressed in some programming language to make a

computer program.

Algorithms written in simple English is called ‘Pseudo code’ and written in computer

programming language is called ‘Program’. Thus every program is an Algorithm but

reverse is not true. An algorithm is very important for any program. If it contains an error

or mistake, one has to recheck the algorithm and restart all process.

Algorithms contain two parts:

17
 First Part tells the purpose of algorithm. It identifies the variables which occur in

the algorithm and lists the input data.

 Second part consists of steps that are to be executed.

Characteristics of Algorithm: The following are some important characteristics of

algorithms.

a) Input: input part reads the data of a given problem by accepting input.

b) Process: process part does the required computations.

c) Finiteness: the algorithm must come to end after a finite number of steps.

d) Effectiveness: every step must be accurate and precise. It must be execute with in

a definite period of time.

Advantage of Algorithms: The following are some of the advantages of algorithms.

 It is step wise solution of a problem.

 It is independent of any programming language.

 It is easy and simple to understand.

 It is easy to convert in any programming language due to step wise

description.

Notations: various notations used in algorithm are:

 Comments

 Variable Names

 Assignment statement

18
 Input/output statement

 Conditional instruction

 Loop instruction

 Starter & Terminator

Comment: Comments are used for clarity and understanding of problem. Each step may

contain comment in brackets or by using // or by using /* …..*/. e.g.

[First comment type]

//second comment type

/* Third comment type*/

Variable Names: Variable names will use capital letter. Single letter names of variables

used as counters or subscript used as capital letter as well as small letter. e.g.

MAX

COUNT

Assignment statement: Assignment statement will use colon-equal notation for

assignment.

e.g.

19
MAX: = COUNT [5]

Some algorithm use backward arrow  or equal sign = or assignment.

Input/output statement: Data may be input and assigned to variables by Read

statement.

e.g.

Read: variable names.

Similarly, Message with in quotation marks and data in variables may be output by Write

or Print statement.

e.g.

Write: Message

Or

Write: variable names.

Conditional instruction: Such statements which choose one process among a few

depending on condition are called conditional instruction or conditional structure. These

are:

IF statement

IF-THEN-ELSE

GO TO Step.

SWITCH CASE

e.g.

IF A>B THEN

20
PRINT A

END IF

IFA>B THEN

GOTO STEP 2

END IF

Loop instruction: When there are certain steps required to be executed repeated again

and again up to certain condition, these constructs are called loop constructs. These are:

i. FOR Loop

ii. WHILE….. DO Loop

iii. REPEAT UNTIL Loop

e.g.

i. FOR <identifier> = <initial value> TO <final value> STEP BY

<increment/decrement>

DO

Statements

END FOR

ii. WHILE <cond.> DO

Statements

ENDWHILE

21
iii. REPEAT

Statements

UNTIL <cond.>

Starter & Terminator: Starting an Algorithm we use START and for ending an

algorithm we use STOP or END. But at some times terminate the execution in between

depending on certain conditions, EXIT is used to terminate.

Example 11: An algorithm for displaying the sum of 50 natural numbers.

//Algorithm for displaying sum of 50 natural numbers i.e SUM = 1+2+3 ……+50 ,

// Variable I for Counter Loop.

Step 1: START

Step 2: SUM = 0, I

[SUM variable used for storing sum and I used as counter in loop]

Step 3: FOR I=1 to 50 STEP 1

DO

SUM=SUM + I

END FOR

Step 4: PRINT SUM

Step 5: STOP

Example 12: An algorithm for printing Largest among three numbers.

22
// Algorithm for Largest among three numbers. Numbers A,B & C are inputted from

//keyboard.

Step 1: START

Step 2: READ A,B,C

Step 3: IF A>B THEN

IF A>C THEN

PRINT ‘A is greatest’

ELSE

PRINT ‘C is greatest’

ELSE IF B>C THEN

PRINT ‘B is greatest’

ELSE

PRINT ‘C is greatest’

[END of IF Structure]

Step 4: STOP

Example 13: An Algorithm to compute factorial of N (N!)

//Algorithm for computing factorial of N .

//N is read from Keyboard. Variable M as Counter in For Loop and Variable F used to

//store the factorial.

Step 1: START

Step 2: READ N

Step 3: M=1, F=1

23
Step 4: FOR M=1 TO N STEP 1

DO

F=F*M;

END FOR

Step 5: PRINT F

Step 6: STOP

Example 14: An algorithm and flowchart for finding the average of two numbers. The

flowchart is shown in Fig. 13.


START

Algorithm:
INPUT x
Step 1: START
INPUT y

Step 2: INPUT x SUM = x + y


Step 3: INPUT y
AVG = SUM/2
Step 4: SUM = x+y

Step 5: AVG = SUM/2


PRINT
AVG
Step 6: PRINT AVG

Step 7: STOP
END

Fig. 13. Flowchart for average of two Numbers

3.5. STRUCTURED PROGRAMMING CONCEPTS

Structured programming techniques assist the programmer in writing effective error free

programs. Structured programming began the theoretical study of programming design. It

24
forced programmers to approach programming from the conceptual point of view,

making them design programs before they wrote code. It cleared up spaghetti code and

forced the concept of correctness into the program

Experience with programming languages and software development over the years has

shown that applying structured programming concepts helps keep software code

amenable to analysis, behaviour prediction, debugging, modification and verification

among others.

One of the most important features of structured programming is that all program

structures have only one entry point and one exit point.

There are three main types of control structures in structured programming. These are

1) Sequence: A sequence of instructions in a sequence structure must all be carried

out. An example of sequence control is shown in Fig. 14.

Fig. 14. A sequence control structure

2) Selection: In a selection structure certain instructions will only be carried out IF a

certain condition is found to be true. An example of a selection (IF-THEN-ESLE)

control structure is shown in Fig. 15.The flowchart in Figure 15 means

25
IF "Condition" is true THEN perform "Procedure 2", ELSE perform "Procedure

3".

Fig. 15. (IF-THEN-ESLE) control structure.

Another example of a selection (IF-THEN-ELSEIF-THEN-ELSE) control

structure is shown in Fig. 16. The flowchart in Fig. 16 means

IF "Condition 1" is true THEN perform "Procedure 2", ELSE IF

"Condition 2" is true THEN perform "Procedure 3" ELSE perform

"Procedure 4".

26
Fig. 16. (IF-THEN-ELSEIF-THEN-ELSE) control structure.

3) Iteration: In an iteration structure certain instructions will be repeatedly carried out

until a condition is no longer true (DO-WHILE) or alternatively until a condition is

no longer false (DO-UNTIL). Such structures consist of a loop which takes the

program back to the top of the instructions to be repeated. An example of an iteration

(DO-WHILE) control structure is shown in Fig. 17. Note that the loop condition (in

this case the question "is i < 10?") is tested before proceding with the rest of the

procedures in the loop and that the loop control variable ("i") is incremented at the

end of the loop. If the loop condition is true then the loop is executed. The loop only

terminates when the loop condition is false. If the loop condition is false upon entry to

the loop then the loop isn't executed at all.

27
Fig. 17. (DO-WHILE) control structure

Another example of an iteration (DO-UNTIL) control structure is shown in Figure 18.

Note that the loop condition (in this case the question "is i > 10?") is tested at the end of

the loop. The loop control variable (in this case "i") can be updated anywhere in the loop

and here is incremented just before the loop condition is tested. If the loop condition is

true then the loop is terminated. The loop only repeats when the loop condition is false.

Even if the loop condition is true upon entry to the loop the loop will be executed at least

once.

28
Fig. 18. (DO-UNTIL) control structure.

3.6. PROGRAMMING METHODOLOGIES

There are two main types of programming methodogies used to develop programs. These

are Top Down Programming and Bottom Up Programming. Both of these are

discussed below.

Top-down Programming : The top-down approach to programming is to start with a set

of high level tasks that will be called from main(), and recursively splitting each task into

subtasks until a level of complexity is attained that permits the definition of reasonably

simple function modules.

29
In top down programming the higher-level functions are implemented in terms of the

lower-level functions.

Top-down program design is useful for defining the overall structure of a program, and

the dependencies between functions. Usually, the functions are first implemented as

interfaces only, with do-nothing internals (also called “dummy” internals). This allows

the program to run without any real utility, and individual functions can be written and

tested within a working skeleton program. Thus, the entire program shell is laid out at the

start, and the function internals are subsequently built and debugged one-at-a-time.

A key limitation of top-down design is that the resulting functions tend to be problem-

specific (i.e., specific to the program at hand). They tend to be non-reusable, and the top-

down design of each new project must start from scratch.

Advantages of the Top-Down Programming: The major advantage of top down

programming is as follows

1) It is easier to comprehend the solution of a smaller and less complicated problem

than to grasp the solution of a large and complex problem.

2) It is easier to test segments of solutions, rather than the entire solution at once.

This method allows one to test the solution of each sub-problem separately until

the entire solution has been tested.

3) It is often possible to simplify the logical steps of each sub-problem, so that when

taken as a whole, the entire solution has less complex logic and hence easier to

develop.

4) Simplified solution takes less time to develop and will be more readable.

5) The program will be easier to maintain.

30
Bottom-up Programming : The bottom-up approach to program design is to identify

various components that will be required by the program, and to build them in isolation

from any design of the overall program structure.

Assuming the appropriate argument types are known, the function interfaces can be

designed, after which the internal implementations are usually straight-forward.

An advantage of bottom-up design is that the resulting modules are often more generic

than those designed in a top-down approach. They tend to be less tied to the program at

hand and more amenable to reuse. In the best-case, a bottom-up component can be

designed even without knowledge of program dependencies. This means it is sufficient to

just assume an interface and build an algorithm.

The disadvanatge of bottom-up program design is that it does not give a clear indication

of how the individual program elements should be merged together. It does not present

the “big picture”, the overall structure of the program with its dependencies and function-

call hierarchy. In addition, because components are developed in isolation, they often

require the writing of drivers to permit testing and debugging. These drivers are small test

programs that allow one to check the response of a component to various inputs. Writing

drivers for a large number of different components can be a tedious process.

Top-down and bottom-up program design are complementary and practical design tends

to use both strategies, working at both ends until they meet in the middle. Top-down

design composes the overall program structure and call hierarchy, and bottom-up design

builds key functionality and reusable components.

31
Example 15: A hotel wants to have a room booking system. When a guest arrives the

receptionist would be able to see which rooms are free and allocate one to the guest.

When the guest leaves, the room would be marked as free again. Each day the cleaners

would be given a list of the rooms that are in use. At any time the receptionist would be

able to use the room number to find the name and home address of a guest, or could

search the room system for a named guest. A top-down design diagram in Fig. 19 shows

how the room booking system could be developed.

Fig. 19. A top down program design to show room booking

4. Summary

The pictorial-representation of step-wise written instructions that are used to develop a

program is known as flowchart.

Flowcharts are of three types, System flowchart, Run flowchart and Program flowchart.

32
The decision table is a chart with four sections listing all the logical conditions and

actions.

The decision tree defines the conditions as a sequence of left to right tests and helps to

show the paths that are possible in a design.

Pseudo code is a kind of structured English for describing algorithms and allows the designer

to focus on the logic of the algorithm without being distracted by details of language syntax.

An Algorithm is a step by step solution for any problem. It is a sequence of statements

designed in such a manner that on execution the desired output is achieved.

Structured programming techniques assist the programmer in writing effective error free

programs.

One important feature of structured programming is that all program structures have only

one entry point and one exit point.

There are three main types of control structures used in structured programming. These

are sequence, selection and iteration.

There are two main types of programming methodogies used to develop programs. These

are Top Down Programming and Bottom Up Programming.

In top down programming the higher-level functions are implemented in terms of the

lower-level functions.

The bottom-up approach to program design is to identify various components and to

build them in isolation from any design of the overall program structure.

33
1. Suggested Reading/Reference Material

1. Sinha, P.K. & Sinha, Priti, “Computer Fundamentals”, BPB

2. Dromey, R.G., “How to Solve it By Computer”, PHI

3. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

4. Norton, Peter, “Introduction to Computers”, McGraw-Hill

5. Leon, Alexis & Leon, Mathews, “Introduction to Computers”, Leon Tech World

6. Rajaraman, V., “Fundamentals of Computers”, PHI

6. Self Assessment Questions

1. What is Flow Chart? List out the Symbol used to draw Flow Chart.

2. Difference B/w Decision Table and Decision Tree.

3. What is Algorithm? Difference between Algorithm and Pseudo codes.

4. What is a flow chart? Draw a flow chart to read ten integers and print the sum of

squares of all ten values.

5. Draw a flow chart to read ten integer values and print the sum of squares of the

values.

6. Draw a flow chart to read ten positive integers and print how many are multiples

of 2.

7. Draw a flowchart for finding maximum of given three integers?

8. Draw a flowchart for finding the sum of ‘n’ numbers starting from 1?

34
9. Draw a flowchart to find maximum and minimum of the given three input

numbers

10. Define the flow chart? Draw a flow chart for finding roots of a quadratic equation

with all cases?

11. Define Algorithm? What are the characteristics that any algorithm should satisfy?

12. What is an algorithm? Write an algorithm to read five integers and find out if the

values are in ascending order.

13. What is an algorithm? Write an algorithm to find out if a given number is a prime.

14. Write an algorithm to find out all the factors of a given positive integer.

15. Write an algorithm to read ten positive integers and find out how many are perfect

squares (such as 49, 81).You may assume that the input values read are in the

range 1 to 10000.

16. A utility company charges its customers based on their monthly utilization in

terms of units as follows: Description charge: First 100 units Rs.10 per unit, Next

200 units Rs. 9 per unit, Next 200 units Rs.8 per unit, Next units Rs.7 per unit

.Write an Algorithm and flowchart that reads monthly units of a customer and

output the charge amount.

17. Write a pseudocode that will create a conversion table to convert degrees Celsius

to degree Fahrenheit. Prompt the user to enter the temperature in degree Celsius

and display the temperature in Fahrenheit. (Fahrenheit = 32+ (9*Celcius/5)

18. What is meant by stepwise refinement or top-down design?

19. List three advantages of using top-down design to solve a problem.

20. Explain why a top-down design approach is sometimes used to solve problems.

35
Lesson 3.

Overview and Elements of C

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1 Overview of C
3.1.1 History of C
3.1.2 Characteristics of C

3.1.3 Importance of C Language

3.2 Structure of a C Program


3.3 Elements of C
3.3.1 The C Character Set
3.3.2 Identifiers and Keywords
3.3.3 Constants
3.3.4 Variables
3.5 Escape Sequences
3.6 C Instructions
3.7 Input / Output Functions
3.8 Compilation and Execution of C Program
4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

2
1. Introduction

Language is a medium through which we interact with other people. Similarly, C

language is a language that is used to interact with the computer or computing machine.

The C programming language is a standardized programming language developed in the

early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating

system. It is one of the most widely used general purpose programming languages. C is

very efficient and is the most popular programming language for writing system

software. C is a medium level language (some refers it as a high level language). But

computer understands machine language i.e. binary values 0 and 1. To make

compatibility with computer, this language uses a compiler or simply a translator which

create the object code that is understandable by the computer.

2. Objectives

After working through this lesson you should be able to:

1. Understand the history of C language.

2. Understand the features, advantages and limitations of C language.

3. Understand the importance of C language.

4. Identify the structural elements and layout of C source code.

5. How to create, compile and run a C program?

3. Presentation of Contents

3
3.1 OVERVIEW OF C

Before starting C Language you must know what Language is. Language is a medium by

which one person can communicate with other person as shown in Fig 1.

Fig. 1. Communication between two persons

But problem arises when Person A knows Hindi only and Person B knows English only.

For this an intermediate or language translator is required as shown in Fig 2.

Fig. 2. Communication b/w two persons via Translator

Now, person A wants to communicate with computer. But computer understand only

machine language (binary language o’s or I’s language). Machine language is very

difficult to understand for us. So we will have to learn programming language like C,

Pascal, Fortran etc. for making program for computer. These languages are easier to learn

as compare to machine language. But, now computer does not understand these

programming languages. For this we uses the intermediate or language translator i.e.

compiler or interpreter to solve this problem as shown in Fig. 3.

4
Fig. 3. Communication b/w Person and Computer via Compiler

Now we start C Language, C is a Programming language developed at AT & T’s Bell

Laboratories of USA in 1972. It was developed and written by a man named Dennis

Ritchie. C is a powerful language designed for developing fast, flexible, efficient,

economical and portable software suited to a variety of information processing

technologies. Its compact size , precision, accuracy and adaptability make it a famous

tool for writing operating systems, compilers, commercial and business data processing

applications.

5
Fig. 4. Comparison of Basic elements b/w English and C Language

The basic elements shown in Fig. 4 used to construct simple C statements. These elements

include the C character set, keywords and identifiers, constants, data types, variables, arrays,

declarations, expressions and statements. These basic elements are used to construct more

comprehensive program components.

3.1.1 HISTORY OF C

The C programming language was developed in the years 1969 to 1973, although the first

published description did not appear until the book The C Programming Language"

written by Brian Kernighan and Dennis Ritchie was published in 1978. The early

6
versions of the C language were strongly influenced by a language called BCPL which

itself was a derivative of Algol.

The early development of C was closely linked to the development of the Unix operating

system. Large portions of the code of the Unix operating system were eventually written

in C and problems encountered in transferring Unix to various computers were reflected

into the design of the C language. The modest hardware available to the Unix developers

was also reflected in the language design, most notably the use of separate library

functions for operations such as input and output. Until the early 1980s the language was

almost exclusively associated with Unix.

The widespread introduction of microprocessor based computer systems in the early

1980s also saw a rapid growth in the use of C on such systems. C compilers were known

to be small.

As early as 1982 it became clear that the informal description of the language in

Kernighan & Ritchie's book was not good enough. ANSI established a committee known

as X3J11 in 1983. This committee produced a report defining the language at the end of

1989. The report was known as X3.159 but the standard was soon taken over by ISO with

the designation ISO/IEC 9899-1990. This version of the language is known as ANSI-C to

distinguish it from the earlier version of the language described by Kernighan and

Ritchie. The earlier version of the language is known as K&R C. C++ and Objective-C

are different languages developed from C. The GNU C compiler, often known by the

command that invokes it, gcc , is public domain software available for both Unix and

MSDOS based systems. It supports a version of the language close to the ANSI standard.

7
The different milestones in C’s development as a language are listed below:

 UNIX developed in 1969 — DEC PDP-7 Assembly Language

 BCPL — a user friendly OS providing powerful development tools developed

from BCPL. Assembler tedious long and error prone.

 A new language “B” a second attempt in 1970.

 A totally new language “C” a successor to “B” in 1971

 By 1973 UNIX OS almost totally written in “C”.

3.1.2 CHARACTERISTICS OF C

C is an excellent language having a lot of characteristics. Some of its main characteristics

in brief are as follows.

1. Low Level Features: C Programming provides various low level features that are

generally provided by the Lower level languages. C is closely related to Lower

level Language such as “Assembly Language“ which use mnemonic codes.

2. Portability: This is the one of the most preferable feature of the C language. As

discussed earlier C language uses compilers which brings its portability. The

portability means it is possible for C programs to run it on different PCs or

systems.

3. Modular Programming: Modular programming is a software design technique

in which software is break down into separate parts, called modules. C Program

Consist of Different Modules that are integrated together to form complete

program

8
4. More Efficient: It is more efficient language and simpler to use. It is an ideal

language for beginners.

5. Extendibility: Ability to extend the existing software by adding new features is

called as extendibility.

6. Flexibility: ‘C’ language has right number of reverse words which allows the

programmers to have complete control on the language.‘C’ is also called as

programmer’s language since it allows programmers to induce creativeness into

the programmers.

7. Other Key Features: The following are some more features of C language.

a) C provides a wide range of Data Types and functions.

b) Various useful Control & Loop Control Statements can be implemented.

c) Contains rich set of operators.

d) C allows the user to add functions to the library.

3.1.3 IMPORTANCE OF C LANGUAGE

C is a relatively small language. C's small, unambitious feature set is a real advantage.

There’s less to learn, but it can also be a disadvantage, since it doesn't do everything for

you, there's a lot you have to do yourself.

C is sometimes referred to as a ``high-level assembly language. If you have programmed

in assembly language, you'll probably find C very natural and comfortable if you haven't

programmed in assembly language, you may be frustrated by C's lack of certain higher-

level features. If you write a C program simply and succinctly, it is likely to result in a

succinct, efficient machine language executable. If you find that the executable program
9
resulting from a C program is not efficient, it's probably because of something silly you

did, not because of something the compiler did behind your back which you have no

control over.

A programming language is a tool, and no tool can perform every task unaided. In the

same way, C does not have built-in features to perform every function that you might

ever need to do while programming.

C imposes relatively few built-in ways of doing things on the programmer. Some

common tasks, such as manipulating strings, allocating memory, and doing input/output

(I/O), are performed by calling on library functions. Other tasks which you might want to

do, such as creating or listing directories, or interacting with a mouse, or displaying

windows or other user-interface elements, or doing color graphics, are not defined by the

C language at all. You can do these things from a C program.

3.2. STRUCTURE OF A C PROGRAM

1. Program’s name, programmer’s name and objectives given in comments.

2. #include and #define statements known as preprocessor directives.

3. Declarations and definitions of global variables and declaration of function

prototype.

4. Declaration and definition of function main ( ) indicating the start of program.

5. Left delimiter (‘{‘ ) beginning of Main ( ) function.

6. Definition and initialization of local variable and declaration of function

prototype.

7. Body of statement and functions.

10
8. Right delimiter (‘}’) which marks the end of function main ( ).

9. Definition of function declared above the main ( ) function and called in the main

( ) function.

Program 1.

/* Name of Program: Program to check no. is even or odd */

/* Author’s name: ABC */

#include<stdio.h> //Preprocessor directives

#define SIZE 10

void check(int x); //Function declaration or prototype (Single line comment)

int s = 20; // Global variable declared and initialized

void main( )

{ // left delimiter or brace indicate the beginning of function

int n; //local variable to main( )

int a[SIZE];

printf(“Enter any no.\n”); //output statement

scanf(“%d”,&n); // input statement

check(n); // function calling

} // right delimiter or brace indicate the end of function

void check(int x) // function definition

if (x%2= =0)

printf(“Entered no. is EVEN”);

else
11
printf(“Enterd no. is ODD”);

1. Program’s Name, Author’s Name and Objectives: Program start with program name

and author’s name. It also describes the purpose of the program in one or two lines for better

documentation.

2. Comments: C Language uses two types of comments.

 Single Line Comment ( // ………………… )

Starts with ‘// ‘(double back slash) and end upto end of line.

 Multi Line Comment (/*………………... */)

Start with ‘/*’ and end with ‘*/’ it contains more than one line as part of comment.

3. Preprocessor Directives: #include<stdio.h> and #define SIZE 10 are preprocessor

directives. A preprocessor directives start with a symbol hash(#) . Directives are instructions

to computer to do something on the text of the program before compilation.

#include<stdio.h>instructs the compiler to insert the stdio.h (header file) file in the source

file. #define SIZE 10 is used to define symbolic constant.

4. Declaration of Global Variables: There are mainly two types of variables: Local &

Global. Global variables and functions are defined and declared outside the main function.

Variable‘s’ and function void check(int x); are global declaration.

12
5. Function Main ( ): Every Program in C have at least one function i.e. main( ). Program

execution start with the first statement of the main( ) and end with the last statement of the

main ( ).

6. Left (‘{‘) and Right (‘}’) Delimiter or Curly Braces : Left brace indicates the beginning

of the function and Right brace indicates the end of function. The left brace(‘{‘) along with

the right braces (‘}’) enclose the entire body of executable statements and functions.

7. Declaration of Function : A Function is a self contained, independent and logical

sequence of declarations and statements which performs a specific task and provides the

results to the main program which calls the function. Declaration of function tells about

function: name of function, return type of function , no. of arguments and their types.

8. Body of Statement and Functions: In between left brace (‘{‘) and right brace(‘}’) in

main ( ) function represent the body of function main( ).

9. Called Functions: These perform a specific task. In the above program void check(int

x) is a called function because main( ) function is calling check ( ). Body of called

function includes the statement of check( ) that represent the task of check( ) function

performed.

3.3. ELEMENTS OF C

The following sections and subsections discusses about the various elements of C

language.

13
3.3.1 THE C CHARACTER SET

C uses:

uppercase letters A to Z,

lowercase letters a to z,

digits 0 to 9 and

special symbols

! *+\”< #) = ; } >

^ ( ],{ ?&-[ :‘ /%

_ = = ~ . (blank) < >

3.3.2 IDENTIFIERS AND KEYWORDS

Identifiers are names given to various elements of a program, such as variables,

functions and arrays.

Rules for identifiers:

 First character should be a letter means not start with digit.

 Anyone can use both uppercase and lowercase letters. But uppercase and

lowercase letters are distinct. e.g. AGE and age are not same.

 Any identifier can start with underscore character, though this is not a good

programming practice.

 Special symbol except underscore are not allowed

 Keyword cannot use as identifier in any case.

14
Valid identifiers are:

She, Z02 , computer_02 , _wind Classes , areal , interest_rate , PERIOD

Invalid identifiers are:

nd
2 , “y”, ship-no, flag error

An identifier can be very long. Some implementation of C recognizes only the

first eight characters, though ANSI standard recognizes 31 characters.

Keywords are certain reserved words that have standard, predefined meanings in C.

These keywords can be used only for their intended purpose, they cannot be used as

programmer-defined identifiers. The standard keywords are listed below in Table 1.

Table 1. List of Keywords

NOTE: It should be kept in mind that keywords are all in lowercase.

3.3.3 CONSTANTS

Constant in C refers to fixed values that do not change during the Program execution.

Declaration of Constant: A declaration has following Syntax to declare a constant:

Const <data type> <constant name>=value;

15
e.g.

const int x=50;

C supports four types of constants:

 Integer Constant

 Character Constant

 String Constant

 Floating-point constant

As the name suggests integer & Floating point constants represent numbers. They are

often referred to collectively as numeric-type constants. The numeric-type constants must

follow the following rules:

 Commas and blank spaces cannot be included within the constant.

 The constant can be preceded by a minus(-) sign if desired.

An integer constant refers to a sequence of digits. There are three types of integers:

 Decimal

 Octal and

 Hexadecimal

Decimal Integer Constant can consist of any combination of digits 0 through 9,

preceded by an optional - or + sign. e.g. :

123, – 345, 0, 5324, +62

16
Octal Integer Constant can consist of any combination of digits 0 through 7 with a

leading o. e.g. :

0, 01, 0456, 05555,

Hexadecimal Integer Constant must begin with either 0x or 0X. It can then be followed

by any combination of digits 0 through 9 and A through F (either upper or lowercase).

Letters A through F represent the numbers 10 through 15 respectively. e.g.:

0x2, 0xaf, 0xbc5, 0x

Floating Point Constant is a base-10 number that contains either a decimal point or an

exponent (or both). Floating point Constant represent in exponential form like:

e.g. mantissa e exponent

0. 1, 0.3, 1.555E+8 .121265e18

If an exponent is present, its effect is to shift the location of the decimal point to the right

if the exponent is positive or to the left if the exponent is negative.

Character Constant is a single character, enclosed in single quotation marks. e.g. :

‘A’, ‘y’ ‘4’ ‘$’

Each character constant has its equivalent ASCII value like ‘A’ has

65, ‘y’ has 121 ‘4’ has 52 & so on.

17
String Constant consist of any number of consecutive characters enclosed in double

quotation marks. e.g :

“Red’’, “Mary Marry quite contrary”, “2*(J+3)/J” and ‘‘ ’’

“A” and ‘a’ are not same. Firtst one is string constant and later one is character constant.

3.3.4 VARIABLES

A Variable is a name given to a variety of values or we can say variable is a name that

represents a storage location in the computer memory. The information which is stored at

that location is known as the value of the variable.

e.g. variable x starting value is 10 shown in Fig. 5 and later some statement value is 20

shown in Fig. 6 so we can say x value vary from 10 to 20.(Changeable during various

part of program)

int x;

x=10;

------

------

18
Fig. 5. Variable X in Memory with value 10

-------

-------

-------

x=20

Fig. 6. Variable x in memory with changed value 20

Declaration of Variable: A declaration associates a group of variables with a specific

data type. In ‘C’ language all variables must be declared before they appear in executable

statements. A declaration has following Syntax to declare a variable

<data type> <variable name>;

19
e.g

int x,y, z;

float p,q,r;

Thus x, y, z are declared to be integer type variables, p, q, r are floating point variables

The programmer can also write above declarations in the following manner:

int x;

int y;

int Z;

float p;

float q;

float r;

3.4. DATA TYPES

C supports different types of data, each of which may be represented differently within

the computer’s memory. There are three type of data types shown in Fig. 7:

 Primitive or built in data types

 Derived data types (Explain in later lesson)

 User defined data types (Explain in later lesson)

20
Fig. 7. Types of Data Type

Primitive or built in data types: it is further divided in two parts shown in Fig. 8:

1. Integral type

2. Floating point type

Integral Types includes integer and character type data types and Floating point type

includes float, double and long double type data types.

1. Integer types: An integer occupies one word space and the size of the word

varies with the machine, the storage of integer is totally dependent on the

computer. E.g. a 16 bit word length , size of integer is limited to the range from

-215 to 215-1 i.e. -32768 to +32767. on the other hand for a 32 bit word length the

size is from -231 to 231-1 i.e. -2147483648 to 2147483647. in C, there are three

classes in which integer can be stored. These are short int, int and long int for

both signed and unsigned forms. A short int may require less space than an

21
ordinary int or it may require the same memory space as that required by an

ordinary int.

2. Floating point types: When floating point or real numbers are stored in 32 bits

there are 6 bits of precision. In C, floating point numbers are denoted by the

keyword float. If a float number cannot provide sufficient accuracy, the number is

represented by the keyword double.

3. Character types: char types represented individual character; therefore, a char

type requires 1 byte memory. The range of signed char is from -128 to 127

whereas the range of unsigned char is from 0 to 255.

Fig. 8. Types of Built in Data Type

Table 2 show the size and range of data types.

22
Data Types
Type Size (in bytes) Range
unsigned char 1 0-255
char 1 -128 to 127
unsigned short 2 0 to 65535
short 2 -32768 to 32767
unsigned int 2 0 to 65535
int 2 -32768 to 32767
unsigned long 4 0 to 4294967295
long 4 -2147483648 to 2147483647
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7e+308
long double 10 3.4E-4932 to 1.1E+4932

Table 2. Data types with range

3.5 ESCAPE SEQUENCES

C also uses some combinations of these characters such as \t, \n to represent special

conditions such as horizontal tab and newline respectively. These character combinations

are called escape sequences. Each escape sequence represents a single character, although

it is a combination of two or more characters.

Escape Sequence Function

\n Newline

\t Horizaontal tab

\v vertical tab

\b backspace

\a bell

\r carriage return

\f form feed

\0 NULL

\’ single quotation mark

23
\”” double quotation mark

\? Question mark

\\ backslash

\ddd 1 to 3 digits in octal code

\xhh 1 to 2 digit in hexadecimal code

3.6 C INSTRUCTIONS

Different types of constants, variables and keywords combined to form instructions.

 Type Declaration Instruction - It declare the type of variables used in program.

 Input/Output Instruction - it performs the function of getting input from keyword

and putting the output to the screen.

 Arithmetic Instruction - it performs the arithmetic operations.

 Control Instruction - it control the sequence flow of execution.

3.7 INPUT / OUTPUT FUNCTIONS

Input Data- Scanf Function : It is used to input any type of data from keyboard.

Syntax:

Scanf(“format specifier”, &variable name);

More about Input functions is discussed in chapter 4.

Output Data- Printf Function : It is used to output any type of data on Screen/Printer.

Syntax:

printf(“ string format specifier”, variable name);

More about Input functions is discussed in lesson 4.

24
Example 1: Which of the following are valid variable name and why

1. void // invalid, because it is a keyword

2. 456 // invalid, never start with digit

3. interestPaid // valid

4. 12age //invalid, never start with digit

5. age12 // valid

6. name of book // invalide, because of spaces

7. name_of_author //valid

Example 2: Point out the errors if any

1. name=’amar’ //error, because of single quotes

2. string1=”123” // no error

3. 3.14*r*r =area /* error, because of expression with

operators in left

a. hand side of assignment operator*/

4. area=3.14*r*r // no error

5. si=principal * rate * time/100 //no error

Example 3: What would be output of the following program segment?

Int i=3;

int j=4,k,l;

float a,b;

k=i / j * j;

25
l=j / i * i;

a=i / j * j;

b=j / i * i;

printf (“\n %d \n %d \n %f \n %f \n ”,k ,l ,a ,b);

OUTPUT:

0.000000

3.000000

Program 1: A Program to show input of various types

/* A Program to show input of various types */

#include<stdio.h>

#include<conio.h>

void main()

int numi;

float numf;

char ch;

char str[20];

clrscr();

printf("Enter any integer");

26
scanf("%d",&numi);

printf("Enter any float no.");

scanf("%f",&numf);

fflush(stdin);

printf("Enter any character");

scanf("%c",&ch);

printf("Enter any string");

scanf("%s",&str);

printf("Entered integer is=%d \nfloat is=%f \ncharacter is=%c \nstring

is=%s",numi,numf,ch,str);

getch();

OUTPUT:

Enter any integer10

Enter any float no.10.5

Enter any characterx

Enter any stringindia.

Entered integer is=10

float is=10.500000

character is=x

string is=india.

27
Program 2: A Program to show octal and hexadecimal representation of decimal

numbers

/* A Program to show octal and hexadecimal representation of decimal no.*/

#include<conio.h>

void main()

int num;

clrscr();

printf("Enter any no.\n");

scanf("%d",&num);

printf("\nOctal representation of entered no is=%o",num);

printf("\nHexadecimal representation of entered no is=%x",num);

getch();

OUTPUT:

Enter any no.

12345

Octal representation of entered no is=30071

Hexadecimal representation of entered no is=3039

28
Program 3: A Program to show format specifier in input and output.

/* A Program to show format specifier in input and output.*/

#include<conio.h>

void main()

int numi;

float numf;

clrscr();

printf("\nEnter 4 digit integer\n");

scanf("%2d",&numi);

printf("\nEnter any float number having precision 3");

fflush(stdin);

scanf("%3f",&numf);

printf("\nEnter integer is=%d",numi);

printf("\nEnter integer is=%10d",numi);

printf("\nEnter float is=%2.2f",numf);

getch();

OUTPUT:

Enter 4 digit integer

29
10

Enter any float number having precision 3

10.5

Enter integer is=10

Enter integer is= 10

Enter float is=10.00

4. Summary

C is a general-purpose, block-structured, procedural, case-sensitive, free-flow,

portable, high-level language.

There are various C standards: Kernighan & Ritchie (K&R) C standard; ANSI

C/Standard C/C89 standard; ISO C/C90 standard; C99 standard.

ANSI C and ISO C are the most popular C standards. Most popular compilers

nowadays are ANSI compliant.

C character set consists of letters, digits, special characters and white space

characters.

Identifier refers to the name of an object. It can be a variable name, a label name, a

typedef name, a macro name, name of a structure, a union or an enumeration.

Keyword cannot form a valid identifier name. The meaning of keyword is predefined

and cannot be changed.

30
Every identifier (except label name) needs to be declared before its use. They can be

declared by using a declaration statement.

The declaration statement introduces the name of an identifier along with its data type

to the compiler before its use.

Data types are categorized as: basic data types, derived data types and user-defined

data types.

The declaration statement can optionally have type qualifiers or type modifiers or

both.

A type qualifier does not modify the type.

A type modifier modifies the base type to yield a new type.

Declaration is different from definition in the sense that definition in addition to

declaration allocates the memory to an identifier.

Variables have both l-value and r-value.

Constants do not have a modifiable l-value. They have an r-value only.

C program is made up of functions.

C program should have at least one function. A function named main is always

required.

5. Suggested Reading/Reference Material

31
1. Gottfried, Byron S., “Programming with C”, Tata McGraw Hill

2. Balagurusamy, E., “Programming in ANSI C”, McGraw-Hill

3. Balagurusamy, E., “Computing Fundamentals & C Programming”, McGraw-Hill

4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

5. Yashwant Kanetker, “Let us C”, BPB

6. Rajaraman, V., “Computer Programming in C”, PHI

6. Self Assessment Questions

1. What is identifier? What are the rules for the naming identifiers?

2. What does the C Character Set consist of?

3. What are keywords or reserved words

4. What is constant? List different types of constants.

5. What is Variable? Differentiate variable with constant with example.

6. What is data type? Explain different types of data type available in c with example.

7. How many types of instruction used in c Program Explain with example.

8. What are escape sequence? List out few escape sequences.

9. What are the steps to create a Complete C Program?

10. What are the tasks performed by input-output functions.

11. In which preprocessor directive the prototype of scanf function is available.

32
Lesson 4:

Operators and Input/output

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1 Operators

3.1.1 Arithmetic Operators

3.1.2 Relational Operators

3.1.3 Logical Operators

3.1.4 Assignment Operators

3.1.5 Bitwise Operators

3.1.6 Conditional Operator

3.2 Precedence (priority) and Associativity of operators

3.3 Library Functions

3.4 Input and Output

3.4.1 Formatted Input and Output

3.4.2 Non-Formatted Input and Output

4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

2
1. Introduction

In the last lesson, you have learned about the history of C language and its importance.

Further, you have also learned about the basic elements of C language and the structure

of a typical program in C language. You know that the processing of data is essential part

of program. Processing involves manipulating of data by different operators like unary

and binary operators, assignment operators, bit wise operators, relational operators and

logical operators.

2. Objectives

After working through this lesson you should be able to:

1. Understand the operands, operators and expressions.

2. Understand the Simple and compound expressions.

3. Understand the Precedence and associativity of operators.

4. How operators are classified?

5. Understand the implicit and explicit type conversions.

6. Understand the various I/O functions.

3. Presentation of Contents

3.1 OPERATORS

Operators are those which operate on operands and form a expression. The data items on

which operators act upon are called operands. Binary operators (e.g. + operator) requires

3
two operands while Unary (++ Operator) require only one operand.

There are following types of operators:

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operator

5. Bit wise Operators

6. Conditional Operator

3.1.1 ARITHMETIC OPERATORS

There are five main arithmetic operators in ‘C’. They are

Operators Function

+ additions

- subtraction

* multiplication

/ division

% remainder (also known as modulus operator)

 Operands can be integer, floating-point or character type.

 The modulus operator requires that both operands be integers & the second

operand be nonzero.

4
 The division operator (/) requires that the second operand be nonzero.

 Division of one integer quantity by another is referred to as integer division. With

this division the decimal portion of the quotient will be dropped.

 If division operation is carried out with two floating- point numbers, or with one

floating-point number. & one integer, the result will be a floating-point quotient.

e.g. if x=20 & y=10 then :

x+y 30

x-y 10

x*y 200

x/y 2

x %y 0

 If one or both operands represent negative values, then the addition, subtraction,

multiplication and division operations will result in values whose signs are

determined by the usual rules of algebra.

 In case of % operator when one of the operands is negative then the sign of first

operand whether + or – will be the sign of result.

1. Conversion & Casting operator

a) Conversion: Operands that differ in type may undergo type conversion before the

5
expression takes on its final value. The final result has highest precision possible,

consistent with data types of the operands. The following rules apply when

neither operand is unsigned.

e.g. Right Hand Side of an Expression

Expression Result

5/2 2

5/2.0 2.5

5.0/2 2.5

5.0/2.0 2.5

When we assign this result into Left Hand Side of Expression

Expression Result on RHS LHS (Int Operand)

5/2 2 2

5/2.0 2.5 2

5.0/2 2.5 2

5.0/2.0 2.5 2

Expression Result on RHS LHS (Float Operand)

5/2 2 2.0

5/2.0 2.5 2.5

5.0/2 2.5 2.5

6
5.0/2.0 2.5 2.5

• If one operand is a floating point type and the other is a char or an int, the

char/int will be converted to the floating point type of the other operand and the

result will be expressed as such. So, an operation between an int and a double will

result in double.

• If both operands are floating-point types with different precisions, the lower-

precision operand will be converted to the precision of the other operand and the

result will be expressed in this higher precision.

b) Casting operator: The value of an expression can be converted to a different data

type if desired. The ‘C’ programmer has the choice of explicitly cast one type of

operand in to another type of operand and this may be accomplished using what is

called the casting operator. The name of data type to which the conversion is to be

made is enclosed in parentheses and placed directly to the left of the value to be

converted; the word “cast” never is actually used. The example of type casting is

as follows:

int a=17;

float b;

b=(float)a+ 11.0;

The cast operator converts the value of int a to its equivalent float representation

7
before the addition of 11.0 is carried out. The cast operator can be used on a

constant or expression as well as on a variable

e.g. (int) 7.179

(float)(a+4)

2. Unary Operators: ‘C’ includes a class of operators that act upon a single operand to

produce a new value. Such operators are known as unary operators. Unary operators

usually precede their single operands, though some unary operators are written after

their operands.

The most common unary operator is unary minus, where a minus sign precedes a

numerical constant, a variable or an expression.

e.g.

-5,-10, -20(numbers)

x=-y(variable) Of all the arithmetic operators, the unary minus has the

highest precedence level.

y=x+z* -b;

in the above expression, evaluation commences with the unary minus, which

negates the value of b. Then z is multiplied by –b, and finally the addition takes

place. The result is stored in the variable y. So, the use of parentheses to separate

8
the two adjacent operators and avoid possible confusion.

Y=x+z*(-b);

Two other commonly used unary operators are:

 increment operator ++ (increases its operand by one)

 decrement operator - - (decrease its operand by one)

These operators used in two ways:

Pre Increment (e.g. ++x )

Post Increment (e.g. x++)

Pre Decrement (e.g. - -x)

Post Decrement (e.g. x- -)

If the operator used before operand, then the value of operand will be altered before

it is used for its intended purpose within the program. If, however the operator used

after the operand then the value of the operand will be changed after it is used.

Another unary operator is the sizeof operator. This operator returns the size of its

operand, in bytes. This operator always precedes its operand.

e.g.

int x;

float y;

sizeof (x); // it will return 2

9
sizeof (y); // it will return 4

3.1.2 RELATIONAL OPERATORS

Relational operators are symbols that are used to test the relationship between two

variables, or between a variable and a constant. We have following relational

operators listed below:

Operator Description

> greater than

< less than

!= not equal to

>= greater than or equal to

<= less than or equal to

== Equality operator

Let us understand operations of these relational operators with the help of an example:

x=2, y=3, z=4.

x<y (2<3) true 1

(x+y) >=z ((2+3)>=4) true 1

5>=4

(y+z)>(x+7) ((3+4)>(2+7)) false 0

10
(5>9)

z!=4 (4!=4) false 0

y ==3 (3==) true 1

Here, true or false represents logical interpretation and they have values 1 and 0

respectively.

3.1.3 LOGICAL OPERATORS

There are two logical operators in C language, they are and, or. They are represented by

&& and !! respectively.

&& AND (Logical AND)

|| OR (Logical OR)

The result of a logical AND (&&) operation will be true only if both operands are true,

whereas the result of a logical OR ( || ) operation will be true if either operand is true or if

both operands are true.

Let us understand it, with the help of a following example:

Suppose x=7, y=5.5, z= 'w'

Logical expressions using these variables are as follows:

(i) (x>=6) &&(z= =’w’) true 1

(x>=6) is true because (7>=6) and

11
z==’w’ also true because (‘w’==’w’) both expression are true so final result is true.

(ii) (x<=6) && (z=='w') false 0

In this case first expression (x<==6) is false and second expression is (z==’w’) is

true. One is false and one is true so according to Logical AND(&&) final result is

false

(iii) (x<=6) || (z==’w’) true 1

In this case first expression (x<==6) is false and second expression is (z==’w’) is

true. One is false and one is true so according to Logical OR (||) final result is

true.

3.1.4 ASSIGNMENT OPERATORS:

There are several different assignment operators in C. All of them are used to form

assignment expression, which assign the value of an expression to an identifier. The most

commonly used assignment operator is =. The assignment expressions that make use of

this operator are written in the form:

Identifier = expression

Where identifier generally represents a variable and expression represents a constant, a

variable or a more complex expression.

Assignment operator = and the equality operator == are distinctly different. The

assignment operator is used to assign a value to an identifier, whereas the equality

operator is used to compare two expressions have the same value. These two operators

12
cannot be used in place of one another.

Multiple assignments of the form Identifier 1= identifier 2 = - - - -= expression are

allowed in ‘C’.

In such situations, the assignments are carried out from right to left.

Let us understand this with the help of following example

x=y=10 (x and y are integer variables)

This will cause the integer value 10 to be assigned to both x and y. Similarly,

x=y=10.5 will cause the integer value 10 to be assigned to both x and y, truncation

occurs when the floating point value 10.5 is assigned to the integer variable y.

‘C’ also contains the additional assignment operators. These are also called short hand

arithmetic assignment operator

+= , -= , *= , /=, &=, %=

expression1 += expression2 is equal to

expression1= expression1 + expression2

3.1.5 BITWISE OPERATORS

As we know that computers understand only binary number system for processing and

storage. A bit is the smallest unit of memory.

13
8 bit = 1 byte

1024 bytes = 1 kilobyte

1024 kilobytes = 1 megabyte

1024 megabyte = 1 gigabyte

This numbering system has a base two. The base two consists of two digits 0 and 1. in

this system, starting from right side, the place value of each bit is an increasing order of

power 2.

e.g.

32 16 8 4 2 1 (place value)

1 0 1 0 0 1 (binary value)

1*1 +0*2 + 0*4 +1*8 +0*16 +1*32

1 +0 +0 +8 +0 +32

41 is the decimal equivalent of binary no. 101001

To convert decimal no. into binary equivalent like :

Operation Quotient Remainder

41/2 20 1

20/2 10 0

10/2 5 0

5/2 2 1

14
2/2 1 0

1/2 0 1

Starting from the bottom, collect all remainder 101001 is the binary equivalent of decimal

no 41.

To act on binary bits, C provide following operators:

- ones compliment

<< Left shift of bits

>> Right shift of bits

& and of bits

| inclusive or of bits

^ exclusive or of bits (xor)

1. The Compliment Operator (-) : This operator change all 1’s to 0 and all 0’s to I.

2. The Left Shift Operator (<<): This operator shifts the bits to left by a specified

number, filling any vacated bits with zeros.

e.g

int x=8;

Statement Before Left Shift After Left Shift

x<<2 x=00001000 00100000

x<<3 x=00001000 01000000

15
3. The Right Shift Operator (>>) : This operator shifts the bits to Right by a specified

number, filling any vacated bits with zeros.

e.g

int x=8;

Statement Before Left Shift After Left Shift

x>>2 x=00001000 00000010

x>>3 x=00001000 00000001

4. The AND Operator (&) : This operator compares two operands bit by bit and if both

bits are 1’s the result is 1 otherwise in all other cases the result is zero.

e.g.

x y x&y

0 0 0

0 1 0

1 0 0

1 1 1

16
Application of and (&) operator

00010011 Decimal no. 19

00010101 Decimal no. 21

--------------

00010001 Decimal no. 17

5. The Inclusive OR Operator (|) : This operator compares two operands bit by bit and

if either of the corresponding bit is 1 the result is 1 otherwise the result is zero.

e.g.

x y x|y

0 0 0

0 1 1

1 0 1

1 1 1

Application of inclusive or (|) operator

00010011 Decimal no. 19

00010101 Decimal no. 21

--------------

17
00010111 Decimal no. 23

6. The Exclusive OR Operator (^) : This operator compare two operands bit by bit and

if one and only of the corresponding bit is 1, the result is 1, otherwise the result is 0.

e.g.

x y x^y

0 0 0

0 1 1

1 0 1

1 1 0

Operation of exclusive or (^) operator

00010011 Decimal no. 19

00010101 Decimal no. 21

--------------

00000110 Decimal no. 6

3.1.6 CONDITIONAL OPERATOR

It is the only ternary operator available in C. Its syntax is

Expression 1 ? expression 2 : expression 3

18
It is discussed in detail in Lesson 5.

3.2 PRECEDENCE (HIERARCHY) AND ASSOCIATIVITY OF OPERATORS

Precedence refers to the definite order in which the operands are evaluated. Associativity

specifies the order in which several operators with equal precedence are evaluated, either

from right to left or from left to right. Where several operators appear in a line, they equal

precedence (priority) and are evaluated according to their associativity.

Precedence in higher order first and Associativity table given below:

Category Operators Associativity

Function, Array, ( ) [ ] , ----> Left to Right

Structure member,

Pointer to structure member

Unary operators - , ! , &, --, ++, sizeof, Right to Left

Multiply, Divide and Remainder *, / ,% Left to Right

Add and Subtract +, - Left to Right

Bitwise Shift Operator <<, >> Left to Right

Relational Operators (inequality) <>, <=, >= Left to Right

Relational Operators (equality) ==, != Left to Right

Bitwise AND & Left to Right

Bitwise Exclusive OR ^ Left to Right

Bitwise Inclusive OR | Left to Right

Logical AND && Left to Right

19
Logical OR || Left to Right

Conditional Operator ?: Right to Left

Assignment Operators =, *=, /=, %= Right to Left

+=,-=, <<=, >>=

&=, |=, ^=

Comma Operator , Left to Right

The operators within C are grouped hierarchically according to their order of evaluation

known as precedence. Obviously operations with a higher precedence are carried out

before operations having a lower precedence. The natural order can be altered by making

use of parentheses.

The operators *, / and % have higher precedence than + and -. In other words,

multiplication, division and remainder operations will be carried out before addition and

subtraction.

Another important point to consider is the order in which consecutive operations within

the same precedence group are carried out. This is known as associativity. Within each of

the precedence groups described above, the associativity is left to right. In other sense,

consecutive addition and subtraction operations are carried out from left to right, as are

consecutive multiplication, division and remainder operations.

e.g.

Let

20
a=5, b=10, c=15;

a+b/c+b*c-a

(i) 5+10/15+10*15-5

In the given expression, /, * have higher precedence than + and -. But / and * have the

same precedence level. Then we see their associativity and associativity of that level is

left to right means which operator appears first from the left evaluate first. So division is

done first because division has a higher precedence than addition.

(ii) 5+0+10*15-5 (10/15=0 because both are integer and result will be integer) after

that multiplication is done.

(iii) 5+0+150-5 after that addition is performed.

(iv) 5+150-5

(v) 155-5 and at last subtraction will performed.

150

3.3 LIBRARY FUNCTIONS

Library functions carry out various commonly used operations or calculations. A library

function is accessed simply by writing the function name, followed by a list of arguments

that represent information being passed to the function. The arguments must be enclosed

in parentheses and separated by commas. The arguments can be constants, variable

names or more complex expressions. The parentheses must be present, even if there are

21
no arguments. This information is generally stored in special files supplied with the

compiler. Thus, the required information can be obtained simply by accessing these

special files. This is accomplished with the preprocessor statement.

# include <filename>

The list of some commonly used library functions are:

abs(i) to determine absolute value of i.

exp(i) raise e to the power i.

log(d) determine natural logarithm of d.

pow(d1,d2) returns d1 raised to the d2 power

putchar(c) send a character to the standard output device

sqrt(d) return the square root of d.

You can see rest of the library functions available in C in Help topic of ‘C’.

3.4 INPUT AND OUTPUT

The C language provides several functions that give different levels of input and output

capability. These functions are, in most cases, implemented as routines that call lower

level input/output functions.

The input and output functions in C are built around the concept of a set of standard data

streams being connected from each executing program to the basic input/output devices.

These standard data streams or files are opened by the operating system and are available

to every C to use without having to open or close the files. These standard files or streams

are called:
22
- stdin : connected to the keyboard

- stdout : connected to the screen

- stderr : connected to the screen

The input/output functions fall into two categories, Formatted display and read

functions, and Un-formatted display and read functions.

3.4.1 FORMATTED INPUT/OUTPUT

Formatted output converts the internal binary representation of the data to ASCII

characters which are written to the output file. Formatted input reads characters from the

input file and converts them to internal form. Formatted I/O can be either "Free" format

or "Explicit" format. Two commonly used formatted Input/output functions are as

follows.

1. scanf Function: It is used to input any type of data from keyboard.

Syntax:

Scanf(“format specifier”, &variable name);

Where format specifier is a list of format specifiers indicating the format and type of

data to be read from the keyboard and stored in the corresponding address. There must

be the same number of format specifiers and addresses as there are input fields.

scanf returns the number of input fields successfully scanned, converted, and stored. The

return value does not include scanned fields that were not stored.

The format specifier is in the form:

%[*][width][F|N|h|l|L] type

23
1 Percent(%): it marks the beginning of format specifications.

2 Asterisk (‘*’) : it called and optional suppression character. It will read the

next input filed but input field will not be stored at address of the argument. It

will suppress assignment of the next field.

3 Width specifier: it is also an optional component. It controls the maximum

number of character that will be inputted from the current input filed. It may

read less digits if it recognizes white space or unconvertible character. E.g. 20

25 it will read only 20 because of white space between 20 and 25.

4 Pointer size modifier: F and N are optional size modifier

5 Argument type modifier: the h, l, L are optional argument type modifier. ‘h’

indicates short int. ‘l’ modifies integer and floating point quantities if the type

is int it makes is long int. if the type is float then it specifies it double. ‘L’

indicates a long double if the type is floating type.

6 Type conversion character.

Type Input Output argument

d Decimal Integer Pointer to int

D Decimal integer Pointer to Long

i Decimal, octal, or Pointer to int hex. integer

I Decimal octal, or Pointer to long hex. integer

o Octal integer Pointer to int

O Octal integer Pointer to long

24
u unsigned Decimal Pointer to unsigned int integer

U unsigned Decimal Pointer to unsigned long integer

x Hex. Integer pointer to int

X Hex. Integer pointer to long

f Floating point Pointer to float

e Floating point Pointer to float

g Floating point Pointer to float

E Floating point Pointer to double

G Floating point Pointer to double

c character pointer to character

s string pointer pointer to array of character

% % character No conversion with “%%” the

second character is stored.

n none it stores the no. of character read

successfully up to the %n.

e.g.

scanf(“%d”,&x); // read integer and store at address of x.

scanf(“%D”,&y) // read signed long number and store it at address of y.

scanf(“%d%d”,&x, &y); //read two integer and store at address of x & y

resp.

&x); /*read not more than 5 digits of integer type value and store at address of x. */

scanf(“%f”,&z); //read a floating value and store at address of z.

25
scanf(“%c”,&ch); //read a character and store at address of ch.

scanf(“%u”,&a); // read an unsigned int type value and store at address of a.

scanf(“%U”,&b); // read an unsigned long value and store at address of b.

scanf(“%s”,name); // read string or array of character,

NOTE: absence of ampersand (&) here

Conversion specification for char type

%c is used for reading a character.

Conversion specification for int type

Data Types Conversion Specification

Unsigned decimal int %u

Signed decimal int %d or %i

Unsigned long %lu or %U

Long %ld or %D or %I

Conversion specification for float and double types

Data Types Conversion Specification

float %f

double %lf

long double %LF

Data in exponential form

float %e

float %g

26
double %le or %E or %G

long double %Le or %Lg

Conversion specification for octal and hexadecimal numbers

Data Types Conversion Specification

Hexadecimal

int %x or %i

long %x or %lx or %I

Octal

int %o or %i

long %O or %lo or %I

2. printf Function: It is used to output any type of data on screen.

Syntax:

printf(“string format specifier”, variable name);

Where format is composed of literal text, escape sequences used as carriage control, and
format specifiers for conversion of data in the arguments to a display format. This
function returns the number of characters printed.

printf() returns the number of bytes output. In the event of error, printf returns EOF.

Format specifier is in the form :

%[flags][width][.precision][F|N|h|l|L] type

1 Percent(%): it marks the beginning of format specifications.

27
2 Flags: it specifies parameters for output justification (left or right), decimal

points, signs etc.

3 Width specifier: it is also an optional component. It indicates the minimum no. of

character to print padding left over places with blanks or zeros.

4 Precision specifier: it specifies maximum no. of character to print for characters

and minimum no. of digits to print for integers.

5 Input size modifiers (N, F, H, l, L): they mean the same as scanf() function wih

minor difference.

6 Conversion type character :

Type Input argument Output format

d Integer signed decimal int

i Integer signed decimal int

o Integer unsigned octal int

x Integer unsigned hex. int with A through F

X Integer unsigned hex. int with A through F

f Floating point signed decimal of the form [-]ddd….ddd

e Floating point signed scientific of the form[-]dd…ddd[+/-]ddd

g Floating point signed in either e or f from depending on size

E Floating point e form with E as exponent

G Floating point g form with E as exponent

c character single character

s string pointer display character until NULL is reached

28
% none % character

n pointer to int stores the no. of characters displayed.

P pointer display near pointers as YYYY(offset only and far

pointer as XXXX:YYYY(segment offset)

FLAGS:

Character output format

- data begins from left (left justified)with spaces to right

+ right justified and it show leading sign ‘+’ or ‘-’

space right justified, it will omit ‘+’ show ‘-’ if value is negative.

# it indicates the alternate form of conversion.

e.g. in case of type x or X, 0x or 0X will be prefixed.

Width specifer: In scanf() there is only one type of width specifier(n). in the printf()

there are three types of optional width specifiers.

e.g.

int x=578;

printf(“%8d”,x); // bbbbb578(no of character less than width so left out places filled

with blanks.)

printf(“%2d”,x); // 578 (no of character more than width so all character will be

displayed.)

printf(“%08d”,x); // 00000578 (left out spaces filled with zeros.)

29
printf(“%*d”,8,x); // bbbbb578 (* specifies the width specifier which is given just

before the actual argument. )

3.4.2 UNFORMATTED INPUT AND OUTPUT

Unformatted Input/Output is the most basic form of input/output. Unformatted

input/output transfers the internal binary representation of the data directly between

memory and the file. The most commonly used unformatted input/output functions are as

follows:

1. puts Function: It displays a string literal or a stored character string on the screen. The

function automatically carriage returns and line feeds at the end of the display. The string

can contain escape sequences but not format specifiers.

int puts( const char *s );

On successful completion, puts () returns a nonnegative value. Otherwise, it returns a

value of EOF. e.g.

#include "stdio.h"

int main()

char name[30];

printf("\nEnter your name:");

gets(name);

printf("\nHello ");

30
puts(name);

return 0;

2. gets Function: It reads characters from the keyboard and stores them in a passed

character array. The reading of keyboard is terminated when the '\n' (RETURN/ENTER)

key is pressed.

char *gets( char *s );

On success, gets() returns the string argument s; it returns NULL on end-of-file or error.

e.g.

#include "stdio.h"

int main()

char name[30];

printf("\nEnter your name:");

gets(name);

printf("\nHello %s",name);

return 0;

3. putchar Function: It writes a character to the stdout data stream.

int putchar( int c );

31
On success, putchar() returns the character c. On error, putchar() returns EOF.

4. putch Function: It writes the character directly to the screen. This function is

available only on PC based compilers.

int putch( int c );

On success, putch returns the characer printed, c. On error, it returns EOF. e.g.

#include "stdio.h"

int main()

int c;

c = 'A';

putchar(c);

putch(c);

return 0;

OUTPUT

AA

5. int getchar( void ); int getch( void ); int getche( void );

32
getchar() reads a single character the from the input data stream; but does not

return the character to the program until the '\n' (RETURN/ENTER) key is

pressed.

getch() reads, without echoing, a single character from the keyboard and

immediately returns that character to the program; available only on PC

compilers.

getche() reads, with echo, a single character from the keyboard and immediately

returns that character to the program; available only on PC compilers.

e.g.

#include "stdio.h"

int main()

int ch;

printf("\nContinue(Y/N)?");

ch = getchar();

return 0;

OUTPUT

Continue(Y/N)?Y < RETURN >

33
Program 1: Write a Program to show operators and expression

/* A Program to show operators and expression.*/

#include<stdio.h>

#include<conio.h>

void main()

int num1,num2,sum,sub,mul,div,rem;

clrscr();

printf("Enter any two nos.");

scanf("%d%d",&num1,&num2);

sum=num1+num2;

sub=num1-num2;

mul=num1*num2;

div=num1/num2;

rem=num1%num2;

printf("sum=%d \nsub=%d \nmul=%d \ndiv=%d \nrem=%d", sum, sub,

mul, div, rem );

getch();

OUTPUT:

Enter any two nos.10

34
3

sum=13

sub=7

mul=30

div=3

rem=1

Example 1. Find out the value of following if x=5 and y = 3:

i) x+y // 8

ii) x–y // 2

iii) x*y // 15

iv) x/y // 1

v) x%y // 2

Example 2. Solve the following expression if x=5, y=3, z=2, where x ,y and z are

integers:

i) x*y/z–z; // 5

ii) (x/z)*y–y; // 3

iii) x+y*z–y; // 8

Example 3. Find out the true or false from the following:

35
i) 19<=15 // false

ii) 19>=11 // true

iii) -19<=0 // true

iv) 19<=11+8 // true

v) 11+8==13+6 // true

Example 4. What would be output of the following program segment.

a)

Int x;

X = 4;

printf(“x =%d \n”, x);

printf (“x =%d\n”, ++x);

printf (“x =%d\n”, x++);

printf (“x =%d\n”, x);

OUTPUT:

b)

36
int x,y,z;

x=4;

y=6;

z=++x + y++;

printf(“x= %d \n y= %d \n z= %d “,x , y , z);

OUTPUT:

11

c)

int x ,y;

x=3;

y=++x * ++x * ++x;

printf(“y= %d\n”,y);

printf(“x= %d\n”,x);

OUTPUT:

216

37
d)

int x ,y;

x=3;

y=x++ * x++ * x++;

printf(“y= %d”,y);

printf(“x= %d”,x);

OUTPUT:

27

4. Summary

Operand is an entity on which operation is performed.

Operator specifies the operation to be performed on an operand.

Expression is made up of operand and operators.

Operands constituting an expression can be identifiers, constants or expression

themselves.

Based on the number of operators in an expression, the expressions are classified as

simple expressions and compound expressions.

Simple expressions have only one operator whereas compound expressions contain more

than one operator.

38
In a compound expression, if operators of different precedence appear together, then

operator of higher precedence operates first.

In an arithmetic expression, if the operands of a binary operator are of a different type, C

automatically applies arithmetic-type conversion to bring the operands to a common type.

The type of result of the binary operator will also be the common type.

Explicit type conversion is done with the help of a type cast operator.

Scanf Function is used to input any type of data from keyboard.

Printf Function is used to output any type of data on screen.

5. Suggested Reading/Reference Material

1. Gottfried, Byron S., “Programming with C”, Tata McGraw Hill

2. Balagurusamy, E., “Programming in ANSI C”, McGraw-Hill

3. Balagurusamy, E., “Computing Fundamentals & C Programming”, McGraw-Hill

4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

5. Yashwant Kanetker, “Let us C”, BPB

6. Rajaraman, V., “Computer Programming in C”, PHI

7. Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language

(Second edition), Prentice Hall, 1988.

8. K. N. Dey, S. K. Bandyopadhyay: C Programming Essentials, Pearson Education

India, 2010.

9. Tim Bailey: An Introduction to the C Programming Language and Software

Design

39
6. Self Assessment Questions

1. Explain different type of operators available in C.

2. What are increment and decrement operator?

3. What are postfix and prefix increment and decrement operators? Illustrate with

example.

4. Explain type conversion with example.

5. What is casting operator explain with example.

6. What is precedence and associativity of operator? Write the table of precedence

and associativity.

7. What are bit wise operators? Explain any three bitwise operators with example.

8. What is expression? How we can solve an expression with multiple operators.

40
Lesson 5:

Control Statements

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1 Control Statements

3.2 Types of Conditional Control Statements or Decision Making Statements

3.2.1. IF Statement

3.2.1.1. Simple IF

3.2.1.2. IF…ELSE

3.2.1.3. Nested IF or Nested IF…ELSE

3.2.1.4. ELSE IF Ladder

3.2.2. Switch Case Statement

3.2.3. Conditional Operator Statement

3.3. GOTO Statement

3.4. Repetition/Looping

3.4.1. WHILE Loop

3.4.2. Reverse Loop

3.4.3. DO-WHILE Loop

3.4.4. FOR Loop

3.4.5. Nested Loops

2
3.5 Jumping Out From Loop or Block (BREAK Statement)

3.6. Skipping A Part of Loop (CONTINUE Statement)

4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

1. Introduction

So far you have learnt that instructions are executed sequentially in the program. Each

instruction is executed once and only once sequentially. Programs do not change or alter

the order of execution. However, most programs require that a group of instructions be

changed order of its execution. This is known as branching and when this branching based

on any condition then it is called conditional branching and when not based on any

condition then called as unconditional branching (e.g. by using GOTO statement)

2. Objectives

After working through this lesson you should be able to:

1. Understand the control statements.

2. Understand the types of control statements like sequencing, selection and

repetition.

3. Understand the use and working of selection statements such as IF-THEN, IF-

THEN-ELSE, SWITCH-CASE etc.

3
4. Understand the use and working of repetition statements such as WHILE, DO-

WHILE and FOR.

5. Understand the use and working of CONTINUE and BREAK statements.

3. Presentation of Contents

3.1 CONTROL STATEMENTS

There are three main types of control structures

Sequence: A sequence of instructions in a sequence structure must all be carried out.

These are discussed in Lesson 2 in detail.

Selection: In a selection structure certain instructions will only be carried out IF a certain

condition is found to be true such as IF-THEN, IF-THEN-ELSE, SWITCH – CASE etc.

These are also called condition control or decision making statements.

Repetition: In a repetition structure certain instructions will be repeatedly carried out until

a condition is no longer true (DO-WHILE) or alternatively until a condition is no longer

false (DO-UNTIL). Such structures consist of a loop which takes the program back to the

top of the instructions to be repeated.

3.2 TYPES OF CONDITIONAL CONTROL STATEMENTS OR DECISION

MAKING STATEMENTS

1. If statement

2. Switch case statement

4
3. Conditional operator statement

3.2.1. IF STATEMENT

This statement can be used in four ways:

1. Simple if

2. if...else

3. nested if or nested if…else

4. else if ladder

3.2.1.1. SIMPLE IF

Statement will execute if the given expression is true. If the user wants to add more than one

statement then there must be pair of curly braces after ‘if’.

Syntax:

if (expression)

statement;

statement;

e.g.

Program 1: Program to show the use of IF statement

1 #include <stdio.h>

5
2 main()

3 {

4 int x;

5 printf(“Enter value of x:”);

6 scanf(“%d”, &x);

7 if(x = = 10)

8 printf(“The value is ok \n”);

9 printf(“Thanks for using this program\n”);

10 }

OUTPUT:

Enter value of x 10

The value is ok

Thanks for using this program

Explanation: line no. 7 if expression (x==10) is true then statement 8 is print in response

to if statement and after that statement 9 will be printed. If we want to run more than one

statement run in response to if statement then we have to enclosed the statements in curly

braces.

3.2.1.2. IF…ELSE

In this type of if statement expression or condition is evaluated and if expression or

condition evaluated to true then statement no. 1 and 2 is run and if condition evaluates to

false then statement 3 and 4 is run.

6
Syntax:

----

----

if(Expression)

statement 1;

statement 2;

else

statement 3;

statement 4;

statement 5;

----

----

e.g.

Program 2: Program to show the use of IF…ELSE statement

1. #include <stdio.h>

2. main()

3. {

4. char sex;

5. printf(“Enter sex ‘m’ for male and ‘f’ for female:”);

7
6. scanf(“%c”, &sex);

7. if(sex= =’m’)

8. {

9. printf(“you have entered”);

10. printf(“MALE \n”);

11. }

12. else

13. {

14. printf(“you have entered”);

15. printf(“FEMALE\n");

16. }

17. printf(“Thanks for using this program”);

18. }

OUPUT:

First Run

Enter sex ‘m’ for male and ‘f’ for female: m

you have entered MALE

Thanks for using this program

Explanation: in the first run of the program when user enters value ‘m’ then the condition

is true and in response to condition evaluates to true statement no. 9 & 10 is executed and

statement no. 14 & 15 is skipped due to condition evaluates to true.

In the second run of program when user enters value ‘f’ then the condition is evaluates to

8
false and in response to condition evaluates to false statement no. 14 & 15 is executed and

statement no. 9 & 10 is skipped due to condition evaluates to false.

And statement no.17 executes in both run because this statement is the other statement of

program other than if …else statements.

3.2.1.3. NESTED IF OR NESTED IF…ELSE

When a clause of the if statement may itself contain another if statement then this construct

known as nesting of if statements. Let us consider an example nested if..else statement:

Syntax:

----

----

If(Expression or condition)

if(Expression or condition)

---

---

else

---

---

9
}

else

Statement x;

Statement y;

Statement z;

e.g. if salary of female is greater than or equal to 5000 then a bonus of Rs. 500 is added to

the salary. In this case two condition will be included. first which check male or female

and second which check salary greater than or equal to 5000 or not.

e.g.

Program 3: Program to show the use of nested IF…ELSE

1. #include <stdio.h>

2. main()

3. {

4. int salary, gross;

5. char sex;

6. int bonus=0;

10
7. printf(“Enter sex ‘m’ for male and ‘f’ for female”);

8. scanf(“%c”, &sex);

9. printf(“Enter salary”);

10. scanf(“%d”, &salary)

11. if (sex= = ‘f ’) // First Condition

12. {

13. if(salary>=5000) // second Condition

14. {

15. bonus=500;

16. gross=salary+bonus;

17. }

18. else

19. {

20. gross=salary+bonus;

21. }

22. else

23. {

24. gross=salary+bonus;

25. }

26.

27. printf(“Gross salary=%d”,gross);

28. }

OUTPUT:

11
First Run

Enter sex ‘m’ for male and ‘f’ for female m [First Condition false then

control goes to outer else

(statement no. 24 )] and bonus 0

is added.

Enter salary 6000

Gross salary 6000

Second Run

Enter sex ‘m’ for male and ‘f’ for female f [First Condition true but second

false then control goes to inner

else (statement no. 24 )] and

bonus 0 is added

Enter salary 4000

Gross salary 4000

NOTE: It is very important to be sure which else clause goes with which if clause. The

rule is that each else matches the nearest if preceding it which has not already been

matched by an else. Addition of braces prevents any association between the if statement

within the braces and the else clause outside them. Even where braces are not necessary,

they may still be used to promote clarity.

3.2.1.4 ELSE IF LADDER

12
When a clause of the else statement may itself contain if statement and inner else further

contain another if and so on then this construct known as Else if Ladder.

Syntax:

----

----

If(Expression or condtion)

Statement x;

Statement y;

else

if(Expression)

---

---

else

if(Expression)

13
---

---

else

So On…

Statement z;

3.2.2. SWITCH CASE STATEMENT

The switch statement uses when we have more than two alternate to a particular problem.

It choses a particular group of statements from several available groups. The selection is

based upon the expression that is included within the switch statement.

Syntax:

---

---

switch (expression)

14
{

case constant :

statement ;

statement;

----

break;

case constant :

statement ;

statement;

----

break;

------

------

------

default:

statement ;

statement;

----

statement x;

Where

15
Expression may be of integer type and also of char type because individual characters

have equivalent integer values but not of float type.

Case Label must be a constant value and unique within a given switch statement and

precede with colon symbol. There are as many as cases. Last case is default means when

no case matches then default will execute.

Each alternative or case is composed of a group of one or more individual statements. For

each alternative (case), the first statement within the group must be preceded by one or

more case labels. The case labels identify the different groups of statements and

distinguish them from one another. Last statement of each case except default is a break

statement. When a particular case match, all the statement of matched case is executed and

control goes to the next statement immediate after the switch case statement i.e statement

x in the above syntax structure.

Thus, the switch statement is in effect an extension of the familiar if…else statement.

Rather than permitting maximum of only two branches, the switch statement permits

virtually any number of branches.

e.g.

Program 4: Program to show the use of Switch Case statement

#include <stdio.h> main()

char ch;

printf(“Enter a character”);

scanf(“%c”,&ch);

16
switch(ch)

case ’a’

printf(“vowel a”);

break;

case ‘e’ :

printf(“vowel e”);

break;

case ‘i’ :

printf(“vowel i”);

break;

case’ o’ :

printf(“vowel o”);

break;

case ‘u’ :

printf(“vowel u”);

break;

default:

printf(“you have not entered vowel, try again!”)

printf(“statement after the switch case

statement”);

17
OUTPUT:

First Run

Enter a character e [Matched case having label ‘e’ ]

Vowel e

statement after the switch case statement

Second Run

Enter a character o [Matched case having label ‘o’ ]

Vowel o

statement after the switch case statement

3.2.3. CONDITIONAL OPERATOR STATEMENT

It is a Ternary operator means it requires three operands to evaluate.

Syntax:

Expression 1 ? expression 2 : expression 3

Expression 1 is always a conditional expression, While evaluating a conditional operator

expression, expression 1 is evaluated first. If expression 1 is true, then expression 2 is

evaluated and this becomes the value of the conditional expression. If expression 1 is false,

then expression 3 is evaluated and this becomes the value of the conditional expression

For example ( i< 1) ? 0:200

i is integer variable here.

18
The expression (i<1) is evaluated first, if it is true the entire conditional expression takes

on the value 0. Otherwise, the entire conditional expression takes on the value 200.

3.3. GOTO STATEMENT

The goto statement is used to alter the normal sequence of program execution by

transferring control to some other part of the program. But it is not good practice to use

goto statement for programming. As much extent we will not use it.

Syntax:

goto label;

Label is an identifier used to label the target statement to which control will be transferred.

Control may be transferred to any other statement within the program. The target statement

must be labeled, and the label must be followed by a colon. Thus the target statement will

appear as

Label : statement ;

NOTE: No two statements have the same label

Program 5: This Program checks whether entered number is ODD or EVEN

#include<stdio.h>

#include<conio.h>

void main()

int num;

19
clrscr();

printf("Enter any number");

scanf("%d",&num);

if(num%2==0)

printf("\nNo is EVEN");

else

printf("\nNo. is ODD");

getch();

OUTPUT:

Enter any number5

No. is ODD

Program 6: This Program determines a leap year

#include<stdio.h>

#include<conio.h>

void main()

int year;

20
clrscr();

printf("Enter any year\n");

scanf("%d",&year);

if(((year%4==0)&&(year%100!=0))||(year%400==0))

printf("Year %d is a Leap Year\n",year);

else

printf("Year %d is not a Leap Year\n");

getch();

OUTPUT:

Enter any year

1996

Year 1996 is a Leap Year

Program 7: Program to check entered number is a perfect square e.g. 144

Root of 144 is 12 so 12*12=144(original no.) i.e. it is perfect square

#include<stdio.h>

#include<conio.h>

#include<math.h>

21
void main()

int num,root=0;

clrscr();

printf("Enter any no.\n");

scanf("%d",&num);

root=sqrt(num);

if((num-root*root)==0)

printf("Entered no %d is a perfect square",num);

else

printf("Entered no %d is not a perfect square",num);

getch();

OUTPUT:

Enter any no.

144

Entered no 144 is a perfect square

22
Program 8: Program of calculator by switch statement

#include<stdio.h>

#include<conio.h>

void main()

int a,b;

int ch;

clrscr();

printf("Enter two integers values\n");

scanf("%d%d",&a,&b);

printf("*******************Menu**************\n");

printf("****** 1.Addition *************\n");

printf("****** 2.Subtraction *************\n");

printf("****** 3.Division *************\n");

printf("****** 4.Multiplication*************\n");

printf("****** 5.Remainder *************\n");

printf("****** 6.Exit *************\n");

printf("press from 1 to 6\n");

scanf("%d",&ch);

23
switch(ch)

case 1:

printf("Addition=%d",a+b);

break;

case 2:

printf("Subtraction=%d",a-b);

break;

case 3:

printf("Division=%d",a/b);

break;

case 4:

printf("Multiplication=%d",a*b);

break;

case 5:

printf("Remainder=%d",a%b);

break;

case 6:

exit(0);

24
break;

default:

printf("invalid choice\n");

getch();

OUTPUT:

Enter two integers values

10

*******************Menu**************

****** 1.Addition *************

****** 2.Subtraction *************

****** 3.Division *************

****** 4.Multiplication*************

****** 5.Remainder *************

****** 6.Exit *************

press from 1 to 6

3.4. REPETITION/LOOPING

25
Most programs, however, require that a group of instructions be executed repeatedly means

more than one time, until some logical condition has been satisfied. This is known as looping

or repetition. Most of the programs require that a logical test be carried out at some particular

point within the program.

Type of Loop:

 Entry Controlled Loop

 Exit Controlled Loop

1. while loop (Entry-controlled)

2. do-while loop (Exit-controlled)

3. for loop (Entry Controlled)

3.4.1. WHILE LOOP

The while loop is used to carry out looping operations. Every loop has three things.

 Declaration and initialization of loop counter.

 Condition check or set the last iteration of loop.

 Increment or Decrement the loop counter

Syntax:

Int i; // declaration of loop counter

i=1; // initialization of loop counter

---

---

while (expression) //condition check or set last iteration of loop

26
{

statement; // body of loop

statement;

i++; //increment or decrement of loop counter

statement x;

NOTE: while loop is entry controlled loop because condition check at entry point of loop.

Without satisfying the condition control can not enter in the body of loop.

All variables used in the test expression of the while statement must be initialized at some

point before the while loop is reached. In addition, the body of the loop must do something to

change the value of the variable used in the expression being tested. Otherwise the condition

would remain true and the loop would never terminate. This situation, known as an infinite

loop (end less loop).

The loop operates in the following fashion:

First of all loop counter i is declared and initialized with value 1. The value of the test

expression enclosed in parentheses is evaluated. If the result is true, then the program

statement (the body of the loop) is executed. The statement may be a compound statement.

Then the test expression, which may be just as complex as any of those found in if statement is

evaluated again. If it is again true, the statement is executed once more. This process continues

until the test expression becomes false. At that point, the loop is terminated immediately, and

program execution continues with the statement x (if any) following the while loop. If there

27
are no more statements, the program terminates.

e.g.

Program 9: A test program for while loop

include<stdio.h>

main( )

int x=1;

while(x<=5)

printf(“line number %d \n”,x);

x++;

OUTPUT:

line number 1

line number 2

line number 3

line number 4

line number 5

NOTE: If x were initialized to a value of 6, the condition in the while loop becomes false to

begin with , and the body of the loop would not be executed at all. It is clear, then, that the

while statement employs a loop pre-test. The loop condition is tested before each iteration, and

28
therefore before the loop is entered at all. If the condition initially fails, the loop is skipped

entirely. so why, this is called entry controlled loop.

3.4.2. REVERSE LOOP

There is another way to use while loop, instead of incrementing the value of variables inside

the loop, you can also decrement it. For example, if you want to print the line number of test

program in reverse order then test expression changes and the program is as follows:

Program 10: A test program for while loop

include<stdio.h>

main( )

int x=5;

while(x>=1)

printf(“line number %d \n”,x);

x- -;

OUTPUT:

line number 5

line number 4

line number 3

line number 2

29
line number 1

There is an option for test expression in while loop, instead of giving some constant value

to test variable you can even given it some variable also. The value of this variable can be

input from the user interactively e.g. if the user wants to calculate the average of numbers,

but ‘how many numbers?’ this number can be input from the user itself and then this

variable can be used in test expression.

If the test expression involves two variables and joined with ‘&&’ or ‘||’ operator

Program 11: Program for while loop involving two variables

#include <stdio.h>

main( )

int x=1;

int a=4;

while (x<6 && a>3)

printf(“ This is line number %d of test program \n”,x);

x++;

The loop executes only while x is less than 6 and a is greater than 3. If at least one of these

conditions becomes false, the loop terminates. If at least one of the conditions is false when the

loop is first encountered, the loop is skipped entirely.

30
The value of a is not changed in the loop, but the value of x is incremented in a way that will

make the loop terminate eventually. If the value of a is less than or equal to 3, then the initial

test fails and the while loop is skipped entirely.

3.4.3. DO-WHILE LOOP

The do… while loop differs from the while loop in entry or exit. That is the condition is not

tested until the body of the loop has been executed once. In the while loop, by contrast, the test

is made on entry to the loop rather than at the end. The effect is that even if the condition is

false when the do-while loop is first encountered, the body of the loop is executed at least

once. If the condition is false after the first iteration, the loop terminates. If the first iteration

has made the condition true, however the loop continues.

Syntax:

Int i; // declaration of loop counter

i=1; // initialization of loop counter

---

---

do

statement; // body of loop

statement;

i++; // increment or decrement of loop counter

}while(expression); //condition check or set last iteration of loop

statement x;

31
}

NOTE: do-while loop is exit controlled loop because condition check at exit point of loop.

Control can enter into the body of loop without satisfying the condition at the very first

iteration. So why, it is called exit controlled loop.

e.g.

Program 12: A test program for do-while loop

#include<stdio.h>

main( )

int x=1;

do

printf(“line number %d \n”,x);

x++;

} while(x<=5);

OUTPUT:

line number 1

line number 2

line number 3

line number 4

32
line number 5

NOTE: In above example , if variable x=6 means expression (x<=5) evaluate to false at

the beginning of loop. Yet, statement printf(“line number %d \n”,x) will be executed once

and loop terminates and continue with next statement after the loop.

3.4.4. FOR LOOP

The for loop is the most commonly used loop in 'C'. This loop includes an expression that

specifies an initial value for loop counter, another expression determines whether or not the

loop is continued and the third expression that increment or decrement the loop counter.

Syntax:

for (exp1 ; exp2 ; exp3)

statement ;

statement;

---

---

 exp1 = initialization expression (initialization of loop counter) which is performed

once before the loop actually begins execution

 exp2 = test expression (condition or compound condition), evaluated before each

33
iteration of the loop and determines whether the loop should continue or be termi-

nated.

 exp3 = modifier expression (increment/ decrement loop counter), changes the value

of the variable used in the test. This expression is executed at the end of each

iteration, after the body of the loop is executed

NOTE: The three loops expressions are separated by two semicolons. No semicolon

should be placed after exp3.

e.g.

Program 13: A test program for ‘for’ loop

include<stdio.h>

main( )

int x;

for(x=1;x<=5;x++)

printf(“line number %d \n”,x);

OUTPUT:

line number 1

line number 2

line number 3

34
line number 4

line number 5

NOTE: The first expression of the for loop can be omitted if the variable is initialized

outside the loop. If one or more expressions are omitted from the for loop, the two

semicolons still must appear, even if they are not preceded or followed by anything.

e.g.

Program 14: Program to show for loop compulsory format

#include<stdio.h>

main( )

int x;

x=1;

for( ; x<=5 ; ) // initialization expression is placed before for loop

and increment exp. Used in the body of for loop

printf(“line number %d\n”,x)

x++;

3.4.5. NESTED LOOPS

Loops can be nested or embedded within another. The inner and outer loops need not be

generated by the same type of control structure. It is essential, however that one loop be

35
completely embedded within the other there can be no overlap. Each loop must be

controlled by a different index. Let us consider an example of nested for loops:

Program 15: Program to print table from 2 to 5

#include<stdio.h>

#include<conio.h>

void main()

int i,j;

clrscr();

for(i=2;i<=5;i++)

printf("table of %d:\n\n",i);

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

printf("%d\t",i*j);

printf("\n\n\n\n");

getch( );

OUTPUT:

table of 2:

36
2 4 6 8 10 12 14 16 18 20

table of 3:

3 6 9 12 15 18 21 24 27 30

table of 4:

4 8 12 16 20 24 28 32 36 40

table of 5:

5 10 15 20 25 30 35 40 45 50

Explanation: In this program firstly, outer for loop will be executed, if the expression (test) is

true, it will print

“table of 2:”

then inner loop will be executed. Inner loop will be executed till the test expression of inner

loop satisfies. And prints

“2 4 6 8 10 12 14 16 18 20”

Then if the expression is false, the pointer again goes to outer loop and then it will re execute

the next iteration and so on. For nested loops any other loop structures could also have been

selected.

3.5 JUMPING OUT FROM LOOP OR BLOCK (BREAK STATEMENT)

The break statement is used to force fully terminate loops or to exit from a switch or any block

of code. It can be used within a while, a do-while, for or a switch statement. The format is

simple as

break;

without any embedded expression or statements. The break statement causes a transfer of

37
control out of the entire block of code, to the first statement following the block of code. If

a break statement is included in a while, in do while or in for loop, then control will

immediately be transferred out of the loop when the break statement is encountered. Thus

provides a convenient way to terminate the loop if an error or other irregular condition is

detected. Let us consider a program segment of break statement in while loop.

Program 16: Program showing use of Break Statement in While loop

#include <stdio.h>

main()

int x;

x=1;

while(x<=10)

if (x==5)

break; //when condition satisfies break statement take control out of

loop

printf(“%d ”,x);

x++;

38
printf(“\nnext statement after while loop”);

OUTPUT:

1 2 3 4

next statement after while loop

3.6. SKIPPING A PART OF LOOP (CONTINUE STATEMENT)

The continue statement is used to bypass the remainder of the current pass through a loop.

The loop does not terminate when a continue statement is encountered, instead the

remaining loop statements are skipped and the computation proceeds directly to the next

pass through the loop. It can also be included within a while, do while or a for statement as

like break statement.

Syntax: continue;

39
Program 17: Program to show binary conversion of decimal integer

#include<stdio.h>

#include<conio.h>

void main()

int num;

int a[15],i;

clrscr();

printf("Enter any decimal integer");

40
scanf("%d",&num);

i=0;

while(num>=1)

a[i]=num%2;

num=num/2;

i++;

for(i=i-1;i>=0;i--)

printf("%d",a[i]);

getch();

OUTPUT:

Enter any decimal integer

12345

11000000111001

41
Program 18: Program to Compute and print Armstrong no.

e.g. 153

if(1*1*1 + 5*5*5 + 3*3*3)==153 i.e. Armstrong no.

#include<stdio.h>

#include<conio.h>

void main()

int n,sum=0,num,r;

clrscr();

printf("Armstrong nos. are given below:\n");

for(n=1;n<=500;n++)

num=n;

while(num)

r=num%10;

sum=sum+r*r*r;

num=num/10;

42
}

if(n==sum)

printf("%d \t",n);

sum=0;

getch();

OUTPUT:

Armstrong nos. are given below:

1 153 370 371 407

Program 19: Program to find a perfect number

e.g 6 whose proper divisors are 1, 2, 3 whose sum is 6 equal to original number so 6 is

perfect number

#include<stdio.h>

#include<conio.h>

43
void main()

int num,i,sum=1;

clrscr();

printf("Enter number:\n");

scanf("%d",&num);

for(i=2;i<=num/2;i++)

if(num%i!=0)

continue;

sum=sum+i;

if(sum==num)

printf("No %d is a perfect number",num);

else

printf("No %d is not a perfect number",num);

getch();

44
OUTPUT:

Enter number:

No 6 is a perfect number

Program 20: Program to print Fibonacci series

#include<stdio.h>

#include<conio.h>

void main()

long num[50],num1,num2,n,m,i,j;

clrscr();

printf("Enter number\n");

scanf("%ld",&n);

num[1]=num[2]=1;

printf("%ld %ld ",num[1],num[2]);

for(i=3;i<=n;i++)

num[i]=num[i-2]+num[i-1];

45
printf("%ld ",num[i]);

getch();

OUTPUT:

Enter number

1 1 2 3 5 8 13

Program 21: Program to Convert digits into words

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

long num,r,dup;

unsigned size=0;

clrscr();

printf("Enter a long number or short integer\n");

46
scanf("%ld",&num);

dup=num;

while(dup)

r=dup%10;

size++;

dup=dup/10;

dup=num;

while(size)

r=dup/pow(10,--size);

switch(r)

case 0:

printf("zero ");

break;

case 1:

47
printf("one ");

break;

case 2:

printf("two ");

break;

case 3:

printf("three ");

break;

case 4:

printf("four ");

break;

case 5:

printf("five ");

break;

case 6:

printf("six ");

break;

case 7:

48
printf("seven ");

break;

case 8:

printf("eight ");

break;

case 9:

printf("nine ");

break;

default:

break;

dup=dup-r*pow(10,size);

getch();

OUTPUT:

Enter a long number or short integer

12458

49
one two four five eight

Program 22: A Program to convert Celsius temperature in to Fahrenheit temperature

#include<stdio.h>

#include<conio.h>

void main()

float fah;

int cel;

clrscr();

printf("Celsius Temp. Fahrenheit Temp.\n");

for(cel=40;cel<=50;cel++)

fah=1.8*cel+32;

printf("%5d %30.2f\n",cel,fah);

getch();

OUTPUT:

50
Celsius Temp. Fahrenheit Temp.

40 104.00

41 105.80

42 107.60

43 109.40

44 111.20

45 113.00

46 114.80

47 116.60

48 118.40

49 120.20

50 122.00

Program 23: Program to find prime numbers between two numbers

#include<stdio.h>

#include<conio.h>

void main()

{ int first,last,i,j,flag=0;

clrscr();

51
printf("Enter first no.");

scanf("%d",&first);

printf("Enter last no.");

scanf("%d",&last);

for(i=first;i<=last;i++)

{ flag=0;

for(j=i-1;j>=2;j--)

if(i%j==0)

flag=1;

break;

if(flag==1)

continue;

52
else;

printf("prime=%d\n",i);

getch();

OUTPUT:

Enter first no.2

Enter last no.25

prime=2

prime=3

prime=5

prime=7

prime=11

prime=13

prime=17

prime=19

prime=23

Program 24: Program to Compute and print the sum of series:

53
sum=1/2 + 2/3 + 3/4.......+(n-1)/n.

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

int i,n;

float sum,f;

clrscr();

printf("Enter value of n\n");

scanf("%d",&n);

sum=0.0;

for(i=2;i<=n;i++)

f=(float)(i-1)/i;

sum=sum+f;

printf("Sum of series is:%.2f",sum);

54
getch();

OUTPUT:

Enter value of n

Sum of series is:3.55

Program 25: Program to reverse a number

#include<stdio.h>

#include<conio.h>

void main()

long num,rev=0;

int rem;

clrscr();

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

scanf("%ld",&num);

printf("original number: %ld",num);

while(num)
55
{

rem=num%10;

rev=rev*10+rem;

num=num/10;

printf("\n Reverse No. is:%ld\n",rev);

getch();

OUTPUT:

Enter a long number

32319

original number: 32319

Reverse No. is:91323

Program 26: Program to print a number in a reverse and sum up its digits

#include<stdio.h>

#include<conio.h>

void main()

56
long num,num1,rem,sum=0;

clrscr();

printf("Enter a long number");

scanf("%ld",&num);

num1=num;

while(num)

rem=num%10;

sum=sum+rem;

num=num/10;

printf("%ld",rem);

printf("\n Sum of Digits=%ld",sum);

printf("\n\n");

sum=0;

for(;num1>0;)

rem=num1%10;

57
sum=sum+rem;

num1=num1/10;

printf("%ld",rem);

printf("\n Sum of Digits=%ld\n",sum);

getch();

OUTPUT:

Enter a long number12345

54321

Sum of Digits=15

54321

Sum of Digits=15

Example 1. Find output of following code if x = 3, y = 4 and z = 6:

i) If ( x == y || y < z )

z= ( x * y ) / z;

58
else

z= ( x + y ) - z;

printf(“z=%d”, z);

OUTPUT:

Z=2

ii) if(x>y && y>z)

printf(“ it is OK”);

else

printf(“it is NOT OK”);

OUTPUT:

it is NOT OK

iii) if(x<y || x>z)

printf(“ Ok”);

else

59
{

printf(“NOT OK”);

OUTPUT:

OK

Example 2. Point out the errors if any

i) main( )

float x=13.25, y=13.54;

If(x = y)

printf (“\n x and y are equal”);

Answer: error, due to assignment operator used in place of equality operator

ii) main ( )

if (‘P’ < ’p’)

printf (“\n ascii value of P is smaller than that of p”);

Answer: No error

iii) main( )

int x = 5;

60
if x >= 3

printf (“\n %d”, x);

Answer: error, due to absence of parenthesis in if statement.

Example 3. Find output of following code:

i) main()

int i=10;

while(i=20)

printf(“\n Computer error”);

OUTPUT: infinite loop because of condition in while is not correct.

ii) main()

int i;

i=10;

while(i<=5)

printf(“%d”,i);

i++;

OUTPUT: loop will not execute because of condition false at very first time.

61
iii) main()

int i;

i=10;

do

printf(“%d”,i);

i++;

while(i<=5);

OUTPUT: loop will execute once due to condition check after loop body.

iv) main()

int i;

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

printf(“%d”,i);

OUTPUT: loop will not execute because of condition false at very first time like while loop.

v) main()

62
int i=0;

for( ; i ; )

printf(“”\n here is some message for you”);

OUTPUT: Nothing will show because of wrong condition in for loop.

Example 4. Point out the errors if any

i) for (i = 1 , i <10 ; i++) // error, due to comma(,) after initialization in place of

Semi colon( ;)

ii) for (i =1, j = 1;i<10;i++) //no error

iii) for ( i =10 ; i >0; i) // error, due to no increment in increment section

iv) for (i =1; i<10 ; i++) // no error

Example 5. Pick out the odd one out:

i) x = x + 1;

ii) x + = 1;

iii) x + +;

iv) x = + 1;

Answer: iv x =+1

4. Summary

There are three ways for taking decisions in a program. First way is to use the if-else

statement, second way is to use the conditional operators and third way is to use the switch

63
statement.

The default scope of the if statement is only the next statement. So, to execute more than

one statement they must be written in a pair of braces.

An if block need not always be associated with an else block. However, an else block is

always associated with an if statement.

If the outcome of an if-else ladder is only one of two answers then the ladder should be

replaced either with an else-if clause or by logical operators.

In C every test expression is evaluated in terms of zero and non-zero values. A zero value

is considered to be false and a non-zero value is considered to be true.

Assignment statements used with conditional operators must be enclosed within a pair of

parenthesis.

The three types of loops available in C are for, while, and do-while.

A break statement takes the execution control out of the loop.

A continue statement skips the execution of the statements after it and takes the control to

the beginning of the loop.

A do-while loop is used to ensure that the statements within the loop are executed at least

once.

5. Suggested Reading/Reference Material

1. Gottfried, Byron S., “Programming with C”, Tata McGraw Hill

2. Balagurusamy, E., “Programming in ANSI C”, McGraw-Hill

3. Balagurusamy, E., “Computing Fundamentals & C Programming”, McGraw-Hill

4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

64
5. Yashwant Kanetker, “Let us C”, BPB

6. Rajaraman, V., “Computer Programming in C”, PHI

7. Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language

(Second edition), Prentice Hall, 1988.

8. K. N. Dey, S. K. Bandyopadhyay: C Programming Essentials, Pearson Education

India, 2010.

9. Tim Bailey: An Introduction to the C Programming Language and Software Design

6. Self Assessment Questions

1. Describe briefly relational operators and logical operators?

2. What is Decision Making in C? Explain with example.

3. What is conditional branching and unconditional branching explain with example.

4. What are control instructions in c and what action perform by them?

5. What are different variant of ‘if’ statement. Explain with example.

6. What is conditional operators How it is different form if statement.

7. Explain the working of switch statement.

8. Difference between switch statement and if statement.

9. What is unconditional branching? How we can achieve unconditional branching in

‘C’.

10. What is looping? How it is useful in C Programming Language?

11. What are entry-controlled and exit-controlled loops in C.

12. Difference between while loop and do-while loop.

13. What are reverse loop explain with example.

14. What is jumping out from loop explain with example.

65
15. What is skipping a part of loop explain with example.

16. Write short note on:

break; continue; nested loops.

17. What is infinte loop (endless loop)? How we can avoid or prevent an infinite loop

situation.

66
Lesson 6:

Functions

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1. What Is Function?

3.1.1 Function Declaration or Prototype

3.1.2 Function Definition

3.1.3 Function Calling

3.2. Formal Arguments/ Parameters

3.3. Passing Argument to a Function

3.4. Recursion Function

3.5. Library Function

4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

1. INTRODUCTION

If a big problem is divided into various small problems then it is easy to solve small problem

than a big problem. In the previous lessons, you have seen how to declare identifiers, how to

write expressions and how to write statements.

In this lesson, you will learn how to group these components in a function so that these

components can be reused in a program. A user-defined function allows a large program to be

broken down into a number of smaller, self-contained components, each of which has some

2
unique, identifiable purpose. Thus a C program can be modularized through the intelligent use

of such functions. You will also learn about the advantages of using functions, how to declare,

define and call them. You will be familiarized with the methods of increasing flexibility of a

function and different ways of passing inputs to a function.

C supports the use of library functions, which are used to carry out a number of commonly

used operations. C also allows programmers to define their own functions for carrying out

various tasks.

2. Objectives

After working through this lesson you should be able to:

1. Understand the functions and their use.

2. Create C functions.

3. Make use of local and global parameters in functions.

4. Can add functions to the library and also use them

5. Create recursive functions in C.

3. Presentation of Contents

3.1. WHAT IS FUNCTION?

Function is a self-contained set of instruction that carries out some specific well-defined task.

Every C program contains one or more functions. Main( ) function is must for every program

because execution begin with the first statement of main( ) function and execution end with

the last statement of main( ) function so we can say that main( ) function is very important

and compulsory for every C program.

3
Every C function has three components:

i) Function Declaration

ii) Function Definition

iii) Function Calling

3.1.1. FUNCTION DECLARATION OR PROTOTYPE

Function prototypes are usually written at the beginning of a program, ahead of any programmer

defined functions. The general form of a function prototype is

data-type function-name (formal argument 1, formal argument 2…formal argument n) ;

where :

data-type is return type of data.

Function-name is any valid identifier.

Formal arguments are optional arguments. If want to use then specifies them.

e.g.

int fun1(int x, int y);

float fun2(int x, float y);

int fun3(int, int);

void fun4( );

NOTE: Function prototypes are not mandatory in C.

3.1.2 FUNCTION DEFINITION

A function definition has two principal components: the first line (including the argument

declarations) and the body of the function. The first line of a function contains the type

specification of the value returned by the function, followed by the function name and

4
optionally a set of arguments, separated by commas and enclosed in parentheses. Each

argument is preceded by its associated type declaration. In general terms, the first line and

body of the function can be written as

data-type function-name (formal argument 1, formal argument 2…formal argument n)

---

statement;

statement; //body of function

---

return statement;

e.g.

a) int fun1(int x, int y)

int z;

z=x+y;

return z;

b) float fun2(int x, float y)

float z;

5
z=x+y;

return z;

c) int fun3( int x, int y)

int z;

z=x+y;

return z;

d) void fun4()

printf(“this function does not return any value”);

3.1.3 FUNCTION CALLING

A function can be called or accessed by specifying its name followed by a list of arguments

enclosed in parentheses and separated by commas. If the function call does not require any

arguments, an empty pair of parentheses must follow the name of the function. In general

terms, the function is called as follows

Function-name( actual argument 1, actual argument 2….actual argument n);

e.g.

int a=10, b=20,s1,s3;

6
float c=10.5,d=20.6,s2;

s1=fun1(a,b);

s2=fun2(c,d);

s3=fun3(a,b);

fun4( );

Points to be noted: The following points must be noted about the functions.

1) The definitions of functions may appear in any order in a program file because they

are independent of one another.

2) Before using any function it must be defined in the program.

3) A function can be executed/call from anywhere within a program.

4) Once the function has been executed, control will be returned to the point from which

the function was accessed.

5) A function contains special identifiers called parameters or arguments through which

information is passed to the function and from functions information is returned via

the return statement.

6) It is not necessary that every function must return information, there are some

functions also which do not return any information then return type will be void e.g.

void abc( ); function.

7) Function returns only single value.

7
3.2. FORMAL ARGUMENTS/ PARAMETERS

They receive information/value from the calling function(from actual parameters) of the

program. They are also known as parameters or formal parameters as shown in Fig. 1.

1) Actual Parameters: These are passed from the calling function to the called function.

The names of actual parameters and formal parameters may be either same or different

but their data type should be same. Information is returned from the called function to

the calling function of the program via the return statement shown in Fig 1. The return

statement also causes control to be returned to the point from which the function was

accessed.

Program 1: Program to show the working of a Function

#include <stdio.h>

main()

int x,y,s=0;

int sum(int, int); /*function declaration: argument name is optional but data type

is must */

printf(“Enter two integer values”);

scanf(“%d %d”’ &x,&y);

s=sum(x,y); /*call to function : x & y are actual argument*/

printf(“sum of x & y: %d”,s);

int sum(int a, int b) /* function definition: a & b are formal parameters*/

8
int c;

c=a+b;

return c;

Fig 1. Showing mechanism of transferring value through argument and retuning

value.

2) Avoidance of function prototype/ declaration: Function prototype must precede the

function call. However, if function definition precedes the first function call, there is

no need for a function prototype.

e.g

Program 2: Program in which definition of the function precedes the first call

#include<stdio.h>

#include<conio.h>

9
void swap( int x, int y) // function definition precede the function call

int z;

printf(“value of x before swap:%d \n”, x);

printf(“value of y before swap:%d \n”, y);

z=x;

x=y;

y=z;

printf(“value of x after swap:%d \n”, x);

printf(“value of y after swap:%d \n”, y);

void main( )

int a,b;

clrscr( );

a=10;

b=20;

swap(a,b);

getch( );

OUTPUT:

value of x before swap:10

value of y before swap:20

10
value of x after swap:20

value of y after swap:10

NOTE: Function Swap(int x, int y); precede the function call so there is no need to include

the function declaration/ prototype in the program.

3.3. PASSING ARGUMENT TO A FUNCTION

Arguments can be passed to a function by two methods.

1. Pass/call by value

2. Pass/call by reference

1. Pass/ Call By Value : When value is passed to a function via an actual argument, the

value of the actual argument is copied into the formal argument. Therefore, the value of

the corresponding formal argument can be altered within the called function, but the value

of the actual argument within the calling function/routine will not change. This procedure

for passing the value of an argument to a function is known as passing by value or call by

value shown in Fig 2. For example,

Program 3: Program to show the call by value parameter passing

#include <stdio.h>

#include<conio.h>

void change(int ); //in declaration argument name is optional

main( )

11
int x=10;

clrscr( );

printf(“\n value of x in main before calling change function: %d”, x);

change(x);

printf(“\n value of x in main after calling change function: %d”, x);

getch( );

return 0;

void change(int y)

printf(“\n value of y in change function before change in y: %d”, y);

y=y+3;

printf(“\n value of y in change function after change in y: %d”, y);

OUTPUT:

value of x in main before calling change function: 10

value of y in change function before change in y: 10

value of y in change function after change in y: 13

value of x in main after calling change function: 10

12
Fig 2. Showing call by value

Points to Note:

(i) Function returns no value and passes no argument: In the following function no

argument is passed and no value is returned by the function.

void fun1(void ); //function declaration

void main()

fun1( ); //calling of function

void fun1(void) // function definition

13
{

---- //Body of Function

----

(ii) Function returns value: In the following function value is returned by the function.

float sum(float a, float b); //function declaration

void main( )

{ -----

-----

z=sum(x,y); // function calling and receiving of returning value in variable z

-----

-----

float sum( float a, float b) // function definition returning value of z

float c;

c=a+b;

return (c);

2. Pass/Call By Reference : In call by reference, reference(address) is passed to a function

via an actual argument, the reference (address) the actual argument is copied into the

formal argument. Therefore, the formal argument can altered the value of the actual

14
argument within the calling function/routine. This procedure for passing the reference of

an argument to a function is known as passing by reference or call by reference. For

receiving the reference/ address of actual argument, function has to need pointer as formal

argument because pointer can store reference or address. So before discuss any more

about call by reference, firstly we discuss about pointer. What is Pointer?

a) Pointer: The memory address of a variable is a constant value. The address can be

assigned to another variable as shown in Fig. 3. A variable that stores the address of

another variable is called a pointer variable or a pointer shown in Fig. 4. Thus a

pointer is just like another variable that stores data; pointer holds memory address of a

variable.

Pointers have their area of application. They have used to access elements of array,

pass argument to a function by reference rather than value in order to modify the

original value of actual argument. Pass string to function, create data structure like list,

stack, queue etc.

Pointer declaration :

Data-type * pointer-name;

Where

Data-type is any valid data type

‘ * ’ (asterisk ) which indicates that the variable is a pointer variable. ‘ * ‘ is called

indirection operator

Pointer-name is any valid identifier.

e.g.

int *ptr1;

float *ptr2;

15
double *ptr3;

void *ptr4;

 Pointer always contain address, never contains value

 Pointer always take 2 bytes in memory regardless of its type (int, float, double

all take 2 bytes)

 Pointer contain address of variable which have the same data type as of

pointer data type.

e.g.

----

----

int x;

x=10;

printf(“%d”,x); // it will print value of x (i.e. 10)

printf(“%u”,&x); // it will print address of x (i.e. 4510)

Fig 3. Showing variable x in memory with memory address

Int *ptr1;

Ptr1=&x;

printf(“%u”,ptr1); // it will print value of ptr1 (address of x i.e. 4510)

16
printf(“%u”,&ptr1); // it will print address of ptr1 (i.e. 5510)

printf(“%d”,*ptr1); // it will print value of x(i.e. 10)

----

----

Fig 4. Showing pointer ptr1 which store the address of int variable x.

NOTE: here ‘*’ operator called as ‘value at address operator’ means a pointer ptr1 which

contain a address and value at this address is 10 (value of variable x)

So we can access value of a variable directly by variable name and indirectly by pointer.

Now, we are coming back to our topic call by reference shown in Fig. 5.

Program 4: Program showing call by reference parameter passing

#include <stdio.h>

#include<conio.h>

void change(int ); //in declaration argument name is optional

main( )

int x=10;

17
clrscr( );

printf(“\n value of x in main before calling change function: %d”, x);

change(&x); //calling of function, address is passed instead of value

printf(“\n value of x in main after calling change function: %d”, x);

getch( );

return 0;

void change(int *y) //funct. Def., pointer instead of simple variable as formal

argument

*y=*y+3; // it will increase the value of actual argument x by 3.

OUTPUT:

value of x in main before calling change function: 10

value of x in main after calling change function: 13

18
Fig. 5. Showing call by reference

3.4. RECURSION FUNCTION

Recursion is a process by which a function calls itself repeatedly, until some specified

condition has been satisfied. The process is used for repetitive computations in which each

action is stated in terms of a precious result. In order to solve a problem recursively, two

conditions must be satisfied. The problem must be written in a recursive form, and the

problem statement must include a stopping condition. The best example of recursion is

calculation of factorial of an integer quantity, in which the same procedure is repeating itself.

Let us consider the example of factorial:

Program 5: Program to find factorial of a number using recursion

#include <stdio.h>

void main( )

int num;

19
long int x;

printf(“Enter number”);

scanf(“%d”, & num);

x=fact(num);

printf(“Factorial of number % d is %ld \n”,num,x);

long int fact(int p )

if(p <=1)

return(1);

else

return(p *fact(p-1));

The point to be noted here is that the function ‘fact’ calls itself recursively, with an actual

argument (n-1) that decrease in value for each successive call. The recursive calls terminate

the value of the actual argument becomes equal to 1.

When a recursive program is executed, the recursive function calls are not executed

immediately. Instead of it, they are placed on a stack until the condition that terminates the

recursion is encountered. The function calls are then executed in reverse order, as they are

popped off the stack.

The use of recursion is not necessarily the best way to approach a problem, even though the

problem definition may be recursive in nature.

20
Advantage of Recursion: Some of the advantages of recursion are as follows.

1. It is more concise and transparent.

2. In certain cases it may be easy to write and understand

3. In linked list, stack, queue recursion is very helpful.

4. In Problem ‘Tower of Hanoi’, recursion may be the only solution.

5. Recursion is powerful in mathematical definitions.

6. Recursion helpful in running program on computers with multiprocessing facilities.

Disadvantage: Some of the disadvantages of recursion are as follows.

1. It consumes more storage space.

2. The computer may run out of memory if the recursive calls are not checked.

3. It is not efficient in terms of speed and execution time.

4. Recursion may result in non-terminating iterations if proper precautions are not taken.

3.5. LIBRARY FUNCTION

C Library functions are inbuilt functions in C Language. Function prototype and data

definitions of these functions are written in their respective header file. For example: If you

want to use printf() function, the header file <stdio.h> should be included.

There are many library functions available in C programming to help the programmer to write

a good efficient program. Suppose, you want to find the square root of a number. You can

write your own piece of code to find square root but, this process is time consuming and the

code you have written may not be the most efficient process to find square root. But, in C

programming you can find the square root by just using sqrt() function which is defined under

header file "math.h" as shown in the following program.

21
Program 6: Program to show the use of library function sqrt( ).

#include <stdio.h>

#include <math.h>

int main(){

float num,root;

printf("Enter a number to find square root.");

scanf("%f",&num);

root=sqrt(num); /* Computes the square root of num and stores in root. */

printf("Square root of %.2f=%.2f",num,root);

return 0;

Adding Function to Library: One way to provide the necessary library functions

declarations is to write them explicitly. C provides us a way by placing the required library

function declarations in special files called header files. The header files also contain other

information related to the use of the library functions such as symbolic constant definitions.

The required header files must be merged with the source program during the compilation

process. This is accomplished by placing one or more #include statements at the beginning of

the source program. The following five steps are used to add function to the library and then

use them in the program.

Step 1 : write a function which you want to add in library and save in a file says sum.c.

e.g

int sum(int x,int y)

22
int z;

z=x+y;

return z;

Step 2 : Compile the sum.c file. A new file is created sum.obj in which object code is created.

Step 3 : add the function to library by giving the command at command prompt by using dos

shell.

C:\tc>tlib math.lib + c:\tc\sum.obj

Here ‘math.lib’ is a library file. ‘+’ is denoted, file is added in library and

‘c:\tc\sum.obj’ is the path of .obj file.

Step 4 : Declare the prototype or declaration of sum()function in header file ‘sum.h’

e.g

int sum(int x, int y);

or

int sum(int,int);

and save in file ‘sum.h’

Step 5 : to use the function present in the library as follows shown in Program 6.

Program 7: Program to show the use of library functions

23
#include<stdio.h>

#include “c:\tc\sum.h”

void main()

int a,b;

printf(“Enter a & b\n”);

scanf(“%d%d”,&a,&b);

c=sum(a,b); // library function sum is used here.

Printf(“\nsum=%d”,c);

OUTPUT:

Enter a & b

10

50

sum=60

Program 8: Program to calculate x raised to power n by recursion

#include<stdio.h>

#include<conio.h>

#include<math.h>

float power(float x,int n);

24
void main()

float x;

int n;

clrscr();

printf("Enter value of x and n\n");

scanf("%f%d",&x,&n);

if(power (x,n))

printf("%.2f\n",power(x,n));

else

printf("Exponent is negative\n");

getch();

float power(float x,int n)

if(n<0)

return 0;

25
if(n==0)

return 1.0;

else

return(x*power(x,n-1));

OUTPUT:

Enter value of x and n

125.00

Example 1: Point out the errors if any

i) main()

float a=16.5;

char ch=’D’;

fun1(a, ch);

void fun1(a, ch) //Error, Data type of arguments is not specified.

26
printf(“\n %f %c”, a, ch);

Answer: Error, Data type of formal arguments is not specified.

ii) main()

int x=25, y=26;

fun1(&x,&y);

printf(“\n %d %d”,x,y);

void fun1(int a, int b) // Error, Data type of arguments is not matched

a=a+a;

b=b+b;

Answer: Error, Data type of arguments is not matched. Addresses are passed from

main function as actual argument and formal arguments are not of pointer type they

are only simple built in type variable.

iii) main()

27
{

int a=10, b=9;

fun1(a,b);

printf(“\n %d %d”,a,b);

void fun1(int x, int y)

printf(“\n %d %d”,x,y);

Answer: No Error, ANSI Function Declaration notation Used.

iv) main()

int a=10, b=9;

fun1(a,b);

printf(“\n %d %d”,a,b);

void fun1(x, y)

int x;

int y;

28
{

printf(“\n %d %d”,x,y);

Answer: No Error, Kernighan and Ritchie Function Declaration notation is used.

Example 2: What would be output of the following program segment.

i) main( )

printf(“we are in main function\n”);

main( );

OUTPUT:

Program will be in infinite loop because main( ) function call itself and no condition `

specified here which jumped out from this from infinite loop.

ii) main( )

int i=45,c;

c=check(i);

29
printf(“\n %d”,c);

check(int ch)

if(ch>=45)

return 100;

else

return

(10*10);

OUTPUT:

100

iii) main()

int i=6, j=3;

fun1(&i,&j);

printf(“\n %d %d”,i , j);

fun1(int *x, int *y)

30
*x = *x * *x ;

*y = *y * *y;

OUTPUT:

36 9

iv) main()

int i=6, j=3;

fun1(&i, j);

printf(“\n %d %d”, i, j );

fun1(int *x, int y)

*x = *x * *x ;

y=y *y;

OUTPUT:

36 3

31
4. Summary

Functions help in modularizing a program into smaller simple parts.

Functions are categorized as: (a) user-defined functions and (b) library functions.

User-defined functions are defined by the user at the time of writing a program and are also

known as programmer-defined functions.

There are three aspects of working with user-defined functions: (a) function declaration, (b)

function definition and (c) function call.

Function definition, also known as function implementation means composing a function.

Every function definition consists of two parts: (a) header of the function and (b) body of the

function.

A function with no input–output does not accept any input and does not return any result.

The execution of a C program always begins with the function main. It need not to be called

explicitly.

Functions whose return type is void are known as void functions. void functions do not return

any value.

While calling a function, the expressions that appear within the parentheses of a function call

are known as actual arguments, and the variables declared in the parameter list in the header

of function definition are known as formal parameters.

32
The return statement is to return the result of computations done in the called function and/or

the program control back to the calling function.

There are two forms of return statement: (a) return; and (b) return expression;.

Depending upon whether values or addresses are passed as arguments to a function, the

argument passing methods in C language are classified as: (a) pass by value and (b) pass by

reference/address.

If arguments are passed by value, the changes made in the values of formal parameters inside

the called function are not reflected back to the calling function.

If the arguments are passed by reference/address, the changes made in the values pointed to

by the formal parameters in the called function are reflected back to the calling function.

A function can return only one value by using the return statement but it can indirectly return

more than one value using the concept of pass by reference/address.

When an array is passed as an argument to a function, it implicitly gets converted to a pointer

type.

Function calling itself is called recursive function and the process is known as recursion.

Recursive functions may be direct recursive/indirect recursive and

A pointer to a function, commonly known as the function pointer, is a variable that points to

the address of a function.

Library functions or pre-defined functions are the functions whose functionality has already

been developed by someone and is available to the user for use.

33
5. Suggested Reading/Reference Material

1. Gottfried, Byron S., “Programming with C”, Tata McGraw Hill

2. Balagurusamy, E., “Programming in ANSI C”, McGraw-Hill

3. Balagurusamy, E., “Computing Fundamentals & C Programming”, McGraw-Hill

4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

5. Yashwant Kanetker, “Let us C”, BPB

6. Rajaraman, V., “Computer Programming in C”, PHI

6. Self Assessment Questions

1. What is function? What are advantages of function?

2. Why we need user defined function? What is difference between user-defined function

and library function?

3. What is function prototype? Specify the characteristics of function prototype.

4. How do you pass argument to a function? Explain two method of passing arguments

to function.

5. What is return type of function? Explain with example.

6. What is recursion? Explain with example.

7. What is pointer? What purpose served by pointer? Explain with example.

8. What is parameter or argument? Differentiate the actual argument and formal

argument.

9. What are differences between function prototype and function definition.

34
10. Should the number of parameters in the function prototype be always equal to the

number of parameters in the calling function? Explain

11. Why the parameters given within a function prototypes are called ”dummy”

parameters?

12. Can we give multiple return statements?

35
Lesson 7:

Storage classes in C

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1. The Storage Class

3.1.1. Automatic or Auto Storage Class

3.1.2. Register Storage Class

3.1.3. Static Storage Class

3.1.4. External Storage Class

3.1.5. The Storage Class Modifiers

3.2. Lifetime And Visibility

3.3. Scope

4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

1. Introduction

In the previous lessons, you have learned how to declare variables of different data types, as

well as to initialize and use those variables. It has been assumed that you can access variables

from anywhere. Now, the question is: Can we declare variables that are accessible only to

2
certain portions of a program? In this lesson you will learn about the scope and storage classes

of data in C.

2. Objectives

After working through this lesson you should be able to:

1. Understand the storage class and their types.

2. Create programs using storage class specifiers.

3. Understand the lifetime and visibility of variables.

4. Understand the scope and their types

3. Presentation of Contents

3.1. THE STORAGE CLASS

The storage class of a variable specifies the lifetime and visibility of a variable. Variables

posses ‘storage class’ and ‘storage class specifier’. Storage class specifies the visibility and

scope of variable and storage class specifier indicates storage class specification. There are

four specifiers and corresponding storage classes that can be used in C language

1. Automatic or Auto Storage Class

2. Register Storage Class

3. Static Storage Class

4. External Storage Class

There are two modifiers that can be used in C language

1. The const Modifier

2. The volatile Modifier

3
3.1.1. AUTOMATIC OR AUTO STORAGE CLASS

An auto variable is defined and accessed with in a function. The auto specifier indicates that

the memory location of a variable is temporary. In other words, a variable's reserved space in

the memory can be erased or relocated when the variable is out of its scope. Only variables

with block scope can be declared with the auto specifier. The auto keyword is rarely used.

The various features this class are

 Storage : Memory

 Default initial value : unpredictable value known as garbage value.

 Scope : Local to block in which it is defined.

 Lifetime : Till the control remains within the block in which it is defined.

Program 1: Program to show the use of auto storage class variables

#include<stdio.h>

void main()

auto int a,b;

a=10;

printf(“%d”,a);

Output:

4
10

3.1.2. REGISTER STORAGE CLASS

The word register is borrowed from the world of computer hardware. Each computer has a

certain number of registers to hold data and perform arithmetic or logical calculations.

Because registers are located within the CPU, it's much quicker to access a register than a

memory location. Therefore, storing variables in registers may help to speed up the program.

The C language provides the register specifier. This specifier is applied to variables when it is

necessary to put the variables into the computer registers.

However, the register specifier only gives the compiler a suggestion. In other words, a

variable specified by the register keyword is not guaranteed to be stored in a register. The

compiler can ignore the suggestion if there is no register available, or if some other

restrictions have to apply.

It's illegal to take the address of a variable that is declared with the register specifier because

the variable is intended to be stored in a register, not in the memory.

In the following lines of code, the integer variable i is declared with the register specifier:

int main()

/* block scope with the register specifier */

register int i;

...

5
for (i=0; i<MAX_NUM; i++){

/* some statements */

...

return 0;

The declaration of i suggests that the compiler store the variable in a register. Because i is

intensively used in for loop, storing i in a register may increase the speed of the code.

The various features this class are

 Storage : CPU Register

 Default initial value : garbage value.

 Scope : Local to block in which it is defined.

 Lifetime : Till the control remains within the block in which it is defined.

Program 2. Program to show the use of Register storage class variables

#include<stdio.h>

void main()

register int a;

a=10;

6
printf(“%d”,a);

Output:

10

3.1.3. STATIC STORAGE CLASS

The static specifier can be applied to variables with either block scope or program scope.

When a variable within a function is declared with the static specifier, the variable has a

permanent duration. In other words, the memory storage allocated for the variable is not

destroyed when the scope of the variable is exited, the value of the variable is maintained

outside the scope, and if execution ever returns to the scope of the variable, the last value

stored in the variable is still there. The various features this class are

 Storage : Memory

 Default initial value : zero

 Scope : Local to block in which it is defined.

 Lifetime : value of variable persists between different function calls.

For example, in the following lines of code the integer variable i has temporary duration by

default. But the other integer variable, j, has permanent duration due to the storage class

specifier static.

int main()

7
int i; /* block scope and temporary duration */

static int j; /* block scope and permanent duration */

return 0;

The following program shows the effect of the static specifier on variables.

Program 3. Using the static specifier.

#include <stdio.h>

int add_two(int x, int y)

static int counter = 1;

printf("This is the function call of %d,\n", counter++);

return (x + y);

/* the main function */

main()

int i, j;

for (i=0, j=5; i<5; i++, j--)

printf("the addition of %d and %d is %d.\n\n",

8
i, j, add_two(i, j));

return 0;

OUTPUT

This is the function call of 1,

the addition of 0 and 5 is 5.

This is the function call of 2,

the addition of 1 and 4 is 5.

This is the function call of 3,

the addition of 2 and 3 is 5.

This is the function call of 4,

the addition of 3 and 2 is 5.

This is the function call of 5,

the addition of 4 and 1 is 5.

The purpose of the above program is to call a function to add two integers and then print out

the result returned by the function on the screen. The function is called several times. A

counter is set to keep track of how many times the function has been called.

The programs of Fig. 1. shows the working of static storage class in comparison with auto

9
storage class

Fig. 1. Showing working of static storage class in comparison with auto storage class

3.1.4. EXTERNAL STORAGE CLASS

A variable with program scope is visible through all source files that make up an executable

program. A variable with program scope is also called a global variable.

But how can a global variable declared in file A, be seen in file B? In other words, how does

the compiler know that the variable used in file B is actually the same variable declared in file

A?

Use the extern specifier provided by the C language to allude to a global variable defined

elsewhere. In this case, we declare a global variable in file A, and then declare the variable

again using the extern specifier in file B.

10
For instance, suppose you have two global int variables, y and z, that are defined in one file,

and then, in another file, you may have the following declarations:

int x = 0; /* a global variable */

extern int y; /* an allusion to a global variable y */

int main()

extern int z; /* an allusion to a global variable z */

int i; /* a local variable */

return 0;

Here, there are two integer variables, y and z, that are declared with the extern specifier,

outside and inside the main() function, respectively. When the compiler sees the two

declarations, it knows that the declarations are actually allusions to the global variables y and

z that are defined elsewhere.

The various features this class are

 Storage : Memory

 Default initial value : zero

 Scope : Global

 Lifetime : Till the end of program’s execution.

11
3.1.5. THE STORAGE CLASS MODIFIERS

C provides two storage class modifiers that can be used to indicate to the C compiler how

variables may be accessed.

1. The const Modifier: If you declare a variable with the const modifier, the content of

the variable cannot be changed after it is initialized. For instance, the following

expression indicates to the compiler that Pi is a variable whose value should not be

changed

const double Pi = 3.141593;

Similarly, the value of the character array str1 declared in the following statement

cannot be changed, either:

const char str1[ ] = "A string constant declaration";

You can also declare a pointer variable with the const modifier so that an object

pointed to by the pointer cannot be changed. For example, consider the following

pointer declaration with the const modifier:

char const *ptr_str = "A string constant declaration ";

After the initialization, you cannot change the content of the string pointed to by the

pointer ptr_str.

2. The volatile Modifier: To declare a variable whose value can be changed without any

explicit assignment statement in the program. For instance, you might declare a global

12
variable that contains characters entered by the user. The address of the variable is

passed to a device register that accepts characters from the keyboard. However, when

the C compiler optimizes your program automatically, it intends to not update the

value held by the variable unless the variable is on the left side of an assignment

operator (=). In other words, the value of the variable is likely not changed even

though the user is typing in characters from the keyboard.

To ask the compiler to turn off certain optimizations on a variable, you can declare the

variable with the volatile specifier. For instance, in the following lines of code, a

variable, keyboard_ch, declared with the volatile specifier, tells the compiler not to

optimize any expressions of the variable because the value saved by the variable may

be changed without execution of any explicit assignment statement:

void read_keyboard()

volatile char keyboard_ch; /* a volatile variable */

3.2. LIFETIME AND VISIBILITY

A variable has a definite lifetime. Lifetime of a variable is period during which its value and

storage exist. Lifetime of a variable may be local or global.

 Lifetime of local variable is limited to the period of execution of the function in which it

is define. Local variable is always defined within the function.


13
 Lifetime of global variable extends to the period of the execution of the program. Global

variable is defined outside the function.

 Visibility or scope of a variable specifies the area or portion of the program where it can

be accessed. Visibility of variable depends on its storage class and storage class specifier.

e.g.

#include<stdio.h>

int x=10; //global variable

void main( )

int y=20; //local variable for the main( ) function.

----

----

void fun1( )

int z=50; //local variable for fun1( ) function.

storage class specifier: every strorage class of a variable tells four thing about variable i.e

 storage place: where it is stored (in memory or in register)

 initial value: initial value, whether it is initialized with garbage value or any other value

14
 visibility or scope: area or portion of the program where it can be accessed.

 lifetime: up to what time a variable kept in memory or in register.

3.3. SCOPE

The scope of an identifier is a region of the program within which the identifier is visible (i.e.

it can be used). In C language, the following four types of scopes are defined, which

determine the visibility of an identifier:

1. Block Scope

2. Function Scope

3. Program Scope

4. File scope

In the complete program, there might be variables that have to be shared by all the functions.

On the other hand, the use of some other variables may be limited to only certain functions.

That is, the visibility of those variables is limited, and values assigned to those variables are

hidden from many functions.

Limiting the scope of variables is very useful when several programmers are working on

different pieces of the same program. If they limit the scope of their variables to their pieces

of code, they do not have to worry about conflicting with variables of the same name used by

others in other parts of the program.

In C, you can declare a variable and indicate its visibility level by designating its scope. Thus,

variables with local scope can only be accessed within the block in which they are declared.

15
1. Block Scope: A block refers to any sets of statements enclosed in braces ({ and }). A

variable declared within a block has block scope. Thus, the variable is active and

accessible from its declaration point to the end of the block. Sometimes, block scope is

also called local scope.

For example, the variable i declared within the block of the following main function has

block scope:

int main()

int i; /* block scope */

return 0;

Usually, a variable with block scope is called a local variable.

Nested Block Scope: You can also declare variables within a nested block. If a

variable declared in the outer block shares the same name with one of the variables in

the inner block, the variable within the outer block is hidden by the one within the

inner block for the scope of the inner block.

Program 4. Program to Print variables with different scope levels

#include <stdio.h>

16
main()

int i = 32; /* block scope 1*/

printf("Within the outer block: i=%d\n", i);

{ /* the beginning of the inner block */

int i, j; /* block scope 2, int i hides the outer int i*/

printf("Within the inner block:\n");

for (i=0, j=10; i<=10; i++, j--)

printf("i=%2d, j=%2d\n", i, j);

printf("Within the outer block: i=%d\n", i);

return 0;

OUTPUT

Within the outer block: i=32

Within the inner block:

i= 0, j=10

i= 1, j= 9

i= 2, j= 8

i= 3, j= 7

i= 4, j= 6

i= 5, j= 5

i= 6, j= 4

17
i= 7, j= 3

i= 8, j= 2

i= 9, j= 1

i=10, j= 0

Within the outer block: i=32

There are two nested blocks in Program 1. The integer variable i declared is visible within

the outer block enclosed by the braces ({ and }). Another two integer variables, i and j, are

visible only within the inner block. Although the integer variable i within the outer block

has the same name as one of the integer variables within the inner block, the two integer

variables cannot be accessed at the same time due to their different scopes.

2. Function Scope: Function scope indicates that a variable is active and visible from the

beginning to the end of a function. In C, only the goto label has function scope. For

example, the goto label, start, shown in the following code portion has function scope:

int main()

int i; /* block scope */

start: /* A goto label has function scope */

18
.

goto start; /* the goto statement */

return 0;

Here the label start is visible from the beginning to the end of the main( ) function.

Therefore, there should not be more than one label having the same name within the

main( ) function.

3. Program Scope: A variable is said to have program scope when it is declared outside

a function. Variables with program scope are also called global variables, which are

visible among different files. These files are the entire source files that make up an

executable program. Note that a global variable is declared with an initializer outside a

function. For example,

int x = 0; /* program scope */

float y = 0.0; /* program scope */

int main()

int i; /* block scope */

19
return 0;

Here the int variable x and the float variable y have program scope.

Program 5. The relationship between program scope and block scope.

#include <stdio.h>

int x = 1234; /* program scope */

double y = 1.234567; /* program scope */

void function_1()

printf("From function_1:\n x=%d, y=%f\n", x, y);

main()

int x = 4321; /* block scope 1*/

function_1();

printf("Within the main block:\n x=%d, y=%f\n", x, y);

/* a nested block */

double y = 7.654321; /* block scope 2 */

function_1();

printf("Within the nested block:\n x=%d, y=%f\n", x, y);

20
return 0;

OUTPUT

From function_1:

x=1234, y=1.234567

Within the main block:

x=4321, y=1.234567

From function_1:

x=1234, y=1.234567

Within the nested block:

x=4321, y=7.654321

4. File Scope: A global variable declared with the static specifier is said to have file

scope. A variable with file scope is visible from its declaration point to the end of

the file. Here the file refers to the program file that contains the source code. Most

large programs consist of several program files. The following lines of code show

variables with file scope:

int x = 0; /* program scope */

static int y = 0; /* file scope */

static float z = 0.0; /* file scope */

int main()

21
int i; /* block scope */

return 0;

Here the int variable y and the float variable z both have file scope.

Example 1. Point out the errors if any

i) main()

long x ;

x = 5;

printf(“\n num=%d”, x);

Answer: No Error

ii) main()

char ch=201;

printf(“\n ch=%d”,ch);

}
22
Answer: Error, it will print undesired value because char ‘s range is -128 to 127

Example 2. What would be output of the following program segment.

i) main()

static int count=6;

printf(“\n Count=%d”,count- -);

if(count!=0)

main();

Output:

Count=6

Count=5

Count=4

Count=3

Count=2

Count=1

ii) main()

int i , j;

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

23
j = fun1( i );

printf(“\n %d”, j);

fun1(int x)

static int p=1;

int b=3;

p+=x;

return (p+x+b);

Output:

13

18

4. Summary

The scope of an identifier is a region of the program within which the identifier is visible

(i.e. it can be used).

24
There are four types of scopes, namely file scope or global scope, block scope or local

scope, function prototype scope and function scope.

Two identifiers have the same scope if and only if their scopes terminate at the same

point.

The keyword extern provides a method for declaring an identifier without defining it.

An identifier can have many identical declarations in the same scope.

It is not allowed to define an identifier more than once in the same scope.

One definition rule states that each object must have only one definition in a scope.

It is possible to define an identifier with the same name more than once if the definitions

lie in different scopes.

Lifetime of an object is the portion of the program execution during which the storage is

guaranteed to be reserved for it.

To fully define an identifier, we also need to specify its storage class.

There are four storage classes, namely auto, register, static and extern.

By default, a variable with block scope has an auto duration, and its memory storage is

temporary.

A variable declared with the static specifier has permanent memory storage, even though

the function in which the variable is declared has been called and the function scope has

exited.

25
A variable declared with the register specifier may be stored in a register to speed up the

performance of a program; however, the compiler can ignore the specifier if there is no

register available or if some other restrictions have to apply.

You can also allude to a global variable defined elsewhere by using the extern specifier

from the current source file.

5. Suggested Reading/Reference Material

1. Gottfried, Byron S., “Programming with C”, Tata McGraw Hill

2. Balagurusamy, E., “Programming in ANSI C”, McGraw-Hill

3. Balagurusamy, E., “Computing Fundamentals & C Programming”, McGraw-Hill

4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

5. Yashwant Kanetker, “Let us C”, BPB

6. Rajaraman, V., “Computer Programming in C”, PHI

7. Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language

(Second edition), Prentice Hall, 1988.

8. K. N. Dey, S. K. Bandyopadhyay: C Programming Essentials, Pearson Education

India, 2010.

9. Tim Bailey: An Introduction to the C Programming Language and Software Design

6. Self Assessment Questions

1. What are storage classes in C? Explain with example.


26
2. How many types of storage classes in C? Explain each with example.

3. Define the concept of Lifetime and visibility in storage class.

4. Difference between local and global variable. Illustrate with example.

5. Write Short Note on:

 Auto

 Static

 Extern

 Register

6. Give the main feature of global variable. Describe its lifetime and visibility.

7. Can a global variable be hidden by a local variable with block scope? Why do you

need the static specifier?

8. Does using the register specifier guarantee to improve the performance of a

program?

9. When you declare a variable with the extern specifier, do you define the variable

or allude to a global variable elsewhere?

10. Given the following code portion, which variables are global variables, and which

ones are local variables with block scope?

int x = 0;

float y = 0.0;

int myFunction()

int i, j;

float y;

...

27
{

int x, y;

...

...

11. When two variables with the same name are defined, how does the compiler know

which one to use?

12. Identify the storage class of each declaration in the following code portion:

int i = 0;

static int x;

extern float y;

int myFunction()

int i, j;

extern float z;

register long s;

static int index;

const char str[] = "Warning message.";

...

13. Given the following declaration:

28
const char ch_str[ ] = "The const specifier";

is the ch_str[9] = `-'; statement legal?

14. Given the following,

 An int variable with block scope and temporary storage

 A constant character variable with block scope

 A float local variable with permanent storage

 A register int variable

 A char pointer initialized with a null character

write declarations for all of them.

15. Compile and run the following program. What do you get on the screen, and why?

#include <stdio.h>

int main()

int i;

for (i=0; i<5; i++){

int x = 0;

static int y = 0;

printf("x=%d, y=%d\n", x++, y++);

return 0;

29
Lesson 8:

Arrays

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1. Defining an Array

3.2. One Dimensional Array

3.2.1. Initializing One Dimensional Array

3.2.2. Processing One Dimensional Array

3.3. Multidimensional Arrays

3.3.1 Initializing Two Dimensional Array

3.3.2 Processing Two Dimensional Array

3.4. Passing Arrays to Functions

3.5. Dynamic Arrays

3.6. Arrays and Strings

4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

1. Introduction

As we know that variable are used to store one value at a time means a variable stores only

single value at a time. In case of storing say 100 values, it is a very difficult task to store 100

2
different variable names with their values. Arrays are the solution to this problem. Arrays are

nothing but a single name to a whole group of similar type of data. The position in terms of

arrays is known as subscript. Each subscript must be expressed as a non-negative integer. The

number of subscripts determines the dimension of the array.

In this lesson, we will discuss two important data types – array and pointer – which come

under the category of derived data types as we have studied earlier in Unit 1. One more

reason why we should read array and pointers is that the concept of array and pointer are

similar to each other. In fact the identifier of an array is equivalent to the address of its first

element, like a pointer is equivalent to the address of the first element that it points to, so in

fact they are similar. In the first half of the lesson we have discussed the methods of

initialization and declaration of arrays, further we have given the use of array in function,

and also defined the multidimensional arrays. All the topics are given with suitable

examples.

2. Objectives

After working through this lesson you should be able to:

1. Initialize and declare the arrays

2. Do the manipulation using arrays

3. Pass on array to a function,

4. Understand the use of dynamic memory allocation.

5. Understand how strings can be created using arrays.

3
3. Presentation of Contents

3.1. DEFINING AN ARRAY

Arrays are defined in much the same manner as ordinary variables except that each array

name must be followed by a size specification. Arrays are of two types, One-Dimensional

Arrays and Multidimensional Arrays. For a one-dimensional array, the size is specified

by a positive integer expression enclosed in single square brackets. When two or more

subscripts are used then array called multidimensional arrays.

3.2. ONE DIMENSIONAL ARRAY

An array is a collection of data storage locations, each of which holds the same type of

data. These storage areas are called elements. Arrays are used to handle large amounts of

data. An array can be thought of as a collection of numbered boxes each containing one

data item. The number associated with the box is the index of the item. To access a

particular item the index of the box associated with the item is used to access the

appropriate box. The index must be an integer and indicates the position of the element in

the array. Thus the elements of an array are ordered by the index. Array subscripts start

with the number 0 (not 1).

If the name of the array is arr, then arr[0] is the name of the element that is in position 0,

arr[1] is the name of the element that is in position 1, etc. In general, the ith element is in

position i – 1. So if the array has n elements, their names are arr[0], arr[1], arr[2], . . . ,

arr[n – 1].

Syntax:

Storage-class data-type array name[expression];

4
e.g.

int a[5]; //storage class is auto by default

Fig. 1 Declaration of Array in memory showing storage at continuous location

char name[100]; // declares an array of 100 characters

static char name1[100];

NOTE: The array’s size can be defined in terms of a symbolic constant rather than a fixed

integer quantity.

3.2.1. INITIALIZING ONE DIMENSIONAL ARRAY

An array can be initialized like other variable. Following are the methods of initializing an

array. e.g.

int a[5]={10,20,30,40,50}; // declares an array of five elements

 At the time of initialization, the size of array can be omitted. e.g.

int a[ ] = {10,20,30,40,50};

 All global and local static array elements are set to 0.

int a[5]={10,20,30}; //In this case a[3] and a[4] that are not initialized and are

automatically set to zero.

5
3.2.2. PROCESSING ONE DIMENSIONAL ARRAY

One dimensional array is a collection of finite number of elements of same data type. Each

element of array has a unique index or subscript starting from 0 and ending at n-1. The

subscript denotes the elements of array. The elements of array are accessed by specifying

the name of the array, beginning square bracket, subscript (index) and closing square

bracket.

Suppose we define an array

int a[5];

The values in the array can be stored by using one of the following methods.

a[0]=10;

a[1]=25;

a[2]=35;

a[3]=55;

a[4]=15;

or

int a[5]={10,25,35,55,15};

or

You can use a loop to store values in the array.

for(i=0;i<5;i++)

scanf(“%d”,a[i]);

6
Fig. 2 Declaration and initialization of array in memory

After storing the values in the array, these can be accessed. Suppose you want to show the

value of 3rd element then the following statement will display the required element.

printf(“%d”,a[2]); // it will print value 35

Program 1. Program to show the use of an array

#include<stdio.h>

#include<conio.h>

void main( )

int n1,n2,n3,n4,n5,n6,n7,n8,n9,n10;

int m[10],I;

clrscr( );

printf(“Enter 10 numbers\n”);

scanf(“%d%d%d%d%d%d%d%d%d%d”,&n1,&n2,&n3,&n4,&n5,&n6,&n7,&n8,&n9,&n

10); // reading 10 numbers without array.

Printf(“%d %d %d %d %d %d %d %d %d %d”,n1,n2,n3,n4,n5,n6,n7

,n8,n9,n10); //displaying 10 numbers without array.

7
for(i=0;i<10;i++)

scanf(“%d”,&m[i]); //reading 10 numbers with array.

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

printf(“%d ”,m[i]); //displaying 10 numbers with array.

getch( );

First part of the program reads 10 numbers from keyboard in 10 different variables naming n1,

n2 up to n10 and similarly display them without an array. And in second part of the program,

above stated works of reading numbers done by using an array. It is easier than first part of

work.

3.3. MULTIDIMENSIONAL ARRAYS

Array with more than one subscript is known as multidimensional array. The following syntax

is used to declare a multidimensional array.

Syntax:

Storage-class data-type array-name[size][size]….[size];

8
An array with two subscript called as two dimensional array. A two dimensional array is a

grid containing rows and columns, in which each element is uniquely specified by means of its

row and column coordinates. e.g.

int a[2] [3]. //first subscript represents row and second subscript represent columns

Fig. 3 Two Dimensional array in memory

3.3.1 INITIALIZING TWO DIMENSIONAL ARRAY

An array can be initialized like other variable. Following are the methods of initializing

two dimensional arrays.

int a[2] [3]={10,20,30,40,50,60}; // Declares an array of two rows and three columns.

 At the time of initialization, the size of array can be omitted. When size will be

omitted then initialization will be in the form below:

int a[ ] [ ] = {

{10,20,30}, //presence of comma here

{40, 50, 60} //absence of comma hers

}; // end of initialization

9
Fig. 4 Declaration and initialization of two dimensional array in memory

where

a[0][0]=10

a[0][1]=20

a[0][2]=30

a[1][0]=40

a[1][1]=50

a[1][2]=60

3.3.2 PROCESSING TWO DIMENSIONAL ARRAY

Value of the elements of the two dimensional array are accessed by specifying the name of

array, row and column of element.

Suppose we define an array

int a[2][3];

The values in the array can be stored by using one of the following methods.

a[0][0]=10

a[0][1]=20

a[0][2]=30

10
a[1][0]=40

a[1][1]=50

a[1][2]=60

or

int a[2] [3]={10,20,30,40,50,60};

or

You can use a loop to store values in the array.

for(i=0;i<2;i++)

for(j=0;j<3;j++)

scanf(“%d”,a[i] [j]);

Fig. 5 Two dimensional array in memory at continuous location

After storing the values in the array, these can be accessed. Suppose you want to show the

value of 2nd row and 2nd column then the following statement will display the required

element.

printf(“%d”,a[1][1]); // it will print value 50

Program 2. A program to add two matrices

11
#include<stdio.h>

#include<conio.h>

void main( )

int a[2][3],i,j;

clrscr();

printf(“Elements of array\n”);

for(i=0;i<2;i++) //outer for loop used for row

for(j=0;j<3;j++) // inner for loop used for column

scanf(“%d”,a[i][j]); //elements read here

printf(“\nentered elements are”);

for(i=0;i<2;i++)

for(j=0;j<3;j++)

printf(“%d ”,a[i][j]); //elements displayed here

12
getch();

Program 3. A program to add two tables of numbers

#include<stdio.h>

#include<conio.h>

void main()

int a[5][5],b[5][5],c[5][5],i,j,row,col;

clrscr();

printf("Enter first matrix row and columns\n");

scanf("%d%d",&row,&col);

printf("\nEnter elements of first matrix\n");

for(i=0;i<row;i++)

for(j=0;j<col;j++)

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

printf("Enter second matrix row and columns\n");

scanf("%d%d",&row,&col);

printf("\nEnter elements of second matrix\n");

13
for(i=0;i<row;i++)

for(j=0;j<col;j++)

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

/*addition of a and b matrix is*/

for(i=0;i<row;i++)

for(j=0;j<col;j++)

c[i][j]=a[i][j]+b[i][j];

printf("\nelements of c matrix are\n");

for(i=0;i<row;i++)

for(j=0;j<col;j++)

printf("%d ",c[i][j]);

printf("\n");

getch();

14
OUTPUT:

Enter first matrix row and columns

Enter elements of first matrix

10

20

30

40

Enter second matrix row and columns

Enter elements of second matrix

10

20

30

40

15
elements of c matrix are

20 40

60 80

3.4. PASSING ARRAYS TO FUNCTIONS

An array name can be used as an argument to a function, thus permitting the entire array to be

passed to the function. An array is itself a pointer. The name of the array points to the address

of the first array element. Hence all array are passed by reference rather than by value. Being

an address, no ampersand(&) precedes array name when used as actual array name.

Program 4. Program to show the passing of array to function

#include<stdio.h>

#include<conio.h>

void rev(int x ,int number[]); //function declaration includes array as formal argument.

void main( )

int i,j,n;

int num[25];

clrscr( );

printf(“Enter no. of elements\n”);

16
scanf(“%d”,&n);

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

scanf(“%d”,&num[i]);

rev(n,num);

printf(“elements of array after function rev()\n\n”);

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

printf(“%d\n”,num[i]);

getch( );

void rev(int x,int number[])

int a,b,temp;

for(a=0,b=x-1;a<b;a++,b- -)

temp=number[a];

number[a]=number[b];

number[b]=temp;

OUTPUT:

Enter no. of elements 5

10

17
5

15

25

elements of array after function rev()

25

15

10

3.5. DYNAMIC ARRAYS

The dynamic array is an array data structure which can be resized during runtime which

means elements can be added and removed. You can see in the given example that we

prompt the user to enter the number of elements that you want to set into the array.

The expression (int*)malloc(n*sizeof (int)) stores the number of elements in the memory.

The malloc is basically used for memory allocation. By using for loop, the variable i reads

the elements from the memory and displays the required array.

Program 5: A Program show the use of dynamic arrays

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

18
int main() {

int* array;

int n, i;

printf("Enter the number of elements: ");

scanf("%d", &n);

array = (int*) malloc(n*sizeof(int));

for (i=0; i<n; i++) {

printf("Enter number %d: ", i);

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

printf("\nThe Dynamic Array is: \n");

for (i=0; i<n; i++) {

printf("The value of %d is %d\n", i, array[i]);

printf("Size= %d\n", i);

getch();

return 0;

3.6. ARRAYS AND STRINGS

Strings can be represented as a one-dimensional character-type array. Each character within

the string will be stored within one element of the array. For example,

19
char name[ ]= {‘I’,‘N’,‘D’,’I’,’A’,‘\0’};

Each character in the array takes one byte of memory and the last character is always ‘\0’.

The terminating null is important, because it is the only way the functions that work with a

string can know where the string ends. In facts, a string which is not terminated by a ‘\0’ is

not really a string but merely a collection of characters.

 The above string can be also initialized as

char name[ ]= “INDIA”;

In this declaration ‘\0’ is not necessary. C inserts the null character automatically. Let us

consider an example to demonstrate printing of string.

Program 6. This program demonstrate printing of string

# include <stdio.h>

main()

char name [ ]=”INDIA”;

int i;

for(i=0;i<5;i++)

printf(“%c”, name [i];

}
20
OUTPUT:

INDIA.

 With the help of null character this program can be written in the following manner:

#include <stdio.h>

main()

char name [ ]=”INDIA”;

int i ;

for(i=0;name[i]!=’\0’;i++)

printf(“%c”, name [i];

OUTPUT:

INDIA

Program 7. A program to print your name

#include<stdio.h>

main()

21
char name[20];

printf(“Enter your name\n”);

scanf(“%s”, name);

printf(“\nyour name is %s”, name);

OUTPUT:

Enter your name

Bharat kumar

your name is Bharat

It will print the same string as entered from the user. The length of string should not exceed the

dimension of the character array. This is because the C compiler doesn’t perform bounds

checking on character arrays.

Program 8. A Program to find the transpose of a matrix

#include<stdio.h>

#include<conio.h>

void main()

int a[5][5],m,n,i,j;

22
clrscr();

printf("Enter rows & cols of a matrix\n");

scanf("%d%d",&m,&n);

printf("Enter elements of matrix:\n");

for(i=0;i<m;i++)

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

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

printf("original matrix is:\n");

for(i=0;i<m;i++)

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

printf("%d ",a[i][j]);

printf("\n");

printf("Transpose of a matrix:\n");

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

for(j=0;j<m;j++)

23
printf("%d ",a[j][i]);

printf("\n");

getch();

OUTPUT:

Enter rows & cols of a matrix

Enter elements of matrix:

original matrix is:

123

24
456

Transpose of a matrix:

14

25

36

Program 9. A Program to multiply two matrices

#include<stdio.h>

#include<conio.h>

void main()

int x[10][10],y[10][10],z[10][10];

int r,c,m,n,j;

clrscr();

printf("Enter rows & cols of matrix\n");

scanf("%d%d",&r,&c);

if(r!=c)

25
printf("Cols of first matrix must equal to rows of second matrix\n");

exit();

printf("Enter elements of first matrix:\n");

for(m=0;m<r;m++)

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

scanf("%d",&x[m][n]);

printf("Enter elements of second matrix:\n");

for(m=0;m<r;m++)

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

scanf("%d",&y[m][n]);

printf("Multiplication of two matrix:\n");

for(m=0;m<r;m++)

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

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

z[m][n]=z[m][n] + x[m][j] * y[j][n];

26
}

for(m=0;m<r;m++)

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

printf("%8d",z[m][n]);

printf("\n");

getch();

OUTPUT:

Enter rows & cols of matrix

Enter elements of first matrix:

27
4

Enter elements of second matrix:

Multiplication of two matrix:

11 14

15 22

Example 1. Point out the errors if any

i) int x[5] //missing semicolon

ii) int x(5); //incorrect braces( )

iii) int x[5+2]; // no error

iv) float y[10] // missing semicolon

v) float y[10+x]; // due to index 10+x

vi) char name[3]=”amar”; // array size is lower

Example 2. What would be output of the following program segment.

i) main()

int i, a[5];

28
for(i=0; i<5; i++)

printf(“%d” , a[ i ] );

OUTPUT: it shows garbage value because of not initialization of array element.

ii) main()

int i;

static int a[5]= {1,5,15,25,35};

for(i=0;i<5;i++);

a[i]*=a[i];

printf(“%d”,a[i]);

OUTPUT: No output because of semicolon at the end of for loop.

iii) main()

int array[26],i;

for(i=0;i<=25;i++)

29
array[i]=’A’+i; // it adds A’s ascii value i.e.65 and

value of i

printf (“\n %d %c \n”, array[i], array[i]); /* it will print ascii value and

character */

OUTPUT: it shows the ascii value and its corresponding character from 65 to 90

because A’s ascii value is 65.

4. Summary

An array is used to store homogeneous data, i.e. data of the same type.

All the elements of an array have the same name, i.e. the array name. They are

distinguished on the basis of their locations in the array. Locations are specified by

using an integer value known as an index or a subscript.

Arrays are also known as indexed variables or subscripted variables.

Array index in C starts with 0.

Arrays are stored in contiguous (i.e. continuous) memory locations.

Arrays are classified as single-dimensional arrays and multi-dimensional arrays.

Subscript operator is used to access the elements of an array.

30
The array name refers to the address of the first element of the array and is a constant

object.

In C language, multi-dimensional arrays are stored in the memory by using row major

order of storage.

5. Suggested Reading/Reference Material

1. Gottfried, Byron S., “Programming with C”, Tata McGraw Hill

2. Balagurusamy, E., “Programming in ANSI C”, McGraw-Hill

3. Balagurusamy, E., “Computing Fundamentals & C Programming”, McGraw-Hill

4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

5. Yashwant Kanetker, “Let us C”, BPB

6. Rajaraman, V., “Computer Programming in C”, PHI

6. Self Assessment Questions

1. What are the limitations of an ordinary variable? How are these removed with an

array?

2. Define array? How many types of array? Explain with example.

3. Explain the method of accessing elements of an array with example.

4. Define multi- dimensional array with example.

5. Write a program that will compute the length of a given character string.

31
6. Write a program that will count the number of occurrences of a specified character

in a given line of text.

7. Write a program to read two matrices A and B and print the following:

(a) A + B (b) A-B

8. Write a program to implement binary search algorithm.

9. Discuss how initial values can be assigned to a multidimensional array.

10. What is a dynamic array? How it is created? Give typical example of a dynamic

array.

11. What happens when an array with a specified size is assigned

(a) With values fewer than the specified size

(b) With values more than the specified size.

12. What is the output of the following program?

main( )

int m[ ] = { 2,3,4,5,6 }

int x, y =0;

for (x=0; x<5; x++)

y=y+m[x];

print (“%d”, y);

32
Lesson 9:

Strings

Dr. Satinder Bal Gupta

1
Structure:

1. Introduction

2. Objectives

3. Presentation of Contents

3.1. String Handling

3.1.1. Initializing Strings

3.1.2 String Constants Versus Character Constants

3.2. Reading And Writing Strings

3.3. String Functions

3.4. Dynamic Strings

4. Summary

5. Suggested Reading/Reference Material

6. Self Assessment Questions

2
1. Introduction

In the last lesson you learned how to use arrays to collect variables of the same type. You also

learned that a character string is actually a character array ended with a null character \0. In this

lesson you'll learn more about strings and C functions that can be used to manipulate strings.

Strings are often needed to be manipulated by programmer according to the need of a problem.

All string manipulation can be done manually by the programmer but, this makes programming

complex and large. To solve this, the C supports a large number of string handling functions.

There are numerous functions defined in "string.h" header file for reading, writing, copying,

comparing, combining, searching, etc.

2. Objectives

After working through this lesson you should be able to:

1. Understand the strings and string handling.

2. How to read and write strings.

3. Understand and use string functions available in string header file.

4. Create programs using string library functions.

5. Understand the dynamic strings.

3. Presentation of Contents

3
3.1. STRING HANDLING

Definition: A string is a character array terminated by a null character (\0). For instance, a

character array, array_ch, declared in the following statement, is considered a character string:

char array_ch[7] = {`H', `e', `l', `l', `o', `!', `\0'};

In C, the null character can be used to mark the end of a string, or to return logical FALSE. C

treats \0 as one character. Each character in a string takes only 1 byte.

A series of characters enclosed in double quotes ("") is called a string constant. The C compiler

can automatically add a null character (\0) at the end of a string constant to indicate the end of

the string.

3.1.1. INITIALIZING STRINGS

A character array can be declared and initialized like this:

char arr_str[6] = {`H', `e', `l', `l', `o', `!'};

Here the array arr_str is treated as a character array. However, if you add a null character (\0)

into the array, you can have the following statement:

char arr_str[7] = {`H', `e', `l', `l', `o', `!', `\0'};

Here the array arr_str is expanded to hold seven elements; the last element contains a null

character. Now, the character array arr_str is considered a character string because of the null

character that is appended to the array.


4
You can also initialize a character array with a string constant. For example, the following

statement initializes a character array, str, with a string constant, "Hello!":

char str[7] = "Hello!";

The compiler can automatically append a null character (\0) to the end of the array, and treat the

character array as a character string. Note that the size of the array is specified to hold up to

seven elements, although the string constant has only six characters enclosed in double quotes.

The extra space is reserved for the null character.

You can declare an unsized character array if you want the compiler to calculate the total number

of elements in the array. For Example, the following statement

char str[ ] = "I like C.";

initializes an unsized character array, str, with a string constant.

3.1.2. STRING CONSTANTS VERSUS CHARACTER CONSTANTS

A string constant is a series of characters enclosed in double quotes (" "). On the other hand, a

character constant is a character enclosed in single quotes (` `).

When a character variable ch1 and a character array str1 are initialized with the same character,

x, such as the following,

char ch1 = `x';

char str1[] = "x";

5
1 byte is reserved for the character variable ch1, and two bytes are allocated for the character

array str1. The reason that an extra byte is needed for str1 is that the compiler has to append a

null character to the array.

Another important thing is that a string is interpreted as a char pointer. Therefore, you can assign

a character string to a pointer variable directly, like this:

char *ptr_str;

ptr_str = "A character string.";

3.2. READING AND WRITING STRINGS

In C, there are several functions you can use for string reading or writing. Some of these

functions are as follows.

1. The gets() Function : The gets() function can be used to read characters from the

standard input stream. The syntax for the gets() function is

#include <stdio.h>

char *gets(char *s);

Here the characters read from the standard input stream are stored in the character array

identified by s. The gets() function stops reading, and appends a null character \0 to the

array, when a newline or end-of-file (EOF) is encountered. The function returns s if it

concludes successfully. Otherwise, a null pointer is returned.

6
2. The puts() Function: The puts() function can be used to write characters to the standard

output stream (that is, stdout). The syntax for the puts() function is

#include <stdio.h>

int puts(const char *s);

Here s refers to the character array that contains a string. The puts() function writes the

string to the stdout. If the function is successful, it returns 0. Otherwise, a nonzero value

is returned. The puts() function appends a newline character to replace the null character

at the end of a character array.

Both the gets() and puts() functions require the header file stdio.h. In the following

program, you can see the working of these two functions.

Program 1. Using the gets() and puts() functions.

#include <stdio.h>

main()

char str[80];

int i, delt = `a' - `A';

printf("Enter a string less than 80 characters:\n");

gets( str );

i = 0;

while (str[i])

{
7
if ((str[i] >= `a') && (str[i] <= `z'))

str[i] -= delt; /* convert to upper case */

++i;

printf("The entered string is (in uppercase):\n");

puts( str );

return 0;

OUTPUT

Enter a string less than 80 characters:

This is a string.

The entered string is (in uppercase):

THIS IS A STRING.

The above program accepts a string of characters entered from the keyboard and then

converts all lowercase characters to uppercase ones. Finally, the modified string is put

back to the screen.

3. Using %s with the printf() Function : You have used the printf() function in many

programs in earlier lessons. Further, you also know that many format specifiers can be

8
used with the printf() function to specify different display formats for numbers of various

types. Similarly, you can use the string format specifier, %s, with the printf() function to

display a character string saved in an array on the screen.

4. The scanf() Function : The scanf() function provides another way to read strings from

the standard input stream. The formats of arguments to the scanf() function are quite

similar to those used in the printf() function. The syntax for the scanf() function is

#include <stdio.h>

int scanf(const char *format, …);

Here various format specifiers can be included inside the format string referenced by the

char pointer variable format. If the scanf() function concludes successfully, it returns the

number of data items read from the stdin. If an error occurs, the scanf() function returns

EOF (end-of-file).

Note that using the string format specifier %s causes the scanf() function to read

characters until a space, a newline, a tab, a vertical tab, or a form feed is encountered.

Characters read by the scanf() function are stored into an array referenced by the

corresponding argument. The array should be big enough to store the input characters.

A null character is automatically appended to the array after the reading.

The following program shows how to use various format specifiers with the scanf()

function.

9
Program 2. A program that uses the scanf() function with various format specifiers.

#include <stdio.h>

main()

char str[80];

int x, y;

float z;

printf("Enter two integers separated by a space:\n");

scanf("%d %d", &x, &y);

printf("Enter a floating-point number:\n");

scanf("%f", &z);

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

scanf("%s", str);

printf("You have entered:\n");

printf("%d %d\n%f\n%s\n", x, y, z, str);

return 0;

OUTPUT

Enter two integers separated by a space:

10 12345

Enter a floating-point number:

1.234567
10
Enter a string:

string

you have entered:

10 12345

1.234567

String

3.3. STRING FUNCTIONS

Strings are often needed to be manipulated by programmer according to the need of a problem.

All string manipulation can be done manually by the programmer but, this makes programming

complex and large. To solve this, the C supports a large number of string handling functions.

There are numerous functions defined in "string.h" header file. Few commonly used string

handling functions are shown in Table 1.

Function Work Of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

strlwr() Converts string to lowercase

11
strupr() Converts string to uppercase

Determines the first occurrence of a given character in a string.


strchr()

Determines the last occurrence of a given character in a string.


strrchr()

Determines the first occurrence of a given string in another string.


strstr()

Reversing all characters of a string.


strrev()

Table 1. Commonly used string handling functions

1. The strlen() Function : This function is used to know how many bytes are taken by a

string, This means it measures the length of a string. The syntax for the strlen() function

is

#include <string.h>

size_t strlen(const char *s);

Here s is a char pointer variable. The return value from the function is the number of

bytes. size_t is a data type defined in the string.h header file. Note that string.h has to be

included in your program before you can call the strlen() function.

The following program shows the use of strlen() function to measure string lengths.

Program 3. Program to measure string lengths.

#include <stdio.h>
12
#include <string.h>

main()

char str1[] = {`A', ` `,

`s', `t', `r', `i', `n', `g', ` `,

`c', `o', `n', `s', `t', `a', `n', `t', `\0'};

char str2[] = "Another string constant";

char *ptr_str = "Assign a string to a pointer.";

printf("The length of str1 is: %d bytes\n", strlen(str1));

printf("The length of str2 is: %d bytes\n", strlen(str2));

printf("The length of the string assigned to ptr_str is: %d bytes\n",

strlen(ptr_str));

return 0;

OUTPUT

The length of str1 is: 17 bytes

The length of str2 is: 23 bytes

The length of the string assigned to ptr_str is: 29 bytes

NOTE: The strlen() function does not count the null characters appended to the two string

constants by the compiler.

13
2. Copying Strings with strcpy() : This function is used to copy a string from one array to

another. You can copy each item of the first array to the corresponding element in the

second array, or you can simply call the C function strcpy(). The syntax for the strcpy()

function is

#include <string.h>

char *strcpy(char *dest, const char *src);

Here the content of the string src is copied to the array referenced by dest. The strcpy()

function returns the value of src if it is successful. The header file string.h must be

included in your program before the strcpy() function is called.

The following program shows how to copy a string from one array to another by either

calling the strcpy() function or by doing it yourself.

Program 4. Program to Copy strings.

#include <stdio.h>

#include <string.h>

main()

char str1[] = "Copy a string.";

char str2[15];

char str3[15];

int i;

14
/* with strcpy() */

strcpy(str2, str1);

/* without strcpy() */

for (i=0; str1[i]; i++)

str3[i] = str1[i];

str3[i] = `\0';

/* display str2 and str3 */

printf("The content of str2: %s\n", str2);

printf("The content of str3: %s\n", str3);

return 0;

OUTPUT

The content of str2: Copy a string.

The content of str3: Copy a string.

3. Concatenates (joins) two strings with strcat(): This function concatenates the strings. It

does not concatenate two strings together and give you a third, new string; what it really

does is append one string onto the end of another. For example,

char string5[20] = "Hello, ";

char string6[] = "world!";

15
printf("%s\n", string5);

strcat(string5, string6);

printf("%s\n", string5);

The first call to printf function prints ``Hello, '', and the second one prints ``Hello,

world!'', indicating that the contents of string6 have been tacked on to the end of string5.

Notice that we declared string5 with extra space, to make room for the appended

characters.

4. Compares two string with strcmp() : This function compares two strings, and returns 0

if they are identical, or a negative number if the first string is alphabetically ``less than''

the second string, or a positive number if the first string is ``greater.'' The meaning of one

string to be ``less than'' another is that it would come first in a dictionary or telephone

book. For example,

char string3[] = "this is";

char string4[] = "a test";

if(strcmp(string3, string4) == 0)

printf("strings are equal\n");

else printf("strings are different\n");

These lines of code will print ``strings are different''. Notice that strcmp does not return a

Boolean, true/false, zero/nonzero answer.

3.4. DYNAMIC STRINGS

16
The dynamic string is an array data structure which can be resized during runtime which means

characters can be added and removed. As you have seen in case of dynamic arrays, in the given

example, we prompt the user to enter the number of elements that you want to set into the array.

The expression (int*)malloc(n*sizeof(char)) allocates the memory equivalent to the number of

characters. By using for loop, the variable i reads the characters from the memory and displays

the required string.

Program 5: A Program show the use of dynamic arrays

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

int main()

int* array;

int n, i;

printf("Enter the number of characters: ");

scanf("%d", &n);

array = (int*) malloc(n*sizeof(char));

for (i=0; i<n; i++) {

printf("Enter character %d: ", i);

scanf("%c", &array[i]);

printf("\nThe Dynamic string is: \n");


17
for (i=0; i<n; i++) {

printf("The value of %d is %c\n", i, array[i]);

printf("Size= %d\n", i);

getch();

return 0;

Program 6: Program for String Comparison

#include<stdio.h>

#include<string.h>

#define MAX_STRING_LEN 80

int main() {

char S1[MAX_STRING_LEN];

char S2[MAX_STRING_LEN];

int i, l, res;

printf("String1:\t");

scanf("%s",S1);

printf("String2:\t");

scanf("%s",S2);

res = strcmp(S1,S2);

printf("strcmp(%sS1,%sS2) = %d\n",S1,S2,res);

18
Program 7: Program to Copy Strings

#include<stdio.h>

#include<string.h>

#define MAX_STRING_LEN 80

int main() {

char* S1 = "AAAAAAAAAA";

char* S2 = "BBBBBBBBBB";

int i, l;

/* assign S1 to S2 */

S2 = S1;

/* change S1 */

S1[0] = S1[1] = S1[2] = '*';

S1[3] = 0;

/* print both strings */

printf("S1:\t%s\n",S1);

printf("S2:\t%s\n",S2);

Program 8: Program to check equality of Strings

#include<stdio.h>

#include<string.h>

#define MAX_STRING_LEN 80

19
int main() {

char* S1 = "AAAAAAAAAA";

char* S2 = "AAAAAAAAAA";

int cmp1, cmp2, cmp3, cmp4;

cmp1 = (S1 == S2);

cmp2 = strcmp(S1,S2);

printf("S1:\t%s\n",S1);

printf("S2:\t%s\n",S2);

printf("S1 == S2:\t%d\n",cmp1);

printf("strcmp(S1,S2):\t%d\n",cmp2);

S2 = S1;

cmp3 = (S1 == S2);

cmp4 = strcmp(S1,S2);

printf("\nafter assignment\n");

printf("S1:\t%s\n",S1);

printf("S2:\t%s\n",S2);

printf("S1 == S2:\t%d\n",cmp3);

printf("strcmp(S1,S2):\t%d\n",cmp4);

Program 9: Program to concatenate two strings

#include<string.h>

20
#include<stdio.h>

#define MAX_STRING_LENGTH 80

int main() {

char S1[MAX_STRING_LENGTH];

char S2[MAX_STRING_LENGTH];

strcat(S1,S2);

printf("S1:\t");

scanf("%s",S1);

printf("S2:\t");

scanf("%s",S2);

strcat(S1,S2);

printf("\nafter strcat(S1,S2)\n");

printf("S1:\t%s\n",S1);

printf("S2:\t%s\n",S2);

You can also create and use two dimensional Arrays of characters. Let us first consider an example

of 2D array of character.

21
Program 10. A program to show 2D array of character

#include <stdio.h>

#include<conio.h>

main()

char sample[6][10]= { "amar", "akbar", "anthony", "ram","sham","ghansham"};

int i, flag, a;

char name[10];

clrscr();

printf("Enter your name\n");

scanf("%s",&name);

flag=0;

for(i=0;i<=5;i++)

a = strcmp(&sample[i][0],name);

if(a== 0)

printf("You are a right candidate");

flag =1;

break;
22
}

if(flag==0)

printf("Wrong candidate");

getch();

OUTPUT:

First Run:

Enter your name

ghansham

You are a right candidate

Second Run:

Enter your name

bharat

Wrong candidate

The program shows how the two dimensional character array has been initialized. The order of the

23
subscripts in the array declaration is important. The first subscript gives the number of names in the

array, while the second subscript gives the length of each item in the array.

4. Summary

A string literal is a sequence of zero or more characters enclosed within double quotes.

A string literal is automatically terminated by a null character.

A null character has an ASCII value of 0 and is written as '\0'.

Due to this additional null character, a string constant takes 1 byte more than the number of

characters present in the string.

String literals are stored in character arrays.

In C language, string type is not separately available and character pointers are used to

represent a string.

The type of string literal constants is const char*. The constant pointer refers to the address

of the first character of the string.

Strings can be read from the keyboard by using scanf and gets functions.

The scanf function is used for reading single-word strings while the gets function can be used

for reading multi-word strings.

Strings are printed on the screen by using printf and puts functions.
24
The printf function does not place a new line character after printing the string but

the puts function places a new line character after printing the string.

The C string library provides a rich set of functionality to manipulate strings in the form of

library functions like strcpy, strcmp, strcat, strrev, etc.

Real-time applications often require storage and processing of a number of strings at a time.

A list of strings can be stored by using an array of strings or by using an array of character

pointers.

The main function can also take string inputs from the command line. The arguments given

to the function main from the command line are known as command line arguments.

5. Suggested Reading/Reference Material

1. Gottfried, Byron S., “Programming with C”, Tata McGraw Hill

2. Balagurusamy, E., “Programming in ANSI C”, McGraw-Hill

3. Balagurusamy, E., “Computing Fundamentals & C Programming”, McGraw-Hill

4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,

Addison Wesley.

5. Yashwant Kanetker, “Let us C”, BPB

6. Rajaraman, V., “Computer Programming in C”, PHI

25
6. Self Assessment Questions

1. Define an array of char(String) with example?

2. What is string terminator? What is its purpose explain its importance with example.

3. Write short note on:

i) strcpy( )

ii) strcat( )

iii) strlen( )

iv) strcmp( )

4. What is a string? How do you know its length?

5. What are the main differences between a string constant and a character constant?

6. Does the gets() function save the newline character from the standard input stream?

7. What types of data can the scanf() function read?

8. In the following list, which statements are legal?

i. char str1[5] = "Texas";

ii. char str2[] = "A character string";

iii. char str3[2] = "A";

iv. char str4[2] = "TX";

9. Given a char pointer variable ptr_ch, are the following statements legal?

i. *ptr_ch = `a';

ii. ptr_ch = "A character string";

iii. ptr_ch = `x';

iv. *ptr_ch = "This is Quiz 2.";

26
10. Can the puts() function print out the null character in a character array?

11. Which format specifier do you use with the scanf() function to read in a string, and which

one do you use to read a floating-point number?

12. Given a character array in the following statement,

char str1[ ] = "This is Program.";

Write a program to copy the string from str1 to another array, called str2.

13. Write a program to measure the length of a string by evaluating the elements in the

character array one by one. To prove you get the right result, you can use the strlen()

function to measure the same string again.

14. Write program that convert all uppercase characters to their lowercase counterparts.

15. Write a program that uses the scanf() function to read in two integers entered by the user,

adds the two integers, and then prints out the sum on the screen.

27
Post Graduate Diploma in Computer Science and Applications

PROBLEM SOLVING THROUGH C

Paper :CS-DE-12 Written by – Dr. Charu

Lesson No: 10 Vetted by:Dr. ShuchitaUpadhyaya

1. INTRODUCTION

2. OBJECTIVE

3. CONTENTS

3.1 WHAT ARE POINTERS?


3.1.1 DECLARING AND INITIALIZING POINTERS
3.1.2 POINTER EXPRESSIONS
3.1.3 POINTER ARITHMATIC
3.2 TYPES OF POINTERS
3.3 ALLOCATING A BLOCK OF MEMORY
3.4 POINTERS AND ARRAY
3.5 POINTERS AND FUNCTIONS
3.5.1 POINTERS TO FUNCTIONS
3.5.2 FUNCTIONS RETURNING POINTERS
3.6 ARRAY OF POINTERS
3.7 POINTERS AND STRINGS

4.EXAMPLE PROGRAMS

4.1PROGRAM TO ADD TWO NUMBERS USING POINTERS

4.2 SORTING A LIST OF NUMBERS USING FUNCTIONS


4.3DEMOSTRATE USE OF SUBSCRIPTING AND POINTER
NOTATIONS WITH ARRAYS

4.4COPYING A STRING USING ARRAY NOTATION AND POINTER


NOTATION.

4.5MULTIPURPOSE SORTING PROGRAM USING FUNCTION


POINTERS

5. SUMMARY

6. SUGGESTED READINGS

7. SELF ASSESSMENT QUESTIONS


1. INTRODUCTION

In C, variables are used to hold data values during the execution of a program. Every variable,
when declared occupies certain memory location. Pointer variable stores the memory address of
any type of variable. It is denoted by, asterisk (*), symbol. With pointers, one can manipulate
memory addresses. It is possible to access and display the address of a memory location of
variable using the pointers. Pointers are also used for the allocation of me ory during run time,
also known as dynamic memory allocation. Dynamic memory allocation is essential for handling
various data structures like, structures, trees, linked lists, stacks, most important, being arrays.
Another use of pointers is command-line arguments. Command line arguments are passed to
programs and stored in an array of pointers.

2. OBJECTIVE

Most of the computer language learners feel that the pointer is a puzzling topic and very difficult
to understand. However, the pointer enables fast and straightforward execution of a program.
With pointers, memory is used most efficiently. Pointers reduce length and the complexity of the
programs.They increase the execution speed and thus reduce the program execution time. C
gives more importance to punters because of their flexible and dynamic nature.Hence, it
becomes important to learn the operation and applications of pointers.Thus, the real power of C
lies in te proper use of pointers. In this lesson, pointers and their usage is described in detail. It
also describes the various operations that can be performed on a pointer variable. How the
pointers can be used to handle functions, arrays and strings is also explained.

3.1 WHAT ARE POINTERS?

A pointer is a variable that represents the location of a data item, such as a variable or anarray
element. Pointers are used frequently in C, as they have a number of useful applications.For
example, pointers can be used to pass information back and forth between a functionand its
reference point. Pointers provide a way to return multiple data items from a functionvia function
arguments to be specified as arguments to a given function.Pointers are also closely associated
with arrays and therefore provide an alternate way toaccess individual array elements.

Within the computer’s memory, every stored data item occupies one or more adjacent memory
cells. The number of memory cells required to store a data item depends on the type of dataitem.
For example, a single character will be stored in 1 byte of memory integer usuallyrequires two
adjacent bytes, a floating point number may require four adjacent bytes.

Suppose V is a variable that represents some particular data item. The compiler will
automaticallyassign memory cells for this data item. The data item can be accessed if we know
thelocation of the first memory cell. The address of V’s memory location can be determined
bythe expression &V, where & is a unary operator, called the address operator, that evaluatesthe
address of its operand.Now let us assign the address of V to another variable, PV. Thus,

PV = & V

This new variable is called a pointer to V, since it “Points” to the location where V is stored
inmemory. PV represents V’s address, not its value. Thus, PV iscalled pointer variable.The data
item represented by V can be accessed by the expression *PV where * is a unaryoperator, that
operates only on a pointer variable. Therefore, PV and V both represent thesame data item.
Furthermore, PV = &V and U = PV, then U and V will bothrepresent the same values i.e., the
value of V will indirectly be assigned to U.

3.1.1 DECLARING AND INITIALIZING POINTERS

Since pointer variables contain addresses that belong to a separate data type, they must
bedeclared as pointers before we use them. The declaration of a pointer variable takes
thefollowing form:

data type * Pt _ name

This tells the compiler three things about the variable Pt_name.

1. The * tells that the variable Pt_name is a pointer variable.

2. Pt_name needs a memory location.

3. Pt_nameponts to a variable of type data type.

For Example :
int * P ;

declares the variable P as a pointer variable that points to an integer data type. and

float * y ;

declares y as a pointer to a floating point variable.

Once pointer variable has been declared, it can be made to point to a variable using anassignment
statement such as

P = & quantity ;

which causes P to point to quantity. P contains the address of quantity. This is known aspointer
initialization.

After declaring a pointer, pointer is assigned a value, so that it can point to a particular variable.

eg. int * P ;

inti ;

P=&i;

This is called assignment expression in which pointer variable P is holding the address of i.

3.1.2 POINTER EXPRESSIONS

Like other variables, pointer variables can be used in expressions. Pointer variables can be
incremented, decremented, assigned to and compared with other variables using relational
operators. However, multiplication and division cannot be performed on pointer variables. For
example, if P1 and P2are properly declared and initialized pointers, then the following
statements are valid.

1) Y = * P1 ;

2) Sum = Sum + * P1 ;

3) Z = S - * P2 / * P1 ;
4) * P2 = * P2 + 10 ;

If P1 and P2 are pointers then the expressions such as,P1 + 4 , P2 - 2 , P1 - P2 , P1 ++ , — P2 are


allowedalso,

Sum =Sum + *P2 ;P1 ++ ;- -P2 ;P1 > P2; P1 = = P2; P1 ! = P2are all allowed expressions.

The expressions such as,P1 / P2 or P1 * P2 or P1/3are not allowed.

3.1.3POINTER ARITHMATIC

Two pointer values can be added, multiplied, divided or subtracted together.

eg. if

inti ;

int j ;

int * P , * q ;

i = 5 , j = 10 ;

Now, various pointer arithmetic can be performed

eg. * j = * i + * j ;

The value of variable j is changed from 10 to 15.

*j=*j-*i;

The value of variable j is changed from 10 to 5.

* i = * i ** j ;

The value of i is changed from 5 to 50 ;

3.2TYPES OF POINTERS
1. Void pointer or generic pointer: It is a special type of pointer that can be pointed at objects
of any data type. A void pointer is declared like a normal pointer, using the void keyword as
the pointer’s type.Pointers defined using specific data type cannot hold the address of the
some other type of variable i.e., it is incorrect to assign the address of an integer variable to a
pointer of type float.

float *f; //pointer of type float


inti; //integer variable
f = &i; //compilation error
The above problem can be solved by general purpose pointer called void pointer.Void pointer
can be declared as follows:

void *v // defines a pointer of type void

The pointer defined in this manner do not have any type associated with them and can hold
the address of any type of variable.
void *v;
int *i;
intivar;
charchvar;
floatfvar;
v = &ivar; // valid
v = &chvar; //valid
v = &fvar; // valid
i = &ivar; //valid
i = &chvar; //invalid
i = &fvar; //invalid

2. Null Pointer: It is always a good practice to assign a NULL value to a pointer variable in
case you do not have exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.The NULL pointer is a
constant with a value of zero defined in several standard libraries. The following program
exemplifies a NULL pointer:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}

When the above code is compiled and executed, it produces following result:
The value of ptr is 0.

On most of the operating systems, programs are not permitted to access memory at address 0
because that memory is reserved by the operating system. However, the memory address 0 has
special significance; it signals that the pointer is not intended to point to an accessible memory
location. But by convention, if a pointer contains the null (zero) value, itis assumed to point to
nothing.

3. Dangling pointer: If any pointer is pointing the memory address of any variable but after
some variable has been deleted from that memory location while pointer is still pointing to
such memory location. Such pointer is known as dangling pointer and this problem is known
as dangling pointer problem.
For example:

#include<stdio.h>

int *call();
void main(){

int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);

}
int * call()
(
int x=25;
++x;
return &x;
}

Output: Garbage value


In the above example, variable x is local variable. Its scope and lifetime is within the function
call hence after returning address of x variable x became dead and pointer is still pointing to that
location. To resolve this problem, the variable x must be declared as a static variable.

#include<stdio.h>

int *call();
void main(){

int *ptr;
ptr=call();

fflush(stdin);
printf("%d",*ptr);

}
int * call(){

static int x=25;


++x;

return &x;
}
Output: 26

4. Constant pointer-A constant pointer is a pointer that cannot change the address its holding.
In other words, we can say that once a constant pointer points to a variable then it cannot
point to any other variable.A constant pointer is declared as follows :

<type of pointer> * const<name of pointer>

For example a declaration for a constant pointer would be like :

int * constptr;

#include<stdio.h>

int main(void)

int var1 = 0, var2 = 0;

int *constptr = &var1;

ptr = &var2;

printf("%d\n", *ptr);

return 0;

}
In the above example, two variables var1 and var2 are declared.A constant pointer ‘ptr’ was
declared and made to point var1. Pointerptr is made to point var2.Finally, we try to print the
value ptr is pointing to.So,an address to a constant pointer is assigned and then address is
changed by assigning the address of some other variable to the same constant pointer.

3.3 ALLOCATING A BLOCK OF MEMORY

A block of memory may be allocated using the function malloc(). The malloc() function
reservesa block of memory of specified size and returns a pointer of type void. This means that
we canassign it to any type of pointer. It takes the following form;

ptr = ( Cast type * ) malloc ( byte size ) ;

ptr is a pointer of type cast type. The malloc() returns a pointer (of cast type) to an area of

memory with size byte - size. For Example :

X = ( int * ) malloc ( 100 *sizeof ( int )) ;

Using this statement, a memory space equivalent to “100 times the sizeof an int” bytes is reserved
and the address of the first byte of the memory allocated is assignedto the pointer X of type int.the
malloc() allocates a block of adjacent bytes. The allocation can fail if the space
in the heap is not sufficient to satisfy the request. If it foils, it returns a NULL. It
shouldtherefore,be checked whether the allocation is successful before using the memory
pointer.

3.4 POINTERS AND ARRAY

When an array is declared, the compiler allocates a base address and sufficient amount ofstorage
to contain all the elements of the array in contiguous memory locations. The baseaddress is the
location of the first element (index 0) of the array. The compiler also defines thearray name as a
constant pointer to the first element suppose we declare an array X asfollows :

static int X [ 6 ] = { 1, 2, 3, 4, 5, 6 } ;
Suppose the base address of X is 1000 and assuming that each integer requires two bytes,the five
elements will be stored as follows :

ELEMENTS x [0] x[1] x[2] x[3] x[4] x[5]

VALUE 1 2 3 4 5 6

ADDRESS 1000 1002 1004 1006 1008 1010

The name X is defined as a constant pointer pointing to the first clement,x[0] and therefore the
value of X is 1000, the location whose X[0] is stored. That is,

X = & x[0] = 1000

If we declare P as an integer pointer, then we can make the pointer P to point to the array X

by the following assignment :

P=X;

This is equivalent to P = & X[0] ;Now we can access every value of x using P++ to move from
one element to another. Therelationship between P and X is :

P = & x[0] ( = 1000)

P+1 = & x[1] ( = 1002)

P+2 = & x[2] ( = 1004)

P+3 = & x[3] ( = 1006)

P+4 = & x[4] ( = 1008)

P+5 = & x[5] ( = 1010)

The address of an element is calculated using its index and the scale factor of the data type.

For instance,

address of X[3] = base address + (3 x Scale factor of int)= 1000 + (3 x 2) = 1006


When handling array, instead of using array indexing, we can use pointers to access
arrayelements. Note that *(x+3) gives the value of X[3]. The pointer accessing method is
morefaster than array indexing.

3.5 POINTERS AND FUNCTIONS

When an array is passed to a function as an argument, only the address of the first element ofthe
array is passed, but not the actual values of the array elements. The function uses thisaddress for
manipulating the array elements. Similarly, we can pass the address of a variableas an argument
to a function in the normal fashion.

When we pass addresses to a function, the parameters receiving the addresses should bepointers.
The process of calling function using pointers to pass the address of variable isknown as call by
reference. The function which is called by reference can change the value ofthe variable used in
the call.

eg.

main ( )

int X ;

X = 40 ;

change ( & X ) ;

printf ( “ %d”, X ) ;

change ( int * P )

* P = * P + 10 ;

}
When the function change is called, the address of the variable X, not its value, is passed intothe
function change ( ). Inside change ( ), the variable P is declared as a pointer and thereforeP is the
address of the variable X. The statement,

* P = * P + 10 ;

means add 10 to the value stored at address P. Since P represents the address of X, thevalue of X
is changed from 50. Therefore, the output of the program will be 50 not 40.Thus, call by
reference provides a mechanism by which the function can change the storedvalues in the calling
function.

3.5.1 POINTERS TO FUNCTIONS

A function like a variable, has an address location in the memory. It is therefore, possible
todeclare a pointer to a function, which can then be used as an argument in another function.
Apointer to a function is declared as follows:

type ( * fp) ( ) ;

This tells the compiler that fp is a pointer to a function which returns type value.

We can make a function pointer to point to a specific function by simply assigning the name
ofthe function to the pointer.

For example,

double (*P1)( ), mul ( ) ;

P1 = mul ;

declare P1 as a pointer to a function and mul as a function and then make P1 to point to
thefunction mul. To call the function mul, we may now use the pointer P1 with the list
ofparameters.

That is,

(*P1) (x,y)
is equivalent to mul ( x,y )

3.5.2 FUNCTIONS RETURNING POINTERS

The way functions return an int, a float, a double or any other data type, it can even return
apointer. However, to make a function return a pointer it has to be explicitly mentioned in
thecalling function as well as in the function declaration. The following program illustrates this:

main ( )

int * P ;

int * fun ( ) ;

P = fun ;

printf ( “\n % Id”, P ) ;

int * fun ( )

inti = 20;

return (& i) ;

In this program, function fun( ) is declared as pointer returning function can return the addressof
integer type value and in the body of the function fun ( ) we are returning the address ofinteger
type variable i into P which is also integer type pointer.

3.6 ARRAY OF POINTERS

The way there can be an array of integersor an array of floats, similarly there can be an array
ofpointers. Since, a pointer variable always contain an address, an array of pointers would
benothing but collection of addresses. The addresses present in the array of pointers can
beaddresses of isolated variables or addresses of array elements or any other addresses. Allrules
that apply to an ordinary array apply to the array of pointers as well. For example,

main ( )

int * arra [ 4 ];

inti = 31, j = 5, k = 19, L = 71, m;

arra [0] = & i ;

arra [1] = & j ;

arra [2] = & k ;

arra [3] = & l ;

for (m=0; m<=3 ; m+ +)

printf (“\n% d”, * (arr[m])) ;

The output will be -

31

19

71

3.7 POINTERS AND STRINGS

Strings are basically character arrays and can be declared as

char str[5]=”great”;
The C compiler automatically inserts a null character ‘\0’ at the end of the string. In C, strings
can also be created using pointer variables of type char. For example,

char *str = “great”;

The above statement creates a string for the literal and then stores its address in the pointer
variable str. The pointer str now points to the first character of the string “great”. The siring
pointer can also be assigned value at the run time as ;

char *str1;

str1=”great”;

Similarly, to print the content of the string C provides puts function other than printf as follows:

printf(“%s”, str1);

puts(str1);

Since, str1 is not only the name of the string bur also the pointer to it, the indirection operator *
is not used to access the string.

4.EXAMPLE PROGRAMS

4.1 PROGRAM TO ADD TWO NUMBERS USING POINTERS

#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Entertwo integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
return 0;

OUTPUT:

Entertwo integers to add

Sum of entered numbers = 9

1.2 SORTING A LIST OF NUMBERS USING FUNCTIONS

#include <stdio.h>

#define SIZE 10

void bubbleSort( int * const array, constint size ); /* prototype */

int main( void )

int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };

inti;

printf( "Data items in original order\n" );

for ( i = 0; i < SIZE; i++ )

printf( "%4d", a[ i ] );

bubbleSort( a, SIZE );
printf( "\nData items in ascending order\n" );

for ( i = 0; i < SIZE; i++ )

printf( "%4d", a[ i ] );

OUTPUT:

Data items in original order

2 6 4 8 10 12 89 68 45 37

Data items in ascending order

2 4 6 8 10 12 37 45 68 89

4.3DEMOSTRATE USE OF SUBSCRIPTING AND POINTER NOTATIONS


WITH ARRAYS

#include <stdio.h>

int main( void )

int b[] = { 10, 20, 30, 40 }; /* initialize array b */

int *bPtr = b; /* set bPtr to point to array b */

inti; /* counter */

int offset; /* counter */

/* output array b using array subscript notation */

printf( "Array b printed with:\nArray subscript notation\n" );


/* loop through array b */

for ( i = 0; i < 4; i++ ) {

printf( "b[ %d ] = %d\n", i, );

} /* end for */

/* output array b using array name and pointer/offset notation */

printf( "\nPointer/offset notation where\n""the pointer is the array name\n" );

/* loop through array b */

for ( offset = 0; offset < 4; offset++ ) {

printf( "*( b + %d ) = %d\n", offset, *( ) );

} /* end for */

/* output array b using bPtr and array subscript notation */

printf( "\nPointer subscript notation\n" );

/* loop through array b */

for ( i = 0; i < 4; i++ ) {

printf( "bPtr[ %d ] = %d\n", i, );

} /* end for */

/* output array b using bPtr and pointer/offset notation */

printf( "\nPointer/offset notation\n" );

/* loop through array b */

for ( offset = 0; offset < 4; offset++ ) {

printf( "*( bPtr + %d ) = %d\n", offset, *( ) );


} /* end for */

return 0; /* indicates successful termination */

} /* end main */

OUTPUT:

Array b printed with:

Array subscript notation

b[ 0 ] = 10

b[ 1 ] = 20

b[ 2 ] = 30

b[ 3 ] = 40

Pointer/offset notation wherethe pointer is the array name

*( b + 0 ) = 10

*( b + 1 ) = 20

*( b + 2 ) = 30

*( b + 3 ) = 40

Pointer subscript notation

bPtr[ 0 ] = 10

bPtr[ 1 ] = 20

bPtr[ 2 ] = 30

bPtr[ 3 ] = 40

Pointer/offset notation
*( bPtr + 0 ) = 10

*( bPtr + 1 ) = 20

*( bPtr + 2 ) = 30

*( bPtr + 3 ) = 40

4.4. COPYING A STRING USING ARRAY NOTATION AND POINTER


NOTATION.

#include <stdio.h>

void copy1( char * const s1, const char * const s2 );

void copy2( char *s1, const char *s2 );

int main( void )

char string1[ 10 ];

char *string2 = "Hello";

char string3[ 10 ];

char string4[] = "Good Bye";

copy1( string1, string2 );

printf( "string1 = %s\n", string1 );

copy2( string3, string4 );

printf( "string3 = %s\n", string3 );

return 0;
}

4.5 MULTIPURPOSE SORTING PROGRAM USING FUNCTION


POINTERS

#include <stdio.h>

#define SIZE 10

void bubble( int work[], constint size, );

int ascending( int a, int b );

int descending( int a, int b );

int main( void )

int order; /* 1 for ascending order or 2 for descending order */

int counter; /* counter */

/* initialize array a */

int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };

printf( "Enter 1 to sort in ascending order,\n"

"Enter 2 to sort in descending order: " );

scanf( "%d", &order );

printf( "\nData items in original order\n" );

/* output original array */

for ( counter = 0; counter < SIZE; counter++ ) {

printf( "%5d", a[ counter ] );


} /* end for */

/* sort array in ascending order; pass function ascending as an

argument to specify ascending sorting order */

if ( order == 1 ) {

printf( "\nData items in ascending order\n" );

} /* end if */

else { /* pass function descending */

printf( "\nData items in descending order\n" );

} /* end else */

/* output sorted array */

for ( counter = 0; counter < SIZE; counter++ ) {

printf( "%5d", a[ counter ] );

} /* end for */

OUTPUT:

Enter 1 to sort in ascending order,

Enter 2 to sort in descending order: 1

Data items in original order

2 6 4 8 10 12 89 68 45 37

Data items in ascending order

2 4 6 8 10 12 37 45 68 89

Enter 1 to sort in ascending order,


Enter 2 to sort in descending order: 2

Data items in original order

2 6 4 8 10 12 89 68 45 37

Data items in descending order

89 68 45 37 12 10 8 6 4 2

5. SUMMARY
1. Pointers are used to store the address of a variable. It is not correct to store the address of
one type of variable into a pointer variable of the other type. Also, a pointer variable
cannot contain the value of a variable.
2. When we pass a parameter by address, the corresponding formal parameter must be a
pointer variable.
3. When an array is passed as an argument, to a function, a pointer is actually passed. Such
arrays must be declared in the header function with proper size.
4. If we increment a pointer, it will point to the next byte in memory.
5. Allocation of the memory at the run time, known as dynamic memory allocation can be
easily done using pointers.
6. Pointers can not be operated upon by relational and conditional operators. Multiplication
and division operations are also not allowed on a pointer.

6. SUGGESTED REAGINGS

1. Pointers in C by YashwanthKanithkar, BPB press


2. Ashok. K. Kamthane,”Programming in C”, Pearson ed.
3. YashwantKanethkar, “Let Us C”, BPB Publications.
4. E. Balaguruswamy,” Programming in ANSI C”, Tata Mc- Graw Hill.
5. Byron Gottfried,” Programming with C”, Tata Mc- Graw Hill
7. SELF ASSESSMENT QUESTIONS
1. What are pointers? Explain giving examples, the importance and the features of pointers.
2. Explain various operations that can be performed on a pointer variable.
3. What is the relation between an array and a pointer? Expaln giving an example.
4. How strings are stored using pointer variables/
5. Explain the concept of dynamic memory allocation. How pointers are used to allocate
memory dynamically.
6. Write a function using pointers to add two matrices and to return the resultant matrix to
the calling function.
7. Write a function using pointer parameter that reverses the elements of an integer array
and a character array.
8. Write a function using pointers to take a character string as an input, and a character as an
input. The function must delete and count all the occurrences of that character in the
string.
Post Graduate Diploma in Computer Science and Applications

PROBLEM SOLVING THROUGH C

Paper :CS-DE-12 Written by – Dr. Charu

Lesson No: 11 Vetted by:Dr. ShuchitaUpadhyaya

1. INTRODUCTION
2. OBJECTIVE
3. CONTENTS
3.1 STRUCTURES
3.2 DEFINING A STRUCTURE
3.2.1 Declaring structure variables
3.2.2 Initializing Structures
3.3 NESTED STRUCTURES
3.4 ARRAYS OF STRUCTURES
3.5 PASSING STRUCTURES TO FUNCTIONS
3.6 UNIONS
3.6.1 Accessing Members of a union

3.7. SAMPLE PROGRAMS


3.7.1 Using structures to add two distances given in inch-feet
system
3.7.2 Using array of structures to display details of 10 students
3.7.3 Passing structure to a function to display student record
3.7.4 Swapping two numbers using call by reference
3.7.5 Using pointer to structure to display record of a student
4. SUMMARY
5. SUGGESTED READINGS
6. SELF ASSESSMENT QUESTIONS
1. INTRODUCTION

A variable stores a single value for a data type. An array however, is a collection of
elements of similar types. In real life, we need to have different data types, to maintain
information about books in the library we should have information like, title, author,
edition ,price and so on. Thus, to, maintain the information about the books, dissimilar
data types are required. Title and author being character types, edition being integer type
and price being float type. All these data types cannot be handled in a single array. Thus,
multiple arrays of different types, one for each type may be declared. This, will lead to a
cumbersome program. To tackle the need for mixed data type problems, C has an
efficient feature called structure. A structure is a collection of one or more variables of
different data types, grouped together under the same name. It is a user-defined data type
because the user can decide the data type to be included in the body of the structure. By
using structures it is possible to group variables, arrays, pointers and even structures. Like
structures are unions. These also contain elements of different types. However unlike
arrays and structures, members of a union share same memory locations. Thus, union
permits several different data items to be stored in the same portion of memory at
different times.

2. OBJECTIVE

Unlike arrays, individual elements in structures can differ in type. Thus, a single structure
may contain integer, character, and floating point elements. Pointers, arrays and other
structures can also be included as structure elements. The individual elements of a
structure are referred to as members of a structure. Through this lesson, we will learn
how structures are defined, and how individual structure members are accessed and
processed within a program. Relationship between pointers, functions, and arrays is also
presented. We will also examine the concepts of nested structures, that is, structure
elements are structures themselves. Closely related to structures are unions. Unions also
contain members of different types. They differ from structures in storage that all the
members share the same storage area. This lesson also explains the concept of unions and
their usage.

3.1STRUCTURES

Arrays can be used to represent a group of data items that belong to the same type, such
as int or float. However, to represent a collection of data items of different types using a
single name, a constructed data type known as structure, is used. A structure can be seen
as analogous to record, which is used to handle logically related data items. Structures
provide an efficient mechanism to handle real-world data.

For example, to represent a book record in a library, various attributes that can be used
are: title, author, publisher, price, edition, date of publication etc. All these attributes are
dissimilar, for example, title, author, publisher are strings, price, edition and date of
publication are integers. To handle multiple records for books either five different arrays,
each to handle the corresponding entry for all the books can be used or we can create a
structure named books with title, author, publisher, price, edition date of publication as
attributes in a single data item.

3.2DEFINING A STRUCTURE

A structure allows for the storage, in contiguous areas of memory, of associated data
items.A structure is one of a group of language constructs that allow the programmer to
compose his/her own data types A structure is a template for a new data type whose
format is defined by the programmer..Unlike arrays, structures must be defined first for
their format that may be used later to declare structure variables.The general form of a
structure template is:

structtag
{
Data type Member1_name;
Data type Member2_name;
------ ;
------;
}variable_name;

Wherestruct is a keyword, that declares a structure with name tag to hold the details of
the member fields, tag is optional and only needs to be present if no variable is present.
The members are variables declared as any C supported data type or composed data
type. A structure is a set of values that can be referenced collectively through a variable
name. The components of a structure are referred to as members of a structure. A
structure differs from an array in that members can be of different data types. The name
of the structure is the tag. The tag is optional when avariable is present and
the variable is optional when the tag is present.Following structure is used to represent
the above mentioned book record

structbook_rec
{
char title[25];
char author[20];
char publisher[20];
int price,
int edition;
int date;
};
A structure template does not occupy any memory space and does not have an address, it
is simply a description of a new data type.

3.2.1Declaring structure variables

A structure variable can be declared after defining a structure format of that


type.Members of structures are not variables themselves. They do not occupy any
memory until they are associated with the structure variables. Storage is allocated for the
structure when a variable of that structure type is declared. The following is another
example of a structure template.
struct Person
{
charlast_name[20];
charfirst_name[16];
int age;
double salary;
};

Three variables of the above data type person would be declared as follows:

struct Person frank, tom, jack;

Thus, structure variable declaration includes,the struct keyword, structure tag name, list
of variable names and a terminating semicolon.Each one of these variables has four
members as specified by the template.
The other way to declare the same is:
struct Person
{
charlast_name[20];
charfirst_name[16];
int age;
double salary;
} frank, tom, jack;

To access individual members of a structure, the ‘dot operator’ or the ‘period operator’ is
used to connect a variable name with an element in the structure. For example,
frank.last_name
is the variable representing the last name of frank and can be treated like any ordinary
variable. The composed name is treated as a variable with the type of the member
variable.Each member of a structure is in a contiguous memory location in relationship to
its previous member and next member.

last_name first_name age salary


0 19 35 37 45

Fig1. Memory allocation for various structure members


For example, all the members of structure person, occupy consecutive 20 bytes for
character array names last_name, 16 bytes for first name, 2 bytes for age and 8 bytes for
salary, summing up to 46 continuous bytes in all for each structure variable declared.

The sizeof operator in C is used to evaluate the number of bytes used to hold all the
members of the structure. The size of structure person can be evaluated using the
following expression:
sizeof(struct person)
Similarly,
sizeof(frank)
will generate the same result 46, as frank is a structure variable of type struct person.
sizeof function will generate the total number of bytes required by the array of the same
structure type. For example, if arr_person is a 10 element array of type struct person,
rhesizeof operator will generate result as 460(10*46).

The following C program shows structure definition, variable declaration and accessing
of the structure members.
struct person
{
charlast_name[20];
charfirst_name[16];
int age;
int salary;
};
main()
{
struct person frank;
printf(“Enter the details of frank”);
scanf(“%s %s %d %d”,frank.last_name, frank.firat_name, &frank.age,
&frank.salary);
printf(“Details of person is “);
printf(“(“Last name is %s \n First name is %s\n Age is %d\n Salary is
%d\n”,frank.last_name,frank.firat_name, frank.age, frank.salary;
}

3.2.2Initializing Structures

Structures can be initialized when the template is created, if a variable of the structure
type is declared with the template creation.

Person employ = {"Ralph","Jones",30, 10000};

This assigns values Ralph Jones, 30, 10000 to employ.last_name, employ.first_name,


employ.age and employ.salaryrespectively.

Likewise, any number of variables of given structure type can be initialized.However, the
order of values enclosed in braces while initializing must match the order of members in
the structure definition.

Values are assigned to individual members of the structure by using the structure variable
name connected with the structure member name.

employ.age = 35;

The dot (.) operator is used to provide the connection between variable name and member
name. When referencing a particular member of a structure, the resulting type of that
expression is that of the member being referenced. The value of one structure variable
can be assigned to another structure variable of the same type.

Person employ1, employ2;


employ = employ2;

The above assignment is a valid statement. The data stored in employ2 would be stored
in employ1, because objects of like type can be assigned to one another. Structure
variables cannot be compared through a relational operator. The following example
attempts to compare two structure variables of the same type.

Person employee, staff;


employee = staff;
if( employee == staff )
...

The above code is invalid, each member of the structure must be compared in order to
establish equality or non-equality.

3.3NESTED STRUCTURES

A structure variable can be a member of another structure template. For example,

struct Vital
{
intage,height,weight;
};
struct Home
{
char f_name[12],l_name[20],city[20],state[3] ,zip_code[11];
};
struct Person
{
Vital emp;
Home place;
} employ;

The above example shows a structure person, whose members, Home and Vital are
structures themselves with 5 and 3 members respectively. In order to access a member of
one of the nested structures, the dot operator is used until the lowest member is reached
in the structure hierarchy. For example, to access height of emp, following statement is
valid.
employ.emp.age

However, employ.zip_code is an invalid reference as it misses out the inner level member
reference.

3.4ARRAYS OF STRUCTURES

Like any other data type in C, a variable of a structure type can be arrayed. For example,
to create a database of vital statistics of 100 persons, we may need to create a structure
vital having 2 members and then create an array stats of 100 members, each member of
which is a structure itself.

struct vital
{
int height;
int weight;
} stats[100];

The above declaration would allow for the storage of 100 items of type vital. Each item
will have height and weight as its membersSincestats isan array, the usual array accessing
methods are used to access individual elements and the dot (.) operator is used to access
members. Any specific item could be referenced as:

stats[index].height
stats[index].weight
For example to print the height and weight of 2nd element, the statement used is,

printf(“ The height and weight of the 2nd element are %d %d”, stats[1].height,
stats[1].weight);

Here, index is the usual array accessing index.In C, single or multi-dimensional arrays
can also be used as structure members. The above structure vital can be modified as:
struct vital
{
int weight;
int height;
intsal_mnth[12];
}stats[100];
In this, we have added a new membersal_mnth, an array to hold the salary for all the
months in a year. To print the salary for the month of aprilfor employee number
23,following statement can be used.

Printf(“ The salary for the month of April is %d”, stats[23].sal_mnth[4]);

3.5PASSING STRUCTURES TO FUNCTIONS

Structures can be passed as an argument to a function simply by writing the variable


name in the argument list when calling the function. C provides three methods to pass
structures as arguments to the functions.
1. .Each member of the structure is passed as an actual argument of the function call,
The actual arguments are then treated independently like ordinary
variable.However, as the size of the structure becomes larger, this techniques
becomes unmanageable and in efficient.
2. A copy of the entire structure to the called function is passed. In this method, as
the function is working on a copy of the structure, any changes to the structure
members within the functions are not reflected in the original structure. Therefore,
the function must return the entire structure back to the calling function.

3. Using pointers to pass the address location of the structures to the function as
argument. The function can access indirectly the entire structure and work on it.
This method is more efficient as compared to the second method mentioned
above.

The general format of sending a copy of a structure to the called functionis:

Function_name(structure _variable_ name);

The called function takes the following format:


Data_typefunction_name(struct_typestructure_variable_name)
{
… ……
… ……
return (expression);
}
The called function must be declared for its type, appropriate to the data type it is
expected to return. The structure variable used as the actual argument and the
corresponding formal argument in the called function must also be of the same struct type
The return statement is necessary only when the function is returning sime data back to
the calling function. The expression may be any simple variable or structure variable or
an expression using simple variable.When a function returns as structure, it must be
assigned to a structure of identical type in the calling function. For example,
main()
{
voidgetData( Person );
Person employee;
getData(employee);
}
voidgetData( Person x )
{
printf("Enter last name”);
scanf(“%s”, x.last_name);
}
If the function being called is to modify or change the data within the structure, the
address of the structure variable can be passed and the called function can work with the
structure members through a pointer. This method is referred to as call by reference.For
example,
main()
{
voidgetData( Person * );
Person employ;
getData(&employ );
}

voidgetData( Person *ptr )


{
printf( "Enter first name:");
scanf(“%s”, ptr->first_name);
printf(“\nEnter last name:");
scanf(“%s”, ptr->last_name);
printf(“\nEnter age:");
scanf(“%d”,ptr->.age);
}
The -> operator, known as arrow operator or member selection operator is used when
referencing a pointer to a structure. Functions can also return pointers to structures.

3.6 UNIONS
A union is an aggregate variable that can declare several data types, but only store the
value of one variable at any one time. Each data type shares the same area of memory.
This can save memory if you have a group of data where only one of the types is used at
a time. . The declaration of a union is similar to that of a structure:

union [union_tag]
{
data_type variable_1;
data_type variable_2;
data_type variable_3;
.
.
.
} [union_variable_name];

As with a structure, a union_tag is optional if a union_variable_name is present. The


compiler allocates only the storage space of the largest data_type declared.

union Data
{
int y;
charstr[6];
float x;
double t;
} var;
The union variable var is given eight(8) bytes of storage; all the elements start at the
same address in memory; the compiler gives the amount of storage needed by the largest
data type, in this case double which is eight bytes.

3.6.1Accessing Members of a union

To access a member of a union the dot operator is used the same as with structures.

var.x = 123.45;
var.str=abc;
var.y=12;

are all valid statements. During accessing, only that member can be accessed whose value
is currently stored. For example, if after making the above declarations, the following
statement is invalid:

printf(“%f”,var.x);

as the storage is currently allocated to the variable var.y. When a different member is
assigned a new value, the new value replaces the previous value assigned to a member.
Unions can also be initialized when the corresponding variable is declared. However,
unlike structures, it can only be initialized with value of the type as of the first union
member. For example:

union Data xyz ={13);

is valid as initialized value is of type int, which is same as of the first defined member
type y. Other members can be initialized either by assigning values or reading values
from the keyboard.For example:
#include <stdio.h>
intmain()
{
union data
{
char a;
int x;
float f;
} myData;
int mode = 1;
myData.a = 'A';
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
myData.x = 42;
mode = 2;
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
myData.f = 101.357;
mode = 3;
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
if( mode == 1 )
printf("The char is being used\n");
else if( mode == 2 )
printf("The int is being used\n");
else if( mode == 3 )
printf("The float is being used\n");
return 0;
}
The above example program declares a union with an int, float, and char. It uses each
field, and after each use prints out all the fields. Here is some sample output:
Here is the Data:
A
577
0.000
Here is the Data:
*
42
0.000
Here is the Data:
1120581321
101.357
The float is being used
There can be different outputs for this program. Clearly the data in the unused fields is
just garbage. This happens because different types are treated differently by the
computer. So if one type is set, the memory is not going to be in the format of the other
types. Also mode is used to keep track of the type.

3.7 SAMPLE PROGRAMS


3.7.1Using structures to add two distances given in inch-feet system
#include<stdio.h>
struct Distance
{
int feet;
float inch;
}d1,d2,sum;
int main()
{
printf("Enter information for 1st distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet);
printf("Enter inch: ");
scanf("%f",&d1.inch);
printf("\nEnterinfromation for 2nd distance\n");
printf("Enter feet: ");
scanf("%d",&d2.feet);
printf("Enter inch: ");
scanf("%f",&d2.inch);
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
/* If inch is greater than 12, changing it to feet. */
if (sum.inch>12.0)
{
sum.inch=sum.inch-12.0;
++sum.feet;
}
printf("\nSum of distances=%d\'-%.1f\"",sum.feet,sum.inch);
return 0;
}

OUTPUT:
Enter information for 1st distance
Enter feet:12
Enter inch:3.45

Enter information for 2nd distance


Enter feet:12
Enter inch:9.2
Sum of distances=25’-0.6”

3.7.2 Using array of structures to display details of 10 students


#include<stdio.h>
struct student
{
char name[50];
int roll;
float marks; };
void main()
{
struct student s[10]; int i;
printf("Enter information of students:\n");
for(i=0;i<10;++i)
{
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n"); }
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i)
{
printf("\nInformation for roll number %d:\n",i+1);
printf("Name: "); puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
}

OUTPUT:
Enter information of students:
For roll number 1
Enter name: Tom
Enter marks: 98

For roll number 2


Enter name: Jerry
Enter marks: 89 …….

Displaying information of students:


Information for roll number 1:
Name: Tom
Marks: 98 . . .

3.7.3 Passing structure to a function to display student record


#include<stdio.h>
struct student
{
char name[50];
int roll; };

void Display(struct student stu);


int main()
{
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument
return 0;
}
void Display(struct student stu)
{
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll
}
OUTPUT:
Enter student's name: Kevin Amla
Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149

3.7.4 Swapping two numbers using call by reference


#include<stdio.h>
struct name
{
int a;
float b;
};
int main()
{
struct name *ptr,p;
ptr=&p;
printf("Enter integer: ");
scanf("%d",&ptr->.a);
printf("Enter number: ");
scanf("%f",&ptr->.b);
printf("Displaying: ");
printf("%d%f",ptr->.a,ptr->.b);
return 0;
}

OUTPUT:
Enter integer
5
Enter number
6
Displaying
6 5

3.7.5 Using pointer to structure to display record of a student


#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
voidfunc(struct student *record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}
voidfunc(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000

4. SUMMARY
1. A structure is used to store dissimilar data items. All the elements of a structure are
stored in contiguous memory locations.
2. Members of a structure can be accessed using dot (.) operator through a structure
variable. Structure elements can be accessed through a pointer to a structure using arrow
(- >) operator.
3. All elements of a structure variable can be assigned to another structure variable using
assignment variable using assignment operator (=). However, it is not possible to
compare two structure variables.
4. When structures are nested, a member must be qualified with all levels of the
structures nesting it
5. Array of structure can be created. Usual array indexing techniques are used to access
the members of the structure, but the dot operator will be used to access individual
member elements of the structure array.
6. A union is just like structures except that members of union share same memory
locations. A union can store only one member at a time.
7. A union can be initialized only withdata that matches only with the type of the first
data type.

5. SUGGESTED READINGS
1. Ashok. K. Kamthane,”Programming in C”, Pearson ed.
2. YashwantKanethkar, “Let Us C”, BPB Publications
3.E. Balaguruswamy,” Programming in ANSI C”, Tata Mc- Graw Hill
4.Byron Gottfried,” Programming with C”, Tata Mc- Graw Hill

6. SELF ASSESSMENT QUESTIONS


1. How does an array different from structure? What is the difference in initializing the
members of arrays and structures?
2. How can the members of a structure
3 Give an example of array of structures and nested structures.
4. Explain various ways in which a structure can be passed to a function.
5How are unionsdifferent from structures?Explain using memory allotment strategy used
to store both.
6. Explain the role of unions in programming environment.
7. Create an employee database to store the name, age, date of birth and date of joining of
the employees in ABC Corporation. Write a program that takes current date as an input
and prints the names of all the employees who have been working since last five years.
8.Wtite a program to maintain student database, name, roll number, branch, marks in five
different subjects and the total marks. Display the roll numbers of the students having
highest marks in each subject and details of the first five toppers of the class.
9. Write a program using functions that compares two given dates. To store a date use a
structure that contains three members namely day, month and year. If the dates are equal
the function should return 0, else it should return 1.
10. Write a program to create an inventory database. Write the modules to enter, delete
and display the records.

You might also like